Python Lab Manual
Python Lab Manual
Course Objectives:
This course helps in gaining foundational programming skills in Python, covering algorithm design, flowcharts,
debugging, conditional and looping constructs, data structures, functions, object-oriented programming, file
handling, and apply them to develop a comprehensive project.
Course Outcomes:
CO1 Able to design and implement algorithms and flowcharts for problems.
CO2 Acquire skills to write and debug Python programs, addressing common issues such as indentation errors.
CO3 Effectively use conditional statements and loops in Python to solve problems
CO4 Manage and manipulate various data structures like strings, sets, lists, tuples, and dictionaries.
CO5 Apply advanced programming concepts and demonstrate their understanding through a comprehensive mini
project.
List of Experiments:
01 Write an algorithm and flowchart for following problems
1.1. Write algorithm and make flowchart to find whether the given natural number n is a prime number or
not.
1.2. Determine if a given number is a Palindrome or not, write algorithm and make flowchart too.
1.3. Fibonacci sequence is generated by adding the previous two terms by starting with 1 and 2, the first
10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, .. write algorithm and make flowchart too.
02 Write program for following problems using basic python
2.1 purposefully raise Indentation Error and Correct it
2.2 Write a program to compute distance between two points taking input from the user (Pythagorean
Theorem)
03 Write a program for following problem using Conditional statements
3.1 Write a program to find largest of three numbers using ‘if statement’.
3.2 Write a program to find given number ‘n’ is even or odd using ‘if else statement’.
3.3 Write a program to test whether the number input by user is positive or negative, and if number is
positive, whether it is even or odd using nested if statements.
3.4 Write a program to print name of day of week when we are given day of week as number (0 for Sunday,
1 for Monday,….., 6 for Saturday).
04 Write program for following problems using Looping statements
4.1 Write a program to find factorial of a whole number ‘n’ using ‘for loop’.
4.2 Write a program to find sum of digits of a natural number using ‘while loop’.
4.3 Write a program to print following pattern using ‘nested for loops’.
1
22
333
4444
55555
4.4 Write a program to illustrate the difference between between ‘break’ and ‘continue’
statements program uses for loop with range (1,11), i.e., list [1,2,3,4,5,6,7,8,9,10]
05 Write program for following problems using strings
5.1 Write a program that reads a word in lowercase and capitalize its alternate letters; For example, it should
print passion as PaSsIoN and radar as RaDaR.
5.2 Write a program that reads a line of text and a word, and prints the number of time given word occurs
(appears) in the line of text.
06 Write program for following problems on sets and lists
6.1 Write a program to illustrate operation on sets (Union, Intersection, difference and comparing)
6.2 Write a program to find the mean(average) of given list. Program should give output the mean rounded
to two decimal digits.
6.3 Write a program to count the frequency of each element in a given list.
07 Write program for following problems on tuples and dictionaries
7.1 Write a program that takes a number as input and prints it in word. For example, if the input number
2370, it should print “Two Three Seven Zero”.
7.2 Write a program that builds a dictionary of months of a year and prints the days in a month for the month
name given as input.
08 Write program for following problems on Functions
8.1 Write a function to find Highest Common Factor (HCF), also known as Greatest Common Divisor (GCD)
of two positive integers m and n.
8.2 Write a function, say int IsPrime(int n) that returns the value 1 if integer argument n represents a prime
number else returns value 0.Use this function in a program to print all three digit prime numbers.
09 Write program for following problems on classes and objects
9.1 Write a program to simulate banking operation with class.
9.2 An employer plans to pay a bonus to all employees as per the following policy:
Earning Bonus
Upto Rs. 1,00,000/- Nil
From Rs. 1,00,001/- to Rs.2,00,00/- Rs.1000 + 10% of the excess over Rs. 1,00,000/-
From Rs. 2,00,001/- to Rs.3,00,000/- Rs.2000 + 20% of the excess over Rs. 2,00,000/-
The input contains the name and earnings of an employee and the desired output is the name and
bonus to be paid to the employee.
Above Rs.3,00,000/- Rs.4000 + 30% of the excess over Rs. 2,00,000/-
Create a class to represent an employee. It should include the following:
Data members:
Name
Earning
Bonus
Member Functions:
To input data
To compute bonus
To output the desired information
Using this class, write a program to accomplish the intended task
10 Write a python program for File handling methods
10.1 To open a file and print its attributes.
10.2 To create a file and then read its contents and display them on the computer screen.
11 Mini Project based on the concepts covered in the syllabus
Text Book:
01 Y.Daniel Liang, “Introduction to Python Programming and Data Structures”, Third Edition, Pearson, 2024.
Reference Books:
01 Dr.R Nageswara Rao, “Core Python Programming”, Third Edition, Dreamtech Press, 2024.
02 Ashok Namdev Kamthane, Amit Ashok Kamthane, “Programming and Problem Solving with Python”, Second
Edition, TMH, 2020.
03 Paul J. Deitel, Harvey Deitel, “Python for Programmers”, 4th Impression, Pearson India Education, 2022.
04 Cay S. Horstmann, Rance D. Necaise, “Python For Everyone”, 3rd Edition, Wiley India, 2024
05 Kenneth A.Labert, “Fundamentals of Python: First Programs with MindTap, Cengage, 2024.
Web References:
01 https://www.udemy.com/course/python-programming-projects/?couponCode=IND21PM
Alternative NPTEL/SWAYAM Course:
01 Programming in Python
https://onlinecourses.swayam2.ac.in/cec24_cs11/preview
01. Write an algorithm and flowchart for following problems
1.1. Write algorithm and make flowchart to find whether the given natural number n is a prime
number or not.
1.2. Determine if a given number is a Palindrome / not, write algorithm and make flowchart too.
program num = 12
temp = num
reverse = 0
while temp > 0:
remainder = temp % 10
print(remainder)
reverse = (reverse * 10) + remainder
temp = temp // 10
if num == reverse:
print('Palindrome')
else:
print("Not Palindrome")
Output Not Palindrome
1.3. Fibonacci sequence is generated by adding the previous two terms by starting with 1 and 2,
the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, .. write algorithm and make flowchart
too.
2.2 Write a program to compute distance between two points taking input from the user
(Pythagorean Theorem)
3.2 Write a program to find given number ‘n’ is even or odd using ‘if else statement’.
program n=int(input("enter n:"))
if n%2==0:
print(n,"is even number")
else:
print(n,"is odd number")
Output enter n: 5
5 is odd number
3.3 Write a program to test whether the number input by user is positive or negative, and if
number is positive, whether it is even or odd using nested if statements.
4.3 Write a program to print following pattern using ‘nested for loops’.
program n = 4 # Number of rows
for i in range(1, n + 1):
for j in range(i):
print(i, end=" ")
print()
Output 1
22
333
4444
4.4 Write a program to illustrate the difference between between ‘break’ and ‘continue’
statements program uses for loop with range (1,11), i.e., list [1,2,3,4,5,6,7,8,9,10]
print("Using continue:")
for i in range(1, 11):
if i == 6:
continue # Skips the iteration when i is 6, but continues the loop
print(i, end=" ")
print() # To end the line
Output Using break: 1 2 3 4 5
Using continue: 1 2 3 4 5 7 8 9 10
05 Write program for following problems using strings
5.1 Write a program that reads a word in lowercase and capitalize its alternate letters; For
example, it should print passion as PaSsIoN and radar as RaDaR.
5.2 Write a program that reads a line of text and a word, and prints the number of time given
word occurs (appears) in the line of text.
# 1. Union
union_set = set_a.union(set_b) # or set_a | set_b
print("Union:", union_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
# 2. Intersection
intersection_set = set_a.intersection(set_b) # or set_a & set_b
print("Intersection:", intersection_set) # Output: {4, 5}
# 3. Difference
difference_set = set_a.difference(set_b) # or set_a - set_b
print("Difference (A - B):", difference_set) # Output: {1, 2, 3}
# 4. Symmetric Difference
symmetric_difference_set = set_a.symmetric_difference(set_b) # or set_a ^ set_b
print("Symmetric Difference:", symmetric_difference_set) # Output: {1, 2, 3, 6, 7,
8}
# 5. Subset
is_subset = set_a.issubset(set_b) # Check if A is a subset of B
print("Is A a subset of B?", is_subset) # Output: False
# 6. Superset
is_superset = set_a.issuperset({4, 5}) # Check if A is a superset of {4, 5}
print("Is A a superset of {4, 5}?", is_superset) # Output: True
# 7. Adding Elements
set_a.add(9)
print("Set A after adding 9:", set_a) # Output: {1, 2, 3, 4, 5, 9}
# 8. Removing Elements
set_b.remove(8) # Raises KeyError if 8 is not present
print("Set B after removing 8:", set_b) # Output: {4, 5, 6, 7}
# 9. Clearing a Set
set_a.clear() # Removes all elements from set A
print("Set A after clearing:", set_a) # Output: set()
Output Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference (A - B): {1, 2, 3}
Symmetric Difference: {1, 2, 3, 6, 7, 8}
Is A a subset of B? False
Is A a superset of {4, 5}? True
Set A after adding 9: {1, 2, 3, 4, 5, 9}
Set B after removing 8: {4, 5, 6, 7}
Set A after clearing: set()
6.2 Write a program to find the mean(average) of given list. Program should give output the
mean rounded to two decimal digits.
program from statistics import mean
lst = [1.1111, 2.2222, 3.3333, 4.4444, 5.5555, 6.6666]
list_avg = mean(lst)
print("Average value of the list:\n", list_avg)
print("Average value of the list with precision upto 3 decimal value:\n",
round(list_avg,2))
Output Average value of the list: 3.88885
Average value of the list with precision upto 3 decimal value: 3.89
6.3 Write a program to count the frequency of each element in a given list.
program # initializing the list
random_list = ['A', 'A', 'B', 'C', 'B', 'D', 'D', 'A', 'B']
frequency = {}
# Driver code
N = "2370"
printWord(N)
Output Two Three Seven Zero
7.2 Write a program that builds a dictionary of months of a year and prints the days in a month
for the month name given as input.
8.1 Write a function to find Highest Common Factor (HCF), also known as Greatest Common
Divisor (GCD) of two positive integers m and n.
program x = 54
y = 24
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
print("The H.C.F. is", hcf)
Output The H.C.F. is 6
8.2 Write a function, say int IsPrime(int n) that returns the value 1 if integer argument n
represents a prime number else returns value 0.Use this function in a program to print all three
digit prime numbers.
def print_three_digit_primes():
"""
Print all three-digit prime numbers.
"""
print("Three-digit prime numbers:")
for num in range(100, 1000): # Iterate through all three-digit numbers
if is_prime(num): # Check if the number is prime
print(num, end=' ') # Print the prime number
def abcd(self):
"""Make the car honk."""
return "Car Details"
def display_info(self):
"""Display the car's information."""
print(f"Car Brand: {self.brand}")
print(f"Car Model: {self.model}")
print(f"Car Year: {self.year}")
# Example usage
if __name__ == "__main__":
# Create a Car object
my_car = Car("Honda City", "Mahindra", 2020)
def get_balance(self):
"""Return the current balance."""
return self.balance
# Example usage
if __name__ == "__main__":
# Create a bank account object
account = BankAccount("Prasad")
# Perform operations
account.deposit(1000)
account.withdraw(300)
print(f"Account balance: ${account.get_balance():.2f}")
Output Deposited: $1000.00. New balance: $1000.00
Withdrew: $300.00. New balance: $700.00
Account balance: $700.00
9.2 An employer plans to pay a bonus to all employees as per the following policy:
program
Output
def print_file_attributes(filename):
"""Print the attributes of the specified file."""
if os.path.exists(filename):
# Get file size
file_size = os.path.getsize(filename)
print(f"File: {filename}")
print(f"Size: {file_size} bytes")
print(f"Created: {time.ctime(creation_time)}")
print(f"Last Modified: {time.ctime(modification_time)}")
print(f"Permissions: {oct(file_permissions)}")
# Convert to octal for better readability
else:
print(f"The file '{filename}' does not exist.")
# Example usage
if __name__ == "__main__":
# Specify the filename
filename = 'example.txt' # Change this to the file you want to check
10.2 To create a file and then read its contents and display them on the computer screen.
File a.py
Name
program # Function to create a file and write content to it
def create_file(filename, content):
with open(filename, 'w') as file: # Open file in write mode
file.write(content) # Write content to the file
print(f"File '{filename}' created and content written.")
# Function to read the contents of a file
def read_file(filename):
with open(filename, 'r') as file: # Open file in read mode
contents = file.read() # Read the entire file
return contents
# Example usage
if __name__ == "__main__":
# Specify the filename and content
filename = 'example.txt'
content = "Hello, this is a sample text file.\nWelcome to Python file handling."