PRACTICAL
FILE
E
Submitted BY
Rahul Bansal
University Roll: 1807652
Branch: C.S.E 5th Semester
Programming in Python Lab
December 2020
MIMIT, MALOUT
-1-
INDEX
Submission
S. No. Description Page No.
Date
Write a Program to demonstrate different number Data Types
1 4 12-08-2020
in Python
Write a program to perform different Arithmetic Operations
2 5 24-08-2020
on numbers in Python
Write a Program to create, concatenate and print a string and
3 6-7 24-08-2020
accessing sub-string from a given string
Write a Program to Demonstrate working with Tuples in
4 8-10 31-08-2020
Python
5 Write a program to demonstrate working with Dictionaries 8 - 10 31-08-2020
6 Write a program create, append, remove lists in python 12-13 07-09-2020
7 Write a program to find the largest of three numbers 14 07-09-2020
Write a program to convert temperatures to and from Celsius
8 15 07-09-2020
and Fahrenheit
9 Write a python program to find factorial of a number using 16-17 14-09-2020
Recursion
10 Write a Python script that prints prime numbers less than 20 18 14-09-2020
11 Write a program to check if a triangle is right angled 19 21-09-2020
12 Write a Python program to construct the following pattern, 20 21-09-2020
using a nested for loop
13 Write a python program to define a module to find Fibonacci 21-22 12-10-2020
Numbers and import the module to another program
14 Write a python program to define a module and import a 23-24 12-10-2020
specific function in that module to another program
2
15 Write a Python class to implement pow(x, n) 25 19-10-2020
16 Write a Python class to reverse a string word by word 26 19-10-2020
Write a script named [Link]. This script should prompt
17 the user for the names of two text files. The contents of the 27-28 20-10-2020
first file should be input and written to the second file
18 Write a program that inputs a text file. The program should 29-30 20-10-2020
print all of the unique words in the file in alphabetical order
3
Program 1
Write a Program to demonstrate different number Data Types in Python
Program
print("\nTask - 1 Print Different Number Data Types\n")
print('int type',type(2))
print('float type', type(2.2))
x = 5 + 5j
print('complex type',type(x))
Output
4
Program 2
Write a program to perform different Arithmetic Operations on numbers
in Python
Program
print("Pr 2. Write a program to perform different Arithmetic Operations
on numbers in Python.\n")
x=5
y = 10
z = 6.9
w = 10.2
print("x =",x,", y =",y,", z =",z,", w =",w)
print("\nAddition x+y: ",x+y,", x+z:","%0.2f"%(x+z),", z+w:","%0.2f"%
(z+w))
print("\nsubtraction x-y: ",x-y,", z-x:","%0.2f"%(z-x),", z-w:","%0.2f"%(z-
w))
print("\nDivision y/x: ",y/x,", z/x:","%0.2f"%(z/x),", integer division:
w/x",w//z)
print("\nMultiplication x*y: ",x*y,", z*w: ",z*w,", z*y: ",z*y)
print("\nModules y%x: ",y%x,", z%x:","%0.2f"%(z%x),", w%x:","%0.2f"%
(w%x))
print("\nPower x^2: ",x**2,", z^2:","%0.2f"%(z**2),", y^x:",y**x)
Output
5
Program 3
Write a Program to create, concatenate and print a string and accessing
sub-string from a given string
Program
print("\nPr 3. Write a program to create, concatenate and print a string
and accessing sub- string from a given string.\n")
# Creating string
str1 = "This is a string"
str2 = " for program 3"
# Printing string
print("str1 : ",str1)
print("str2 : ",str2)
# Concatenating strings
print("\nConcatenating Strings")
str3 = str1 + str2
print("str3 = str1 + str2 : ",str3)
# Accessing sub-string
print("\nMethod 1 - Indexing and Slicing :")
print("accesing only 3th element: ",str1[2])
print("accessing only first 4 characters: ",str1[:4])
print("\nMethod 2 - looping :")
tmp = ""
for i in range(len(str3)):
if i not in [1,2,3,9,25,23]:
tmp += str3[i]
print(tmp)
Output
6
Program 4
Write a Program to Demonstrate working with Tuples in Python
Program
print("Pr 4 : Write a program to demonstrate working with tuples.\n")
#Empty tuple
x = ()
print("Initializing an empty tuple: ",x,type(x))
#Tuple methods
tup1 = (1,2,3,4,5)
print("the tuple is: ",tup1)
print("number of elements in the tuple is: ",len(tup1))
# Tuples can be multivalued and multidimensional
tupmul = (1,2,"name",5.6,"Tuple")
tupdim = ((1,2),(4,5),(6,7),("srt1","str2"),100,200)
print("MultiValued tuple: ",tupmul,type(tupmul))
# Accessing elements of tuple
tup2 = ("Rahul","CSE","5Th",360,1807652,8.90)
print("\nAccessing tuple elements using Indexing and slicing")
print("tup2: ",tup2)
print("1st element tup2[0]: ",tup2[0])
print("3rd element tup2[2]: ",tup2[2])
print("last element tup2[-]: ",tup2[-1])
print("2nd to 5th element tup2[1:5]: ",tup2[1:5])
print("Skiping 1 element in between tup2[0::2]",tup2[0::2])
# Tuples are Immutable
print("\nTuples are Immutable.")
print("Method 1 to modify a tuple")
print("create a new tuple and assign to the same variable")
print("tup2: ",tup2)
# Modify first value
tup2 = tup2[1:]
print("Modified tup2 removed first element: ",tup2)
temp = ("Abhishek",)
temp2 = tup2[:]
tup2 = (temp+temp2) #Concatenating tuples
print("Modified tup2 added element at 1st index: ",tup2)
print("\nMethod 2")
tup2 = list(tup2) #recommended only for small tuples.
[Link](0,"Name")
7
[Link]()
tup2 = tuple(tup2)
print("Modifies tup2 added element at index 0 and removed last
element: ",tup2)
#Opertions on tuple
print("\nOperations on tuple")
tup3 = (10, 20, 30, 40, 50.5, 100, 89)
print("tup3: ", tup3)
print("Sum of all elements sum(tup3): ", sum(tup3))
print("max element from max(tup3): ", max(tup3))
print("min element from min(tup3): ", min(tup3))
print("scalar multiplication of tuple tup3*2: ", tup3*2)
print("Type conversion to list is allowed list(tup3): ", list(tup3),
type(list(tup3)))
Output
8
Program 5
Write a program to demonstrate working with Dictionaries
Program
print("Pr 5 : Write a program to demonstrate working with dictionaries
in python\n")
# creating Empty Dictionary
dict1 = {}
print("Creating empty dictionary:",dict1,type(dict1))
# Initializing dictionary, it takes key, value pair
dict2 = {1 : "one", 2 : "Two", 3 : "Three"}
print("Simple dictionary:",dict2)
# Dict. can be multivalued
dict2 = {1 : "one", "Two" : 2, "four" : "4" , 5 : 5, 2 : 2, (1,2) : "tuple key",
"tuple" : (1,2,3)}
print("Dictionaries can be multivalued:",dict2)
# Dictionaries key can not be of immutable data type for e.g. list
# any two keys in dictionary can't be same they are always different
print("\nDictionaries can contain same values")
print("dict2['Two']",dict2['Two'],"dict2[2]",dict2[2])
print("\nDictionaries key are immutable and are always Unique")
print("If we try to create the dictionary { 1 : 'one', 'two' : 2, [1,2] :
'list'} then ")
try:
dict_temp = {1: 'one', 'two': 2, [1, 2]: 'list'}
except Exception as error:
print(error, " -- This is error occurs")
# Accessing elements of a dictioanry
print("\nAccessing elements of a dictionary")
print("dictionaries are unordered so we can not use indexing instead
we use keys to access there values")
dict2 = {1 : "one", "Two" : 2, "four" : "4" , 5 : 5, (1,2) : "tuple key", "tuple"
: (1,2,3)}
print("Dictionary dict2:",dict2)
print("Accessing element with key 1 dict2[1]:", dict2[1])
print("Accessing element with key 'four' dict2['four']:", dict2['four'])
print("Accessing element with key (1,2) dict2[(1,2)]:", dict2[(1,2)])
print("To get all the keys in a dictionary [Link]():",[Link]())
print("to get all the values in a dictioanry [Link]():",[Link]())
# Dictionaries are Mutable
print("\nDictioanries are Mutable")
dict3 = {"name" : "Rahul", "Rollno" : 360, "Class" : "CSE"}
9
dict3["name"] = "Harri"
print("changing the value of key name in dict3['name'] = 'Harri':
",dict3["name"])
dict3["Rollno"] = 1313
print("changing some value in dict3['Rollno'] = : 1313: ",dict3["Rollno"])
dict3['Class'] = 5
print("changing some value in dict3['Class'] = 5: ",dict3['Class'])
# Looping on dictionaries
print("Looping on dictionaries")
print(dict2)
for i in dict2:
print(i,dict2[i])
# Get method in dictionary
print("Get method in dictionary")
print("If we key is not present than to avoid error we use get for eg.")
print("dictionary is dict3: ",dict3)
print("dict3['Std']: ",[Link]('std'))
print("other variation dict3[123]: ",[Link](123,"invalid key"))
Output
10
11
Program 6
Write a program create, append, remove lists in python
Program
print("Pr 6 : Write a program to create, append, and remove lists in
python")
# Creating Empty list
lst1 = []
print("Empty list: ",lst1,type(lst1))
# Initializing a list
# list are multivalued
lst2 = [10,"Hello",(1,2),{"Dictionary" : 89}]
print("Initializing a multivalued list lst2: ",lst2)
# nested lists or Multidimensional lists
lst3 = [89,["nested","list"],[3,"dimensions",["3rd"]] ]
print("Nested lists or Multidimensional list lst3: ",lst3)
# Appending items
print("\nlst2: ",lst2)
[Link]("appended")
print("Appended item 'appended' to list [Link](item): ",lst2)
# appending another list elements to a list
[Link](["extended list",89,8,9])
print("Appended elements from a list [Link](list): ",lst2)
# Inserting element at some index
[Link](0,"inserted at 0")
print("Inserting item at 0th index [Link](0,item): ",lst2)
# Removing items from list
lst2 = [10,"Hello",(1,2),{"Dictionary" : 89},"appended","extended",89]
print("\nlst2: ",lst2)
rem_item = [Link]()
print("Removing item at last pos. from list [Link](): ",lst2)
print("removed item: ",rem_item)
# Removing element by value
print("removing item by its value [Link](10): ",[Link](10))
#Removing item by index
[Link](-2)
print("Removing item by index [Link](index): ",lst2)
12
Output
13
Program 7
Write a program to find the largest of three numbers
Program
print("Pr 7 : Write a python program to find largest of three numbers.\
n")
def max3(a,b,c):
if a>=b:
if a>=c:
return a
else:
return c
elif b>a:
if b>=c:
return b
else:
return c
a = float(input("Enter first no.: "))
b = float(input("Enter second no.: "))
c = float(input("Enter third no.: "))
num = max3(a,b,c)
print("\nBiggest no. is: ",num)
Output
14
Program 8
Write a program to convert temperatures to and from Celsius and
Fahrenheit
Program
print("Pr 8 : Write a Python program to convert temperatures to and
from Celsius, Fahrenheit.\n")
print("1. Press 1 for Celsius to Fahrenheit conversion.")
print("2. Press 2 for Fahrenheit to Celsius conversion.\nEnter here: ")
con = int(input())
if con == 1:
temp = float(input("Enter the temperature in Celsius: "))
far = float(temp*(9/5)+32)
print(f"\nThe Temperature {temp} degree celsius in Fahrenheit is
{far}")
else:
temp = float(input("Enter the temperature in Fahrenheit: "))
cel = float((temp-32)*5/9)
print(f"\nThe Temperature {temp} degree Fahrenheit in Celsius is
{cel}")
Output
15
16
Program 9
Write a python program to find factorial of a number using Recursion.
Program
print("Pr 9 : Write a python program to find factorial of a number using
Recursion.\n")
def fact(n):
if n in [1,0]:
return 1
return n*fact(n-1)
n = int(input("Enter an Integer to find its factorial: "))
print(f"The factorial of {n} is: ",fact(n))
Output
17
Program 10
Write a Python script that prints prime numbers less than 20
Program
print("Pr 10 :Write a Python script that prints prime numbers less than
20\n")
def isprime(n):
for i in range(2,n//2 + 1):
if n%i == 0:
return False
return True
print("Here are the prime numbers less than 20:")
for i in range(2,21):
if isprime(i):
print(i,end=" ")
Output
18
Program 11
Write a program to check if a triangle is right triangle
Program
print("Pr 11 :Write a program to check if a triangle is right triangle.\n")
print("Enter the sides of the triangle")
sides = []
for i in range(3):
[Link](float(input()))
[Link]()
def is_right(sides):
if pow(sides[2],2) == pow(sides[0],2) + pow(sides[1],2):
return True
if is_right(sides):
print(f"\nThe triangle with sides {sides[2]}, {sides[1]}, {sides[0]} is a
right angled triangle")
else:
print("\nThe triangle is not a right angled triangle")
Output
19
Program 12
Write a Program to construct to construct the following patter, using a
nested for loop
Program
print("Pr 12 :Write a Python program to construct the following pattern, using a nested for
loop\n")
"""
*
**
***
****
***
**
*
"""
n = int(input("Enter an odd number(>=3) for pattern printing: "))
print("Printing pattern....")
k=2
for i in range(n+1):
if i <= (n+1)/2:
for j in range(i):
print("*",end=" ")
else:
for j in range(i-k):
print("*",end=" ")
k += 2
print()
Output
20
Program 13
Write a python program to define a module to find Fibonacci Numbers
and import the module to another program
Note – Both the files are in the same directory.
File 1 – [Link]
Source code
# This is the custom module with one function fib
def fib(num):
"""(int) -> list of int
The function returns a list containing fibonacci series numbers"""
if num == 1:
return [0]
if num == 2:
return [0,1]
fib_lst = [0,1]
for i in range(2,num):
j = fib_lst[i-1] +fib_lst[i-2]
fib_lst.append(j)
return fib_lst
File 2 – Pr 13. WAP to import custom module and use it
Source code
import Fibonacci
print("""Pr 13 : Write a python program to define a module to find
Fibonacci Numbers
and import the module to another program.""")
#Calling fib function from custom module Fibonacci
print("\nThe first 20 fibonacci series numbers are: ")
result = list(map(str,[Link](20)))
print(" ".join(result))
21
Output
22
Program 14
Write a python program to define a module and import a specific function
in that module to another program.
Note – Both the files are in the same directory.
File 1 – [Link]
Source code
def fact(n):
res = 1
for i in range(1,n+1):
res = res*i
return res
def surprise(num):
""" (int) -> prints something
Function takes an integer input and prints something."""
for i in range(num):
for j in range(1,num-i):
print(" ",end="")
for k in range(0,i+1):
coff = int(fact(i)/(fact(k)*fact(i-k)))
print(" ",coff,end=" ")
print()
File 2 – Pr 14. WAP to import a specific function from custom module
Source code
from Surprise import surprise
print("""Pr 14 : Write a python program to define a module and import
a specific function in that module to another program.\n""")
# calling the importes function
surprise(10)
23
Output
24
Program 15
Write a program to implement pow(x,n) in a class.
Program
print("""Write a Python class to implement pow(x, n)""")
class pow:
def __init__(self,x,n):
self.x = x
self.n = n
def __call__(self):
x = self.x
n = self.n
sum = 1
for i in range(n):
sum = sum * x
return sum
x = float(input("\nEnter the number whom u want to calculate pow: "))
n = int(input("Enter the degree(power) of the number: "))
test = pow(x,n)
# we use __add__ magic function to make the object behave
#like a function
print()
print(f'{test() : .2f}')
Output
25
Program 16
Write a Python class to reverse a string word by word
Program
print("Write a Python class to reverse a string word by word.")
# creating a class to reverse a string
class rev_str:
def __init__(self,str1):
self.string1 = str1
# this will make object callable like a function.
def __call__(self, *args, **kwargs):
string1 = self.string1
fin_str = ''
for i in reversed(string1):
fin_str += i
return fin_str
in_str = input("Enter the string you want to reverse: ")
test = rev_str(in_str)
# usign __call__ magic method to make object behave like a function.
print(test())
Output
26
Program 17
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.
File – [Link]
Source Code
import os
# I used ANSI escape code (ANSI style text) to display colored text.
# It may not show the colored text in windows CMD depending upon VT100
# terminal emulation is enabled or not. It will work on pycharm.
TBLUE = '\033[34m'
TRED = '\033[31m'
TGREEN = '\033[32m'
DEFAULT = '\033[m'
print(TGREEN+ """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.\n""" + DEFAULT)
def multi_input():
text = []
try:
while True:
line = input() + '\n'
[Link](line)
except EOFError:
return text
return text
path = [Link]()
print(TRED + "Note - Both the text files will be created at the follwoing
location:"+ DEFAULT)
print(' ',path,'\n')
file1_name = input("Enter the name of first text file: ")
file2_name = input("Enter the name of second text file : ")
print(TRED+"\nWarning - If any file with the above names already exists all data
of files will be lost!!\n" + DEFAULT)
# writing contents to first file and copying them
with open(path+'/'+file1_name+'.txt','w+') as f1:
# erasing any previous content in the file if exists
[Link](0)
# input the data
print("Enter the text you want to write to the file, Ctrl-D (windows) to save it:\
27
n")
text = multi_input()
# writing data in the file
[Link](text)
# reading the file content inputed by the user
[Link](0)
content = [Link]()
print("\nThe content of the file is:")
print(TBLUE+content+DEFAULT)
# writing to the second file
with open(path+'/'+file2_name+'.txt','w+') as f2:
[Link](0)
[Link](content)
Output
28
Python Program 18
Write a program that inputs a text file. The program should print all of the
unique words in the file in alphabetical order.
File – Pr 18. unique [Link]
Source code
# These ANSI escape code(ANSI style text) will only work in pycharm or
# may work in windows terminal if VT100 terminal emulation is enabled
TBLUE = '\033[34m'
TRED = '\033[31m'
TGREEN = '\033[32m'
DEFAULT = '\033[m'
print(TGREEN + """Write a program that inputs a text file. The program
should print all of the
unique words in the file in alphabetical order.""" + DEFAULT)
# Uncomment below 2 lines to use the below GUI method
#from [Link] import askopenfile
#file = askopenfile('r')
# Comment the below whole loop to use the above GUI method
while True:
path = input("Enter the path of the file: ").replace("\\","/")
try:
file = open(path,'r')
break
except:
print('Invalid path!, try again')
# reading the file text
text = [Link]().replace('\n',' ').split(' ')[:-1]
# closing the opened file
[Link]()
# getting unique words in the text
uniq_set = set()
for word in text:
uniq_set.add(word)
# sorting in alphabetical order
29
word_list = sorted(uniq_set)
# displaying the words
print("The unique words in alphabetical order:")
for word in word_list:
print(TBLUE+word)
Output
File – [Link]
30