0% found this document useful (0 votes)
14 views28 pages

Python Lab Manual

The document is a lab manual for a Python programming course, containing various exercises and projects aimed at teaching fundamental programming concepts. It includes exercises on even/odd checks, largest number determination, factorial calculation, prime number checking, and more, along with pseudocode and sample programs for each task. Additionally, it covers string manipulation, list operations, tuple operations, and file handling, providing a comprehensive guide for students to practice and enhance their programming skills.

Uploaded by

rajeahyuvarai
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)
14 views28 pages

Python Lab Manual

The document is a lab manual for a Python programming course, containing various exercises and projects aimed at teaching fundamental programming concepts. It includes exercises on even/odd checks, largest number determination, factorial calculation, prime number checking, and more, along with pseudocode and sample programs for each task. Additionally, it covers string manipulation, list operations, tuple operations, and file handling, providing a comprehensive guide for students to practice and enhance their programming skills.

Uploaded by

rajeahyuvarai
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/ 28

CS25C02

Computer Programming:
Python

LAB MANUAL
INDEX
S.No Exercise Name
1a. Even or Odd Number

1b. Largest of Three Numbers

1c. Factorial of a Number

2a. Check Whether a Number is Prime

2b. Fibonacci Series (n terms)

2c. Check Whether a Number is Positive, Negative, or Zero

2d. Grade Calculation Based on Marks

2e. Check Whether a Year is a Leap Year or Not

3a. Function to Find Square and Cube of a Number

3b. Function to Calculate Simple Interest

3c. Function to Find Sum of Digits of a Number

4a. String Manipulation – Count Words and Reverse String

4b List Operations – Sum, Maximum, and Sorting

4c Tuple Operations – Concatenation and Indexing

4d. Set Operations – Union, Intersection, Difference

4e. Dictionary Operations – Add, Update, and Iterate

5a. Write and Read from a Text File

5b. Read a File Line by Line and Count Words

5c. Read Numbers from a File and Sort Them

6a. Usage of Modules and Packages-Using the math Module

6b. Usage of Modules and Packages-Using the random Module

6c. Usage of Modules and Packages-Using the datetime Module


6d. Project1: Temperature Conversion Tool
6e. Project 2:Basic Calculator Using a Module
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

Problem Analysis Chart:

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 :

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


if n % 2 == 0:
print(n, "is Even")
else:
print(n, "is Odd")

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

1. Start the program.


2. Input three numbers: num1, num2, and num3.
3. Compare the numbers using conditional logic:
o If num1 > num2 and num1 > num3, then num1 is the largest.
o Else if num2 > num3, then num2 is the largest.
o Else, num3 is the largest.
4. Display the largest number.
5. Stop the program.

Problem Analysis Chart:

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 :

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))

if num1 > num2 and num1 > num3:


largest = num1
elif num2 > num3:
largest = num2
else:
largest = num3

print("The largest number is:", largest)

Output:

Enter first number: 25


Enter second number: 12
Enter third number: 40
The largest number is: 40

1c.Factorial of a Number
Aim

To write a Python program that calculates the factorial of a given number using a loop.

Algorithm

1. Start the program.


2. Input a number n.
3. Initialize a variable fact = 1.
4. Repeat a loop from i = 1 to n:
o Multiply fact by i.
5. After the loop ends, fact will contain the factorial of n.
6. Display the factorial.
7. Stop the program.

Problem Analysis Chart:

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

2a.Check Whether a Number is Prime


Aim

To write a Python program that checks whether a given number is a prime number using conditional
statements and loops.

Algorithm

1. Start the program.


2. Input a number n.
3. If n <= 1, then print "n is not a prime number" and stop.
4. Otherwise, set a flag variable prime = True.
5. Repeat a loop from i = 2 to n-1:
o If n % i == 0, then set prime = False and break the loop.
6. After the loop:
o If prime is True, print "n is a prime number".
o Else, print "n is not a prime number".
7. Stop the program.

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

2b.Fibonacci Series (n terms)


Aim

To write a Python program that generates the Fibonacci series up to n terms using a loop.

Algorithm

1. Start the program.


