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

Python Programming Codes

The document outlines a Python programming lab with various experiments, including downloading and installing Python IDLE, calculating the area of a triangle, swapping variables, solving quadratic equations, and checking for leap years. It provides sample code and expected outputs for each task, covering topics like prime numbers, Fibonacci sequences, and string manipulations. Additionally, it includes exercises on lists and tuples, such as finding the largest number, counting occurrences, and sorting tuples.

Uploaded by

syedmaazqaiser6
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)
3 views35 pages

Python Programming Codes

The document outlines a Python programming lab with various experiments, including downloading and installing Python IDLE, calculating the area of a triangle, swapping variables, solving quadratic equations, and checking for leap years. It provides sample code and expected outputs for each task, covering topics like prime numbers, Fibonacci sequences, and string manipulations. Additionally, it includes exercises on lists and tuples, such as finding the largest number, counting occurrences, and sorting tuples.

Uploaded by

syedmaazqaiser6
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/ 35

Python Programming Lab

Experiment
1) A) Download and Install IDLE.
Aim :- How to download and install python IDLE

Steps to download and install Python IDLE.

a) open any browser like chrome , opera mini


b) search python download on browser
c) open python.org and download the latest version of python
(3.12)
d) open the download file and install in C drive
e) open command prompt to check the version of python (python
–version) whether it is install or not.

B) Write and execute Python program to Calculate the Area of a Triangle where its three
sides a, b, c are given. s=(a+b+c)/2, Area=square root of s(s-a)(s-b)(s-c) (write program
without using function)
Aim:- Calculate the Area of a Triangle where its three sides a, b, c are given. s=(a+b+c)/2,
Area=square root of s(s-a)(s-b)(s-c)

Code:-

import math

a = float(input("Enter the length of side a: "))

b = float(input("Enter the length of side b: "))

c = float(input("Enter the length of side c: "))

s = (a + b + c) / 2

area = math.sqrt(s * (s - a) * (s - b) * (s - c))

print("The area of the triangle is:", area)

output:-

Enter the length of side a: 5


Enter the length of side b: 6
Enter the length of side c: 7
The area of the triangle is: 14.696938456699069
C) Write and execute Python program to Swap Two Variables

pg. 2

1
Python Programming Lab

Aim:- Python program to Swap Two Variables

Code:-

a = input("Enter the value for variable a: ")

b = input("Enter the value for variable b: ")

print("Before swapping: a =", a, ", b =", b)

a, b = b, a

print("After swapping: a =", a, ", b =", b)

Output:-
Enter the value for variable a: 10
Enter the value for variable b: 20
Before swapping: a = 10 , b = 20
After swapping: a = 20 , b = 10

D) Write and execute Python program to Solve quadratic equation for real numbers.

Aim:- execute Python program to Solve quadratic equation for real numbers.
Code:-

import math

a = float(input("Enter coefficient a: "))

b = float(input("Enter coefficient b: "))

c = float(input("Enter coefficient c: "))

D = b**2 - 4*a*c

if D > 0:

root1 = (-b + math.sqrt(D)) / (2 * a)

root2 = (-b - math.sqrt(D)) / (2 * a)

pg. 3

2
Python Programming Lab

print("The roots are real and different.")

print("Root 1:", root1)

print("Root 2:", root2)

elif D == 0:

root = -b / (2 * a)

print("The roots are real and the same.")

print("Root:", root)

else:

print("The equation has no real roots.")

Output:-
Enter coefficient a: 1
Enter coefficient b: -3
Enter coefficient c: 2
The solutions are: (2+0j) and (1+0j)

2). A) Write and execute Python program to Check if a Number is Positive, Negative or
zero.
Aim:- Python program to Check if a Number is Positive, Negative or zero.
Code:-

number = float(input("Enter a number: "))

if number > 0:

print("The number is positive.")

elif number < 0:

print("The number is negative.")

else:

pg. 4

3
Python Programming Lab

print("The number is zero.")

Output:-

Enter a number: 5
The number is positive.

B) Write and execute Python program to Check whether the given year is a Leap Year.
Aim:- Python program to Check whether the given year is a Leap Year.
Code:-

year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):

print(year, "is a leap year.")

else:

print(year, "is not a leap year.")

Output:-
Enter a year: 2024
2024 is a leap year.

C) Write and execute Python program to Print all Prime Numbers in an Interval.
Aim:- Python program to Print all Prime Numbers in an Interval.
Code:-

def is_prime(num):

"""Check if a number is prime."""

if num <= 1:

return False

for i in range(2, int(num**0.5) + 1):

pg. 5

4
Python Programming Lab

if num % i == 0:

return False

return True

def print_primes_in_interval(lower, upper):

"""Print all prime numbers in the specified interval."""

print(f"Prime numbers between {lower} and {upper}:")

for num in range(lower, upper + 1):

if is_prime(num):

print(num, end=' ')

def main():

# Input the interval

lower = int(input("Enter the lower bound of the interval:


"))

upper = int(input("Enter the upper bound of the interval:


"))

print_primes_in_interval(lower, upper)

if __name__ == "__main__":

main()

Output:-
Enter the lower bound of the interval: 10
Enter the upper bound of the interval: 30
Prime numbers between 10 and 30:
11 13 17 19 23 29

D) Write and execute Python program to Display the multiplication Table based on the
given input.

pg. 6

5
Python Programming Lab

Aim:- Python program to Display the multiplication Table based on the given input.
Code:-

num = int(input("Enter a number to display its multiplication


table: "))

print(f"Multiplication Table for {num}:")

for i in range(1, 11): # Multiplying from 1 to 10

print(f"{num} x {i} = {num * i}")

Output:-
Enter a number to display its multiplication table: 5
Multiplication Table for 5:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

E) Write and execute Python program to Print the Fibonacci sequence.


Aim:- Python program to Print the Fibonacci sequence.
Code:-

n_terms = int(input("Enter the number of terms in the


Fibonacci sequence: "))

a, b = 0, 1

print("Fibonacci sequence:")

for _ in range(n_terms):

print(a, end=" ")

# Update the values of a and b

pg. 7

6
Python Programming Lab

a, b = b, a + b

output:-
Enter the number of terms in the Fibonacci sequence: 5
Fibonacci sequence:
0 1 1 2 3

f) Write and execute Python program to Find the Factorial of a Number.


Aim:- Python program to Find the Factorial of a Number.
Code:-

num = int(input("Enter a number to find its factorial: "))

factorial = 1

if num < 0:

print("Factorial is not defined for negative numbers.")

else:

for i in range(1, num + 1):

factorial *= i

print(f"The factorial of {num} is {factorial}.")

output:-
Enter a number to find its factorial: 5
The factorial of 5 is 120.

3) A) Write and execute Python program to Check whether the string is Palindrome

Aim:- Python program to Check whether the string is Palindrome


Code:-

string = input("Enter a string: ")

cleaned_string = string.replace(" ", "").lower()

pg. 8

7
Python Programming Lab

if cleaned_string == cleaned_string[::-1]:

print(f"'{string}' is a palindrome.")

else:

print(f"'{string}' is not a palindrome.")

Output:-
Enter a string: abcba
'abcba' is a palindrome.

a) Write and execute Python program to Reverse words in a given String in Python

Aim:- Python program to Reverse words in a given String in Python


Code:-

string = "I am a python programmer"

words = string.split()

words = list(reversed(words))

print(" ".join(words))

Output:-
programmer python a am I

b) identify in a strings the name, position and counting of vowels.


Aim:- Python program to identify in a strings the name, position and counting of vowels.
Code:-

string = input("Enter a string: ")

vowels = "aeiouAEIOU"

vowel_positions = []

for index, char in enumerate(string):

pg. 9

8
Python Programming Lab

if char in vowels:

vowel_positions.append((char, index))

vowel_count = len(vowel_positions)

print("Vowels found:", vowel_positions)

print("Total number of vowels:", vowel_count)

Output:-
Enter a string: spoon
Vowels found: [('o', 2), ('o', 3)]
Total number of vowels: 2

d) Count the Number of matching characters in a pair of string (set)


Aim:- Python program to Count the Number of matching characters in a pair of string (set)
Code:-

string1 = input("Enter the first string: ")

string2 = input("Enter the second string: ")

set1 = set(string1)

set2 = set(string2)

matching_characters = set1.intersection(set2)

