Python Programming (20CS31P)
Student Name :
Register Number :
Roll No :
Course Name : Python Programming
Course Code : 20CS31P
Semester : III SEM
Programme : Computer Science and Engineering
College: Government Polytechnic, Karwar (114)
Course Coordinator HOD
List of Programs
Sl. Program Name Page
No No.
1 Program to demonstrate input and output 7
statement
2 Program to Evaluate Expression and formatted 9
output
3 Program to demonstrate if conditional statement 10
4 Program to demonstrate nested if else statement 12
5 Program to demonstrate for loop 14
6 Program to demonstrate while loop 16
7 Program to demonstrate set concept 18
8 Program to demonstrate tuple concept 20
9 Program to demonstrate list concept 22
10 Program to demonstrate list concept 25
11 Program to demonstrate string concept 28
12 Program to demonstrate array concept 32
13 Program to demonstrate function concept 35
14 Program to demonstrate module concept 39
15 Program to demonstrate module concept 41
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
Python is a widely used high-level programming language. To write and
execute code in python, we first need to install Python on our system.
Installing Python on Windows takes a series of few easy steps.
Step 1: Download the Full Installer
Follow these steps to download the full installer:
• Open a browser window and navigate to the [Link] Downloads
page for Windows.
• Under the “Python Releases for Windows” heading, click the link for
the Latest Python 3 Release - Python 3.x.x. As of this writing, the
latest version was Python 3.10.
• Scroll to the bottom and select either Windows x86-64 executable
installer for 64-bit or Windows x86 executable installer for 32-bit.
Step 2 − Run Executable Installer
We downloaded the Python 3.10 Windows 64 bit installer.
Run the installer. Make sure to select both the checkboxes at the bottom
and then click Install New.
On clicking the Install Now, The installation process starts.
Department of Computer Science and Engineering 1|P a ge
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
The installation process will take few minutes to complete and once the
installation is successful, the following screen is displayed.
Step 3 − Verify Python is installed on Windows
To ensure if Python is successfully installed on your system. Follow the
given steps
• Open the command prompt.
• Type ‘python’ and press enter.
The version of the python which you have installed will be displayed if
the python is successfully installed on your windows.
Department of Computer Science and Engineering 2|P a ge
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
PyCharm is a cross-platform editor developed by JetBrains. Pycharm
provides all the tools you need for productive Python development.
Below are the detailed steps for installing PyCharm
Step1: To download PyCharm visit the website
[Link] and Click the
“DOWNLOAD” link under the Community Section.
Step 2) Once the download is complete, run the exe for install PyCharm.
The setup wizard should have started. Click “Next”.
Department of Computer Science and Engineering 3|P a ge
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
Step 3) On the next screen, Change the installation path if required.
Click “Next”.
Step 4) On the next screen, you can create a desktop shortcut if you
want and click on “Next”.
Step 5) Choose the start menu folder. Keep selected JetBrains and click
on “Install”.
Department of Computer Science and Engineering 4|P a ge
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
Step 6) Wait for the installation to finish.
Step 7) Once installation finished, you should receive a message screen
that PyCharm is installed. If you want to go ahead and run it, click the
“Run PyCharm Community Edition” box first and click “Finish”.
Department of Computer Science and Engineering 5|P a ge
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
Step 8) After you click on “Finish,” the Following screen will appear.
Department of Computer Science and Engineering 6|P a ge
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
1. Write a Program to input a Student Name, Semester, City name, and
Pin code from keyboard and display the same on output screen.
Algorithm:
Step1: Input a student name, semester, city name and pincode from the
keyboard.
Step2: display the same information.
Program:
name=input("Enter your name:")
sem=int(input("Enter your semester:"))
city=input("Enter your city name:")
pincode=int(input("Enter a pincode of your city:"))
print("\n\n\n")
print("Student Name :",name)
print("Semester:",sem)
print("City:",city)
print("Pincode:",pincode)
:OUTPUT 1:
Department of Computer Science and Engineering 7|P a ge
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
:OUTPUT 2:
:OUTPUT 3:
Department of Computer Science and Engineering 8|P a ge
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
2. Write a program to Evaluate expressions and displays formatted output.
Algorithm:
Step 1: Consider two variables a, b and store values.
Step 2: Calculate sum and difference of these values and store these result in
variables called sum and sub respectively.
Step 3: Display the values of a, b, sum, sub using string format function.
(a) string formatting using format() function
a = 20
b = 10
sum = a + b
sub = a- b
print('The value of a is { } and b is { }'.format(a,b))
print('{2} is the sum of {0} and {1}'.format(a,b,sum))
print('{sub_value} is the subtraction of {value_a} and {value_b}'.format(value_a =
a ,value_b = b,sub_value = sub))
:OUTPUT 1:
Department of Computer Science and Engineering 9|P a ge
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
3. If the ages of Ram, Shyam and Ajay are input through the keyboard,
write a program to determine the youngest of the three.
Algorithm:
Step1: Take a input for ages if Ram,Shyam and Ajay.
Step2: If Ram age is greater than Shyam age and Ajay age , display “Ram is
youngest”.
Step3: Otherwise,If Shyam age is greater than Ram age and Ajay age , display
“Shyam is youngest”.
Step4: Otherwise display “Ajay is youngest”.
Program:
ram=int(input("Enter a age of Ram:"))
shyam=int(input("Enter a age of Shyam:"))
ajay=int(input("Enter a age of Shyam:"))
if (ram>shyam)and ( ram>ajay):
print("Ram is youngest.")
elif shyam>ram and shyam>ajay:
print("Shyam is youngest.")
else:
print("Ajay is youngest.")
Department of Computer Science and Engineering 10 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
:OUTPUT 1:
:OUTPUT 2:
Department of Computer Science and Engineering 11 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
4. Since the introduction of the Gregorian calendar (in 1582), the
following rule is used to determine the kind of year:
• if the year number isn't divisible by four, it's a common year;
• otherwise, if the year number isn't divisible by 100, it's a leap year;
• otherwise, if the year number isn't divisible by 400, it's a common
year; otherwise, it's a leap year.
Algorithm:
Step1: Input a value of a year from the keyboard.
Step2: If year is smaller than 1582 ,display “Year is not in Gregorian calender”.
Step3: Otherwise again checking for a condition.
Step4: If the year is not divisible by 4,display “common year”.
Step5: Otherwise ,If the year is not divisible by 100,display “leap year”.
Step6: Otherwise ,If the year is not divisible by 400,display “common year”.
Step7 :Otherwise, display “leap year”.
Program:
year=int(input("Enter the value of year:"))
if (year<1582):
print("Year is not in Gregorian calender.")
else:
if(year%4!=0):
print("Common year.")
elif (year%100!=0):
print("Leap year.")
elif(year%400!=0):
print("Common year.")
else:
print("Leap year.")
Department of Computer Science and Engineering 12 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
:OUTPUT 1:
:OUTPUT 2:
Department of Computer Science and Engineering 13 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
5. Write a program that asks for a word, phrase, or sentence. The program
should then print whether the input is a palindrome.
Note: Use For Loop
Algorithm:
Step1: Input a word ,phrase or statement from the keyboard.
Step2: Find the reverse of a word using for loop.
Step3: Store that reverse string in another variable.
Step4: If the original string is equal to reverse string, display “ The word is
palindrome”.
Step5: Otherwise ,display “The word is not a pakindrome”.
Program:
letter=input("Enter a word,phrase or sentence:")
reverse=""
for i in letter:
reverse=letter[::-1]
print("Reversed word,phrase or sentence is:",reverse)
if letter==reverse:
print("The word,phrase or sentence is palindrome.")
else:
print("The word,phrase or sentence is not palindrome.")
Department of Computer Science and Engineering 14 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
:OUTPUT 1:
:OUTPUT 2:
Department of Computer Science and Engineering 15 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
6. Write a program to find the factorial value of any number entered
through the keyboard.
Note: Use While Loop.
Algorithm:
Step1: Input a number from the keyboard.
Step2: Initialize the result to 1 and store it to one variable.
Step3: Start a loop and multiply the result by the number.
Step4: Reduce one from the number in each iteration.
Step5: End the loop once the number reaches 1
Step6: display the result value.
Program:
n=int(input("Enter a number:"))
temp=n
fact=1
while n!=0:
fact*=n
n-=1
print("Factorial of {0} is {1}.".format(temp,fact))
Department of Computer Science and Engineering 16 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
:OUTPUT 1:
:OUTPUT 2:
Department of Computer Science and Engineering 17 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
7. Write a program to create two sets using set comprehension and
perform following set operations:
(i) Union
(ii) Difference
(iii) Symmetric Difference
(iv) Intersection.
Algorithm:
Step1: Create a two sets.
Step2: Perform a union operation using | operator and display it’s result.
Step3: Perform a difference operation using - operator and display it’s result.
Step4: Perform a symmetric difference operation using ^ operator and display
it’s result.
Step5: Perform a intersection operation using & operator and display it’s
result.
Program:
set1={var**2 for var in range(1,11)}
set2={i for i in range(1,11) if i%2==0}
print("Elements of Set1 are :",set1 )
print("Elements of Set2 are :",set2 )
print("Union Operation",set1|set2)
print("Intersection Operation",set1&set2)
print("Difference Operation",set1-set2)
print("Symmetric Difference Operation",set1^set2)
Department of Computer Science and Engineering 18 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
:OUTPUT 1:
Department of Computer Science and Engineering 19 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
8. Write a program to create a tuple and perform following operations
(i) Display the elements of tuple
(ii) Find an item using index method
(iii) Reverse all the elements
(iv) Display the elements from 3 rd position to 7th position
(v) Delete entire tuple
ALGORITHM:
Step 1: Start
Step 2: Declare and Initialize tuple1
Step 3: Display tuple1
Step 4: Find an item using index method.
Step 5: Reverse tuple1 elements and Display
Step 6: Display elements from 3rd to 7th position
Step 7: Delete tuple1
Step 8: Stop
PROGRAM:
tuple1=(1,2,3,4,7,8,9)
print("Elements of tuple are:\n")
for i in range(len(tuple1)):
print(tuple1[i])
find=int(input("Enter element to search in tuple "))
i=[Link](find)
print("\n Element %d found at index %d in tuple \n"%(find,i))
print("Elements of tuple in reverse order \n ",tuple1[::-1])
print("Elements from 3 rd position to 8 th position",tupl1[3:8])
Department of Computer Science and Engineering 20 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
print("Deleting a tuple")
del tuple1
print("Elements of tuple are ",tuple1)
:OUTPUT 1:
Department of Computer Science and Engineering 21 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
[Link] a program to create a List of 10 odd numbers using List
Comprehension and perform the following:
i) Display all the elements
(ii) Find the length of list
(iii) Adding new items to list using append(), insert()
(iv) Remove certain items using pop(), remove()
(v) Find the particular item using index()
ALGORITHM:
Step 1: Start
Step 2: Declare and initialize List1 using Comprehension
Step 3: Display List1
Step 4: Obtain the length of List1
Step 5: Add items using append(), insert() to List1
Step 6: Remove items using pop(), remove() from List1
Step 7: Find the particular item using index() and display
Step 8: Stop
PROGRAM:
list1=[i for i in range(20) if i%2!=0]
print("Elements of List are ")
for i in range(len(list1)):
print(list1[i])
print("Length of list is ", len(list1))
print("Adding new item using append method")
Department of Computer Science and Engineering 22 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
[Link](99)
print("Adding new item using insert method")
[Link](1,2)
print("Elements are: ", list1)
print("Removing an item using pop method")
[Link](1)
print("Removing an item using remove method")
[Link](3)
print("Elements are: ", list1)
find=int(input("Enter the element to search"))
pos=[Link](find)
print("%d element found at index %d"%(find,pos))
Department of Computer Science and Engineering 23 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
:OUTPUT 1:
Department of Computer Science and Engineering 24 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
[Link] a program to create a List of 10 Even numbers using List
Comprehension and perform the following:
(i) Sort List
(i) Reverse List
(iii) Find Max, Min, and Sum
(iv) Display the range of items using slicing operator
(v) Clear all elements
(vi) Delete the list
ALGORITHM:
Step 1: Start
Step 2: Declare and initialize List1 using Comprehension
Step 3: Display List1
Step 4: Sort List1
Step 5: Reverse List1
Step 6: Display max, min and sum of List1
Step 7: Display items in range
Step 8: Clear List1
Step 9: Delete List1
Step 10: Stop
PROGRAM
list1=[i for i in range(20) if i%2==0]
print("Elements of List are ")
for i in range(len(list1)):
print(list1[i])
Department of Computer Science and Engineering 25 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
print("Elements of list before sort ",list1)
[Link]()
print("Elements of list after sort ",list1)
[Link]()
print("Elements of list after reverse ",list1)
print("Maximum ",max(list1))
print("Minimum ",min(list1))
print("Sum of elements ",sum(list1))
print("Elements from 3 rd position to 7 position",list1[3:8])
print("Clearing list" )
[Link]()
print("Elements of list are ",list1)
Department of Computer Science and Engineering 26 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
:OUTPUT 1:
Department of Computer Science and Engineering 27 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
11. Consider Two strings S1 “Government Polytechnic” and S2 “Karwar,
Uttarakannada” Create a program to create these 2 strings and perform
the following:
(i) Find First character in S1
(ii) Find Last but one character in S2
(iii)Find length of both strings
(iv)Reverse S1
(v)Apply strip(),lower(),upper(),split(),replace(),find(),join(),max(),min()
methods
ALGORITHM:
Step 1: Start
Step 2: Declare S1 and assign “Government polytechnic” to S1
Step 3: Declare S2 and assign “Karwar, Uttarakannad” to S2
Step 4: Display first character of S1
Step 5: Display last character of S2
Step 6: Obtain length of S1 and display
Step 7: Obtain length of S2 and display
Step 8: Declare variable reverse
Step 9: Use a for loop to iterate through S1
Step 10: Reverse S1 string and assign to reverse variable
Step 11: Display reverse
Step 12: Declare a string list , assign to str
Step 13: Use join() to join str , assign to str2
Step 14: Display str2
Step 15: Apply strip() and display
Step 16: Apply split() and display
Step 17: Apply lower() and display
Department of Computer Science and Engineering 28 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
Step 18: Apply upper() and display
Step 19: Apply find() and display
Step 20: Apply max() and display
Step 21: Apply min() and display
Step 22: Apply replace() and display
Step 23: Stop
Program
S1 = "Government Polytechnic"
S2 = "Karwar, Uttarakannada"
print("String1 is ", S1)
print("String2 is ", S2)
print("First character of S1: ",S1[0])
print("Last but one character of S2: ",S2[-2])
print("Length of String1 is:", len(S1))
print("Length of String2 is:",len(S2))
reverse =""
for i in S1:
reverse = i + reverse
print("Reversed string of String1",reverse)
print("Demonstration of String Operations")
str = ["Strings", "In", "Python"]
str2=(" ").join(str)
print(str2)
print("Strip method",[Link]())
print("Split method",[Link]())
print("Lowercase",[Link]())
Department of Computer Science and Engineering 29 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
print("Uppercase",[Link]())
print("Find Method:",[Link]("G"))
print("Max Method:",max(S1))
print("Min Method:",min(S1))
S = [Link]("Government Polytechnic" , "Diploma college")
print(S)
Department of Computer Science and Engineering 30 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
:OUTPUT 1:
Department of Computer Science and Engineering 31 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
[Link] a program to create two arrays (i) integer numbers array (ii)
floating point numbers array and perform following operations:
(a) Insert new elements using insert()
(b) Remove Existing elements using pop(),remove()
(c) print elements from beginning to a range use [:Index].
(d) print elements from end use [:-Index]
(e) print elements from specific Index till the end use [Index:]
(f) print elements within a range, use [Start Index : End Index]
(g) print whole List with the use of slicing operation, use [:].
(h) print whole array in reverse order, use [::-1].
ALGORITHM:
Step 1: Start
Step 2: Import array module
Step 3: Declare array of integer numbers and assign to ary1
Step 4: Declare array of floating point numbers and assign to ary2
Step 5: Insert an item using insert() method
Step 6: Remove Existing elements using pop() , remove()
Step 7: Display elements from beginning to a range
Step 8: Display elements from end
Step 9: Display elements from specific Index to till the end
Step 10: Display elements within a range
Step 11: Display ary2
Step 12: Display ary2 in reverse order
Step 13: Stop
Department of Computer Science and Engineering 32 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
PROGRAM:
import array as arr
ary1 = [Link]('i' , [1,2,3,4,5,6,7,8,9])
ary2 = [Link]('d' , [1.1,2.5,6.7,3.5,2.8,9.1])
print("Elements of First array are :")
for i in range(len(ary1)):
print(ary1[i])
print("Elements of Second array are :")
for i in range(len(ary2)):
print(ary2[i])
print("Insertion")
[Link](0 , 10)
print("Updated array is ",ary1)
print("Removal")
[Link](10)
print("Updated array is ",ary1)
[Link](8)
print("Updated array is ",ary1)
print("Slicing Oparation")
print(ary1[ : len(ary1)])
print(ary1[-1 : ])
print(ary1[2 : ])
Department of Computer Science and Engineering 33 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
print(ary1[2 : 8])
print(ary2[ : ])
print(ary2[ : : -1])
:OUTPUT 1:
Department of Computer Science and Engineering 34 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
13. The Fibonacci sequence is a series of numbers where a number is the
addition of the last two numbers, starting with 0, and 1.
The Fibonacci Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55…
Written as a rule, the expression is: Xn = Xn-1 + Xn-2
Write a program to find n Fibonacci sequence by
(a) By defining function
(b) By using recursion
ALGORITHM: (a) By defining function
Step 1: Start
Step 2: Declare function fib()
if n < 1 then return 0
if n < 3 then return 1
Declare and initialize variables val1 = val2 = 1
Declare and initialize variable sum = 0
Use for loop to iterate through range between 3 and n+1
Add val1 and val2, assign result to sum
Assign val1 to val2
Assign sum to val1
Return sum
Step 3: Input n value
Step 4: Use for loop to iterate in range of n value & Call function fib() and
display values
Step 5: Stop
ALGORITHM: (b) By using recursion
Step 1: Start
Department of Computer Science and Engineering 35 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
Step 2: Declare function fib()
if n < 1 then return 0
if n < 3 then return 1
Return fib(n - 1) + fib(n - 2)
Step 3: Input n value
Step 4: Use for loop to iterate in range of n value Call function fib() and display
values
Step 9: Stop
PROGRAM: (a) By defining function
def fib(n):
if n < 1:
return 0
if n < 3:
return 1
val1 = val2 = 1
sum = 0
for i in range(3, n+1):
sum = val1 + val2
val2 = val1
val1 = sum
return sum
n = int(input(“Enter the Fibonacci term: “))
for i in range(n):
print(i, “-->”, fib(i))
Department of Computer Science and Engineering 36 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
PROGRAM: (b) By using recursion
def fib(n):
if n < 1:
return 0
if n < 3:
return 1
return fib(n-1) + fib(n-2)
n = int(input(“Enter the Fibonacci term: “))
for i in range(n):
print(i, “-->”, fib(i))
:OUTPUT 1:
Department of Computer Science and Engineering 37 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
:OUTPUT 2:
Department of Computer Science and Engineering 38 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
14. Write a program to demonstrate import module.
ALGORITHM:
STEP1: Create a python script [Link]
STEP2: Create a python file [Link] and import specified function defined in
[Link] file
STEP3: Create a python file [Link] and import all function defined in
[Link] file
PROGRAM
[Link]
def summation(a,b):
return a+b
def subtraction(a,b):
return a-b;
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;
[Link]
from cal import summation ,divide
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b))
print("Division = ",divide(a,b))
[Link]
import from cal
a = int(input("Enter the first number"))
Department of Computer Science and Engineering 39 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b))
print("Product = ",multiplication(a,b))
print("Difference = ",subtract(a,b))
:OUTPUT 1:
Department of Computer Science and Engineering 40 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
15. Write a program to demonstrate math and random modules.
ALGORITHM:
STEP1: import math , random module
STEP2: write a code to demonstrate various inbuilt function of math and
random module
PROGRAM
(a) math module
import math
print("Euler Value is :",math.e)
print("PI Value is :",[Link])
print("Factorial :",[Link](5))
print("GCD :",[Link](5,57))
print("Square root :",[Link](5))
print("Ceil Value :",[Link](5.35))
print("Floor Value :",[Link](5.35))
print("Sin Theta Value:",[Link](45))
print("Cos Theta Value:",[Link](45))
print("Tan Theta Value:",[Link](45))
(b) random module
import random
print("Random integers between 0 to 5:",[Link](0,5))
print("Random Floating numbers between 0 to 1:",[Link]())
list1= [1,4,True,800,"python",27,"hello"]
print("Random element from list is :",[Link](list1))
Department of Computer Science and Engineering 41 | P a g e
Government Polytechnic, Karwar Date:
Python Programming –Practical Lab Record
:OUTPUT 1:
:OUTPUT 2:
Department of Computer Science and Engineering 42 | P a g e