0% found this document useful (0 votes)
4 views

Lab Record Python

Useful python PDFs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lab Record Python

Useful python PDFs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

WEEK 1
Design algorithms and create flowcharts to solve fundamental problems like swapping
variables and summing numbers.
1.1 Swapping Two Variables
Aim
Write an algorithm, draw a flowchart and pseudocode to swap the values of two variables.
Example: Given A = 5 and B = 10, after the swap, A = 10 and B = 5.
Flowchart

Output:

Algorithm
Input: Two values to be swapped
Procedure:
Step 1: Start

1
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Step 2: Assign two values to variables a and b


Step 3: Store a into temp, Store b into a, Store temp into b
Step 4: Display a and b
Step 5: End
Output: Values after swapping

1.2 Summation of Numbers


Aim
Create an algorithm, flowchart and pseudocode that calculates the sum of a given set of
numbers. Example: Given the numbers 12, 15, 7, 10, the program should compute their total
sum: 44.
Flowchart

2
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Output:

Algorithm
Input: Number of elements for which sum is to be calculated.
Procedure:
Step 1: Start
Step 2: Read number of elements into variable n
Step 3: Initialize variable i to 1
Step 4: repeat until i > n

3
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Step 4.1: store input from user into list a[i]


Step 4.2: increment i by 1
Step 5: set i to 1
Step 6: set variable sum to 0
Step 7: repeat until i > n
Step 7.1: sum = sum + a[i]
Step 7.2: increment i by 1
Step 8: print total sum
Step 9: End
Output: Sum of the elements

1.3 Decimal to Binary Conversion


Aim
Design an algorithm, flowchart and pseudo code to convert a given decimal number to its
binary equivalent.
Example: Convert 10 to its binary form, which is 1010.
Flowchart

4
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Output:

5
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Algorithm
Input: Decimal number
Procedure:
Step 1: Start
Step 2: Read decimal number into n from user
Step 3: initialize variable i to 1
Step 4: repeat until n value becomes 0
Step 4.1: Store value of n%2 in variable r
Step 4.2: Store r value in list a[i]
Step 4.3: increment i by 1
Step 4.4: assign value of floor(n/2) to n
Step 5: decrement i by 1
Step 6: repeat until i becomes less than 1
Step 6.1: print a[i]
Step 6.2: decrement i by 1
Step 7: End
Output: Binary sequence of the entered number

1.4 Reversing the Digits of an Integer


Aim
Develop an algorithm, flowchart and pseudo code to reverse the digits of an integer.
Example: If the input is 12345, the output should be 54321.
Flowchart

6
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Output:

Algorithm
Input: An integer
Procedure:
Step 1: Start
Step 2: Read the number entered by user into variable n
Step 3: initialize variable s to 0
Step 4: repeat until n=0
Step 4.1: Store value of n%2 in variable r
Step 4.2: s = s*10 + r
Step 4.3: n = floor(n/10)
Step 5: Display value of s
Step 6: End
Output: Reverse of entered number

7
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

1.5 Finding the Greatest Common Divisor (GCD)


Aim
Write an algorithm, draw a flowchart and pseudo code to find the GCD of two numbers.
Example: Find the GCD of 48 and 18.
Flowchart

8
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Output:

Algorithm
Input: Two numbers
Procedure:
Step 1: Start
Step 2: Read first number from user into variable a
Step 3: Read second number from user into variable b
Step 4: initiate variable n to 1
Step 5: if a < b:
Step 5.1: assign value of ‘a’ to variable lowest
Step 6: else:
Step 6.1: assign value of b to variable lowest
Step 7: repeat until n > lowest
Step 7.1: if a%n=0 and b%n=0:
Step 7.1.1: gcd=n
Step 7.2: increment n by 1
Step 8: Display value of gcd
Step 9: End
Output: GCD of the two numbers

9
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

1.6 Prime Number Check


Aim
Develop an algorithm, flowchart and pseudo code to find prime numbers in the given range.
Example: Display the prime numbers in the range 1 to 100.
Flowchart

10
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

11
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Output:

Algorithm
Input: Range of numbers
Procedure:
Step 1: Start
Step 2: Read first number in range into variable a
Step 3: Read last number in range into variable b
Step 4: initialize variable count to ‘a’
Step 5: Repeat until count > b
Step 5.1: initialize variable i to 1
Step 5.2: initialize variable factors to 0
Step 5.3: repeat until i > count
Step 5.3.1: if count%i=0:
Step 5.3.1.1: increment factors by 1
Step 5.3.2: increment i by 1
Step 5.4: if factors = 2:
Step 5.4.1: Display ‘count’
Step 5.5: increment count by 1
Step 6: End
Output: Prime numbers in a given range

12
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

1.7 Arranging Numbers in Ascending Order


Aim
Write an algorithm, flowchart and pseudo code that sorts a given set of numbers in ascending
order.
Example: Sort the numbers 8, 3, 15, 6 into 3, 6, 8, 15
Flowchart

