Python Programming Laboratory
Experiment 1 : Setup Python environment and explore different ways to run python
program.
Step 1 : To download Pycharm, visit the website 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”.
Step 3 : On that screen, change the installation path if required. Click “Next”.
Step 4 : On that 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”.
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”.
Step 8 : After you click on “Finish”, you can execute now.
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 1
Python Programming Laboratory
Program 2(a) : Write a python program to add two numbers using I/O statements.
x = input("type a number:")
y = input("type another number:")
sum = int(x) + int(y)
print("the sum of x and y is :",sum)
Output :
Program 2(b) : Evaluate expressions to examine operator precedence.
a = 20
b = 10
c = 15
d=5
e=0
e = (a+b)*c/d
print ("the output of the above expressions is",e)
e = ((a+b)*c)/d
print ("the output of the above expressions is",e)
e = (a)+(b*c)/d
print ("the output of the above expressions is",e)
Output :
Syntactic error :
x = input ("type a number:")
y = input ("type another number;")
sum = int(x) "+" int(y)
print = ("the sum of x & y is :",sum)
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 2
Python Programming Laboratory
Output:
Semantic error :
x = input("type a number:")
y = input(" type another number :")
sum = int(x) + int(y)
print ('the sum of x and y is',y)
Output:
Program 3(a) : Find the largest number using if statement.
a = 33
b = 00
if b>a:
print("b is greater than a")
Output:
Program 3(b) : Compare two numbers using elif statement.
a = 33
b = 33
if b>a:
print("b is greater than a")
elif a==b:
print("a and b are equal")
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 3
Python Programming Laboratory
Output:
Program3(c): Compare two numbers using else statement.
a = 200
b = 33
if b>a:
print("b is greater than a")
elif a==b:
print("a and b are equal")
else:
print("a is greater than b")
Output:
Program3(d) Code, execute and design program to check whether the x value is
greater than 10 and 20 using nested if statement.
x = 41
if x>10:
print("above 10,")
if x>20:
print("and also above 20.")
else:
print("but not above 20.")
Output:
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 4
Python Programming Laboratory
Syntactic error:
a = 33
b = 200
if b>a:
print("b is greater than a")
Output:
Semantic Error:
a = 33
b = 200
if b>a:
print("a and b are equal")
Output:
Program 4(a) : Write a Python program to print table of a given number using for
loop and range function.
n = int (input ("enter the number "))
for i in range(1,11):
c = n*i
print (n,"*",i,"=",c)
Output :
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 5
Python Programming Laboratory
Program 4(b) : Write a Python program to add number 3 to the values using while
loop.
num = 1
while num <10:
print (num)
num = num+3
Output:
Program 4(c) : Write a Python program to demonstrate for loop and conditional
statement.
for i in range (0,5):
print(i)
else:
print("for loop completely exhausted")
Output :
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 6
Python Programming Laboratory
Program 4(d) : Write a Python program to print Fibonacci series using while loop
and conditional statement.
terms = int (input("enter the terms"))
a=0
b=1
count = 0
if (terms <=0):
print("please enter a valid integer")
elif(terms==1):
print("fibonacci sequence upto", limit,":")
print(a)
else:
print("finacci sequence:")
while(count < terms):
print (a,end ='')
c = a+b
a=b
b=c
count +=1
Output :
Syntactic error:
list = [10,30,23,43,65,12
sum = 0
for i in list:
sum = sum+i
print ("the sum is :",sum)
Output:
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 7
Python Programming Laboratory
Semantic error:
list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("the sum is:",sum)
Output:
Program 5(b) : Write a python program to print repeated values using set
comprehension.
input_list = [1,2,3,4,4,5,6,6,7,7]
set_using_comp ={var for var in input_list if var%2==0}
print("Output set using set comprehensions:",set_using_comp)
Output:
Program 5(c) : Code execute and debug programs do performs basic operations on
tuples.
tup1 = ('Ajay kumar','Engineering',2000,20200301)
print(tup1)
tup2 = ('Vijay kumar','MBBS',1999,202014357)
print(tup2)
tup3 = tup1 + tup2
print(tup3)
del tup1
print("after deleting tup1")
print(tup1)
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 8
Python Programming Laboratory
Output:
Program 5(a) : Code, execute and debug programs to perform set operations.
set1 = set()
set2 = set()
for i in range(1,6):
[Link](i)
for i in range(3,8):
[Link](i)
print("set1 =",set1)
print("set2 =",set2)
print("\n")
set3=set1|set2
print("Union of set1 & set2:set3=",set3)
set4 = set1 & set2
print("Intersection of set1 & set2:set4=",set4)
print("\n")
if set3 > set4:
print("set3 is superset of set4")
elif set3 <_set4:
print("set3 is superset of set4")
else:
print("set3 is same as set4")
if set4 < set3:
print("set4 is subset of set3")
print("\n")
set5 = set3-set4
print("Elements in set3 and not in set4:set5=",set5)
print("\n")
if [Link](set5):
print("set4 and set5 have nothing in common\n")
[Link]()
print("After applying clear on sets set5:")
print("set5 =",set5)
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 9
Python Programming Laboratory
Output:
Program 5(d) : Code, execute and debug programs to perform tuple indexing and
slicing.
my_tuple = ('a','b','c','d')
print(my_tuple[1:])
print(my_tuple[:2])
print(my_tuple[1:3])
print(my_tuple[1:2])
Output:
Syntactic Error :
tup1 = ('physics',chemistry,1997,2000)
tup2 = (1,2,3,4,5,6,7)
print("tup[0]:",tup1[0])
print("tup2[1:5]:",tup2[1:5])
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 10
Python Programming Laboratory
Output :
Semantic Error :
tup1 = ('physics','chemistry',1997,2000)
tup2 = (1,2,3,4,5,6,7)
print("tup[0]:",tup1[0:2])
print("tup2[1:5]:",tup2[1:5])
Output :
Program 6(a) : Write a code snippet to perform basic operations on list
list = [1,2,3,4,5,6,7,8,9]
print ("intial list:")
print (list)
[Link](3,12)
[Link](0,'python')
print ("\n list after insert operation:")
print(list)
list = [1,2,3,4,5,6]
print ("intial list:")
print (list)
[Link](5)
[Link](6)
print("\n list after removal of two elements:")
print (list)
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 11
Python Programming Laboratory
Output:
Program 6(b) : Write a code snippet to perform indexing and slicing on list.
my_list = ['a','b','c','d']
print(my_list [1:])
print(my_list[:2])
print(my_list[1:3])
print(my_list[::2
Output:
Program 6(c) : Write a code snippet to perform list compression .
fruits = ["apple","banana","cherry","kiwi","mango"]
newlist = [x for x in fruits if "a"in x ]
print(newlist)
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 12
Python Programming Laboratory
Output:
Syntactic error:
fruits = ["apple","bannana","cherry","kiwi","mango"]
newlist = [x for x in fruits if a in x ]
print(newlist)
Output:
Semantic error:
fruits = ["apple","bannana","cherry","kiwi","mango"]
newlist = [x for x in fruits if "a" in x ]
print(fruits)
Output:
Program 7(a) : Code, execute and debug program to perform basic operations on
dictionary.
dict = {1:'hello', 2:'good',3:'morning'}
print(dict)
dict[0] = 'hi'
print(dict)
del dict[0]
print(dict)
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 13
Python Programming Laboratory
Output:
Program 7(b) : Code, execute and debug program to perform dictionary indexing.
a_dict = {"a":1,"b":2}
values = a_dict.values ()
values_list = list (values)
a_values = values_list[0]
print(a_values)
Output:
Program 7(c): Code, execute and debug program to perform basic operations on
dictionary iterating.
statesandcapitals = {'gujarat':'gandhinagar', 'maharastra':'mumbai', 'rajsthan':'jaipur',
'bihar':'patna'
}
print('list of given states:\n')
for state in statesandcapitals:
print(state)
Output:
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 14
Python Programming Laboratory
Program 7(d) : Code, execute and debug program to perform dictionary
comprehension.
mydict = {x:x**2 for x in [1,2,3,4,5]}
print(mydict)
Output:
Syntactic Error :
a_dict = {"a":1,"b":2}
values = a_dict.values()
values_list = list(values)
a_value = value_list[0]
print(a_value)
Output:
Semantic Error :
a_dict = {"a":1,"b":2}
values = a_dict.values()
values_list = list(values)
a_values = values_list[0]
print(a_dict)
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 15
Python Programming Laboratory
Output:
Program 8(a) : Code, execute and debug programs to perform string manipulation.
word = "Hello World"
print(word)
letter = word[6]
print(letter)
print(len(word))
print([Link]('l'))
print([Link]("e"))
s = "Count the number of spaces"
print([Link](''))
print([Link]('l'))
print([Link]("d"))
print([Link]("w"))
print([Link]("H"))
print([Link]("h"))
print('.'*10)
print([Link]("Hello","Good Bye"))
print([Link]())
print([Link]())
print(''.join(reversed(word)))
Output:
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 16
Python Programming Laboratory
Program 8(b) : Code, execute and debug programs to perform Array manipulation.
cars = ["Ford","Volvo","BMW"]
x = cars[0]
print(x)
cars[0] = "Toyota"
print(cars)
y = len(cars)
print(y)
for z in cars:
print(z)
[Link]("Honda")
print(cars)
[Link](2)
print(cars)
[Link]("Volvo")
print(cars)
Output:
Syntactic Error :
cars = ["Ford","Volvo","BMW"]
x = cars[0]
print(x)
cars[5] = "Toyota"
print(cars)
Output:
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 17
Python Programming Laboratory
Semantic Error :
cars = ["Ford","Volvo","BMW"]
x = cars[0]
print(cars)
Output:
Program 9(a) : Write a Python program to convert the decimal number into
hexadecimal, octal and binary using built-in functions.
x = bin(36)
print(x)
y = hex(36)
print(y)
z = oct(36)
print(z)
Output :
Program 9(b) : Write a Python program to print factorial of a number using
recursion.
def recursive_factorial(n):
if n ==1:
return n
else:
return n * recursive_factorial(n-1)
num =6
if num<0:
print("invalid input! please enter a positive number:")
elif num == 0:
print ("factorial of a number 0 is 1")
else:
print("factorial of a number",num,"=",recursive_factorial(num))
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 18
Python Programming Laboratory
Output :
Program 9(c) : Program to define doubler and tripler of any number using
anonymous function.
def myfunc(n):
return lambda a:a*n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Output :
Syntactic Error :
def myfunc(n):
return lambda a:a*n
mydoubler = myfun(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Output :
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 19
Python Programming Laboratory
Semantic Error :
def myfunc(n):
return lambda a:a*a
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Output :
Program 10(a) : Create modules and packages using Python.
[Link]
person1 = {
"name":"John",
"age":36,
"country":"Norway"
}
[Link]
import mymodule
a = mymodule.person1["age"]
print(a)
b = mymodule.person1["name"]
print(b)
Output:
Program 10(b) : Code, execute and debug programs using built-in modules.
import platform
x = [Link]()
print(x)
y = dir(platform)
print(y)
Output:
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 20
Python Programming Laboratory
Program 11(a) : Python program to demonstrate basic operations on single array
using NumPy module.
import numpy as np
a = [Link]([[1,2],[3,4]])
b = [Link]([[4,3],[2,1]])
print ("Adding 1 to every element : ",a+1)
print ("\n Subtracting 2 from each element : ",b-2)
print ("\n sum of all array elements :",[Link]())
print ("\n array sum:",a+b)
Output :
Program 11(b) : Write a python program to assign your own index to the data using
series.
import pandas as pd
from pandas import Series
arr = Series([25, 50, 75, 100, 125], index=[2, 4, 6, 8, 10])
print(arr)
print('\nValues in this Array : ', [Link])
print('Index Values of this Array : ', [Link])
Output:
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 21
Python Programming Laboratory
Program 11(c) : Write a code snippet to select columns using dataframes.
import pandas as pd
data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Age': [27, 24, 22, 32],
'Address': ['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
'Qualification': ['Msc', 'MA', 'MCA', 'Phd']}
df = [Link](data)
print(df[['Name', 'Qualification']])
Output:
Syntactic Error :
import pandas as pd
from pandas import Series
arr = Series([25, 50, 75, 100, 125] index=[2, 4, 6, 8, 10])
print(arr)
print('\nValues in this Array : ', [Link])
print('Index Values of this Array : ', [Link])
Output :
Semantic Error :
import pandas as pd
from pandas import Series
arr = Series([25, 50, 75, 100, 125], index=[2, 4, 6, 8, 10])
print(arr)
print('\nValues in this Array : ', [Link])
print('Index Values of this Array : ', arr)
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 22
Python Programming Laboratory
Output :
Program 12(a) : Write a code snippet to perform following operations on different
type of files(read file, write to file).
file1 = open("[Link]", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
[Link]("Hello \n")
[Link](L)
[Link]()
file1 = open("[Link]", "r+")
print("Output of Read function is ")
print([Link]())
print()
[Link](0)
print("Output of Readline function is ")
print([Link]())
print()
[Link](0)
print("Output of Read(9) function is ")
print([Link](9))
print()
[Link](0)
print("Output of Readline(9) function is ")
print([Link](9))
[Link](0)
print("Output of Readlines function is ")
print([Link]())
print()
[Link]()
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 23
Python Programming Laboratory
Output:
Program 12(b) : Write code to perform file operations using dataframes on different
file types.
import pandas as pd
data = {
'CHN': {'COUNTRY': 'China', 'POP': 1_398.72, 'AREA': 9_596.96,
'GDP': 12_234.78, 'CONT': 'Asia'},
'IND': {'COUNTRY': 'India', 'POP': 1_351.16, 'AREA': 3_287.26,
'GDP': 2_575.67, 'CONT': 'Asia', 'IND_DAY': '1947-08-15'},
'USA': {'COUNTRY': 'US', 'POP': 329.74, 'AREA': 9_833.52,
'GDP': 19_485.39, 'CONT': '[Link]',
'IND_DAY': '1776-07-04'}}
columns = ('COUNTRY', 'POP', 'AREA', 'GDP', 'CONT', 'IND_DAY')
df = [Link](data=data, index=columns).T
df.to_csv('[Link]')
df = pd.read_csv('[Link]', index_col=0)
print(df)
Output:
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 24
Python Programming Laboratory
Syntactic Error :
import pandas as pd
data = {
'CHN': {'COUNTRY': 'China', 'POP': 1_398.72, 'AREA': 9_596.96,
'GDP': 12_234.78, 'CONT': 'Asia'},
'IND': {'COUNTRY': 'India', 'POP': 1_351.16, 'AREA': 3_287.26,
'GDP': 2_575.67, 'CONT': 'Asia', 'IND_DAY': '1947-08-15'},
'USA': {'COUNTRY': 'US', 'POP': 329.74, 'AREA': 9_833.52,
'GDP': 19_485.39, 'CONT': '[Link]',
'IND_DAY': '1776-07-04'}}
columns = ('COUNTRY', 'POP', 'AREA', 'GDP', 'CONT', 'IND_DAY')
df = [Link](data=data, index=columns).T
df.to_csv('[Link]')
df = pd.read_csv('[Link]', index_col=0)
print(df)
Output :
Semantic Error :
import pandas as pd
data = {
'CHN': {'COUNTRY': 'China', 'POP': 1_398.72, 'AREA': 9_596.96,
'GDP': 12_234.78, 'CONT': 'Asia'},
'IND': {'COUNTRY': 'India', 'POP': 1_351.16, 'AREA': 3_287.26,
'GDP': 2_575.67, 'CONT': 'Asia', 'IND_DAY': '1947-08-15'},
'USA': {'COUNTRY': 'US', 'POP': 329.74, 'AREA': 9_833.52,
'GDP': 19_485.39, 'CONT': '[Link]',
'IND_DAY': '1776-07-04'}}
columns = ('COUNTRY', 'POP', 'AREA', 'GDP', 'CONT', 'IND_DAY')
df = [Link](data=columns, index=columns).T
df.to_csv('[Link]')
df = pd.read_csv('[Link]', index_col=0)
print(df)
Output :
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 25
Python Programming Laboratory
Program 13(a) : Write a Python program to handle NameError and
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!")
Output:
Program 13(b) : Write a code snippet to handle 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)
Output:
Program 13(c) : Write a code snippet to raise exceptions and stop the program if x
is less than 0.
x = -1
if x<0:
raise Exception("Sorry, no numbers below zero")
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 26
Python Programming Laboratory
Output:
Syntactic Error :
x = -1
if x<0:
raiseException("Sorry, no numbers below zero")
Output:
Semantic Error:
x = -1
if x<0:
raise Exception("Sorry, no numbers below ten")
Output:
Varalakshmi P,Lecturer/CS[The Oxford Polytechnic] Page 27