COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL
LAB SYLLABUS
1. Write a program to demonstrate different number data types in Python.
2. Write a program to perform different Arithmetic Operations on numbers in Python.
3. Write a program to create, concatenate and print a string and accessing sub-string
from a given string.
4. Write a python script to print the current date in the following format “Sun May 29
[Link] IST 2017”
5. Write a program to create, append, and remove lists in python.
6. Write a program to demonstrate working with tuples in python.
7. Write a program to demonstrate working with dictionaries in python.
8. Write a python program to find largest of three numbers.
9. Write a Python program to convert temperatures to and from Celsius, Fahrenheit. [
Formula : c/5 = f-32/9 ]
10. Write a Python program to construct the following pattern, using a nested for loop
**
* * *2
****
*****
****
***
**
1
11. Write a Python script that prints prime numbers less than 20.
12. Write a python program to find factorial of a number using Recursion.
13. Write a program that accepts the lengths of three sides of a triangle as inputs. The
program output should indicate whether or not the triangle is a right triangle (Recall
from the Pythagorean Theorem that in a right triangle, the square of one side equals
the sum of the squares of the other two sides).
14. Write a python program to define a module to find Fibonacci Numbers and import the
module to another program.
15. Write a python program to define a module and import a specific function in that
module to another program.
16. Write a script named [Link]. This script should prompt the user for the names of
two text files. The contents of the first file should be input and written to the second
file.
17. Write a program that inputs a text file. The program should print all of the unique
words in the file in alphabetical order.
18. Write a Python class to convert an integer to a roman numeral.
19. Write a Python class to implement pow(x, n)
20. Write a Python class to reverse a string word by word.
2
EXPERIMENT - 1
OBJECTIVE:
Write a program to demonstrate different number data types in Python.
SOURCECODE:
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
INPUT ANDOUTPUT:
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True
3
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True
EXPERIMENT - 2
OBJECTIVE:
Write a program to perform different Arithmetic Operations on numbers in Python.
SOURCECODE:
x = 15
y=4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
INPUT ANDOUTPUT:
x + y = 19
x - y = 11
x * y = 60
4
x / y = 3.75
x // y = 3
x ** y = 50625
EXPERIMENT -3
OBJECTIVE:
Write a program to create, concatenate and print a string and accessing sub-string
from a given string.
SOURCECODE:
# all of the following are equivalent
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
print(my_string)
c=" mlritm"
print(my_string+c)
# substring function
print(my_string[5:11])
INPUT ANDOUTPUT:
Hello
Hello
Hello
Hello, welcome to
the world of Python
Hello, welcome to
the world of Python mlritm
, welc
5
EXPERIMENT -4
OBJECTIVE:
Write a python script to print the current date in the following format “Sun May 29
[Link] IST 2017”
SOURCECODE:
from datetime import date
today =[Link]()
# dd/mm/YY
d1 =[Link]("%d/%m/%Y")
print("d1 =", d1)
# Textual month, day and year
d2 =[Link]("%B %d, %Y")
print("d2 =", d2)
# mm/dd/y
d3 =[Link]("%m/%d/%y")
print("d3 =", d3)
# Month abbreviation, day and year
d4 =[Link]("%b-%d-%Y")
print("d4 =", d3)
INPUT ANDOUTPUT:
d1 = 25/12/2018
d2 = December 25, 2018
d3 = 12/25/18
d4 = 12/25/18
6
EXPERIMENT -5
OBJECTIVE:
Write a program to create, append, and remove lists in python.
SOURCECODE:
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
# Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list)
# Output: 'o'
print(my_list.pop(1))
# Output: ['r', 'b', 'l', 'e', 'm']
print(my_list)
# Output: 'm'
print(my_list.pop())
# Output: ['r', 'b', 'l', 'e']
print(my_list)
my_list.clear()
# Output: []
print(my_list)
INPUT ANDOUTPUT:
my_list=['p','r','o','b','l','e','m']
>>>my_list[2:3]=[]
>>>my_list
['p','r','b','l','e','m']
>>>my_list[2:5]=[]
>>>my_list
['p','r','m']
7
EXPERIMENT -6
OBJECTIVE:
Write a program to demonstrate working with tuples in python.
SOURCECODE:
# empty tuple
# Output: ()
my_tuple = ()
print(my_tuple)
# tuple having integers
# Output: (1, 2, 3)
my_tuple = (1, 2, 3)
print(my_tuple)
# tuple with mixed datatypes
# Output: (1, "Hello", 3.4)
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# nested tuple
# Output: ("mouse", [8, 4, 6], (1, 2, 3))
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
# tuple can be created without parentheses
# also called tuple packing
# Output: 3, 4.6, "dog"
my_tuple = 3, 4.6, "dog"
print(my_tuple)
# tuple unpacking is also possible
# Output:
#3
# 4.6
# dog
a, b, c = my_tuple
print(a)
print(b)
print(c)
8
EXPERIMENT -7
OBJECTIVE:
Write a program to demonstrate working with dictionaries in python.
SOURCECODE:
my_dict = {'name':'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# Trying to access keys which doesn't exist throws error
# my_dict.get('address')
# my_dict['address']
INPUT ANDOUTPUT:
Jack
26
9
EXPERIMENT -8
OBJECTIVE:
Write a python program to find largest of three numbers.
SOURCECODE:
# Python program to find the largest number among the three input numbers
# change the values of num1, num2 and num3
# for a different result
num1 = 10
num2 = 14
num3 = 12
# uncomment following lines to take three numbers from user
#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number between",num1,",",num2,"and",num3,"is",largest)
INPUT ANDOUTPUT:
The largest number between 10, 14 and 12 is 14.0
10
EXPERIMENT -9
OBJECTIVE:
Write a Python program to convert temperatures to and from Celsius, Fahrenheit. [
Formula : c/5 = f-32/9 ]
SOURCECODE:
# Python Program to convert temperature in celsius to fahrenheit
# change this value for a different result
celsius = 37.5
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))
11
EXPERIMENT -10
OBJECTIVE:
Write a Python program to construct the following pattern, using a nested for loop
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
SOURCECODE:
n=5;
for i in range(n):
for j in range(i):
print ('* ', end="")
print('')
for i in range(n,0,-1):
for j in range(i):
print('* ', end="")
print('')
INPUT ANDOUTPUT:
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
EXPERIMENT -11
12
OBJECTIVE:
Write a Python script that prints prime numbers less than 20.
SOURCECODE:
r=int(input("Enter upper limit: "))
for a inrange(2,r+1):
k=0
foriinrange(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(a)
INPUT ANDOUTPUT:
Enter upper limit: 15
2
3
5
7
11
13
EXPERIMENT -12
Write a python program to find factorial of a number using Recursion.
13
SOURCECODE:
# Python program to find the factorial of a number provided by the user.
# change the value for a different result
num = 7
# uncomment to take input from the user
#num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
14
EXPERIMENT -13
Write a program that accepts the lengths of three sides of a triangle as inputs. The
program output should indicate whether or not the triangle is a right triangle (Recall
from the Pythagorean Theorem that in a right triangle, the square of one side equals
the sum of the squares of the other two sides).
SOURCECODE:
# Python Program to find the area of triangle
a=5
b=6
c=7
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
INPUT ANDOUTPUT:
The area of the triangle is 14.70
15
EXPERIMENT -14
OBJECTIVE:
Write a python program to define a module to find Fibonacci Numbers and import the
module to another program.
SOURCECODE:
# Program to display the Fibonacci sequence up to n-th term where n is provided by the user
# change this value for a different result
nterms = 10
# uncomment to take input from the user
#nterms = int(input("How many terms? "))
# first two terms
n1 = 0
n2 = 1
count = 0
# check if the number of terms is valid
if nterms<= 0:
print("Please enter a positive integer")
elifnterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count <nterms:
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
INPUT ANDOUTPUT:
Fibonacci sequence upto10 :
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
Experiment 15
Write a python program to define a module and import a specific function in that
16
module to another program.
SOURCECODE:
# Python Program to find numbers divisible by thirteen from a list using anonymous function
# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]
# use anonymous function to filter
result = list(filter(lambda x: (x % 13 == 0), my_list))
# display the result
print("Numbers divisible by 13 are",result)
INPUT ANDOUTPUT:
Numbers divisible by 13 are [65, 39, 221]
17
EXPERIMENT -16
OBJECTIVE:
Write a script named [Link]. This script should prompt the user for the names of
two text files. The contents of the first file should be input and written to the second
file.
SOURCECODE:
withopen("[Link]")as f:
withopen("[Link]","w")as f1:
for line in f:
[Link](line)
INPUT ANDOUTPUT:
Case 1:
Contents of file([Link]):
Hello world
Output([Link]):
Hello world
Case 2:
Contents of file([Link]):
Sanfoundry
Output([Link]):
Sanfoundry
18
EXPERIMENT -17
OBJECTIVE:
Write a program that inputs a text file. The program should print all of the unique
words in the file in alphabetical order.
SOURCECODE:
items = input("Input comma separated sequence of words")
words = [word for word in [Link](",")]
print(",".join(sorted(list(set(words)))))
INPUT ANDOUTPUT:
Input comma separated sequence of words red, black, pink,
green
black, green, pink, red
19
EXPERIMENT -18
OBJECTIVE:
Write a Python class to convert an integer to a roman numeral.
SOURCECODE:
class py_solution:
def int_to_Roman(self, num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syb = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
20
roman_num = ''
i=0
while num> 0:
for _ in range(num // val[i]):
roman_num += syb[i]
num -= val[i]
i += 1
return roman_num
print(py_solution().int_to_Roman(1))
print(py_solution().int_to_Roman(4000))
INPUT ANDOUTPUT:
I
MMMM
EXPERIMENT -19
OBJECTIVE:
Write a Python class to implement pow(x, n)
SOURCECODE:
class py_solution:
def pow(self, x, n):
if x==0 or x==1 or n==1:
return x
if x==-1:
if n%2 ==0:
return 1
else:
return -1
if n==0:
return 1
if n<0:
return 1/[Link](x,-n)
21
val = [Link](x,n//2)
if n%2 ==0:
return val*val
return val*val*x
print(py_solution().pow(2, -3));
print(py_solution().pow(3, 5));
print(py_solution().pow(100, 0));
INPUT ANDOUTPUT:
0.125
243
EXPERIMENT -20
OBJECTIVE:
Write a Python class to reverse a string word by word.
SOURCECODE:
def reverseWords(input):
# split words of string separated by space
inputWords = [Link](" ")
# reverse list of words
# suppose we have list of elements list = [1,2,3,4],
# list[0]=1, list[1]=2 and index -1 represents
# the last element list[-1]=4 ( equivalent to list[3]=4 )
# So, inputWords[-1::-1] here we have three arguments
# first is -1 that means start from last element
# second argument is empty that means move to end of list
# third arguments is difference of steps
inputWords=inputWords[-1::-1]
# now join words with space
output = ' '.join(inputWords)
return output
22
if name == " main ":
input = 'geeks quiz practice code'
print reverseWords(input)
INPUT ANDOUTPUT:
"code practice quiz geeks"
23