matching_count = len(matching_characters)

print("Matching characters:", matching_characters)

print("Number of matching characters:", matching_count)

Output:-
Enter the first string: apple
Enter the second string: mango
Matching characters: {'a'}

pg. 10

9
Python Programming Lab

Number of matching characters: 1

e) Python program for removing i-th character from a string


Aim:- Python program for removing i-th character from a string
Code:-

string = input("Enter a string: ")

i = int(input("Enter the index of the character to remove (0-


based index): "))

if 0 <= i < len(string):

modified_string = string[:i] + string[i+1:]

print("Modified string:", modified_string)

else:

print("Index out of range.")

Output:-
Enter a string: spoon
Enter the index of the character to remove (0-based index): 3
Modified string: spon

4) a) Write and execute Python program to find largest number in a given list without
using max().

Aim:- Python program to find largest number in a given list without using max().

Code:-

numbers = input("Enter numbers separated by spaces: ")

num_list = [int(num) for num in numbers.split()]

largest = num_list[0]

for num in num_list:

pg. 11

10
Python Programming Lab

if num > largest:

largest = num

print("The largest number in the list is:", largest)

Output:-
Enter numbers separated by spaces: 1 2 3 4 5 68 897
The largest number in the list is: 897

b) Write and execute Python program to find the common numbers from two lists.
Aim:- Python program to find the common numbers from two lists.
Code :-

list1 = input("Enter the first list of numbers separated by


spaces: ")

list1 = [int(num) for num in list1.split()]

list2 = input("Enter the second list of numbers separated by


spaces: ")

list2 = [int(num) for num in list2.split()]

common_numbers = set(list1).intersection(set(list2))

print("Common numbers:", common_numbers)

Output:-
Enter the first list of numbers separated by spaces: 11 12 1 3
34
Enter the second list of numbers separated by spaces: 11 2 34
5
Common numbers: {34, 11}
C) Write and execute Python program create a list of even numbers and another
list of odd numbers from a given list.
Aim :- Python program create a list of even numbers and another list of odd numbers from a
given list.
Code:-

pg. 12

11
Python Programming Lab

numbers = input("Enter a list of numbers separated by spaces:


")

num_list = [int(num) for num in numbers.split()]

even_numbers = []

odd_numbers = []

for num in num_list:

if num % 2 == 0:

even_numbers.append(num)

else:

odd_numbers.append(num)

print("Even numbers:", even_numbers)

print("Odd numbers:", odd_numbers)

Output:-
Enter a list of numbers separated by spaces: 23 24 45 76
Even numbers: [24, 76]
Odd numbers: [23, 45]

d) Write and execute Python program to find number of occurrences of given number
without using built-in methods.
Aim:- Python program to find number of occurrences of given number without using built-in
methods.
Code:-

numbers = input("Enter a list of numbers separated by spaces:


")

num_list = [int(num) for num in numbers.split()]

target = int(input("Enter the number to count occurrences: "))

count = 0

pg. 13

12
Python Programming Lab

for num in num_list:

if num == target:

count += 1

print(f"The number {target} occurs {count} times in the


list.")

Output:-
Enter a list of numbers separated by spaces: 1 4 5 6 78 9 68 4
5 6
Enter the number to count occurrences: 4
The number 4 occurs 2 times in the list.
5) A) Write and execute Python program to find the index of an item of a tuple.

Aim:- Python program to find the index of an item of a tuple.

Code:- :', index)

vowels = ('a', 'e', 'i', 'o', 'i', 'u')

index = vowels.index('e')

print('Index of e:', index)

index = vowels.index('i')

print('Index of i:', index)

Output:-
Index of e: 1
Index of i: 2

b) Write and execute Python program to find the length of a tuple.

Aim:- Python program to find the length of a tuple.


Code:-

tuple1= (123456, 'xyzabc',12,'ckjk',64)

pg. 14

13
Python Programming Lab

print ("First tuple length : ", len(tuple1))

Output:-
First tuple length : 5

c) Write and execute Python program to to reverse a tuple.


Aim:- Python program to to reverse a tuple.
Code:-

tuple_values = (1, 2, 'Python', 'Java', 23.4, 77, 10)

print("The original tuple is: ", tuple_values)

