0% found this document useful (0 votes)
11 views19 pages

Python Practical Programs

The document contains two assignments focused on Python programming, covering various topics such as arithmetic operators, area calculations, temperature conversion, variable swapping, random number generation, and string manipulation. It includes programs for checking number properties, calculating electricity bills, and working with lists, tuples, and dictionaries. Each section provides code snippets and explanations for different tasks, demonstrating fundamental programming concepts and operations in Python.

Uploaded by

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

Python Practical Programs

The document contains two assignments focused on Python programming, covering various topics such as arithmetic operators, area calculations, temperature conversion, variable swapping, random number generation, and string manipulation. It includes programs for checking number properties, calculating electricity bills, and working with lists, tuples, and dictionaries. Each section provides code snippets and explanations for different tasks, demonstrating fundamental programming concepts and operations in Python.

Uploaded by

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

Assignment 1

1. Arithmetic Operators
# Program for Arithmetic Operators

a = int(input("Enter First number: "))


b = int(input("Enter Second number: "))
print(f"\nThe Addition of {a} and {b} is {a+b}")
print(f"The Subtraction of {a} and {b} is {a-b}")
print(f"The Multiplication of {a} and {b} is {a*b}")
print(f"The Division of {a} and {b} is {a/b}")
print(f"The Modulus of {a} and {b} is {a%b}")
print(f"The Floor division of {a} and {b} is {a//b}")
print(f"The Exponential of {a} and {b} is {a**b}")

2. Python Program to Calculate the Area of a Triangle


# Area of Triangle
a = float(input('Enter the base of Triangle: '))
b = float(input('Enter the height of Triangle: '))
print('The Area of Triangle is ', (1/2 * a * b))

3. Python Program to Calculate the Area and Perimeter of a Circle


# Area and Perimeter of Circle
r = float(input('Enter the radius of Circle: '))
print('The Area of Circle is: ', (3.14 * r * r))
print('The Perimeter of Circle is: ', 2 * 3.14 * r)

4. Python Program to Convert Temperature into Celsius


# Fahrenheit to Degree Celsius Conversion

f = float(input('Enter the Temperature (In Fahrenheit): '))


print('The Temperature in Celsius is: ', (f-32)*(5/9))

5. Python Program to Swap Two Variables


# Swap a and b usig third variable

a = int(input('Enter the number A: '))


b = int(input('Enter the number B: '))
print(f'Before Swapping\nA = {a}\tB = {b}')
temp = a
a=b
b = temp
print(f'After Swapping\nA = {a}\tB = {b}')

6. Python Program to Generate a Random Number


import random
print(random.randint(0,9))

7. Write a Python Program to Check if a Number is Positive, Negative or Zero


# Program to check the number is positive, negative or zero

num = int(input('Enter the number: '))


if num >= 0:
if num == 0:
print('Number is Zero')
else:
print('Number is Positive')
else:
print('Number is Negative')

8. Write a Python Program to Check if a Number is Odd or Even


a = int(input('Enter a number: '))
if a%2==0:
print('Even')
else:
print('Odd')

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')

10. Python Program to find the maximum of 2 numbers


a = int(input(Enter the first number: ))
b = int(input(Enter the first number: ))
if(a>b):
print(f’{a} is the maximum number’)
else:
print(f’{b} is the maximum number’)

11. Write a Python Program to Find the Factorial of a Number


# Program to calculate factorial

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

print('Your Electricity bill amount is: ', total1 + total2)

13. Write a Python Program to Check Prime Number


# Program to check a number is prime or not
Flag = False
num = int(input('Enter a number: '))
for i in range(2,num):
if(num % i == 0):
Flag = True
break

if(Flag == True):
print(f'{num} is not Prime')
else:
print(f'{num} is Prime')

14. Write a Python Program to Check Armstrong Number


# Program to Check the given number is Armstrong number or not
sum = 0
num = int(input('Enter a number: '))
num2 = len(str(num))
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** num2
temp //= 10

if(num == sum):
print(f'{num} is an Armstrong number')
else:
print(f'{num} is not an Armstrong number')

15. Write a Python Program to Find the Sum of Natural Numbers


# Program to Calculate the sum of n natural numbers

sum = 0
num = int(input('Enter a number: '))
for i in range(1, num+1):
sum += i

print(f'Sum of {num} natural numbers are {sum}')

16. To print the Multiplication table form 1 to 10


# To print Multiplication tableof given number

# num = int(input('Enter a number: '))


for i in range (1, 11):
for j in range (1, 11):
print(f'{i} x {j} = {i * j}')
print('')

