Python Programming (20CS31P)
2a. Develop a python program to take two values from user to find the summation.
Algorithm:
Step 1: Start
Step 2: Prompt the user to enter the first number and store it in the variable a.
Step 3: Prompt the user to enter the second number and store it in the variable b.
Step 4: Add both a and b and assign the result to variable sum
Step 5: Print the sum
Step 6: End
Program:
a=int(input(“Enter the First number”))
b=int(input(“Enter the Second number”))
sum=a+b
print(“The sum of two numbers is “,sum)
Output:
2b. Develop a program to take two values from user to perform arithmetic operations
and display the results.
Algorithm:
Step 1: Prompt the user to enter the first number and store it in the variable a.
Step 2: Prompt the user to enter the second number and store it in the variable b.
Step 3: Calculate sum, difference , product and quotient of a and b
Step 4: Display sum, difference, product and quotient of both a and b
Step 5: End of algorithm.
Dept. of CSE
Python Programming (20CS31P)
Program:
a=int(input("enter first number "))
b=int(input("enter second number "))
sum=a+b
sub=a-b
mul=a*b
div=a/b
print(f"sum of {a} and {b} = {sum}")
print(f"difference of {a} and {b} = {sub}")
print(f"product of {a} and {b} = {mul}")
print(f"quotient of {a} and {b} = {div}")
Output:
2c. Develop a Python program to evaluate expressions to examine Operator precedence.
Algorithm:
Step 1: Prompt the user to enter the first number and store it in the variable a.
Step 2: Prompt the user to enter the second number and store it in the variable b.
Step 3: Prompt the user to enter the third number and store it in the variable c.
Step 4: Prompt the user to enter the fourth number and store it in the variable d.
Step 5: Calculate and print the result of expressions and display it with a label:
Step 6: End
Program:
a = int(input("enter a number "))
b = int(input("enter a number "))
Dept. of CSE
Python Programming (20CS31P)
c = int(input("enter a number "))
d = int(input("enter a number "))
e = a+b*c/d
print("Value of a+b*c/d is", e)
e = (a+b)*c/d
print("Value of (a+b)*c/d is", e)
e = a*(b-c)+d
print("Value of a*(b-c)+d is", e)
Output:
Dept. of CSE
Python Programming (20CS31P)
Dept. of CSE
Python Programming (20CS31P)
3a. Develop a Python program to display the passing class by taking percentage from
student
Algorithm:
Step 1: Prompt the user to enter the percentage and assign to num variable.
Step 2: Check the value of num using conditional statements:
Step 3: If num is greater than or equal to 70, print as first class with Distinction
Step 4: If num is greater than or equal to 60 and less than 70, print as first class
Step 5: If num is greater than or equal to 40 and less than 60, print as Second class
Step 6: If num is less than 40, print as failed.
Step 7: End the algorithm
Program:
num=int(input("Enter your percentage"))
if num>=70:
print("Congratulations!! you obtained FCD")
elif num>=60 and num<70:
print("You obtained First class")
elif num>=40 and num<60:
print("You passed in Second class")
else:
print("Sorry!! You failed")
Output:
Dept. of CSE
Python Programming (20CS31P)
Dept. of CSE
Python Programming (20CS31P)
4a. Develop a Python program to print multiplication table of a given number using for
loop and range function.
Algorithm:
Step 1: Prompt the user for a number and store in variable n
Step 2: Repeat following steps from i=1 to 10
Step 3: Calculate: c = n * i
Step 4: Display the result in the format: n x i = c.
Step 5: End
Program:
n=int(input("Enter the number ")
for i in range(1,11):
c=n*i
print(n,"x",i,"=",c)
Output:
Dept. of CSE
Python Programming (20CS31P)
4b. Develop a Python program to print Fibonacci series using while loop and
conditional statement.
Algorithm:
Step 1: Input the value of n (number of terms to generate).
Step 2: Declare two variables a & b with first two fixed values i.e a=0, b=1
Step 3: Declare and initialize sum, to store current fibonacci number and count to track the number of
terms
Step 4: Print the message "Fibonacci Series:".
Step 5: Repeat following steps until count is less than or equal to n
Step 6: Print variable sum, which contains fibonacci series current value
Step 7: Increment count by 1
Step 8: Update the variables accordingly
Step 9: End
Program:
n = int(input("Enter the value of 'n': "))
a=0
b=1
sum = 0
count = 1
print("Fibonacci Series: ", end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a=b
b = sum
sum = a + b
Output:
Dept. of CSE
Python Programming (20CS31P)
Dept. of CSE
Python Programming (20CS31P)
5a. For a given Set, compose a Python code to perform different operations based on
user choice
1. Add an Item to set 2. Delete an Item from set
3. Display the contents of set 4. Search an Item in the set 5. Exit
Algorithm:
Step 1: Start
Step 2: Declare and initialize an empty set s1.
Step 3: Repeat following steps until user enters choice as 5
Step 4: Display the menu as below:
Step 5: 1. Add 2. Delete 3. Display 4. Search 5. Exit
Step 6: Read the user choice and store in a variable like choice
Step 7: check the user entered choice using conditional statement
Step 8: if the choice is 1, ask for an item and add to set
Step 9: if the choice is 2, delete an item from the set
Step 10: if the choice is 3, display the set items
Step 11: if the choice is 4, ask user to enter item to search and using conditional statement, search for
the item
Step 12: if the choice is 5, Exit the loop
Step 13: End
Program:
s1=set()
while(True):
print("[Link] 2. DELETE 3. DISPLAY 4. SEARCH [Link]")
choice = int(input("Enter your choice: "))
if(choice==1):
data = int(input("Enter the value: "))
[Link](data)
print(s1)
elif(choice==2):
[Link]()
print(s1)
elif(choice==3):
print(s1)
elif(choice==4):
key = int(input("Enter the item to search: "))
Dept. of CSE
Python Programming (20CS31P)
if key in s1:
print("Item is present")
else:
print("Item is not present")
else:
break;
Output:
5b. Write a python program to print a sequence (Even number & City names) using
comprehension.
Algorithm:
Step 1: Start
Step 2: Initialize a set with city names
Step 3: Generate a set of even numbers using set comprehension
Step 4: Generate a set of city names from earlier set using condition city name should contain letter 'b'
using set comprehension
Step 5: Print the set of even numbers
Step 6: Print the set of city names
Step 7: Stop
Dept. of CSE
Python Programming (20CS31P)
Program:
set1={"bagalkot","ilkal","bijapur","dharwad","hubli"}
set2={var for var in range(2,20,2)}
set3={var for var in set1 if 'b' in var}
print("Even number set comprehension : ",set2)
print("City names containing B letter : ",set3)
Output:
5c. For a given Tuple, compose a python code to perform different operations based on
user choice
1. Length of a tuple 2. Maximum item of a tuple 3. Minimum item of a tuple
4. Display the contents of tuple 5. Search an item in the tuple 6. Exit
Algorithm:
Step 1: Start
Step 2: Declare and initialize an tuple
Step 3: Repeat following steps until user enters choice 6
Step 4: Display the following menu:
1. LENGTH 2. MAXIMUM 3. MINIMUM 4. DISPLAY 5. SEARCH 6. EXIT
Step 5: Read the user choice and store in a variable like choice
Step 6: check the user entered choice using conditional statement
Step 7: if the choice is 1, display the length of tuple
Step 8: if the choice is 2, display the maximum from tuple
Step 9: if the choice is 3, display the minimum from tuple
Step 10: if the choice is 4, display the tuple
Step 11: if choice is 5, prompt user to enter an value to search and using conditional statement, search
for the item
Step 12: if choice is 6, exit the loop
Step 13: End
Dept. of CSE
Python Programming (20CS31P)
Program:
x = (10,20,30,40,50,60,70,80)
print(x)
while(True):
print("[Link] 2. MAXIMUM 3. MINIMUM 4. DISPLAY [Link] [Link]")
choice = int(input("Enter your choice: "))
if(choice==1):
print("The length of tuple=",format(len(x)))
elif(choice==2):
print("The maximum item=",format(max(x)))
elif(choice==3):
print("The minimum item=",format(min(x)))
elif(choice==4):
print(x)
elif(choice==5):
key = int(input(("Enter the item to search: ")))
if key in x:
print("Item is Present")
else:
print("Item is Not Present")
else:
break;
Output:
Dept. of CSE
Python Programming (20CS31P)
5d. Prepare a python program to demonstrate the indexing, slicing and nested indexing
operation on tuple.
Algorithm:
Step 1: Start
Step 2: Declare and Initialize an tuple
Step 3: Display message like Indexing operations on tuple
Step 4: Using index, access and display an item from tuple
Step 5: Display message like slicing operations on tuple
Step 6: Using index, extract multiple items at a time from tuple and display
Step 7: Declare and initialize another tuple for nested operations
Step 8: Display message like nested indexing operations on tuple
Step 9: Using index, access and display items from nested tuple
Step 10: End
Program:
t1 = (10,"Bagalkot",20,"Bijapur",30,40,50)
print("The tuple : ",t1)
print()
print("Following are example for indexing: ")
print("2nd item from tuple: ",t1[1])
print("5th item from tuple: ",t1[4])
print()
print("Following are slicing examples ")
print("Item from 3rd place to last: ",t1[2:])
print("Item from 1st place to 4th: ",t1[:4])
print("All items at even idex: ",t1[::2])
print()
print("Following are nested idexing examples: ")
t2 = (10,20,30,40,(70,80),(5,6,7))
print(t2[1])
print(t2[4])
print(t2[4][1])
print(t2[5][2])
Dept. of CSE
Python Programming (20CS31P)
Output:
Dept. of CSE
Python Programming (20CS31P)
6a. For a given list, compose a Python code to perform different operations based on
following user choice.
1. Add an item to list 2. Delete an item from the list 3. Display the contents of the list
4. Sort the items of list 5. Reverse the item of list 6. Search an item in the list
7. Exit
Algorithm:
Step 1: Start
Step 2: Declare and initialize an tuple
Step 3: Repeat following steps until user enters choice 6
Step 4: Display the following menu:
Step 5: 1. ADD 2. DELETE 3. DISPLAY 4. SORT 5. REVERSE 6. SEARCH 7. EXIT
Step 6: Read the user choice and store in a variable like choice
Step 7: check the user entered choice using conditional statement
Step 8: if the choice is 1, prompt user to enter an item to add to list
Step 9: if the choice is 2, prompt user to enter an item to delete from the list
Step 10: if the choice is 3, display the list
Step 11: if the choice is 4, sort and display the list items in ascending order
Step 12: if the choice is 5, sort and display the list items in descending order
Step 13: if the choice is 6, prompt user to enter an value to search and using conditional statement,
search for the item
Step 14: if choice is 7, exit the loop
Step 15: Stop
Program:
x=list([15,61,22,28])
while(True):
print("[Link] 2. DELETE 3. DISPLAY 4. SORT 5. REVERSE 6. SEARCH [Link]")
choice = int(input(("Enter your choice: ")))
if(choice==1):
data = int(input("Enter the value: "))
[Link](data)
print(x)
elif(choice==2):
[Link]()
print(x)
elif(choice==3):
print(x)
Dept. of CSE
Python Programming (20CS31P)
elif(choice==4):
[Link]()
print(x)
elif(choice==5):
[Link]()
print(x)
elif(choice==6):
key = int(input("Enter the item to search: "))
if key in x:
print("Item is present")
else:
print("Item is not present")
else:
break;
Output:
O
Dept. of CSE
Python Programming (20CS31P)
6b. For a given list, compose a Python code to demonstrate indexing, slicing and nested
indexing concepts.
Algorithm:
Step 1: Start
Step 2: Declare and Initialize an list
Step 3: Display message like Indexing operations on list
Step 4: Using index, access and display an item from list
Step 5: Display message like slicing operations on list
Step 6: Using index, extract multiple items at a time from list and display
Step 7: Declare and initialize another list for nested operations
Step 8: Display message like nested indexing operations on list
Step 9: Using index, access and display items from nested list
Step 10: End
Program:
a = [10,"Bagalkot",20,"Bijapur",30,40,50]
print("The list : ",a)
print()
print("Following are example for indexing: ")
print("2nd item from list: ",a[1])
print("5th item from list: ",a[4])
print()
print("Following are slicing examples ")
print("Item from 3rd place to last: ",a[2:])
print("Item from 1st place to 4th: ",a[:4])
print("All items at even idex: ",a[::2])
print()
print("Following are nested idexing examples: ")
b = [10,20,30,40,[70,80],[5,6,7]]
print(b[1])
print(b[4])
print(b[4][1])
print(b[5][2])
Dept. of CSE
Python Programming (20CS31P)
Output:
Dept. of CSE
Python Programming (20CS31P)
7a. For a given dictionary, compose a Python code to perform different operations based on user
choice.
1. Add an item to dictionary 2. Delete an item from dictionary 3. Display all the Keys
4. Display all the Values 5. Display both key-value pair
6. Sort the dictionary based on values 7. Exit
Program:
d = {1:'Monday',2:'Tuesday',3:'Wednesday',4:'Thursday'}
while(True):
print("[Link] 2. Delete 3. Display Keys 4. Display Values [Link] Both [Link] Values 7. Exit")
choice = int(input(("enter your choice: ")))
if(choice==1):
key = int(input("enter the key: "))
value = input("enter the value: ")
d[key] = value
print(d)
elif(choice==2):
print([Link]())
print(d)
elif(choice==3):
print([Link]())
for x in [Link]():
print(x)
elif(choice==4):
print([Link]())
for x in [Link]():
print(x)
elif(choice==5):
print([Link]())
for x in [Link]():
print(x)
elif(choice==6):
print(sorted([Link]()))
else:
break;
Dept. of CSE
Python Programming (20CS31P)
Output:
7b. Code, execute and debug python program to perform Dictionary indexing, Iterating through the
values and dictionary comprehension
Program:
student = {"name": "Anand", "age": 21, "course": "Python"}
print("\nAccessing values using keys (Indexing)")
print("Student Name:", student["name"])
print("Student Age:", student["age"])
print("Student Course:", student["course"])
print("\n--- Iterating through Dictionary ---")
for key, value in [Link]():
print(key, ":", value)
print("\n--- Dictionary Comprehension ---")
# Example: square numbers from 1 to 5
squares = {x: x**2 for x in range(1, 6)}
print("Squares Dictionary:", squares)
Dept. of CSE
Python Programming (20CS31P)
Output:
Dept. of CSE
Python Programming (20CS31P)
8a. Code, execute and debug python program to perform string manipulation
Program:
# Input string
text = " Python Programming is Fun! "
# 1. Remove extra spaces
clean_text = [Link]()
print("After Removing space:", clean_text)
# 2. Convert to uppercase and lowercase
print("Uppercase:", clean_text.upper())
print("Lowercase:", clean_text.lower())
# 3. Find length of string
print("Length of string:", len(clean_text))
# 4. Indexing and slicing
print("First character:", clean_text[0])
print("Last 5 characters:", clean_text[-5:])
# 5. Replace a word
new_text = clean_text.replace("Fun", "Powerful")
print("After replace():", new_text)
# 6. Splitting and joining
words = clean_text.split() # split into list
print("Words List:", words)
joined = "-".join(words) # join with '-'
print("Joined String:", joined)
# 7. Check substring
print("Does string contain 'Python'?", "Python" in clean_text)
Dept. of CSE
Python Programming (20CS31P)
Output:
8b. For a given array, compose a Python code to perform different operations based on user choice.
1. Add an item to array 2. Delete an item from array 3. Display
4. Reverse the items of list 5. Exit
Program:
import array as arr
a1 = [Link]('i', [10, 23, 35,67,99,43])
while(True):
print("[Link] 2. DELETE 3. DISPLAY 4. REVERSE [Link]")
choice = int(input(("enter your choice: ")))
if(choice==1):
data = int(input("enter the value: "))
[Link](data)
print(a1)
elif(choice==2):
[Link]()
print(a1)
elif(choice==3):
print(a1)
for x in a1:
print(x)
elif(choice==4):
[Link]()
print(a1)
else:
break;
Dept. of CSE
Python Programming (20CS31P)
Output:
Dept. of CSE
Python Programming (20CS31P)
9. Develop a python code using functions
a) To convert given decimal number to binary, hexadecimal and octal
b) To find area of a circle
c) To find factorial of a number using recursion
d) To find cube of a number using lambda function.
Program:
#inbuilt functions
a=int(input("Enter an number"))
x=hex(a)
y=oct(a)
z=bin(a)
print("\nDecimal to Hexadecimal, Octal, Binary is respectively:",x,y,z)
#User defined function
def area_of_circle(r):
return(2*3.142*r)
print("\narea of a circle is",area_of_circle(a))
#Recursion function
def fact(n):
return n*fact(n-1) if n>1 else 1
print("\nThe factorail of a given number is:",fact(a))
#cube of a number using lambda
myfunc=lambda n:n*n*n
print("\nThe cube of a number is:",myfunc(a))
Output:
Dept. of CSE
Python Programming (20CS31P)
10a. Create user defined module by using python programming and demonstrate usage by importing
into another python file.
Program:
#Create a module with file name [Link]
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
#Create another file with name calling_module.py
import calc
x=int(input("enter the first number"))
y=int(input("enter the second number"))
addition=[Link](x,y)
print(f"the Sum of {x}+{y}=",addition)
substract=[Link](x,y)
print(f"the substraction of {x}-{y}= ",substract)
multi=[Link](x,y)
print(f"The multiplication of {x}x{y}=",multi)
division=[Link](x,y)
print(f"The division of {x}/{y}=",division)
Dept. of CSE
Python Programming (20CS31P)
Output:
Dept. of CSE
Python Programming (20CS31P)
10b. Develop a python code to demonstrate different math module built-in functions.
Program:
import math
print("The value of 3**4 is:",[Link](3,4))
print("The value of e power -3 is:",[Link](-3))
print("The value of log 2 with base 3:",[Link](2,3))
print("The value of log 2 of 16 is:",math.log2(16))
print("The value of log 10 of 10000:",math.log10(10000))
print("The square root of 25 is :",[Link](25))
print("The absolute value of -9 is :",[Link](-9))
print("The floor value of 3.65 is :",[Link](3.65))
print("The ceil value of 3.65 is :",[Link](3.65))
print("The factorial of 5 is :",[Link](5))
print("The gcd of 5 and 15 is :",[Link](5,15))
print("The value of pi is :",[Link])
print("The value of 2 in degrees :",[Link](2))
print("The value of 60 in radians :",[Link](60))
print("The sine value of 2 is:",[Link](2))
print("The cosine value of 3 is:",[Link](3))
Output:
Dept. of CSE
Python Programming (20CS31P)
11. Develop a Python program to
a) To write content to file
b) To read all contents from file
c) To read 10 bytes from file
d) To read first 2 lines of data from file
e) To read character by character
Program:
#writing to a file
f = open("[Link]", "w")
[Link]("Hello, welcome to gpt Bagalkot\n")
l = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
[Link](l)
[Link]()
#reading from a file
f = open("[Link]", "r")
print([Link]())
#read 10 bytes
f = open("[Link]", "r")
print([Link](10))
#read line by line
f = open("[Link]", "r")
print([Link]())
print([Link]())
#read character by character
f = open("[Link]", "r")
for x in f:
print(x)
[Link]()
Dept. of CSE
Python Programming (20CS31P)
Output:
Dept. of CSE
Python Programming (20CS31P)
12. Write a Python program to handle NameError, ZeroDivisionError and FileNotFoundError.
Program:
#NameError , ZeroDivisionError
try :
print(x)
except NameError:
print("variable x is not defined")
except :
print("something else went wrong")
try:
print(6/0)
except ZeroDivisionError:
print("you can’t divide by zero!")
#FileNotFoundError
filename = '[Link]'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file "+ filename + " does not exist."
print(msg)
Ouput:
Dept. of CSE