13
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

14
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Output:

Algorithm
Input: Number of values which has to be sorted
Procedure:
Step 1: Start
Step 2: initialize variable i to 1
Step 3: repeat until i > n:
Step 3.1: store value entered by user into list a[i]
Step 3.2: increment i by 1
Step 4: set i value to 1
Step 5: return until i > n
Step 5.1: initialize variable j to 1
Step 5.2: repeat until j > n – i
Step 5.2.1: if a[j] > a[j+1]:
Step 5.2.1.1: store value of a[j] in variable ‘temp’
Step 5.2.1.2: store value of a[j+1] in a[j]
Step 5.2.1.3: store value of temp in a[j+1]
Step 5.2.2: increment j by 1
Step 5.3: increment i by 1
Step 6: Set i value to 1

15
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Step 7: repeat until i > n


Step 7.1: Display a[i]
Step 7.2: increment i by 1
Step 8: End
Output: List of numbers are arranged in ascending order

1.8 Finding the Square Root of an Integer


Aim
Design an algorithm, flowchart and pseudo code to find the square root of an integer, using any
suitable method (e.g., the Babylonian method). Example: Find the square root of 64.
Flowchart

Output:

Algorithm
Input: Enter a number
Procedure:
Step 1: Start
Step 2: Read value entered by user into variable n
Step 3: p = sqrt(n)
Step 4: Display p
Step 5: End
Output: Square root of the number

16
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

1.9 Factorial of a Number


Aim
Create an algorithm, flowchart and pseudo code to calculate the factorial of a given number.
Example: Calculate 5! = 5 * 4 * 3 * 2 * 1 = 120.
Flowchart

Output:

17
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Algorithm
Input: A number
Procedure:
Step 1: Start
Step 2: initialize variable count to 1
Step 3: initialize variable result to 1
Step 4: repeat until count > n
Step 4.1: result = result * count
Step 4.2: count = count + 1
Step 5: Display value of ‘result’
Step 6: End
Output: Factorial of the number

18
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

WEEK 2
Generate Fibonacci sequences, solve quadratic equations, and implement array and
matrix operations.
2.1 Fibonacci sequence Generation
Aim
Write an algorithm, flowchart and pseudo code that generates the first ‘n’ terms of the
Fibonacci sequence. Example: Generate the first 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
Flowchart

19
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Output:

Algorithm
Input: Number of terms in Fibonacci series
Procedure:
Step 1: Start
Step 2: initialize variable ‘a’ to 0
Step 3: Display ‘a’ value
Step 4: initialize variable ‘b’ to 1
Step 5: Display ‘b’ value
Step 6: Read number of terms in Fibonacci series into variable ‘n’
Step 7: Initialize variable count to 1
Step 8: repeat until count > n-2
Step 8.1: c = a + b
Step 8.2: Display ‘c’ value
Step 8.3: assign ‘b’ value to ‘a’
Step 8.4: assign ‘c’ value to ‘b’
Step 8.5: increment count by 1

20
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Step 9: End
Output: Fibonacci series with n terms

2.2 Exponentiation of a Number


Aim
Develop an algorithm, flowchart and pseudo code to compute the result of a number raised to
the power of another integer. Example: Calculate 4^3 and (1.5) ^3.
Flowchart

21
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Output:

Algorithm
Input: Base and exponent
Procedure:
Step 1: Start
Step 2: Read base value entered by user into variable ‘x’
Step 3: Read exponent value entered by user into variable ‘n’
Step 4: initiate variable ‘result’ to 1
Step 5: initiate variable ‘i’ to 1
Step 6: repeat until i > n
Step 6.1: result = result * x
Step 6.2: increment i by 1
Step 7: Display ‘result’
Step 8: End
Output: Value after exponentiation

2.3 Reversing the Elements of an Array


Aim
Design an algorithm, flowchart and pseudo code to reverse the elements in a given array.
Example: Reverse the array [1, 2, 3, 4, 5] to [5, 4, 3, 2, 1].
Flowchart

22
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Output:

23
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Algorithm
Input: Number of elements in array
Procedure:
Step 1: Start
Step 2: Read number of elements in array into variable n
Step 3: initiate variable i to 1
Step 4: repeat until i > n
Step 4.1: read value entered by user into list a[i]
Step 4.2: increment i by 1
Step 5: set variable i to 1
Step 6: repeat until i > n
Step 6.1: r[i] = a[n-i+1]
Step 6.2: Display r[i]
Step 6.3: increment i by 1
Step 7: End
Output: The elements in array is reversed

2.4 Finding the Largest Number in an Array


Aim
Write an algorithm, flowchart and pseudo code to find the largest number in a given array.
Example: Find the largest number in the array [150, 160, 170, 180].
Flowchart

24
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Output:

25
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Algorithm
Input: Number of elements
Procedure:
Step 1: initiate variable i to 1
Step 2: repeat until i > n
Step 2.1: Read value entered by user into list a[i]
Step 2.2: increment i by 1
Step 3: set variable i to 2
Step 4: largest = a[1]
Step 5: repeat until i > n
Step 5.1: If a[i] > largest:
Step 5.1.1: largest = a[i]
Step 5.2: increment i by 1
Step 6: Display ‘largest’
Output: Largest number in array is displayed

2.5 Multiplication of Two Matrices


Aim
Create an algorithm, flowchart and pseudo code to multiply two matrices.

26
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

27
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

28
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

29
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

2.6 Solving a Quadratic Equation


Aim
Design an algorithm, flowchart and pseudo code to find the roots of a quadratic

equation of the form ax^2 + bx + c = 0. Solve: x^2 + 2x +5=0, x^2 −5x+6=0,

x^2 −4x+4=0.
Flowchart

30
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Algorithm
Input: Coefficients of the equation and constant
Procedure:
Step 1: Start
Step 2: Read the coefficients of the equation, a, b and c from the user.
Step 3: Calculate discriminant = (b * b) – (4 * a * c)
Step 4: If discriminant > 0:
Step 4.1: Calculate root1 = ( -b + sqrt(discriminant)) / (2 * a)
Step 4.2: Calculate root2 = ( -b - sqrt(discriminant)) / (2 * a)

31
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Step 4.3: Display "Roots are real and different"


Step 4.4: Display root1 and root2
Step 5: Else if discriminant = 0:
Step 5.1: Calculate root1 = -b / (2 *a)
Step 5.2: root2 = root1
Step 5.3: Display "Root are real and equal"
Step 5.4: Display root1 and root2
Step 6. Else:
Step 6.1: Calculate real = -b / (2 * a)
Step 6.2:Calculate imaginary = sqrt(-discriminant) / (2 * a)
Step 6.3: Display “Roots are imaginary”
Step 6.4: Display real, "±" , imaginary, "i"
Step 7. End
Output: Roots of quadratic equation

32
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

WEEK 3
Demonstrate Python concepts by manipulating data types, handling input/output and
applying operators effectively.

3.1: Literal Constants and Variables


AIM:
Write a Python program that stores the following information about a student: their name
(string), age (integer), GPA (float), and enrollment status (boolean). Then, display this
information. Modify the program to update the students GPA and enrollment status, and display
the updated information.
Program:
#name=input("Enter the name ")
#age=int(input("Enter the age "))
print("name is Sameer")
print("age is 18")
name = "Sameer"
age = 18
print("name is ",name)
print("age is ",age)

Output:

3.2: Understanding Data Types


AIM:
Create a program that demonstrates different data types in Python, such as integers, floats, and
strings, by storing and displaying real-world items like the number of books you own (integer),
your daily expenses (float), and your favourite book (string).
Program:
fav_book= "\"Grandmother Tales\"" #We use '\' in this sentence so that
output will get "Grandmother Tales" i.e,"" in output
no_of_books = 79
daily_expenses = 258.37
print("My favourite book is ",fav_book)
print("I own ",no_of_books," books")
print("My daily expenses are ",daily_expenses)
Output:

33
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

3.3: Using Operators in Python


AIM:
Develop a program that uses arithmetic operators to perform basic operations (addition,
subtraction, multiplication, division) and relational operators to compare two user-inputted
numbers. Include logical operators to combine multiple conditions and display the results.
Program:
a=int(input("Enter first number "))
b=int(input("Enter second number "))
print("Arithmetic operators :")
print("a+b= ",a+b)
print("a-b= ",a-b)
print("a*b= ",a*b)
print("a/b= ",a/b)
print("Realtional operators :")
print("a==b is ",a==b)
print("a!=b is ",a!=b)
print("a>b is ",a>b)
print("a>=b is ",a>=b)
print("a<b is ",a<b)
print("a<=b is ",a<=b)
print("Logical operators :")
print("Combining multiple conditions ")
print("a==b and a>b is",a==b and a>b)
print("a!=b or a<=b is ",a!=b or a<=b)
print("a>b not a!=b is ",not a!=b)
Output:

34
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

3.4 Handling Input and Output in Python