tuple_values = tuple_values[::-1]

print("The reversed tuple is: ", tuple_values)

Output:-
The original tuple is: (1, 2, 'Python', 'Java', 23.4, 77, 10)
The reversed tuple is: (10, 77, 23.4, 'Java', 'Python', 2, 1)

d) Write a Python program to sort a list of tuple by its float element. Sample data: [('item1',
'12.20'), ('item2', '15.10'), ('item3', '24.5')] Expected Output: [('item3', '24.5'), ('item2',
'15.10'), ('item1', '12.20')]
Aim:- Python program to sort a list of tuple by its float element.
Code:-

data = [('item1', '12.20'), ('item2', '15.10'), ('item3',


'24.5')]

sorted_data = sorted(data, key=lambda x: float(x[1]),


reverse=True)

print("Sorted list of tuples:", sorted_data)

Output:-
Sorted list of tuples: [('item3', '24.5'), ('item2', '15.10'),
('item1', '12.20')]

pg. 15

14
Python Programming Lab

6) a) Write and execute Python program to create an intersection of sets.


Aim:- Python program to create an intersection of sets.
Code:-

set1_input = input("Enter the first set of numbers separated


by spaces: ")

set1 = set(int(num) for num in set1_input.split())

set2_input = input("Enter the second set of numbers separated


by spaces: ")

set2 = set(int(num) for num in set2_input.split())

intersection = set1 & set2

print("Intersection of the two sets:", intersection)

Output:-
Enter the first set of numbers separated by spaces: 45 457 457
Enter the second set of numbers separated by spaces: 457 445
56 45
Intersection of the two sets: {457, 45}

b) create a union of sets.


Code:-

set1_input = input("Enter the first set of numbers separated


by spaces: ")

set1 = set(int(num) for num in set1_input.split())

set2_input = input("Enter the second set of numbers separated


by spaces: ")

set2 = set(int(num) for num in set2_input.split())

union = set1 | set2 # You can also use set1.union(set2)

print("Union of the two sets:", union)

pg. 16

15
Python Programming Lab

Output:-
Enter the first set of numbers separated by spaces: 45 456 5
54 433 67
Enter the second set of numbers separated by spaces: 4 34 54
45 43
Union of the two sets: {34, 67, 4, 5, 456, 43, 45, 433, 54}

c) create set difference.


Code:-

set1_input = input("Enter the first set of numbers separated


by spaces: ")

set1 = set(int(num) for num in set1_input.split())

set2_input = input("Enter the second set of numbers separated


by spaces: ")

set2 = set(int(num) for num in set2_input.split())

difference = set1 - set2

print("Difference of the two sets (set1 - set2):", difference)

Output:-
Enter the first set of numbers separated by spaces: 56 43 35
66 546
Enter the second set of numbers separated by spaces: 43 234
546 35
Difference of the two sets (set1 - set2): {56, 66}

d) check if two given sets have no elements in common.


Code:-

set1_input = input("Enter the first set of numbers separated


by spaces: ")

set1 = set(int(num) for num in set1_input.split())

set2_input = input("Enter the second set of numbers separated


by spaces: ")

pg. 17

16
Python Programming Lab

set2 = set(int(num) for num in set2_input.split())

if set1.isdisjoint(set2):

print("The two sets have no elements in common.")

else:

print("The two sets have common elements.")

Output:-
Enter the first set of numbers separated by spaces: 43 64 56
67
Enter the second set of numbers separated by spaces: 64 56 35
54
The two sets have common elements.

7) a) Write and execute Python program to Write a Python script to concatenate two
dictionaries to create a new one
Aim:- Python program to Write a Python script to concatenate two dictionaries to create a
new one
Code:-

dict1 = {'a': 1, 'b': 2}

dict2 = {'c': 3, 'd': 4}

new_dict = dict1.copy() # Create a copy of dict1

new_dict.update(dict2) # Update with dict2

print(new_dict)

Output:-
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

b) Write a Python script to merge two Python dictionaries.


Code:-

pg. 18

17
Python Programming Lab

dict1 = {1: 'John', 2: 'Sam', 3: 'Tim'}


dict2 = {3: 'Kim', 4: 'Kelly'}

# Using copy() and update()


dict3 = dict2.copy()
dict3.update(dict1)
print('Merged dictionary:', dict3)

Output:-
Merged dictionary: {3: 'Tim', 4: 'Kelly', 1: 'John', 2: 'Sam'}

C) Write a Python program to combine two dictionary adding values for common keys. d1
= {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} Sample output: d({'a': 400, 'b':
400, 'd': 400, 'c': 300})
Code:-
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}
combined_dict = {}
for key, value in d1.items():
combined_dict[key] = value
for key, value in d2.items():
if key in combined_dict:
combined_dict[key] += value
else:
combined_dict[key] = value

