Python Lab Manual
Python Lab Manual
Computer Programming:
Python
LAB MANUAL
INDEX
S.No Exercise Name
1a. Even or Odd Number
Aim:
To write a program that checks whether a given number is even or odd.
Algorithm:
1. Start
2. Accept a number from the user.
3. Check if the number is divisible by 2 (number % 2 == 0).
4. If true, print "Even".
5. Otherwise, print "Odd".
6. End
Element Description
Problem Statement Check if a given number is even or odd.
Input An integer number
Processing Use modulo operator to check parity
Output "Even" or "Odd"
Flowchart:
Pseudocode:
START
INPUT number
IF number MOD 2 = 0 THEN
PRINT "Even"
ELSE
PRINT "Odd"
ENDIF
END
Program :
Output:
Enter a number: 7
7 is Odd
1b.Largest of Three Numbers
Aim
To write a Python program that accepts three numbers from the user and determines the largest among
them using conditional statements.
Algorithm
Element Description
Problem Statement Find the largest of three numbers
Input Three numbers
Processing Use conditional comparisons
Output The largest number
Pseudocode:
START
INPUT num1, num2, num3
IF num1 > num2 AND num1 > num3 THEN
largest ← num1
ELSE IF num2 > num3 THEN
largest ← num2
ELSE
largest ← num3
ENDIF
PRINT "Largest number is", largest
END
Program :
Output:
1c.Factorial of a Number
Aim
To write a Python program that calculates the factorial of a given number using a loop.
Algorithm
Element Description
Problem Statement Find the factorial of a number
Input A non-negative number n
Processing Multiple all integers from 1 to n
Output Factorial of n
Flowchart:
Pseudocode:
START
INPUT n
fact ← 1
FOR i FROM 1 TO n DO
fact ← fact × i
ENDFOR
PRINT "Factorial is", fact
END
Program :
n = int(input("Enter a number: "))
fact = 1
for i in range(1, n + 1):
fact *= i
print("Factorial of", n, "is:", fact)
Output:
Enter a number: 5
Factorial of 5 is: 120
To write a Python program that checks whether a given number is a prime number using conditional
statements and loops.
Algorithm
Program :
n = int(input("Enter a number: "))
if n <= 1:
print(n, "is not a prime number")
else:
prime = True
for i in range(2, n):
if n % i == 0:
prime = False
break
if prime:
print(n, "is a prime number")
else:
print(n, "is not a prime number")
Output:
Enter a number: 17
17 is a prime number
To write a Python program that generates the Fibonacci series up to n terms using a loop.
Algorithm
Program :
Output:
Enter number of terms: 7
Fibonacci series:
0112358
To write a Python program that checks whether the given number is positive, negative, or zero using
conditional statements.
Algorithm
Program :
n = int(input("Enter a number: "))
if n > 0:
print(n, "is Positive")
elif n < 0:
print(n, "is Negative")
else:
print("The number is Zero")
Output:
Enter a number: -15
-15 is Negative
Aim
To write a Python program that assigns a grade to a student based on their marks using conditional
statements.
Algorithm
Program :
Output:
Enter marks (out of 100): 82
Grade: B
Aim
To write a Python program that checks whether the given year is a leap year using conditional statements.
Algorithm
Program:
Output:
Enter a year: 2024
2024 is a Leap Year
Aim
To write a Python program using a function to calculate and display the square and cube of a given
number.
Algorithm
1. Start
2. Define a function square_and_cube(n) that:
o Calculates the square of n as n ** 2.
o Calculates the cube of n as n ** 3.
o Returns both values.
3. In the main program:
o Read a number from the user.
o Call the function square_and_cube() with the entered number.
o Store the returned square and cube in separate variables.
4. Display the square and cube values.
5. Stop
Program:
def square_and_cube(n):
return n ** 2, n ** 3
# Main program
num = int(input("Enter a number: "))
sq, cb = square_and_cube(num)
print("Square:", sq)
print("Cube:", cb)
Output:
Enter a number: 4
Square: 16
Cube: 64
Aim
To write a Python program using a function to calculate the Simple Interest for a given principal, rate of
interest, and time.
Algorithm
1. Start
2. Define a function simple_interest(p, r, t) that:
o Calculates Simple Interest using the formula:SI=P×R×T/100
o Returns the calculated Simple Interest.
3. In the main program:
o Read Principal amount p from the user.
o Read Rate of interest r from the user.
o Read Time t in years from the user.
o Call the function simple_interest(p, r, t) and display the result.
4. Stop
Program :
# Main program
p = float(input("Enter Principal amount: "))
r = float(input("Enter Rate of interest: "))
t = float(input("Enter Time (in years): "))
print("Simple Interest =", simple_interest(p, r, t))
Output:
Aim
To write a Python program using a function to calculate the sum of digits of a given number.
Algorithm
1. Start
2. Define a function sum_of_digits(n) that:
o Initialize total to 0.
o While n is greater than 0:
Add the last digit of n (i.e., n % 10) to total.
Remove the last digit from n by integer division (n //= 10).
o Return the value of total.
3. In the main program:
o Read a number num from the user.
o Call the function sum_of_digits(num) and store the result.
o Display the sum of digits.
4. Stop
Program :
def sum_of_digits(n):
total = 0
while n > 0:
total += n % 10
n //= 10
return total
# Main program
num = int(input("Enter a number: "))
print("Sum of digits =", sum_of_digits(num))
Output:
Aim
To write a Python program to count the number of words in a given sentence and display the reversed
sentence.
Algorithm
1. Start
2. Read a sentence text from the user.
3. Split the sentence into words using the split() function and store them in a list words.
4. Count the number of words by calculating the length of the list words and store it in word_count.
5. Reverse the sentence using slicing (text[::-1]) and store it in reversed_text.
6. Display the original sentence, number of words, and reversed sentence.
7. Stop
Program :
Output:
Aim
To write a Python program to perform basic operations on a list, including finding the sum, maximum
element, and sorting the list.
Algorithm
1. Start
2. Define a list numbers with some integer elements.
3. Display the list.
4. Calculate the sum of all elements in the list using the sum() function and display it.
5. Find the maximum element in the list using the max() function and display it.
6. Sort the list in ascending order using the sorted() function and display it.
7. Stop
Program :
Output:
Aim
To write a Python program to perform basic operations on tuples, including concatenation and accessing
specific elements.
Algorithm
1. Start
2. Define two tuples, tuple1 and tuple2, with integer elements.
3. Display tuple1 and tuple2.
4. Concatenate tuple1 and tuple2 using the + operator and store the result in combined.
5. Display the concatenated tuple.
6. Access and display the first element of tuple1 using tuple1[0].
7. Access and display the last element of tuple2 using tuple2[-1].
8. Stop
Program :
Output:
Aim
To write a Python program to perform basic operations on sets, including union, intersection, and
difference.
Algorithm
1. Start
2. Define two sets, set1 and set2, with integer elements.
3. Display set1 and set2.
4. Calculate the union of the sets using set1 | set2 and display it.
5. Calculate the intersection of the sets using set1 & set2 and display it.
6. Calculate the difference of the sets (set1 - set2) and display it.
7. Stop
Program:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print("Set 1:", set1)
print("Set 2:", set2)
print("Union:", set1 | set2)
print("Intersection:", set1 & set2)
print("Difference (Set1 - Set2):", set1 - set2)
Output:
Set 1: {1, 2, 3, 4, 5}
Set 2: {4, 5, 6, 7, 8}
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference (Set1 - Set2): {1, 2, 3}
Aim
To write a Python program to perform basic operations on a dictionary, including adding, updating, and
iterating through key-value pairs.
Algorithm
1. Start
2. Define a dictionary student with keys like "name", "age", and "course".
3. Display the original dictionary.
4. Add a new key-value pair ("marks": 85) to the dictionary.
5. Update the value of an existing key ("age") to 21.
6. Display the updated dictionary.
7. Iterate through the dictionary using a loop:
o For each key-value pair, display the key and its corresponding value.
8. Stop
Program :
Output:
Aim
To write text into a file and then read the contents back using Python.
Algorithm
Program :
# Writing to a file
file = open("sample.txt", "w")
file.write("Hello World\n")
file.write("Python File Handling Practice\n")
file.write("File handling is important in Python\n")
file.close()
# Reading from the file
file = open("sample.txt", "r")
content = file.read()
file.close()
Output:
File Content:
Hello World
Python File Handling Practice
File handling is important in Python
Aim
To read a file line by line and count the total number of words using Python.
Algorithm
Program :
Output:
File Lines:
Python is simple
Python is powerful
Python is popular
Total words in file: 9
Aim
To read numbers from a file, sort them in ascending order, and store them back into another file.
Algorithm
1. Open a file in write mode and write numbers into it.
2. Close the file.
3. Open the file in read mode and read numbers line by line.
4. Convert each number (string) into an integer.
5. Sort the numbers using Python’s sort() function.
6. Display the sorted list.
7. Write the sorted numbers back into another file.
Program :
Output:
Aim
To demonstrate the usage of Python modules and packages to solve problems using at least three different
examples.
Algorithm
1. Import the math module.
2. Take a number input from the user.
3. Calculate and display its square root using math.sqrt().
4. Calculate and display its factorial using math.factorial().
5. Stop.
Program
import math
num = int(input("Enter a number: "))
sqrt_num = math.sqrt(num)
fact_num = math.factorial(num)
print("Square root:", sqrt_num)
print("Factorial:", fact_num)
Output:
Enter a number: 5
Square root: 2.23606797749979
Factorial: 120
Algorithm
Program
import random
rand_int = random.randint(1, 100)
rand_float = random.random()
print("Random integer:", rand_int)
print("Random float:", rand_float)
Output:
Random integer: 47
Random float: 0.732645378
Algorithm
Program
import datetime
now = datetime.datetime.now()
print("Current date and time:", now)
print("Year:", now.year)
print("Month:", now.month)
print("Day:", now.day)
print("Hour:", now.hour)
print("Minute:", now.minute)
Output:
Current date and time: 2025-09-10 14:35:28.123456
Year: 2025
Month: 9
Day: 10
Hour: 14
Minute: 35
Project 1:
Aim
To write a Python program to convert temperatures between Celsius and Fahrenheit using a module.
Algorithm
Module: temperature.py
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32
def fahrenheit_to_celsius(f):
return (f - 32) * 5/9
import temperature
if choice == "F":
print("Temperature in Fahrenheit:", temperature.celsius_to_fahrenheit(temp))
elif choice == "C":
print("Temperature in Celsius:", temperature.fahrenheit_to_celsius(temp))
else:
print("Invalid choice")
Output:
Convert to (C/F): F
Enter temperature: 37
Temperature in Fahrenheit: 98.6
Project 2:
Aim
To write a Python program that performs addition, subtraction, multiplication, and division using a
custom module.
Algorithm
Module: calculator.py
import calculator
if op == '+':
print("Result:", calculator.add(a, b))
elif op == '-':
print("Result:", calculator.subtract(a, b))
elif op == '*':
print("Result:", calculator.multiply(a, b))
elif op == '/':
print("Result:", calculator.divide(a, b))
else:
print("Invalid operation")
Output: