Python Programming Codes
Python Programming Codes
Experiment
1) A) Download and Install IDLE.
Aim :- How to download and install python IDLE
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
s = (a + b + c) / 2
output:-
pg. 2
1
Python Programming Lab
Code:-
a, b = b, a
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
D = b**2 - 4*a*c
if D > 0:
pg. 3
2
Python Programming Lab
elif D == 0:
root = -b / (2 * a)
print("Root:", root)
else:
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:-
if number > 0:
else:
pg. 4
3
Python Programming Lab
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:-
else:
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):
if num <= 1:
return False
pg. 5
4
Python Programming Lab
if num % i == 0:
return False
return True
if is_prime(num):
def main():
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:-
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
a, b = 0, 1
print("Fibonacci sequence:")
for _ in range(n_terms):
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
factorial = 1
if num < 0:
else:
factorial *= i
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
pg. 8
7
Python Programming Lab
if cleaned_string == cleaned_string[::-1]:
print(f"'{string}' is a palindrome.")
else:
Output:-
Enter a string: abcba
'abcba' is a palindrome.
a) Write and execute Python program to Reverse words in a given String in Python
words = string.split()
words = list(reversed(words))
print(" ".join(words))
Output:-
programmer python a am I
vowels = "aeiouAEIOU"
vowel_positions = []
pg. 9
8
Python Programming Lab
if char in vowels:
vowel_positions.append((char, index))
vowel_count = len(vowel_positions)
Output:-
Enter a string: spoon
Vowels found: [('o', 2), ('o', 3)]
Total number of vowels: 2
set1 = set(string1)
set2 = set(string2)
matching_characters = set1.intersection(set2)
matching_count = len(matching_characters)
Output:-
Enter the first string: apple
Enter the second string: mango
Matching characters: {'a'}
pg. 10
9
Python Programming Lab
else:
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:-
largest = num_list[0]
pg. 11
10
Python Programming Lab
largest = num
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 :-
common_numbers = set(list1).intersection(set(list2))
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
even_numbers = []
odd_numbers = []
if num % 2 == 0:
even_numbers.append(num)
else:
odd_numbers.append(num)
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:-
count = 0
pg. 13
12
Python Programming Lab
if num == target:
count += 1
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.
index = vowels.index('e')
index = vowels.index('i')
Output:-
Index of e: 1
Index of i: 2
pg. 14
13
Python Programming Lab
Output:-
First tuple length : 5
tuple_values = tuple_values[::-1]
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:-
Output:-
Sorted list of tuples: [('item3', '24.5'), ('item2', '15.10'),
('item1', '12.20')]
pg. 15
14
Python Programming Lab
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}
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}
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}
pg. 17
16
Python Programming Lab
if set1.isdisjoint(set2):
else:
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:-
print(new_dict)
Output:-
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
pg. 18
17
Python Programming Lab
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
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
reversed_string = reverse_string(input_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):
CI = amt - p
return CI
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):
if n < 0:
if n == 0 or n == 1:
return 1
result = 1
result *= i
return result
if r > n:
return 0
n = 5
r = 2
result = combinations(n, r)
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:
if sset:
return [current]
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'
def display():
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
Output:-
student_id -> V12
student_name -> Ernesto Mendez
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
pg. 24
23
Python Programming Lab
class Flyer:
def fly(self):
class Swimmer:
def swim(self):
def quack(self):
duck_instance = Duck()
Output:-
Can fly
Can swim
Duck quacks
iii. Multilevel inheritance
class Animal:
def eat(self):
class Mammal(Animal):
def walk(self):
pg. 25
24
Python Programming Lab
class Dog(Mammal):
def bark(self):
dog_instance = Dog()
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
class String:
pg. 26
25
Python Programming Lab
self.value = value
class Number:
self.value = value
s1 = String("Hello, ")
s2 = String("World!")
n1 = Number(10)
n2 = Number(5)
Output-
Hello, World!
15
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()
Output:-
Meow
Woof
return x + y
# Different types
output:-
pg. 28
27
Python Programming Lab
8
8.0
Hello, World!
class A:
@classmethod
def identify(cls):
class B:
@classmethod
def identify(cls):
def class_identifier(cls):
print(cls.identify())
class_identifier(A)
class_identifier(B)
output:-
Class A
Class B
class Parent:
pg. 29
28
Python Programming Lab
def show(self):
class Child(Parent):
def show(self):
parent_instance = Parent()
child_instance = Child()
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
def handle_type_value_zero_division():
try:
# TypeError example
except TypeError as e:
print("TypeError:", e)
try:
# ValueError example
except ValueError as e:
print("ValueError:", e)
try:
# ZeroDivisionError example
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
def handle_name_index_key_error():
try:
# NameError example
except NameError as e:
print("NameError:", e)
try:
# IndexError example
lst = [1, 2, 3]
except IndexError as e:
print("IndexError:", e)
try:
# KeyError example
d = {"key1": "value1"}
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'
def handle_io_error():
try:
content = file.read()
except IOError as e:
print("IOError:", e)
finally:
handle_io_error()
output:-
IOError: [Errno 2] No such file or directory:
'non_existent_file.txt'
Execution of try-except-finally block complete.
pg. 33
32
Python Programming Lab
def file_operations():
file.write("Hello, World!\n")
try:
print("\nContents of 'example.txt':")
content = file.read()
print(content)
except FileNotFoundError:
pg. 34
33
Python Programming Lab
content = file.read()
print(content)
file_operations()
Output:-
Contents of 'example.txt':
Hello, World!
This is a file operations demonstration.
Let's see how we can read from this file.
pg. 35
34
Python Programming Lab
pg. 36
35