0% found this document useful (0 votes)
3 views13 pages

Practical Programming in Python

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views13 pages

Practical Programming in Python

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

OPERATORS:

[Link] a list of numbers and write a program to check whether a particular element is present or not
using membership operators.
Explanation: This program takes a list of numbers and a target search number from the user. It then
uses the Python membership operator in to check if the target number exists within the list.

# Read numbers from the user as a space-separated string and convert to a list of integers
numbers_input = input("Enter numbers separated by spaces (e.g., 10 20 30): ")
num_list = [int(x) for x in numbers_input.split()]

# Read the element to search for


search_element = int(input("Enter the number to search for: "))

# Check presence using the membership operator 'in'


if search_element in num_list:
print(f"Yes, {search_element} is present in the list.")
else:
print(f"No, {search_element} is not present in the list.")
2. Read your name and age and write a program to display the year in which you will turn 100 years
old.
Explanation: This program asks for the user's name and current age, calculates how many years are left
until they reach 100, and adds that to the current calendar year to find the target year.
import datetime

# Read name and age from the user


name = input("Enter your name: ")
age = int(input("Enter your age: "))

# Fetch the current year dynamically


current_year = [Link]().year

# Calculate the year they turn 100


years_to_hundred = 100 - age
year_turning_hundred = current_year + years_to_hundred

# Display the output


print(f"Hello {name}! You will turn 100 years old in the year {year_turning_hundred}.")
c. Read radius and height of a cone and write a program to find the volume of a
cone.
Explanation: This program calculates the volume of a cone using the standard mathematical
formula:
a. Read your email id and write a program to display the no of vowels,
consonants, digits and white spaces in it using if...elif...else statement.
Explanation: This program loops through each character of the entered email string. It checks
whether the character is a vowel, a consonant (alphabet but not a vowel), a digit, or a space, and
increments the respective counters.
# Read the email ID
email = input("Enter your email ID: ")

# Initialize counters
vowels = 0
consonants = 0
digits = 0
spaces = 0

# Convert email to lowercase to make checking easier


email_lower = [Link]()

# Loop through each character


for char in email_lower:
if char in 'aeiou':
vowels += 1
elif [Link](): # If it's an alphabet but not a vowel, it's a consonant
consonants += 1
elif [Link]():
digits += 1
elif [Link]():
spaces += 1

# Display the counts


print(f"Vowels: {vowels}")
print(f"Consonants: {consonants}")
print(f"Digits: {digits}")
print(f"White Spaces: {spaces}")
b. Write a program to create and display a dictionary by storing the antonyms of
words. Find the antonym of a particular word given by the user from the
dictionary using while loop.
Explanation: First, we build a static dictionary containing words and their opposites. Then, a
while loop keeps running to let the user search for antonyms until they decide to type 'exit'.
# Create a pre-defined dictionary of antonyms
antonym_dict = {
"hot": "cold",
"fast": "slow",
"big": "small",
"happy": "sad",
"light": "dark"
}

# Display the dictionary


print("Available Dictionary:")
print(antonym_dict)
print("-" * 30)

# Search using a while loop


while True:
search_word = input("\nEnter a word to find its antonym (or type 'exit' to quit): ").lower()

if search_word == 'exit':
print("Exiting the program. Goodbye!")
break

# Check if the word exists in the dictionary


if search_word in antonym_dict:
print(f"The antonym of '{search_word}' is '{antonym_dict[search_word]}'.")
else:
print(f"Sorry, '{search_word}' is not found in the dictionary.")
c. Write a Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!. (Input :n = 5,
Output : 2.70833)

import math
# Read the value of n
n = int(input("Enter the value of n: "))

series_sum = 0.0

# Compute the sum of the series


for i in range(1, n + 1):
term = i / [Link](i)
series_sum += term

# Display output up to 5 decimal places to match the image prompt example


print(f"The sum of the series is: {series_sum:.5f}")
a. Simple File Count (Sentences, Words, Characters)
filename = "[Link]"

with open(filename, "r") as file:


text = [Link]()

char_count = len(text)
word_count = len([Link]())
sentence_count = [Link]('.')

print("Characters:", char_count)
print("Words:", word_count)
print("Sentences:", sentence_count)
Sample Input (Content inside [Link]):
Hello world. Welcome to Python programming. It is easy.
Plaintext
Characters: 53
Words: 9
Sentences: 3
b. Copy only Lowercase Letters to another file
Python Code:
Python
with open("[Link]", "r") as f1, open("[Link]", "w") as f2:
lines = [Link]()

for line in lines:


lower_line = [Link]()
[Link](lower_line)

print("Total lines copied:", len(lines))


