Python Practical Programs
Python Practical Programs
1. Arithmetic Operators
# Program for Arithmetic Operators
9. Write a Python Program to check whether given age is eligible for voting or not
# program of given age is eligible for voting or not
age = int(input("Enter your age: "))
if age >= 18:
print('You can Vote')
elif age < 18:
print('You can not Vote')
else:
print('Invalid age')
fact = 1
num = int(input('Enter a number: '))
for i in range(2, num+1):
fact *= i
print(f'Factorial of {num} is {fact}')
12. Calculate the electricity bill based on the following criteria
First 100 units: no charge
Next 100 units: Rs 5 per unit
Above 100 units: Rs 10 per unit
# Program to Calculate the Electricity bill
total1 = 0
total2 = 0
unit = int(input('Enter the units: '))
if unit >= 100 and unit <= 200:
rem1 = unit - 100
total1 = rem1 * 5
elif unit > 200:
rem2 = unit - 200
total1 = 500
total2 = rem2 * 10
if(Flag == True):
print(f'{num} is not Prime')
else:
print(f'{num} is Prime')
if(num == sum):
print(f'{num} is an Armstrong number')
else:
print(f'{num} is not an Armstrong number')
sum = 0
num = int(input('Enter a number: '))
for i in range(1, num+1):
sum += i
String
3. Write a python program to count the number of digits, letters or alphabets in the given string.
# Count digits, letters in string
5. Write a python program to remove i’th character from string in different ways
# Program to remove i'th character from string in different ways
1. Program to create a list for student data (roll no, name, department, city) and perform list operations.
# Program to create a list for student data (roll no, name, department, city) and perform list operations
print('\nEnumerate Function')
for index, s in enumerate(Student): # Enumerate function
print(f'Index {index}: {s}')
print('\n Concatenation')
concat = Student + Student2 # Concatenation of two lists
print('After concatenation of 2 list are = ', concat)
2. Create a list of 10 elements having numbers 82, 44, 120, 44, 12, 61, 44 and perform the following operations.
1) Total Sum
2) Sort in ascending order
3) Remove first occurrence of 44
4) Pop last element
5) Insert 100 at 3rd position
6) Add 200 at end
7) Length of list
8) Print index number of 200
9) Count total occurrence of 44
10) Reverse list
num = [82, 44, 120, 44, 12, 61, 44]
num.sort()
print('\nAfter sorting the list in Ascending order =', num)
num.remove(44)
print('List after removing second element =', num)
num.pop()
print('After pop operation =', num)
num.insert(2, 100)
print('Inserting 100 at the third position =', num)
num.append(200)
print('Adding 200 at the end of the list =', num)
3. Create a tuple Fruits containing elements 1, banana, 2, apple, 3, cherry, 4, pineapple and perform questions.
1) Print all elements using loop
2) Use enumerate function
3) Create another list like City: pune, nagar, nashik, Mumbai
4) Convert above list into tuple
5) Concatenate both tuple
6) Perform repetition of tuple city * 4 times
7) Check whether “Pune” in tuple or not
Fruits = (1, 'banana', 2, 'apple', 3, 'cherry', 4, 'pineapple')
print()
for index, fruit in enumerate(Fruits):
print(f'Index {index}: {fruit}')
City = ['pune','nagar','nashik','mumbai']
print('\nCity =', City)
City2 = tuple(City)
print('\nAfter converting the list City into tuple =', City2)
print('pune' in City2)
print(f'\nThe maximum number from tuple is {max(num)} and minimum number from tuple is {min(num)}')
1. Create a dictionary of employee data having keys like name, age and empid. And perform the following operations.
1) Print all the keys.
2) Print all the values.
3) Print all the key-value pair.
4) Print the value using key.
5) Update the value of an existing key.
6) Remove an entry using del.
7) Check for the key existence using if.
Emp = {'Name': 'Onkar B', 'age': 19, 'EmpId': 'B123'}
keys = Emp.keys()
print("All Keys = ", keys)
item = Emp.items()
print("All key-value pairs = ", item)
Emp['age'] = 18
print("Updated age of Employee is ", Emp)
del Emp['EmpId']
print("Emp data after removal ''EmpId'", Emp)
if ('age') in Emp:
print("Age exists in Emp data.")
else:
print("Age does not exists in Emp data.")
Inventory = {"Laptop": 20, "Smartphone": 50, "headphones": 30, "Keyboard": 15, "Mouse": 40}
inventory2 = inventory.copy()
print("Backup Inventory: ", inventory2)
new_inventory = dict.fromkeys(inventory.keys(), 0)
print("New Inventory with quantities set to 0: ", new_inventory)
stock = inventory.get("Smartphone")
print("Units of smartphone in stock: ", stock)
inventory.setdefault("Tablet", 10)
print("Inventory after adding Tablet if not already present: ", inventory)
inventory.clear()
print("Inventory after clear(): ", inventory)
Set
electronics.add("Monitor")
print("Electronics after adding Monitor: ", electronics)
accessories.remove("Headphones")
print("Accessories after removing Headphones: ", accessories)
accessories.discard("Charger")
print("Accessories after discarding Charger: ", accessories)
all_products = electronics.union(accessories)
print("All products (union of electronics and accessories): ", all_products)
common_products = electronics.intersection(accessories)
print("Common products (intersection of electronics and accessories): ", common_products)
ele_not_in_accs = electronics.difference(accessories)
print("Products in electronics but not in accessories: ", ele_not_in_accs)
exclusive = electronics.symmetric_difference(accessories)
print("Exclusive products (in either electronics or accessories, but not in both): ", exclusive)
2. You are managing a list of employee skills in two sets team A Skills and team B Skills.
Team A Skills = {}
Team B Skills = {}
new = Team_A_Skill.copy()
print("Copy of Team A Skills: ", new)
common = Team_A_Skill.isdisjoint(Team_A_Skill)
print("Common skill of both teams: ", common)
subset = Team_A_Skill.issubset(Team_B_Skill)
print("Team A is subset of B or not: ", subset)
superset = Team_B_Skill.issuperset(Team_A_Skill)
print("Team B is superset of A or not: ", superset)
remove = Team_B_Skill.pop()
print("Removed an element from team B: ", Team_B_Skill)
Team_A_Skill.update(Team_B_Skill)
print("All Skills: ", Team_B_Skill)
Team_A_Skill.clear()
print(Team_A_Skill)
Function
max_number = max_3()
print("The maximum number is ", max_number)
max_number = max(a, b, c)
print("The maximum number is ", max_number)
l = []
n = int(input("Enter the number of elements: "))
for i in range(n):
element = int(input("Enter the element: "))
l.append(element)
3. Write a Python function that accepts a string and counts the number of upper and lower case letters.
def count_case(input_str):
upper_bound = 0
lower_bound = 0
for char in input_str:
if char.isupper():
upper_bound += 1
elif char.islower():
lower_bound += 1
return upper_bound, lower_bound
4. Write a Python function that takes a list and returns a new list with unique elements of the first list.
def unique_list(input_list):
return list(set(input_list))
l = []
n = int(input("Enter how many elements: "))
for i in range(n):
element = int(input("Enter the element: "))
l.append(element)
5. Create a user defined function to calculate the square of given number. Accept the value from user.
# Calculate the square of given number
def square(n):
return n * n
6. Write a Python function and call it to print the “Hello World” message on the screen using void function.
# Print the message on screen using void function
def display():
print('Hello World')
result = display()
print(result)
print(type(result))
def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num - 1)
str_numbers = ['4', '3', '2', '8', '7', '4', '3', '1', '5', '9', '6', '10', '14']
int_numbers = map(int, str_numbers)
def square(num):
return num ** 2
numbers = [1, 2, 3, 4, 5]
13. Calculate the product of all numbers in a list using reduce and lambda functions.
# Calculate product of all numbers in list using reduce and lambda functions
num = [5, 4, 3, 2, 1]
print(product)
print(even_no)
15. Write a filter function using lambda and without lambda to print positive number from list of 10 elements.
# Filter function using lambda to print positive number
def is_positive(n):
return n >= 0
print(pos_no)
def starts_with_a(words):
return words.startswith('a')
18. Creating a list of numbers which are divisible by 3 from an existing list using list comprehension.
# Creating a list of numbers which are divisible by 3 from an existing list using comprehension
Blank = []
print(Blank)
list2 = []
print(m)
print(squares)
sentence = 'The quick brown fox jumps over the lazy dog'
print(long_words)
Assignment 3
Exception Handling
1. Write a Python program to demonstrate the zero division error, overflow error and value error.
# exception handling
import math
# ZeroDivisionError
try:
num = 10
denom = 0
result = num / denom
print(f'Result: {result}')
except ZeroDivisionError as e:
print(f'ZeroDivisionError occured: {e}')
# OverflowError
try:
result = math.exp(1000)
print(f'Result: {result}')
except OverflowError as e:
print(f'OverflowError occured: {e}')
# ValueError
try:
invalid_int = int('5')
print(f'Converted integer: {invalid_int}')
except ValueError as e:
print(f'ValueError occured: {e}')
2. Write a Python program to find the fruit with index number from a list.
# program to find the fruit with index number from a list
try:
index = int(input('Enter the index of the fruit you want(0-4): '))
fruit = fruits[index]
except IndexError:
print('Error: Index out of Range. Please enter a valid index between 0 to 4.')
except ValueError:
print('Error: Invalid input. Please enter an integer.')
else:
print(f'The fruit at index {index} is {fruit}.')
try:
name = input('Enter the country name: ')
grade = grades[name]
except KeyError:
print(f'Error: {name} is not in the grade list.')
else:
print(f"{name}'s grade is {grade}.")
Regular Expression
import re
txt = "India is my country"
x = re.findall("[a-m]", txt)
print(x)
import re
txt = "Today's date 11 Feb 25"
x = re.findall("\d", txt)
print(x)
3. Any Character
# Any character
import re
txt = "I live in India and Studying in Indira College"
x = re.findall("In.i..", txt)
print(x)
import re
5. $ - Ends with
# $ - Ends With
import re
txt = "I live in India and studying in Indira College"
x = re.findall("College$", txt)
if x:
print("Yes")
import re
import re
pattern = r'gr(a|e)y'
txt = "The color can be gray or grey"
print(matches)
8. Write a Python function that validates a Gmail ID using a regular expression. The function should ensure the following:
1) The email should belong to the domain gmail.com
2) The local part (before the @) should only contain
a) Letters (both lowercase and uppercase)
b) Digits
c) Periods (‘)
d) Underscore (-)
import re
gmail_reg_ex = r'^[a-zA-Z][a-zA-Z0-9._][email protected]$'
def validate_email(email):
if re.match(gmail_reg_ex, email):
return True
return False
if validate_email(email):
print("Valid Email ID!")
else:
print("Invalid Email ID!")
9. Write a Python function to validate an Indian mobile phone number using a regular expression. The function should ensure the following:
1) The mobile phone number must be exactly 10 digit long.
2) The phone number should start 7 – 9.
import re
phone_reg_ex = r'^[7-9]\d{9}$'
def validate(phone):
if re.match(phone_reg_ex, phone):
return True
return False
if(validate(phone)):
print("Valid Phone number!")
else:
print("Invalid Phone number!")
10. Program to remove all characters except letters letters and numbers.
# Program to remove all characters except letters letters and numbers.
import re
def remove(input_str):
result = re.sub(r'[^a-zA-Z0-9]', ' ', input_str)
return result
11. Program to match a string that contains only upper and lowercase letters and underscores.
# Program to match a string that contains only upper and lowercase letters and underscores.
import re
def check_valid_str(input_str):
pattern = r'^[a-zA-Z0-9_]*$'
if re.match(pattern, input_str):
return True
else:
return False
if check_valid_str(input_str):
print("The string is valid (contains only letters, numbers and undrscores.)")
else:
print("The string is invalid (contains only characters).")
12. Write a python Regex program to accept string starting with vowel.
import re
def vowel(s):
return bool(re.match(r'^[aeiouAEIOU]', s))
if vowel(string):
print(f"The String '{string}' starts with a vowel.")
else:
print(f"The String '{string}' does not start with a vowel.")
13.
import re
if check_string(input_str, allowed_char):
print("The string contains only allowed characters.")
else:
print("The string contains characters that are not allowed.")
Assignment 4
File Handling
2. Write a Python program to compute the number of characters, words and lines in a file.
# Program to compute number of char, words, lines in a file
try:
file = open(file_name, "r")
for l in file:
line += 1
char += len(l)
word += len(l.split())
file.close()
except FileNotFoundError:
print(f"File {file_name} was not Found")
except IOError:
print("An error occured while trying to read the file.")
3. Write a Python script to print the current date in following format “Sun May 29 02:26:23 IST 2017”
# program to print the current date in following format "Sun May 29 02:26:23 IST 2017"
import pytz
time = pytz.timezone('Asia/Kolkata')
cur_time = datetime.now(time)
4. Write a Python program to append text to a file and display the text.
# program to append text to a file and display the text
file = open("f1.txt","a")
print(file.read())
file.close()
rev_line = line.rstrip()[::-1]
print(rev_line)
6. Write a Python program to print date, time for today and now.
# program to print date, time for today and now
import datetime
now = datetime.datetime.now()
print(now.strftime("%d-%m-%y, %H-%M-%S"))
Assignment 5
1. Write a Python program to create a calculator class. Include methods for basic arithmetic operations.
# program to create a calculator class. Include methods for basic arithmetic oprations.
class Calculator:
calc = Calculator()
try:
print("Division: 10 / 5 = ", calc.div(10,5))
except ValueError as e:
print(e)
2. Class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle (implement both
constructor parameterised and default constructor concept of python).
# Class named Circle constructed by radius and two methods which will compute the area and perimeter of the circle
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
circle = Circle(5)
print(f"Area: {circle.area():.2f}")
print(f"Perimeter: {circle.perimeter():.2f}")
3. Write a Python program to create a class representing a stack data structure. Include methods for pushing and popping elements.
#Program to create a class representing a stack data structure. Include methods for pushing and popping elements.
class Stack:
def __init__(self):
self.stack = []
def pop(self):
if not self.is_empty():
item = self.stack.pop()
print(f"{item} popped from stack")
return item
else:
print("Stack is empty, cannot pop")
return None
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
print("Stack is Empty")
return None
def is_empty(self):
return len(self.stack) == 0
def size(self):
return len(self.stack)
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
stack.pop()
print(f"Stack size after pop: {stack.size()}")
4. Implement the following class hierarchy using the concept of inheritance in python
# Class Hierarchy
class Shape:
def __init__(self, name):
self.name = name
def display(self):
print(f"This is a {self.name}.")
class Circle(Shape):
def __init__(self):
super().__init__("Circle")
class Rectangle(Shape):
def __init__(self):
super().__init__("Rectangle")
class Square(Rectangle):
def __init__(self):
super().__init__()
self.name = "Square"
circle = Circle()
circle.display()
rectangle = Rectangle()
rectangle.display()
square = Square()
square.display()
5. Implement the following class hierarchy using the concept of inheritance in python
Student: id, name (Id and name have protected access specifier)
StudentExam (derived from Student): Marks of n subjects (n can be variable)
StudentResult (derived from StudentExam): percentage, grade
# class Hierarchy
class Student:
def __init__(self, student_id, name):
self._id = student_id
self._name = name
class StudentExam(Student):
def __init__(self, student_id, name, marks):
super().__init__(student_id, name)
self.marks = marks
class StudentResult(StudentExam):
def __init__(self, student_id, name, marks):
super().__init__(student_id, name, marks)
self.percentage = sum(self.marks) / len(self.marks)
self.grade = self.calculate_grade()
def calculate_grade(self):
if self.percentage >= 90:
return 'A'
elif self.percentage >= 75:
return 'B'
elif self.percentage >= 60:
return 'C'
elif self.percentage >= 40:
return 'D'
else:
return 'F'
def display_result(self):
print(f"ID: {self._id}, Name: {self._name}")
print(f"Marks: {self.marks}")
print(f"Percentage: {self.percentage:.2f}%")
print(f"Grade: {self.grade}")
Tkinter
1. Create a window and set its title. Create a label widget and set font size.
# Create a window and set its title. Create a label widget and set font size
import tkinter
from tkinter.ttk import Label
root = tkinter.Tk()
2. Create the main window (container). Add any number of widgets to the main window.
# Create the main window (container). Add any number of widgets to the main window
import tkinter
from tkinter import *
master = tkinter.Tk()
master.title("Change the font size of Label")
master.geometry("600x500")
Label(master, text = "Indira College", font = ("Arial", 25)).grid(row = 0)
Label(master, text = "First Name").grid(row = 1)
Label(master, text = "Last Name").grid(row = 2)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row = 1, column = 1)
e2.grid(row = 2, column = 1)
v = int()
Radiobutton(master, text = "Male", variable = v, value = 1).grid(row = 3)
var1 = int()
Checkbutton(master, text = "Singing", variable = var1).grid(row = 5, sticky = 'W')
var2 = int()
Checkbutton(master, text = "Dancing", variable = var2).grid(row = 6, sticky = 'W')
Lb = Listbox(master)
Label(master, text = 'Select Subject:').grid(row = 7)
Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.insert(4, 'Any Other')
Lb.grid(row = 8)
menu = Menu(master)
master.config(menu = menu)
filemenu = Menu(menu)
menu.add_cascade(label = 'file', menu = filemenu)
filemenu.add_command(label = 'New')
filemenu.add_command(label = 'Open')
filemenu.add_separator()
filemenu.add_command(label = 'Exit', command = master.quit)
helpmenu = Menu(menu)
menu.add_cascade(label = 'Help', menu = helpmenu)
helpmenu.add_command(label = 'About')
master.mainloop()
import tkinter as tk
def change_button_colours():
button.config(fg = 'white', bg = 'blue')
root = tk.Tk()
root.title("Change Button Colour")
root.geometry("300x200")
button = tk.Button(root, text = "Click Me", command = change_button_colours, fg = 'red', bg = 'green', font = ('Arial',
12))
button.pack()
root.mainloop()
Database
1. Write a Python program to connect a Dept_Emp database and create Dept and Emp (relationship between Dept and Emp table is one to
many) table within the database.
import psycopg2
try:
conn = psycopg2.connect(
host = "localhost",
database = "b03python",
user = "postgres",
password = "postgres"
)
print("Connection Successful!")
except Exception as e:
print(f"Error connecting to PostgreSQL database: {e}")
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS Employee(EmpId SERIAL PRIMARY KEY, EmpName VARCHAR(100) NOT NULL, Salary
FLOAT NOT NULL, Dept VARCHAR(50) NOT NULL) """)
conn.commit()
print("Employee Table created successfully.")
cursor.execute("INSERT INTO Employee (EmpName, Salary, Dept) VALUES (%s, %s, %s)", ("ABC", 50000, "IT"))
conn.commit()
cursor.close()
conn.close()
print("Database connection closed.")
2. Student database
import psycopg2
try:
conn = psycopg2.connect(
host = "localhost",
database = "b03python",
user = "postgres",
password = "postgres"
)
print("Connection Successful!")
except Exception as e:
print(f"Error connecting to PostgreSQL database: {e}")
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS Student(RollNo SERIAL PRIMARY KEY, S_Name VARCHAR(100) NOT
NULL,Class VARCHAR(50) NOT NULL) """)
conn.commit()
print("Student Table created successfully.")
cursor.execute("INSERT INTO Student (S_Name, Class) VALUES (%s, %s)", ("Onkar", "CS"))
conn.commit()
cursor.close()
conn.close()
print("Database connection closed.")
3. Person Database
import psycopg2
try:
conn=psycopg2.connect(
user="postgres",
password="postgres",
database="poorva",
host="localhost"
)
print("Connection successful!")
except Exception as e:
print(f"Error connecting to postgreSQL database:{e}")
cur=conn.cursor()
create_table_query="""
CREATE TABLE IF NOT EXISTS person(
name VARCHAR(100),
course VARCHAR(50),
roll DECIMAL
);
"""
cur.execute(create_table_query)
conn.commit()
print("Table created successfully.")
insert_query="""
INSERT INTO person(name, course, roll)
VALUES(%s,%s,%s)
"""
cur.execute(insert_query,student_data)
conn.commit()
print("Data inserted successfully.")
update_query="""
UPDATE person
SET roll=%s
WHERE name=%s"""
update_data=(4,"John Doe")
cur.execute(update_query,update_data)
conn.commit()
print("Data updated succesfully.")
delete_query="""
DELETE FROM person
WHERE name=%s"""
delete_data=("John Doe",)
cur.execute(delete_query, delete_data)
conn.commit()
print("Data deleted successfully")
cur.close()
conn.close()
print("Connection closed.")