17. Write a Python Program to Print the Fibonacci sequence


# To print Fibonacci Sequence upto n number

term = int(input('Enter a number: '))


a, b = 0, 1
count = 0
while count < term:
print(a, end=' ')
a, b = b, a+b
count += 1

18. Print a Pattern


# Program to print pattern
'''
*
**
***
****
'''

level = int(input('Enter the number of levels: '))


for i in range(1, level + 1):
print(''*(level - i)+'*'*(2 * i - 1))
Assignment 2

String

1. Write a python program to Reverse a given String.


# to print reverse of String

text = input('Enter a String: ')


rev_text = ''
for char in text:
rev_text = char + rev_text
print('The reversed String is ',rev_text)

2. Write a python program to Reverse a given String (using Slicing).


# Reverse the given string using Slicing

string = input('Enter a string to reverse: ')


reversed_string = string[::-1]
print(f'The reversed string is: {reversed_string}')

3. Write a python program to count the number of digits, letters or alphabets in the given string.
# Count digits, letters in string

text = input('Enter a String: ')


digits = letters = 0
for char in text:
if char.isdigit():
digits += 1
elif char.isalpha():
letters += 1
print(f'Letters are {letters} and digits are {digits}')

4. Write a python program to check whether the string is Palindrome.


# program of Palindrome Checker

text = input('Enter a String: ')


left, right = 0, len(text)-1
is_palindrome = True
while left < right:
if text[left] != text[right]:
is_palindrome = False
break
left += 1
right -= 1
if is_palindrome:
print(f'{text} is Palindrome')
else:
print(f'{text} is not Palindrome')

# Program to check if string is Palindrome or not using Slicing

String = input('Enter a String to check if it is a Palindrome: ')


reversed_string = String[::-1]
if String == reversed_string:
print(f'"{String}" is a Palindrome.')
else:
print(f'"{String}" is not a Palindrome.')

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

string = input('Enter a String: ')


i = int(input("Enter the index of character to remove: "))
new_str = string[:i] + string[i+1:]
print(f'The string after removing the character at index {i} is: {new_str}.')

6. Write a python program to print even length words in a string


# Program to print even length words in a String

string = input('Enter a String: ')


words = string.split()
for word in words:
if len(word) % 2 == 0:
print(word)

7. Write a python program to check if a substring is present in a given string or not.


# Program to check if a Substring is present in a given string or not

string = input('Enter a string: ')


substring = input('Enter the Substring to check: ')
if substring in string:
print(f'The Substring "{substring}" is present in the String.')
else:
print(f'The Substring "{substring}" is not present in the String.')
List

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

Student = [3, 'Onkar', 'Computer Science', 'Pune'] # creation of list


Student2 = [20, 'Vaibhav', 'MBA', 'Mumbai']
sum_list = [3, 2, 20, 14, 5]

print('Student =', Student)


print('Student2 =', Student2)
print('sum_list =', sum_list)

print('\nPrinting list using loop: ')


for s in Student:
print(s)

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)

print('Repitition of the list is =', Student2 * 2) # Repetition of list

print('banana' in Student) # Membership Testing

print('Length of Student list is =', len(Student)) # len() Function

Student.append('Hello World') # Append Function


print('After append function the list is =', Student)

print('Before insert the list is =', sum_list)


sum_list.insert(3, 2) # Insert Function
print('After insert the list is =', sum_list)

print('Before remove function the list is =', Student)


Student.remove(3) # Remove Function
print('After remove function the list is =', Student)

popped = Student2.pop() # Pop Function


print('Popped element is =', popped)
print('After pop operation the list is =', Student2)

print('Before sorting the list is =', sum_list)


sum_list.sort() # Sorting of list
print('After sorting the list is = ', sum_list)

print('Before reverse the list is =', Student)


Student.reverse() # Reverse Function
print('After reverse the list is =', Student)

print('The position of "Onkar" in the list is =', Student.index('Onkar')) # Index Function

print('Count of 2 in the list is =', sum_list.count(2)) # Count Function

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]

print('Total of all the elements are =', sum(num))

print('\nTotal elements in the list are =', len(num))

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)

print('Index of the element 200 is =', num.index(200))


Tuple

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')

for fruit in Fruits:


print(fruit)

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)

concat = Fruits + City2


print('\nAfter concatenation of both tuples =', concat)

print('\nRepeating the tuple City for 4 times =', City2 * 4)

print('pune' in City2)

4. Create a tuple containing 10 integer elements and perform operations