2. Input the number of terms n.
3. Initialize variables:
o a = 0 (first term)
o b = 1 (second term)
o count = 0 (term counter)
4. Print "Fibonacci series:".
5. Repeat while count < n:
o Print the value of a.
o Compute c = a + b.
o Update values: a = b, b = c.
o Increment count by 1.
6. Stop the program.

Program :

n = int(input("Enter number of terms: "))


a, b = 0, 1
count = 0
print("Fibonacci series:")
while count < n:
print(a, end=" ")
c=a+b
a, b = b, c
count += 1

Output:
Enter number of terms: 7
Fibonacci series:
0112358

2c.Check Whether a Number is Positive, Negative, or Zero


Aim

To write a Python program that checks whether the given number is positive, negative, or zero using
conditional statements.

Algorithm

1. Start the program.


2. Input a number n.
3. Check the condition:
o If n > 0, then print "n is Positive".
o Else if n < 0, then print "n is Negative".
o Otherwise, print "The number is Zero".
4. Stop the program.

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

2d.Grade Calculation Based on Marks

Aim
To write a Python program that assigns a grade to a student based on their marks using conditional
statements.

Algorithm

1. Start the program.


2. Input marks obtained by the student (out of 100).
3. Check conditions in order:
o If marks >= 90, assign grade "A".
o Else if marks >= 75, assign grade "B".
o Else if marks >= 50, assign grade "C".
o Else if marks >= 35, assign grade "D".
o Else, assign grade "F".
4. Print the grade.
5. Stop the program.

Program :

marks = int(input("Enter marks (out of 100): "))


if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 50:
grade = "C"
elif marks >= 35:
grade = "D"
else:
grade = "F"
print("Grade:", grade)

Output:
Enter marks (out of 100): 82
Grade: B

2e.Check Whether a Year is a Leap Year or Not

Aim
To write a Python program that checks whether the given year is a leap year using conditional statements.

Algorithm

1. Start the program.


2. Input a year.
3. Apply the conditions:
o If the year is divisible by 400, it is a leap year.
o Else if the year is divisible by 4 but not divisible by 100, it is a leap year.
o Otherwise, it is not a leap year.
4. Print the result.
5. Stop the program.

Program:

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


if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 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

3a.Function to Find Square and Cube of a Number

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

3b.Function to Calculate Simple Interest

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 :

def simple_interest(p, r, t):


return (p * r * t) / 100

# 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:

Enter Principal amount: 5000


Enter Rate of interest: 5
Enter Time (in years): 2
Simple Interest = 500.0

3c.Function to Find Sum of Digits of a Number

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:

Enter a number: 1234


Sum of digits = 10

4a.String Manipulation – Count Words and Reverse String

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 :

text = input("Enter a sentence: ")


words = text.split()
word_count = len(words)
reversed_text = text[::-1]
print("Original Text:", text)
print("Number of words:", word_count)
print("Reversed Text:", reversed_text)

Output:

Enter a sentence: Python programming is powerful


Original Text: Python programming is powerful
Number of words: 4
Reversed Text: lufrewop si gnimmargorp nohtyP

4b.List Operations – Sum, Maximum, and Sorting

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 :

numbers = [12, 45, 67, 23, 89, 34]


print("List:", numbers)
print("Sum of elements:", sum(numbers))
print("Maximum element:", max(numbers))
print("Sorted list:", sorted(numbers))

Output:

List: [12, 45, 67, 23, 89, 34]


Sum of elements: 270
Maximum element: 89
Sorted list: [12, 23, 34, 45, 67, 89]

4c.Tuple Operations – Concatenation and Indexing

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 :

tuple1 = (10, 20, 30)


tuple2 = (40, 50, 60)
combined = tuple1 + tuple2
print("Tuple 1:", tuple1)
print("Tuple 2:", tuple2)
print("Concatenated Tuple:", combined)
print("First element of Tuple 1:", tuple1[0])
print("Last element of Tuple 2:", tuple2[-1])

Output:

Tuple 1: (10, 20, 30)


Tuple 2: (40, 50, 60)
Concatenated Tuple: (10, 20, 30, 40, 50, 60)
First element of Tuple 1: 10
Last element of Tuple 2: 60

4d.Set Operations – Union, Intersection, Difference

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}

4e.Dictionary Operations – Add, Update, and Iterate

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 :

student = {"name": "Alice", "age": 20, "course": "CSE"}