Sample Input (Content inside [Link]):
HELLO
World Python 123
Welcome Here
Output (On Screen):
Plaintext
Total lines copied: 3
Output (Content inside the new [Link] file):
Plaintext
hello world
python 123
welcome here
c. Store Student Records and Print by Branch
Python Code:
# 1. Save data to a file
with open("[Link]", "w") as file:
n = int(input("Enter number of students: "))

for i in range(n):
name = input("Enter Name: ")
roll = input("Enter Roll No: ")
branch = input("Enter Branch: ")
[Link](f"{name},{roll},{branch}\n")

# 2. Search and print by branch


search_branch = input("\nEnter branch to search: ")

with open("[Link]", "r") as file:


for line in file:
name, roll, branch = [Link]().split(",")
if branch == search_branch:
print(f"Name: {name}, Roll: {roll}, Branch: {branch}")

Output (When Running the Program):


Enter number of students: 3
Enter Name: Rahul
Enter Roll No: 101
Enter Branch: ECE
Enter Name: Priya
Enter Roll No: 102
Enter Branch: CSE
Enter Name: Arun
Enter Roll No: 103
Enter Branch: ECE

Enter branch to search: ECE


Name: Rahul, Roll: 101, Branch: ECE
Name: Arun, Roll: 103, Branch: ECE

class Employee:
# Constructor
def __init__(self, name, id, age, salary):
[Link] = name
[Link] = id
[Link] = age
[Link] = salary

# Method to display info


def employee_info(self):
print(f"ID: {[Link]} | Name: {[Link]} | Age: {[Link]} | Salary: {[Link]}")

# List to store all employee objects


employees_list = []

# Get number of employees from user


n = int(input("How many employees do you want to add? "))

# Loop to get details for multiple employees


for i in range(n):
print(f"\nEnter details for Employee {i+1}:")
name = input("Enter Name: ")
emp_id = input("Enter ID: ")
age = int(input("Enter Age: "))
salary = float(input("Enter Salary: "))

# Create object and add to list


emp = Employee(name, emp_id, age, salary)
employees_list.append(emp)

# 1. Displaying all using the method


print("\n--- Displaying All Employees Using Method ---")
for emp in employees_list:
emp.employee_info()

# 2. Displaying all using __dict__


print("\n--- Displaying All Employees Using __dict__ ---")
for emp in employees_list:
print(emp.__dict__)

output:
How many employees do you want to add? 2

Enter details for Employee 1:


Enter Name: Ramesh
Enter ID: E101
Enter Age: 28
Enter Salary: 45000

Enter details for Employee 2:


Enter Name: Kavitha
Enter ID: E102
Enter Age: 25
Enter Salary: 50000

--- Displaying All Employees Using Method ---


ID: E101 | Name: Ramesh | Age: 28 | Salary: 45000.0
ID: E102 | Name: Kavitha | Age: 25 | Salary: 50000.0

--- Displaying All Employees Using __dict__ ---


{'name': 'Ramesh', 'id': 'E101', 'age': 28, 'salary': 45000.0}
{'name': 'Kavitha', 'id': 'E102', 'age': 25, 'salary': 50000.0}

Write a program to create a Bank account [Link] class should support the
following methods for
i) Deposit
ii) Withdraw
iii) GetBalance
iv) Pinchange
class BankAccount:
# Constructor to initialize Account Holder Name and initial Balance (default 0)
def __init__(self, account_holder, initial_balance=0):
self.holder_name = account_holder
[Link] = initial_balance
print(f"\nAccount created successfully for {self.holder_name}!")

# Method to deposit money


def deposit(self, amount):
if amount > 0:
[Link] += amount
print(f"₹{amount} deposited successfully.")
else:
print("Invalid deposit amount!")

# Method to withdraw money


def withdraw(self, amount):
if amount > [Link]:
print("Insufficient balance! Transaction failed.")
elif amount <= 0:
print("Invalid withdrawal amount!")
else:
[Link] -= amount
print(f"₹{amount} withdrawn successfully.")

# Method to check current balance


def check_balance(self):
print(f"Current Balance for {self.holder_name}: ₹{[Link]}")

# --- Main Program Execution ---

# 1. Getting account creation details from the user


name = input("Enter Account Holder Name: ")
opening_balance = float(input("Enter Initial Deposit Amount: "))

# 2. Creating the Object


user_account = BankAccount(name, opening_balance)

# 3. Interactive Menu using a while loop


while True:
print("\n--- BANK MENU ---")
print("1. Deposit Money")
print("2. Withdraw Money")
print("3. Check Balance")
print("4. Exit")

choice = input("Select an option (1-4): ")

if choice == '1':
amt = float(input("Enter amount to deposit: "))
user_account.deposit(amt)
elif choice == '2':
amt = float(input("Enter amount to withdraw: "))
user_account.withdraw(amt)
elif choice == '3':
user_account.check_balance()
elif choice == '4':
print("Thank you for banking with us!")
break
else:
print("Invalid choice! Please select a valid option.")

Thank you for banking with us!

STUDENT MARKLIST
class Student:
# Constructor
def __init__(self, name, roll, m1, m2):
[Link] = name
[Link] = roll
self.m1 = m1
self.m2 = m2
# Calculate total marks
[Link] = m1 + m2

# Method to display student marks


def display(self):
print("Roll:", [Link], "| Name:", [Link], "| Total Marks:", [Link])

# Empty list to store students


student_list = []
# Ask number of students
n = int(input("Enter number of students: "))

# Loop to get details


for i in range(n):
print(f"\nStudent {i+1} Details:")
name = input("Enter Name: ")
roll = input("Enter Roll No: ")
m1 = int(input("Enter Mark 1: "))
m2 = int(input("Enter Mark 2: "))

# Create object and add to list


s = Student(name, roll, m1, m2)
student_list.append(s)

# Displaying the final list


print("\n--- Student Mark List ---")
for s in student_list:
[Link]()

# Simulated Database dictionary to store {username: password} pairs


user_db = {}

# 1. Registration Function with validation


def register():
print("\n--- REGISTRATION PAGE ---")
username = input("Choose a Username: ").strip()

# Validation 1: Check if username already exists


if username in user_db:
print("❌ Error: Username already exists! Try another.")
return

password = input("Enter Password: ")


confirm_password = input("Confirm Password: ")

# Validation 2: Check if passwords match


if password == confirm_password:
# Validation 3: Basic empty check
if username == "" or password == "":
print("❌ Error: Fields cannot be empty!")
else:
user_db[username] = password
print("✅ Registration Successful! You can now login.")
else:
print("❌ Error: Passwords do not match!")

# 2. Login Function with validation


def login():
print("\n--- LOGIN PAGE ---")
username = input("Enter Username: ").strip()
password = input("Enter Password: ")

# Validation: Check credentials against our user_db dictionary


if username in user_db and user_db[username] == password:
print(f"🎉 Login Successful! Welcome back, {username}.")
else:
print("❌ Error: Invalid Username or Password!")

# --- Main Interactive Program Loop ---


while True:
print("\n===== MAIN MENU =====")
print("1. Register")
print("2. Login")
print("3. Exit")

choice = input("Choose an option (1-3): ")

if choice == '1':
register()
elif choice == '2':
login()
elif choice == '3':
print("Exiting application. Goodbye!")
break
else:
print("Invalid choice! Please enter 1, 2, or 3.")
QUIZ PROGRAM:
# A structured list of dictionaries to store questions, options, and correct answers
quiz_data = [
{
"question": "Which of the following is an immutable data type in Python?",
"options": ["A. List", "B. Dictionary", "C. Tuple", "D. Set"],
"answer": "C"
},
{
"question": "What is the correct way to initialize a constructor in a Python class?",
"options": ["A. def build(self)", "B. def __init__(self)", "C. def class(self)", "D. def
new(self)"],
"answer": "B"
},
{
"question": "Which Python module is used to handle file path operations dynamically across
OS platforms?",
"options": ["A. sys", "B. os", "C. path", "D. math"],
"answer": "B"
},
{
"question": "What keyword is used to handle exceptions in Python?",
"options": ["A. catch", "B. throw", "C. except", "D. try-error"],
"answer": "C"
}
]

def run_quiz(questions):
score = 0
total_questions = len(questions)

print("=" * 50)
print(f"{'WELCOME TO THE ADVANCED PYTHON QUIZ':^50}")
print("=" * 50)

# Loop through each question block


for index, q in enumerate(questions, start=1):
print(f"\nQuestion {index}: {q['question']}")
# Display options line by line
for option in q['options']:
print(option)

# Get and validate user input


while True:
user_choice = input("Your Answer (A/B/C/D): ").strip().upper()
if user_choice in ['A', 'B', 'C', 'D']:
break
print("⚠️Invalid choice! Please select from A, B, C, or D.")

# Evaluate user answer against data


if user_choice == q['answer']:
print("✅ Correct Answer!")
score += 1
else:
print(f"❌ Wrong! The correct answer was: {q['answer']}")

print("-" * 50)

# Final Score Evaluation & Display Summary


print("\n" + "=" * 50)
print(f"{'QUIZ COMPLETED':^50}")
print("=" * 50)
print(f"Total Questions Attempted : {total_questions}")
print(f"Correct Answers : {score}")
print(f"Wrong Answers : {total_questions - score}")

percentage = (score / total_questions) * 100


print(f"Final Score Percentage : {percentage:.2f}%")
print("=" * 50)

# --- Execute Program ---


if __name__ == "__main__":
run_quiz(quiz_data)

You might also like