360 - Python Practical File Final
360 - Python Practical File Final
FILE
E
Submitted BY
Rahul Bansal
University Roll: 1807652
Branch: C.S.E 5th Semester
MIMIT, MALOUT
-1-
INDEX
Submission
S. No. Description Page No.
Date
10 Write a Python script that prints prime numbers less than 20 18 14-09-2020
2
15 Write a Python class to implement pow(x, n) 25 19-10-2020
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('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
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
# 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])
Output
6
Program 4
Write a Program to Demonstrate working with Tuples in Python
Program
#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))
print("\nMethod 2")
tup2 = list(tup2) #recommended only for small tuples.
tup2.insert(0,"Name")
7
tup2.pop()
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
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])
Output
10
11
Program 6
Write a program create, append, remove lists in python
Program
# 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)
lst2.append("appended")
print("Appended item 'appended' to list lst2.append(item): ",lst2)
# appending another list elements to a list
lst2.extend(["extended list",89,8,9])
print("Appended elements from a list lst2.extend(list): ",lst2)
# Inserting element at some index
lst2.insert(0,"inserted at 0")
print("Inserting item at 0th index lst2.insert(0,item): ",lst2)
12
Output
13
Program 7
Write a program to find the largest of three numbers
Program
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
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
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
def fact(n):
if n in [1,0]:
return 1
return n*fact(n-1)
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
Output
18
Program 11
Write a program to check if a triangle is right triangle
Program
sides.sort()
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")
"""
*
**
***
****
***
**
*
"""
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 – Fibonacci.py
Source code
def fib(num):
"""(int) -> list of int
return fib_lst
Source code
import Fibonacci
21
Output
22
Program 14
File 1 – Surprise.py
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
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()
Source code
from Surprise import surprise
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
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.")
def __init__(self,str1):
self.string1 = str1
test = rev_str(in_str)
Output
26
Program 17
Write a script named copyfile.py. 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 – copyfile.py
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 copyfile.py. 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'
text.append(line)
except EOFError:
return text
return text
path = os.getcwd()
print(TRED + "Note - Both the text files will be created at the follwoing
location:"+ DEFAULT)
print(' ',path,'\n')
print(TRED+"\nWarning - If any file with the above names already exists all data
of files will be lost!!\n" + DEFAULT)
27
n")
text = multi_input()
# writing data in the file
f1.writelines(text)
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.
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'
# 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')
29
word_list = sorted(uniq_set)
Output
File – test.txt
30