1) Count the number of occurrences of a number
2) Print index of specific number
3) Print max and min of all numbers in tuple
4) Print total of all elements
5) Print total numbers in tuple
num = (1,5,9,4,6,1,6,9,5,2)
print(num)

print('\nOccurence of 9 in tuple is =', num.count(9))

print('\nIndex of the number "2" is =', num.index(2))

print(f'\nThe maximum number from tuple is {max(num)} and minimum number from tuple is {min(num)}')

print('\nTotal of the all the elements in tuple is =', sum(num))

print('\nThe total elements present in the tuple are =', len(num))


Dictionary

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)

print("All values = ", Emp.values())

item = Emp.items()
print("All key-value pairs = ", item)

print("Value of Name = ", Emp['Name'])

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.")

2. Inventory Management System


You are managing the inventory of a store that sells various products. The store uses a python dictionary to track product names and their
quantities in Stock. The current inventory is as follows:

Inventory = {"Laptop": 20, "Smartphone": 50, "headphones": 30, "Keyboard": 15, "Mouse": 40}

Perform the following operations on the inventory dictionary.


1) Use clear() to remove all products from the inventory.
2) Use copy() to create a backup of the current inventory.
3) Use fromkeys() to create a new dictionary with product names as keys.
4) Use get() to check how many units of “smartphone” are in Stock.
5) Use items() to print all products and their quantities in stock.
6) Use keys() to list all the product names in inventory.
7) Use pop() to remove the “keyboard” from the inventory and print how many units were in Stock.
8) Use popitem() to randomly remove a product form the inventory and print it’s name and quantity.
9) Use setdefault() to add a new product “Tablet” with an initial stock of 10 units, if doesn’t exist.
10) Use update() to add more Mouse units or add a new product Monitor with 25 units if doesn't exist.
11) Use values() to see the current quantities of all products in Stock.
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)

print("All products and their quantities in Stock: ")


for product, quantity in inventory.items():
print(f"{product} : {quantity}")

print("Product names in the inventory: ", list(inventory.keys()))

keyboard_stock = inventory.pop("Keyboard", "Product not Found")


print("Removed keyboard from inventory, Stock was ", keyboard_stock)

removed_product , removed_quantity = inventory.popitem()


print(f"Randomly removed product: {removed_product}, Quantity: {removed_quantity}")

inventory.setdefault("Tablet", 10)
print("Inventory after adding Tablet if not already present: ", inventory)

inventory.update({"Mouse": inventory.get("Mouse", 0) + 20, "Monitor": 25})


print("Inventory after updating Mouse and adding monitor: ", inventory)

print("Current quantities of all products in stock: ", list(inventory.values()))

inventory.clear()
print("Inventory after clear(): ", inventory)
Set

1. Set operations on Product Categories


You are managing two categories of products in a Store: Electronics and Accessories. The products in sets are follows:

Electronics = {"Laptop", "Smartphone", "Tablet", "Smartwatch"}


Accessories = {"Headphones", "Keyboard", "Mouse", "Smartwatch", "Charger", "Laptop"}

Perform the following set operations.


1) Use add() to add “Monitor” to the electronics set.
2) Use remove() to remove “Headphones” from the accessories set.
3) Use discard() to remove “Charger” from the accessories set.
4) Use union() to create a set that contains all products from both electronics and accessories.
5) Use intersection() to create a set of products that are present in both electronics and accessories.
6) Use difference() to find products that are in electronics but not in accessories.
7) Use symmetric_difference() to find products that are in either electronics or accessories, but not in both.
electronics = {"Laptop", "Smartphone", "Tablet", "Smartwatch"}

accessories = {"Headphones", "Keyboard", "Mouse", "Smartwatch", "Charger", "Laptop"}

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 = {}

Perform the following set operations.


1) Use disjoint() to check if there are common skills between team A and team B skills.
2) Use copy() to create a copy of team A skills set.
3) Use issubset() to check if team A skills is a subset of team B skills.
4) Use issuperset() to check if team B skills are superset of team A skills.
5) Use pop() to remove a random skill from team B skills and print the removed skill.
6) Use update() to add the skills from team A skills to team B skills.
7) Finally, use clear() to remove all skills from team A skillset.
Team_A_Skill = {'Python', 'Java', 'SQL', 'machine Learning'}

Team_B_Skill = {'Python', 'Javascript', 'SQL', 'Data Analysis'}

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

1. Write a Python function to find the Max of three numbers.


a) Without using max() function
def max_3():
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))

if a > b and a > c:


return a
elif b > a and b > c:
return b
else:
return c

max_number = max_3()
print("The maximum number is ", max_number)

b) Using max() function


a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))

max_number = max(a, b, c)
print("The maximum number is ", max_number)

2. Write a Python function to sum all the numbers in a list.


def sum(num):
total = 0
for no in num:
total += no
return total

l = []
n = int(input("Enter the number of elements: "))

for i in range(n):
element = int(input("Enter the element: "))
l.append(element)

print("List is: ", l)


result = sum(l)
print("The sum of list is: ", result)

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

input_str = input("Enter a String: ")


upper, lower = count_case(input_str)

print(f"Numbers of Uppercase letters: {upper}")


print(f"Numbers of Lowercase letters: {lower}")

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)

print("List with duplicates ", l)


unique_elements = unique_list(l)
print("List with unique elements: ", unique_elements)

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

num = int(input("Enter a number: "))


result = square(num)
print(f"Square of {num} is {result}")

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))

7. Write a lambda function to add 2 numbers.


add = lambda x, y: x + y
print(add(4, 3))
8. Write a recursive function to calculate the factorial of a number.
# Recursive function to calculate factorial of a number

def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num - 1)

n = int(input('Enter a number: '))


print(f'Factorial of {n} is {factorial(n)}')

9. Convert String into numbers.


# Convert string into numbers

str_numbers = ['4', '3', '2', '8', '7', '4', '3', '1', '5', '9', '6', '10', '14']
int_numbers = map(int, str_numbers)

print('String into numbers list: ', list(int_numbers))


print('Original list: ', str_numbers)

10. Define a function that computes square of a number.


# function that computes square of number

def square(num):
return num ** 2

numbers = [1, 2, 3, 4, 5]

sq_num = map(square, numbers)


print(list(sq_num))

11. Convert any number to it’s absolute value.


# converts any number into it's absolute value

num = [-2, -1, 0, 1, 2]

absolute = list(map(abs, num))


print(absolute)
print(list(map(float, num)))

12. Doubling each number in a list using map and lambda.


# Doubling each number in a list using map and lambda

num = [2, 4, 6, 8, 10]


double = list(map(lambda n: n*2, num))
print(double)

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

from functools import reduce

num = [5, 4, 3, 2, 1]

product = reduce(lambda x, y: x*y, num)

print(product)

14. Filtering even numbers from a list using filter()


# filtering even numbers from a list using filter()

num = [5, 10, 15, 20, 27, 39]

even_no = list(filter(lambda n: n%2 == 0, num))

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

num_list = [-2, -3, 1, 2, 3, 4, -1, 0, 9, 6]

pos_no = list(filter(lambda n: n >= 0, num_list))


print(pos_no)

# filter function without using lambda function to print positive number

num_list = [-2, -3, 1, 2, 3, 4, -1, 0, 9, 6]

def is_positive(n):
return n >= 0

pos_no = list(filter(is_positive, num_list))

print(pos_no)

16. Filtering words starting with specific letter.


# Filtering words starting with a specific letter
#without using lambda function

words = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']

def starts_with_a(words):
return words.startswith('a')

words_a = list(filter(starts_with_a, words))

print("Words starting with 'a': ", words_a)


# Filtering words starting with a specific letter
# Using lambda function

words = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']

words_a = list(filter(lambda word: word.startswith('a'), words))

print("Words starting with 'a': ", words_a)

17. Creating a list of squares of even numbers using list comprehension.


# Creating a list of squares of even numbers using list comprehension
numbers = [1,2,3,4,5]
squares_of_even = [x ** 2 for x in numbers if x % 2 == 0]
print(squares_of_even)

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 = []

for a in range(1, 10):


Blank.append(a)

print(Blank)

list2 = []

m = [h for h in range(1, 10) if h % 3 == 0]

print(m)

19. Generating squares of numbers from 1 to 10.


# Using list comprehension to generate squares of numbers from 1 to 10

squares = [num ** 2 for num in range(1, 11)]

print(squares)

20. Extracting words with specific length.


# Extracting words with specific length

sentence = 'The quick brown fox jumps over the lazy dog'

long_words = [word for word in sentence.split() if len(word) > 3]

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

fruits = ['apple', 'banana', 'cherry', 'orange', 'watermelon']

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}.')

3. Dictionary Key Access.


# Dictionary Key Access

grades = {'China':85, 'India':92, 'SriLanka':78, 'Bangladesh':67, 'US':89, 'UAE':99, 'England':59}

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

1. [] – A set of characters: “[a-m]” –


# [] - A set of characters : "[a - m]" -

import re
txt = "India is my country"

# alphabetically between "a" and "m":

x = re.findall("[a-m]", txt)
print(x)

2. \ - signals a special sequence (can also be to escape special characters): "\d"


# \- signals a special sequence (can also be to escape special characters) : "\d"

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)

4. ^ - Starts with – “^hello”


# ^ - Starts with - "^ hello"

import re

txt = "Hi friends"


x = re.findall("^Hi", txt)
print(x)
print(type(x))

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")

6. * - zero or more occurrence = “I*a”


# * - Zero or more occcurence - "I*a"

import re

txt = "I live in India and studying in Indira College"


x = re.findall("I*a", txt)
print(len(x))

7. Grouping with Alteration


# Grouping With Alteration

import re

pattern = r'gr(a|e)y'
txt = "The color can be gray or grey"

matches = re.findall(pattern, txt)

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

email = input("Enter your Email address: ")

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

phone = input('Enter an Indian phone number: ')

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

input_str = input("Enter a string: ")


print("String with only letters and numbers: ", remove(input_str))

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

input_str = input("Enter a String: ")

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))

string = input('Enter a String: ')

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

def check_string (input_str, allowed_char):


pattern = f"^[{allowed_char}]*$"
if re.match(pattern, input_str):
return True
else:
return False

allowed_char = input("Enter allowed characters: ")


input_str = input("Enter a String: ")

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

1. Write a Python program to read an entire text file.


# Reading a file

file = open("f1.txt", "r")


print(file.read())

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

file_name = input("Enter the file name: ")


line = 0
word = 0
char = 0

try:
file = open(file_name, "r")

for l in file:
line += 1
char += len(l)
word += len(l.split())

file.close()

print("No. of lines: ", line)


print("No. of words: ", word)
print("No. of chars: ", char)

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"

from datetime import datetime

import pytz

time = pytz.timezone('Asia/Kolkata')

cur_time = datetime.now(time)

print("Unformatted Current Time ", cur_time)

formatted = cur_time.strftime("%a %b %d %H:%M:%S IST %Y")

print("\nFormatted Current Time ", formatted)

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")

file.write("This line will add in the File")

file = open("f1.txt", "r")

print(file.read())

file.close()

5. Write a Python program to print each line of a file in reverse order.


# Program to print each line of a file in reverse order.

with open("f1.txt", "r") as file:

for line in file:

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

Object Oriented Programming

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:

def add(self, x, y):


return x + y

def sub(self, x, y):


return x - y

def mul(self, x, y):


return x * y

def div(self, x, y):


if y == 0:
raise ValueError("Cannot divide by zero.")
return x / y

calc = Calculator()

print("Addition: 10 + 5 = ", calc.add(10,5))


print("Subtraction: 10 - 5 = ", calc.sub(10,5))
print("Multiplication: 10 * 5 = ", calc.mul(10,5))

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

def perimeter (self):


return 2 * math.pi * self.radius

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 push(self, item):


self.stack.append(item)
print(f"{item} pushed to 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)

print(f"Top element: {stack.peek()}")


print(f"Stack size: {stack.size()}")

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}")

marks = [85, 90, 78, 92, 88]


student = StudentR
Assignment 6

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()

root.title("Change the font size of Label")


root.geometry("400x250")
Label(root, text = "Indira College", font = ("Arial", 25)).pack()
root.mainloop()

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)

Radiobutton(master, text = "Female", variable = v, value = 2).grid(row = 4)

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)

submitbutton = Button(master, text = "Submit", fg = 'red')


submitbutton.grid(row = 9)

resetbutton = Button(master, text = 'Reset', fg = 'brown')


resetbutton.grid(row = 10)

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()

3. Add button widget and change foreground and background.


# Addd button widget and change foreground and background

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()

print("Employee Added Successfully.")

cursor.execute("SELECT * FROM Employee")


rows = cursor.fetchall()
print("Employee Records: ")

for row in rows:


print(row)

cursor.execute("UPDATE Employee SET Salary = %s WHERE EmpId = %s", (60000, 1))


conn.commit()
print("Salary updated successfully.")

cursor.execute("DELETE FROM Employee WHERE EmpId = %s", (1,))


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()

print("Student Added Successfully.")

cursor.execute("SELECT * FROM Student")


rows = cursor.fetchall()
print("Student Records: ")

for row in rows:


print(row)

cursor.execute("UPDATE Student SET Class = %s WHERE RollNo = %s", ("IT", 1))


conn.commit()
print("Class updated successfully.")

cursor.execute("DELETE FROM Student WHERE RollNo = %s", (2,))


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)
"""

student_data=("John Doe", "Software Engineer", 1)

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.")

You might also like