AIM:
Design a program that prompts the user for their favourite movie, actor, and genre, then
responds with a personalized message including all this information.
Program:
fav_movie=input("What is your favourite movie? ")
genere=input('What is your favourite GENERE? ')
fav_actor=input('Who is your favourite Actor? ')
print('Your favourite movie is ',fav_movie,'\nYour favourite genere is
',genere,'\nYour favourite actor is ',fav_actor)
Output:

3.5 Reserved Words and Identifiers in Python


AIM:
Experiment with using reserved words as variable names and observe the syntax errors.
Rewrite the program with valid identifiers, explaining why reserved words are essential for
Python syntax.
Program:
#if=10
if1=10
print(if1)
Output:

3.6 Understanding Indentation in Python


AIM:
Develop a Python program with correct indentation, then intentionally introduce incorrect
indentation to observe the resulting errors and unexpected behaviour. Discuss why proper
indentation is crucial in Python.
Program:
marks = 10
if(marks>=50):
print("Pass")
else:

35
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

print("Fail")

Output:

36
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

WEEK 4
Construct programs to check leap years, manipulate strings, and analyze while loop
execution with error handling.
4.1: Leap Year Program:AIM:
Design algorithm, flowchart and a Python program to check if a given year is a leap year. A
year is a leap year if:
It is divisible by 4.
If divisible by 100, it must also be divisible by 400.
Program:
def is_leap_year(year):
if year % 4 != 0:
return False
elif year % 100 == 0:
return year % 400 == 0
else:
return True

year = 2024
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")

Output:

4.2 Printing Numbers Using While Loop:


AIM:
Task: Design algorithm, flowchart and a program that prints numbers from 1 to 10 using a
whileloop.
Extension: Allow the user to input the start and end numbers. Implement error handling for
invalid inputs (e.g., non-numeric input or when the start is greater than the end).

Program:
#Display numbers from 1 to 10 using while loop
i=1

37
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

while(i<=10):
print(i)
i+=1

#Display numbers from n1 to n2 using while loop


n1=input("Enter the first number:")
n2=input("Enter the second number:")
if(n1.isdigit() and n1.isdigit()):
n1=int(n1)
n2=int(n2)
while(n1<=n2):
print(n1)
n1+=1

else:
print("Invalid input entered")

Output:

4.3 String Manipulation:


AIM:
Task: Design algorithm, flowchart and a program that takes a user’s full name as input and
outputs their initials in uppercase.
Extension: Handle names with multiple parts, such as middle names or suffixes. Ensure correct
formatting regardless of the input format.

Program:
name=input("Enter your name:")

38
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

print(name.title())

Output:

4.4 Formatted String Output:


AIM:
Task: Design algorithm, flowchart and a program that takes a person’s name, age, and city as
input and outputs a structured introduction.
Extension: Allow additional inputs like occupation and hobbies, creating a more detailed and
personalized message.

Program:
name=input("Enter your name:")
age=input("Enter your age:")
city=input("Enter your city:")
hobby=input("Enter your hobby:")
occupation=input("Enter your occupation:")
print("Meet the person %s, he/she is %s old , lives in %s,having
hobbies %s,occupation is %s"%(name,age,city,hobby,occupation))

Output:

4.5 Number Classification (if-elif-else):


AIM:
Task: Design algorithm, flowchart and a program that categorizes a number as positive,
negative, or zero.
Extension: Modify the program to handle multiple inputs and give clear messages explaining
each classification.

39
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Program:
while(True):
n=int(input("Enter any number:\nEnter 555 to exit:"))
if(n==555):
break
else:
if(n>0):
print("The given number is positive")
elif(n<0):
print("The given number is negative")
else:
print("The given number is ",n)
continue

Output:

4.6 Multiplication Table Using Nested Loops:


AIM:
Task: Design algorithm, flowchart and a program that prints a multiplication table up to 10
using nested loops.
Extension: Allow the user to specify the table size and ensure proper formatting. Evaluate the
efficiency by reviewing execution speed and readability.
Program:
n=int(input("Enter the table number :"))
m=int(input("Enter the table upto which number :"))
for i in range(1,m+1):
print("%d x %d = %d"%(n,i,n*i))

40
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Output:

4.7 String Slicing:


AIM:
Task: Design algorithm, flowchart and a program that takes a sentence as input and prints the
first half and second half separately.
Extension: Implement different slicing techniques, such as slicing by word or by character,
and evaluate their effectiveness in different situations.
Program:
s="Python Programming"
l=len(s)
half=l//2
print("First half is ",s[:half])
print("Second half is ",s[half+1:])
s1=s.split(" ")
print("After splitting by word:",s1)
s2=list(s)
print("Splitting by character:",s2)

Output:

41
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

WEEK 5
Develop interactive games and programs, debug code, and classify numbers based on
specified criteria.
5.1 Number Guessing Game:
AIM:
Task: Develop a game where the user guesses a number between 1 and 100. Provide feedback
after each guess.
Extension: Add difficulty levels (easy, medium, hard) based on the range of numbers and the
number of allowed guesses. Include a scoring system and a leader board for an engaging
experience.
Program:
import random
level=int(input("Enter the level: \n1.Easy \n2.Medium \n3.Difficult"))
if(level==1):
n=7
elif(level==2):
n=6
elif(level==3):
n=5
key=random.randint(1,100)
for i in range(1,n+1):
num=int(input("Enter any number"))
if(num==key):
print("Entered number is correct")
break
elif(num>key):
print("key is lesser")
elif(num<key):
print("key is greater")
else:
print("Failed, no more attempts avalable.\nKey is ",key)

Output:

42
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

5.2 Text Processing Program:


AIM:
Task: Create a program that processes a paragraph of text, counting the number of words,
finding the longest word, and converting the text to title case.
Extension: Add more features, such as finding the most frequent word, replacing specific words
with synonyms, and highlighting keywords.
Program:
#Text processing program
text= "hello world python hellow123 hello this is programming ba abcce
lab programs"
words=text.split(" ")
print(len(words))
long=0
frequent=0
for i in range(0,len(words)):
if(len(words[i])>long):
long=len(words[i])
long_index=i
c=words.count(words[i])
if(c>frequent):
frequent=c
frequent_index=i
print("Longest word is ",words[long_index])
print("Text in title case : ",text.title())
print("Most frequent word is: ",words[frequent_index])

Output:

5.3 Debugging a Program to Calculate Average:


AIM:
Task: Debug a program that calculates the average of a list of numbers. Fix issues with the sum
calculation and handle the case when the list is empty.
Extension: Ensure the program gracefully handles lists of varying sizes and provides
meaningful error messages.
Program:
n=int(input("Enter the number of values:"))
sum=0
for i in range(0,n):
x=input("Enter any value:")
if(x==""):
print("Enter a valid number")
break

43
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

else:
sum+=int(x)
else:
print(sum//n)

Output:

5.4 Factorial Calculation Program:


AIM:
Task: Debug and fix a Python program that calculates the factorial of a number. Ensure the
base case for 0 is handled properly.
Program:
n=int(input("Enter a number"))
if n < 0:
print("Factorial is not defined for negative numbers.")
elif n == 0:
print(1)
else:
result = 1
for i in range(1, n + 1):
result *= i
print(result)

Output:

5.5 Printing Even Numbers:


AIM:
Task: Fix the program that prints all even numbers from 1 to a given number n. Correct the
logical and printing issues.
Extension: Allow the user to specify the range of numbers and handle invalid inputs.

Program:

44
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

start=input("Enter starting value")


end=input("Enter ending value")
if(start.isdigit() and end.isdigit()):
start=int(start)
end=int(end)
for i in range(start,end+1):
if(i%2==0):
print(i)
else:
print("Enter valid number")

Output:

5.6 Bubble Sort Algorithm:


AIM:
Task: Design and implement a bubble sort algorithm that sorts a list of item quantities entered
by the user.
Extension: Evaluate the program’s efficiency and suggest improvements in execution speed.

Program:
#Bubble sort program
values=[30,15,40,50,20,10]
for i in range(0,len(values)):
for j in range(0,len(values)-i-1):
if values[j]>values[j+1]:
temp=values[j]
values[j]=values[j+1]
values[j+1]=temp
print(values)

Output:

45
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

WEEK 6
Compute LCM, analyze maze paths with recursion, and evaluate the results of summing
digits until a single digit is achieved.

6.1 LCM Calculation:


AIM:
Task: Design a flowchart and write a Python program to calculate the Least Common Multiple
(LCM) of two integers.
Input: Two integers.
Output: The LCM of the two integers.
Example:
Input: 8, 15
Output: 120
Input: 9, 14
Output: 126

Program:
n1=int(input("Enter first number"))
n2=int(input("Enter second number"))
if(n1>n2):
high=n1
else:
high=n2
while(True):
if(high%n1==0 and high%n2==0 ):
break
else:
high+=1
print("L.C.M is ",high)

Output:

46
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

6.2 Sum of Digits Repeatedly Until Single Digit:


AIM:
Task: Design a flowchart Write a Python program that sums the digits of a number repeatedly
until a single-digit result is obtained.
Example:
Input: 8756
Process: 8 + 7 + 5 + 6 = 26, 2 + 6 = 8
Output: 8

Program:
n = int(input("enter any number"))
s=0
while(True):
r = n%10
s = s+r
n = n//10
if(n==0):
if(s>9):
n=s
s=0
else:
break
print(s)

Output:

6.3 HCF (Highest Common Factor) Calculation:


AIM:
Task: Design a flowchart and write a Python program to compute the HCF of two integers.
Input: Two integers.
Output: The HCF of the two integers.
Example:
Input: 15, 20
Output: 5
Input: 17, 21
Output: 1

47
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Program:
#HCF
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
if(n1<n2):
least=n1
else:
least=n2
for i in range(1,least+1):
if(n1%i==0 and n2%i==0):
hcf=i
print("HCF is ",hcf)

Output:

6.4 Palindrome Checker for Preprimary School:


AIM:
Task: Design a flowchart Write a program that checks if a string is a palindrome and rewards
the student with a point for each correct palindrome. Deduct a point for incorrect entries.
Extension: Handle multiple strings and maintain a score throughout the session.

Program:
score=0
while(True):
s=input("Enter any word, enter 'end' to exit")
if(s=="end"):
break
else:
if(s==s[::-1]):
score+=1
else:
score-=1
print("Your score is ",score)

48
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Output:

6.5 Selection Sort Algorithm:


AIM:
Task: Design a flowchart and implement a selection sort algorithm to sort a list of values
provided by the user.
Extension: Evaluate the program’s performance for different input sizes and suggest
improvements.

Program:
#Selection sort algorithm
values=[30,15,25,69,90,19]
for i in range(len(values)):
for j in range(i+1,len(values)):
if(values[i]>values[j]):
temp=values[i]
values[i]=values[j]
values[j]=temp
print(values)

Output:

49
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

WEEK 7
Organize and retrieve data using Python data structures like lists, sets, and dictionaries
to demonstrate data processing techniques.

7.1 Storing and Retrieving Data


AIM:
Develop a program to demonstrate how to store and retrieve data using Python data
structures:
tuples, lists, sets, and dictionaries. Implement examples for:
● Adding and removing elements in lists.
● Accessing elements in a tuple.
● Performing set operations like union, intersection, and difference.
● Using a dictionary to store key-value pairs. Compare the advantages and limitations
of each data structure.

Program:
list1=[10,15,30,'hello',5.6]
list1.append(66)
print("List after adding element is :",list1)
list1.remove(30)
print("List after removing element is :",list1)
t1=(10,15,30,'hello',5.6)
print("Accessing second element in tuple:",t1[1])
set1={10,15,30,'hello',5.6}
set2={17,20,5.6,15}
print("union:",set1.union(set2))
print("intersection:",set1.intersection(set2))
print("difference:",set1.difference(set2))
di={"college":"VRSEC","dept":"cse","year":1}
print(di)

Output:

50
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

7.2 Nested Data Structures


AIM:
Create a program that models a library system using nested lists and dictionaries. Include
functionality to:
● Add new genres and books.
● List books by genre.
● Update book details. Ensure the program can handle multiple layers of data and
updates dynamically.

Program:
books={

"book1":{"title":"titleabc","genere":"comedy","author":"authorabc"},
"book2":{"title":"titledef","genere":"drama","author":"authordef"},

"book3":{"title":"titlexyz","genere":"comedy","author":"authorxyz"},
"book4":{"title":"title123","genere":"drama","author":"author123"}
}

print("List of books by comedy genere")


for book in books:
if(books[book]['genere']=='comedy'):
print(books[book])
print("List of books by drama genere")
for book in books:
if(books[book]['genere']=='drama'):
print(books[book])
books["book4"]["author"]="author456"
print("Updated book details :",books["book4"])

Output:

7.3 Set Operations


AIM:
Develop a program that uses set operations to demonstrate:
● Union (combining two sets of data).
● Intersection (finding common elements between sets).

51
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

● Difference (elements unique to one set). Include functionality for dynamically adding
and removing items from the sets.

Program:
set1={10,15,30,'hello',5.6}
set2={17,20,5.6,15}
print("union:",set1.union(set2))
print("intersection:",set1.intersection(set2))
print("difference:",set1.difference(set2))

Output:

7.4 List Comprehensions


AIM:
Write a program using list comprehensions to generate lists based on certain conditions, such
as:
● Generating a list of squares of even numbers between 1 and 20.
● Filtering a list of strings based on whether they start with a specific letter.

Program:
#List comprehension
even_squares = [i**2 for i in range(2,21,2)]
print(even_squares)
#filtering strings
strings=["cse","program","computer","python"]
for s in strings:
if(s[0]=="p"):
print(s)
for s in strings:
if(s[0]=="c"):
print(s)

Output:

52
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

7.5 Tuples vs. Lists


AIM:
Create a program to compare the use of tuples (immutable) and lists (mutable). Use tuples to
store immutable data like coordinates and lists for mutable data like a shopping list. Discuss
scenarios where one is more appropriate than the other.

Program:
#Tuple v.s Lists
coordinates=(20.4567,52.9754)
shopping=["Pen","book","plank","file"]
'''coordinates[1]=69.6969
Tuple is immutable so it cant be modified'''
shopping[2]="Color papers"
print(shopping)

Output:

7.6 Dictionaries for Key-Value Storage


AIM:
Develop a program that demonstrates dictionary usage to store, update, and remove key-value
pairs. Apply this concept to a practical use case, such as managing a contact list or user profiles.

Program:
#Dictionaries for Key-Value Storage
contacts={"DJ
Tillu":9609333222,"Subrahmanyam":9848032919,"Sivamani":9848022338}
while(True):
print("Enter your choice")
choice=input("1.Store\n2.Update\n3.Remove\n4.Exit")
if(choice=='1'):
name=input("Enter the name:")

53
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

mn=int(input("Enter mobile number :"))


contacts[name]=mn
print("Updated contact list:",contacts)
elif(choice=='2'):
name=input("Enter the name:")
mn=int(input("Enter mobile number :"))
contacts[name]=mn
print("Updated contact list:",contacts)
elif(choice=="3"):
name=input("Enter name")
contacts.pop(name)
print("After removing:",contacts)
elif(choice=="4"):
break
else:
print("Invalid Input. Enter valid input")

Output:

54
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

WEEK 8
Formulate functions, apply lambda expressions, and construct custom modules to
perform tasks efficiently.
8.1 Functions
Aim
Create a program that defines several functions to perform tasks like:
 Calculating the area of a rectangle.
 Finding the maximum of a list of numbers.
 Printing personalized greetings.
Demonstrate variable scope by modifying variables inside and outside functions.

Program
def area_rectangle(l,b):
print("area of rectangle is",l*b)

def max_list(values):
max = 0
for n in values:
if(n>max):
max=n
print("maximum value is",max)

def greetings(name):
print("hello %s ! greetings"%name)

area_rectangle(12,5)
values = [15,18,30,11,99,55]
max_list(values)
greetings("siddhartha")

Output

8.2 Lambda Functions


Aim
Develop a program using lambda functions to:
Sort a list of tuples based on specific criteria.
Filter a list of numbers to retain only those greater than a certain value.

Program
#sorting list of tuples
data = [(1, 'b'), (2, 'a'), (3, 'c')]
data.sort(key=lambda item: item[1])
print(data)

#filter list of numbers


numbers = [i for i in range(1,21)]

55
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

values = list(filter(lambda x: x > 10, numbers))


print(values)

Output

8.3 Modules and Packages


Aim
Create a program that utilizes Python’s built-in modules (math, random, etc.) to perform
various calculations and tasks. Develop a custom module with string manipulation functions,
and import it into your main program.

Program for built in modules


import math,random
print(math.sqrt(25))
print(random.randint(1,100))

Output

Program for creating user-defined module (strman.py)


def strcat(s1,s2):
s1 = s1+" "+s2
print("after manipulation",s1)

Program for importing user-defined module


import strman
strman.strcat("hello","world")
Output

8.4 Variable Lifetime and Scope


Aim
Write a program that demonstrates variable lifetime by defining local and global variables
within and outside of functions. Show how global variables retain their values across function
calls.

Program
x = 10 # Global variable
def my_function():
y = 5 # Local variable
print(y) #prints 5

56
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

print(x) #prints 10
# print(y) # Error: y is not accessible outside the function

Output

8.5 Functions Returning Values


Aim
Develop a set of functions that return various values, such as:
The factorial of a number.
A list of Fibonacci numbers.

Program
def fact(n):
f=1
for i in range(2,n+1):
f = f*i
return f

def fib(n):
a = 0
b = 1
fibs = [a,b]
for i in range(1,n-1):
c = a+b
a = b
b =c
fibs.append(c)
return fibs

print("factorial is",fact(5))
print("fibonacci series is",fib(10))

Output

8.6 Class Methods and Instance Methods


Create a class with both class methods and instance methods. Implement class-level operations
(e.g., counting instances) and instance-specific methods (e.g., updating attributes of individual
objects).

Program
class employees:

57
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

count=0
dept = "marketing"
def __init__(self):
employees.count+=1

ob1=employees()
ob2=employees()
ob3=employees()
print("number of instances are",employees.count)
ob2.dept= "finance" #updating attributes of individual objects
print(ob1.dept)
print(ob2.dept)
print(ob3.dept)

Output

58
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

WEEK 9
Create custom data structures, model real-world objects using classes, and demonstrate
inheritance and method overriding.
9.1 Constructors and Attributes
Aim
Develop a class with a constructor that initializes attributes based on user input. Include
methods to update and display these attributes. Use this class to model real-world objects, such
as vehicles or products.

Program
class vehicle:
def __init__(self,color,year):
print("displaying from constructor:",color,year)

color = input("enter color: ")


year = input("enter year: ")
ob1 = vehicle(color,year)

Output

9.2 Inheritance and Method Overriding


Aim
Create a program demonstrating class inheritance, where a base class Vehicle has subclasses
like Car and Airplane. Implement methods specific to each subclass, such as drive() for Car
and fly() for Airplane.

Program
class vehicle:
color = "white"

class car(vehicle):
wheels = 4
def drive(self):
print("from car class")
print("car color:",self.color)
print("wheels:",self.wheels)

class airplane(vehicle):

59
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

wings = 2
def fly(self):
print("from airplane class")
print("air plane color:",self.color)
print("air plane wings:",self.wings)

c1 = car()
c1.drive()
c2 = airplane()
c2.fly()

Output

9.3 Custom Data Structures


Aim
Implement a personal library system using object-oriented principles. Define classes for books,
authors, and genres. Create methods to:
 Add new books.
 Search for books by author or genre.
 Display a list of books in the library.

Program
class books:
titles = ["Programming in C", "Java complete Reference",
"Wednesday Soul"]
authors = ["Balagurusamy", "Herbert Schildt", "Sorabh Pant"]
genres = ["education", "education", "comedy"]

b1 = books()
while(True):
print("enter your choice")
choice = input("1.Add new Book, 2.Search by Genre, 3.Display,
4.End")
if(choice=='1'):
title = input("enter title")
author = input("enter author")

60
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

genre = input("enter genre")


b1.titles.append(title)
b1.authors.append(author)
b1.genres.append(genre)
elif(choice=='2'):
genre = input("enter genre")
for i in range(len(b1.genres)):
if(b1.genres[i]==genre):
print(b1.titles[i], b1.authors[i], b1.genres[i])
elif(choice == '3'):
for i in range(len(b1.titles)):
print(b1.titles[i], b1.authors[i], b1.genres[i])
elif(choice == '4'):
break
else:
print("please enter valid choice")

Output

9.4 Object Aggregation


Aim
Write a program that models a computer system using aggregation. Define a Computer class
containing a CPU object. Show how the Computer performs tasks based on the CPU’s
specifications.

Program
class computer:

61
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

RAM = "16GB"
def __init__(self,model):
print("processor",model)

cpu = computer("i5")

Output

9.5 Composition in Game Development


Aim
Design a character system for a game using composition. Define a Character class that includes
components like Skill, Weapon, and Armor. Simulate battles between characters based on their
composition and evaluate how different setups affect outcomes.

Program
class character:
skill = "Taekwondo"
weapon = "Axe"
armor = "Ceramic Plate"

def __init__(self):
print('character class object created')

def battle1(self):
print('character class method executed')
print("character details are",self.skill, self.weapon,
self.armor)

class Composite:
def __init__(self):
self.obj1 = character()
def battle(self):
print('Composite class battle2 method executed')
self.obj1.battle1()

obj2 = Composite()
obj2.battle()

62
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Output

63
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

WEEK 10
Implement recursive functions, apply search algorithms, and optimize sorting techniques
to handle large datasets efficiently

10.1 Recursive Functions


Aim
Develop a function for a math app that calculates the factorial of a number. Additionally,
implement a recursive function to generate the nth Fibonacci number.

Program
#factorial calculation
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(5))

#fibonacci series generation


def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
for i in range(5):
print(fibonacci(i))

Output

10.2 Search Algorithms


Aim

64
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

Implement a binary search algorithm to find a specific product in a sorted list of prices for a
shopping app. Discuss the efficiency of this approach for large datasets.

Program
prices = [220, 320, 1100, 340, 650, 30, 500, 630]
prices.sort()
print(prices)
key = 630
left = 0
right = len(prices)-1
while(left<=right):
mid = (left+right)//2
if(key==prices[mid]):
print("key found at index",mid)
break
elif(key>prices[mid]):
left=mid+1
else:
right = mid-1
else:
print("key not found")

Output

10.3 Sorting Algorithms


Aim
Write a Quick Sort algorithm to efficiently sort event start times for a scheduling application.
Evaluate the performance for different input sizes and types.

Program
def partition(array, low, high):
pivot = array[high]
i = low -1
for j in range(low, high):
if array[j] <= pivot:
i = i + 1
(array[i], array[j]) = (array[j], array[i])
(array[i + 1], array[high]) = (array[high], array[i + 1])
return i + 1

65
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

def quickSort(array, low, high):


if low < high:
pi = partition(array, low, high)
quickSort(array, low, pi - 1)
quickSort(array, pi + 1, high)

Start_Times = [9, 7, 6, 10, 5, 12, 11, 8]


print("Unsorted Start Times")
print(Start_Times)
size = len(Start_Times)
quickSort(Start_Times, 0, size - 1)
print('Sorted Start Times in Ascending Order:')
print(Start_Times)

Output

10.4 Handling Large Data


Aim
Develop a merge sort algorithm to sort user files by size in a cloud storage application. Discuss
the benefits of merge sort over other sorting techniques for large datasets.

Program
def mergeSort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
leftHalf = arr[:mid]
rightHalf = arr[mid:]
sortedLeft = mergeSort(leftHalf)
sortedRight = mergeSort(rightHalf)
return merge(sortedLeft, sortedRight)

def merge(left, right):


result = []
i = j = 0
while(i < len(left) and j < len(right)):
if left[i] < right[j]:

66
I Year I Semester 2024-25
Problem Solving with Python Lab Computer Science and Engineering Roll No: 24EU04

result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result

unsortedArr = [95, 78, 64, 105, 86, 123, 115, 52]


sortedArr = mergeSort(unsortedArr)
print("Sorted file sizes:", sortedArr)

Program

10.5 Case-Insensitive Search


Aim
Implement a case-insensitive search algorithm to find a keyword in a large body of text for a
document search feature.

Program
text = "This is a sample Text considered in the python program to
Perform case insensitive search"
text = text.lower()
keyword = "PERFORM"
keyword = keyword.lower()
textlist = text.split(" ")
for i in range(len(textlist)):
if(textlist[i]==keyword):
print("keyword is at index",i)
break
else:
print("keyword not found")

Output

67
I Year I Semester 2024-25

You might also like