print("Original Dictionary:", student)
# Add new key-value
student["marks"] = 85
# Update existing value
student["age"] = 21
print("Updated Dictionary:", student)
# Iterate through dictionary
print("Keys and Values:")
for key, value in student.items():
print(key, ":", value)

Output:

Original Dictionary: {'name': 'Alice', 'age': 20, 'course': 'CSE'}


Updated Dictionary: {'name': 'Alice', 'age': 21, 'course': 'CSE', 'marks': 85}
Keys and Values:
name : Alice
age : 21
course : CSE
marks : 85

5a.Write and Read from a Text File

Aim

To write text into a file and then read the contents back using Python.

Algorithm

1. Open a file in write mode.


2. Write multiple lines of text into the file.
3. Close the file.
4. Reopen the file in read mode.
5. Read the entire file content.
6. Display the content.

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

print("File Content:\n", content)

Output:

File Content:
Hello World
Python File Handling Practice
File handling is important in Python

5b.Read a File Line by Line and Count Words

Aim

To read a file line by line and count the total number of words using Python.

Algorithm

1. Open a file in write mode and insert some text lines.


2. Close the file.
3. Open the file in read mode.
4. Read all lines into a list.
5. Initialize word_count = 0.
6. For each line, split into words and count them.
7. Display file content and total word count.

Program :

# Writing content to file


file = open("data.txt", "w")
file.write("Python is simple\n")
file.write("Python is powerful\n")
file.write("Python is popular\n")
file.close()
# Reading and counting words
file = open("data.txt", "r")
lines = file.readlines()
file.close()
word_count = 0
for line in lines:
word_count += len(line.split())
print("File Lines:")
for line in lines:
print(line.strip())
print("Total words in file:", word_count)

Output:

File Lines:
Python is simple
Python is powerful
Python is popular
Total words in file: 9

5c.Read Numbers from a File and Sort Them

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 :

# Writing numbers to file


file = open("numbers.txt", "w")
file.write("45\n12\n89\n23\n56\n")
file.close()
# Reading numbers from file
file = open("numbers.txt", "r")
numbers = file.readlines()
file.close()
# Convert strings to integers
numbers = [int(num.strip()) for num in numbers]
# Sort numbers
numbers.sort()
print("Sorted Numbers:", numbers)
# Writing sorted numbers back to file
file = open("sorted_numbers.txt", "w")
for num in numbers:
file.write(str(num) + "\n")
file.close()

Output:

Sorted Numbers: [12, 23, 45, 56, 89]

6.Usage of Modules and Packages

a. Using the math Module

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

b.Using the random Module

Algorithm

1. Import the random module.


2. Generate a random integer between 1 and 100 using random.randint().
3. Generate a random floating-point number between 0 and 1 using random.random().
4. Display the generated numbers.
5. Stop.

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

c.Using the datetime Module

Algorithm

1. Import the datetime module.


2. Get the current date and time using datetime.datetime.now().
3. Display the current year, month, day, hour, and minute.
4. Stop.

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:

Temperature Conversion Tool

Aim

To write a Python program to convert temperatures between Celsius and Fahrenheit using a module.

Algorithm

1. Create a module temperature.py with two functions:


o celsius_to_fahrenheit(c)
o fahrenheit_to_celsius(f)
2. In the main program, import the module.
3. Take input from the user for temperature and type of conversion.
4. Call the appropriate function and display the result.
5. Stop.

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

choice = input("Convert to (C/F): ").upper()


temp = float(input("Enter 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:

Basic Calculator Using a Module

Aim

To write a Python program that performs addition, subtraction, multiplication, and division using a
custom module.

Algorithm

1. Create a module calculator.py with functions:


o add(a, b)
o subtract(a, b)
o multiply(a, b)
o divide(a, b)
2. In the main program, import the module.
3. Take two numbers and an operation choice from the user.
4. Call the corresponding function and display the result.
5. Stop.

Module: calculator.py

def add(a, b):


return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b):


if b != 0:
return a / b
else:
return "Cannot divide by zero"

import calculator

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


b = float(input("Enter second number: "))
op = input("Choose operation (+, -, *, /): ")

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:

Enter first number: 10


Enter second number: 5
Choose operation (+, -, *, /): *
Result: 50.0

You might also like