print("Combined dictionary with added values for common keys:",


combined_dict)

Output:-
Combined dictionary with added values for common keys: {'a': 400, 'b':
400, 'c': 300, 'd': 400}

8) a) Write and execute Python program to Write a Python function for reversing a string
and call it.
Aim:- Python program to Write a Python function for reversing a string and call it.
Code:-

def reverse_string(s):

return s[::-1]

pg. 19

18
Python Programming Lab

input_string = "Hello, World!"

reversed_string = reverse_string(input_string)

print("Original string:", input_string)

print("Reversed string:", reversed_string)

Output:-
Original string: Hello, World!
Reversed string: !dlroW ,olleH
b) Write a Python function for calculating compound interest and call it.
Code:-

import math

def compound_interest(p,r,t):

amt = p * (math.pow((1 + (r/100)),t))

print("Compound Amount: ",amt)

CI = amt - p

return CI

p=float(input("Enter Principal Amount: "))

r=float(input("Enter Rate of Interest: "))

t=float(input("Enter Time Period in years: "))

print("Compound interest is",compound_interest(p,r,t))

Output:-
Enter Principal Amount: 100000
Enter Rate of Interest: 12
Enter Time Period in years: 5
Compound Amount: 176234.16832000008
Compound interest is 76234.16832000008

pg. 20

19
Python Programming Lab

c) Write a Python function for calculating the factorial of a number and call it to calculate
!n/(!r)*!(n-r)) where symbol “! “ stands for factorial.
Code:-

def factorial(n):

"""Calculate the factorial of a non-negative integer n."""

if n < 0:

raise ValueError("Factorial is not defined for


negative numbers")

if n == 0 or n == 1:

return 1

result = 1

for i in range(2, n + 1):

result *= i

return result

def combinations(n, r):

if r > n:

return 0

return factorial(n) // (factorial(r) * factorial(n - r))

n = 5

r = 2

result = combinations(n, r)

print(f"C({n}, {r}) = {result}")

pg. 21

20
Python Programming Lab

output:-
C(5, 2) = 10

9) a) Write Python program using OOP approach to create an instance of a specified class
and display the namespace of the said instance
Aim:- Python program using OOP approach to create an instance of a specified class and
display the namespace of the said instance
Code:-

class py_solution:

def sub_sets(self, sset):

return self.subsetsRecur([], sorted(sset))

def subsetsRecur(self, current, sset):

if sset:

return self.subsetsRecur(current, sset[1:]) +


self.subsetsRecur(current + [sset[0]], sset[1:])

return [current]

for name in py_solution.__dict__:

print(name)

Output:-
__module__

sub_sets

subsetsRecur

__dict__

__weakref__

__doc__

b) create a Python class named Student with two attributes: student_id, student_name.
Add a new attribute: student_class. Create a function to display all attributes and their
values in the Student class.

pg. 22

21
Python Programming Lab

Code:-

class Student:

student_id = 'V10'

student_name = 'Jacqueline Barnett'

def display():

print(f'Student id: {Student.student_id}\nStudent


Name: {Student.student_name}')

print("Original attributes and their values of the Student


class:")

Student.display()

Output:-
Original attributes and their values of the Student class:
Student id: V10
Student Name: Jacqueline Barnett
c) Create a Python class named Student with two instances student1, student2 and assign
values to the instances' attributes. Print all the attributes of the student1, student2
instances
Aim:- Create a Python class named Student with two instances student1, student2 and
assign values to the instances' attributes. Print all the attributes of the student1, student2
instances
Code:-
class Student:
school = 'Forward Thinking'
address = '2626/Z Overlook Drive, COLUMBUS'
student1 = Student()
student2 = Student()
student1.student_id = "V12"
student1.student_name = "Ernesto Mendez"
student2.student_id = "V12"
student2.marks_language = 85
student2.marks_science = 93
student2.marks_math = 95
students = [student1, student2]
for student in students:
print('\n')

pg. 23

22
Python Programming Lab

for attr in student.__dict__:


print(f'{attr} -> {getattr(student, attr)}')

Output:-
student_id -> V12
student_name -> Ernesto Mendez

student_id -> V12


marks_language -> 85
marks_science -> 93
marks_math -> 95

d) Write programs to demonstrate use of following types of inheritance:


i. Single inheritance
ii. Multiple inheritance
iii. Multilevel inheritance

Code:-
i. Single inheritance
class Animal:
def speak(self):
return "Animal speaks"
class Dog(Animal):
def bark(self):
return "Dog barks"
dog_instance = Dog()
print(dog_instance.speak())
print(dog_instance.bark())

Output:-
Animal speaks
Dog barks

ii. Multiple inheritance

pg. 24

23
Python Programming Lab

class Flyer:

def fly(self):

return "Can fly"

class Swimmer:

def swim(self):

return "Can swim"

class Duck(Flyer, Swimmer):

def quack(self):

return "Duck quacks"

duck_instance = Duck()

print(duck_instance.fly()) # Method from Flyer class

print(duck_instance.swim()) # Method from Swimmer class

print(duck_instance.quack()) # Method from Duck class

Output:-
Can fly
Can swim
Duck quacks
iii. Multilevel inheritance

class Animal:

def eat(self):

return "Animal eats"

class Mammal(Animal):

def walk(self):

pg. 25

24
Python Programming Lab

return "Mammal walks"

class Dog(Mammal):

def bark(self):

return "Dog barks"

dog_instance = Dog()

print(dog_instance.eat()) # Method from Animal class

print(dog_instance.walk()) # Method from Mammal class

print(dog_instance.bark()) # Method from Dog class

Output:-
Animal eats
Mammal walks
Dog barks
e) Demonstrate use of polymorphism with following situations:
i. Polymorphism in operator
ii. Polymorphism in user defined method
iii. Polymorphism in built-in function
iv. Polymorphism with class method
v. Polymorphism with method overriding

Aim:- Demonstrate use of polymorphism with following situations:


i. Polymorphism in operator
Code:-

# Demonstrating polymorphism in the '+' operator

class String:

def __init__(self, value):

pg. 26

25
Python Programming Lab

self.value = value

def __add__(self, other):

return String(self.value + other.value)

class Number:

def __init__(self, value):

self.value = value

def __add__(self, other):

return self.value + other.value

s1 = String("Hello, ")

s2 = String("World!")

print((s1 + s2).value) # String concatenation

n1 = Number(10)

n2 = Number(5)

print(n1 + n2) # Numeric addition

Output-
Hello, World!
15

ii. Polymorphism in user defined method


Code:-

class Cat:

def sound(self):

return "Meow"

pg. 27

26
Python Programming Lab

class Dog:

def sound(self):

return "Woof"

def animal_sound(animal):

print(animal.sound())

# Instances

cat = Cat()

dog = Dog()

animal_sound(cat) # Calls Cat's sound method

animal_sound(dog) # Calls Dog's sound method

Output:-
Meow
Woof

iii. Polymorphism in built-in function


Code:-

def add(x, y):

return x + y

# Different types

print(add(5, 3)) # Adding integers

print(add(5.5, 2.5)) # Adding floats

print(add("Hello, ", "World!")) # Concatenating strings

output:-

pg. 28

27
Python Programming Lab

8
8.0
Hello, World!

iv. Polymorphism with class method


Code:-

class A:

@classmethod

def identify(cls):

return "Class A"

class B:

@classmethod

def identify(cls):

return "Class B"

def class_identifier(cls):

print(cls.identify())

class_identifier(A)

class_identifier(B)

output:-
Class A
Class B

v. Polymorphism with method overriding


code:-

class Parent:

pg. 29

28
Python Programming Lab

def show(self):

return "Parent method"

class Child(Parent):

def show(self):

return "Child method"

parent_instance = Parent()

child_instance = Child()

print(parent_instance.show()) # Calls Parent's method

print(child_instance.show()) # Calls Child's overridden


method

Output:-
Parent method
Child method

10) a) Using exception handling feature such as try…except, try finally- write
minimum three programs to handle following types of exceptions.
i. Type Error
ii. Name Error
iii. Index Error
iv. Key Error v. Value Error
vi. IO Error
vii. Zero Division Error

Aim:- Using exception handling feature such as try…except, try finally- write
minimum three programs to handle following types of exceptions.

Code:-

pg. 30

29
Python Programming Lab

Program 1: Handling Various Exceptions

def handle_type_value_zero_division():

try:

# TypeError example

a = "10" + 5 # Trying to add string and integer

except TypeError as e:

print("TypeError:", e)

try:

# ValueError example

num = int("abc") # Trying to convert non-numeric


string to integer

except ValueError as e:

print("ValueError:", e)

try:

# ZeroDivisionError example

result = 10 / 0 # Division by zero

except ZeroDivisionError as e:

print("ZeroDivisionError:", e)

handle_type_value_zero_division()

output:-
TypeError: can only concatenate str (not "int") to str
ValueError: invalid literal for int() with base 10: 'abc'

pg. 31

30
Python Programming Lab

ZeroDivisionError: division by zero

Program 2: Handling NameError, IndexError, and KeyError

def handle_name_index_key_error():

try:

# NameError example

print(undefined_variable) # Using an undefined


variable

except NameError as e:

print("NameError:", e)

try:

# IndexError example

lst = [1, 2, 3]

print(lst[5]) # Accessing an out-of-bounds index

except IndexError as e:

print("IndexError:", e)

try:

# KeyError example

d = {"key1": "value1"}

print(d["key2"]) # Accessing a non-existing key

except KeyError as e:

print("KeyError:", e)

pg. 32

31
Python Programming Lab

handle_name_index_key_error()

output:-
NameError: name 'undefined_variable' is not defined
IndexError: list index out of range
KeyError: 'key2'

Program 3: Handling IOError and finally block

def handle_io_error():

try:

# IOError example (attempting to open a non-existent


file)

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

content = file.read()

except IOError as e:

print("IOError:", e)

finally:

print("Execution of try-except-finally block


complete.")

handle_io_error()

output:-
IOError: [Errno 2] No such file or directory:
'non_existent_file.txt'
Execution of try-except-finally block complete.

10) b) Write Python program to demonstrate file operations.

pg. 33

32
Python Programming Lab

def file_operations():

# 1. Create and write to a file

with open('example.txt', 'w') as file:

file.write("Hello, World!\n")

file.write("This is a file operations


demonstration.\n")

file.write("Let's see how we can read from this


file.\n")

print("File 'example.txt' created and written to.")

# 2. Read from the file

try:

with open('example.txt', 'r') as file:

print("\nContents of 'example.txt':")

content = file.read()

print(content)

except FileNotFoundError:

print("Error: File not found.")

# 3. Append to the file

with open('example.txt', 'a') as file:

file.write("Appending a new line to the file.\n")

pg. 34

33
Python Programming Lab

print("New line appended to 'example.txt'.")

# 4. Read the updated file

with open('example.txt', 'r') as file:

print("\nUpdated contents of 'example.txt':")

content = file.read()

print(content)

# Run the file operations

file_operations()

Explanation of File Operations

1. Creating and Writing to a File:


o The program opens (or creates) a file named example.txt in write mode
('w').
o It writes several lines to the file.
2. Reading from the File:
o The program opens the file in read mode ('r') and reads its contents.
o It prints the contents to the console.
3. Appending to the File:
o The program opens the file in append mode ('a') and adds a new line of text.
4. Reading the Updated File:
o Finally, the program reads and prints the updated contents of the file.

Output:-

File 'example.txt' created and written to.

Contents of 'example.txt':
Hello, World!
This is a file operations demonstration.
Let's see how we can read from this file.

New line appended to 'example.txt'.

pg. 35

34
Python Programming Lab

Updated contents of 'example.txt':


Hello, World!
This is a file operations demonstration.
Let's see how we can read from this file.
Appending a new line to the file.

pg. 36

35

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy