Python Programming Lab Manual
Python Programming Lab Manual
(AUTONOMOUS)
OBJECTIVES:
LIST OF EXPERIMENTS
1 a) Write a program to purposefully raise Indentation Error and correct it.
b) Write a program to compute distance between two points taking input
from the user (Pythagorean Theorem).
c) Write a program add.py that takes 2 numbers as command line
arguments and prints its sum.
2 a) Write a Program for checking whether the given number is a even
number or not.
b) Using for loop, write a program that prints out the decimal equivalents
of 1/2, 1/3, 1/4, . . . , 1/10.
c) Write a program using for loop that loops over a sequence. What is
sequence?
d) Write a program using a while loop that asks the user for a number,
and prints a countdown from that number to zero.
3 a) Find the sum of all the primes below two million.
b) Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will
be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
By considering the terms in the Fibonacci sequence whose values do
not exceed four million, find the sum of the even-valued terms.
c) Write a program to count the numbers of characters in the given string
and store them in a dictionary data structure
d) Write a program to use split and join methods in the given string and
trace a birthday with a dictionary data structure.
4 a) Write a program to combine two lists into a dictionary.
b) Write a program to count frequency of characters in a given file. Can
you use character frequency to tell whether the given file is a Python
program file, C program file or a text file?
5 a) Write a program to print each line of a file in reverse order.
b) Write a program to compute the number of characters, words and
lines in a file.
6 a) Write a function ball _collide that takes two balls as parameters and
computes if they are colliding. Your function should return a Boolean
representing whether or not the balls are colliding.
Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the
radius. If (distance between two balls centers) <= (sum of their radii)
then (they are colliding)
b) Find mean, median, mode for the given set of numbers in a list.
7 a) Write a function nearly_ equal to test whether two strings are nearly
equal. Two strings a and b are nearly equal when a can be generated
by a single mutation on b.
b) Write a function dups to find all duplicates in the list.
c) Write a function unique to find all the unique elements of a list.
8 a) Write a function cumulative_product to compute cumulative product
of a list of numbers.
b) Write a function reverse to reverse a list. Without using the reverse
function.
9 Create a Regular Expression and implement the following
a) Recognize the following strings: “bat,” “bit,” “but,” “hat,” “hit,” or
“hut.”
b) Match any pair of words separated by a single space, i.e., first and last
names.
c) Match any word and single letter separated by a comma and single
space, as in last name, first initial.
10 Write a python program to implement multithreading scenarios.
11 Write a python program to simulate the banking operations using Class.
12 Write a python program to demonstrate the Queue / Stack operations
using Class.
INDEX
1.
a) Write a program to purposefully raise Indentation Error and correct it.
Example1-
Program:
if5>2:
Output:
Example 2-
Program:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Output:
1 b)Write a program to compute distance between two points taking input from the
user (Pythagorean Theorem).
Program:
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print(result)
Output:
1 c)Write a program add.py that takes 2 numbers as command line arguments and
prints its sum.
Output:
python add.py 5 7
The result is: 12
2.a)Write a Program for checking whether the given number is a even number or
not.
Program:
n=int(input("Number"))
if n%2==0:
print("Number is even")
else:
print("Number is odd")
Output:
2.b)Using for loop, write a program that prints out the decimal equivalents of 1/2,
1/3, 1/4, ..1/10.
Program:
fori in range(2,11):
print(1/i)
Output:
2.c)Write a program using for loop that loops over a sequence. What is sequence?
Strings
byteSequences
byte arrays
lists
tuples
range objects
Program:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Output:
2.d)Write a program using a while loop that asks the user for a number, and prints
a countdown from that number to zero.
Program:
n=int(input("number"))
while n>=0:
print(n)
n=n-1
Output:
s=0
fori in range(2,2000000):
f=0
for j in range(2,int(i**0.5)+1):
ifi%j==0:
f=f+1
break
if f==0:
s=s+i
print("sum is",s)
Output:
Sum is 142,913,828,922
3 .b) Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21,
34, 55, 89
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
Program:
s=0
while(i<n-2):
c=a+b
if(c%2==0):
s=s+c
a=b
b=c
3 .c)Write a program to count the numbers of characters in the given string and
store them in a dictionary data structure
Program:
x=input("enter string")
r={}
fori in x:
ifi in r:
r[i]+=1
else:
r[i]=1
print(r)
Output:
3.d)Write a program to use split and join methods in the given string and trace a
birthday with a dictionary data structure.
Program:
str1=input("Enter date of birth:")
sp=str1.split(".")
bday='/'.join(sp)
d1={"birthday":bday
}
if "birthday" in d1:
print(d1["birthday"])
Output:
t1=["name","clg","age"]
t2=["abc","mrec",34,]
res = {}
for key in t1:
for value in t2:
res[key] = value
t2.remove(value)
break
print(res)
Output:
4.b)Write a program to count frequency of characters in a given file. Can you use
character frequency to tell whether the given file is a Python program file, C
program file or a text file?
Program:
import collections
importpprint
file_input = input('File Name: ')
with open(file_input, 'r') as info:
count = collections.Counter(info.read().upper())
value = pprint.pformat(count)
print(value)
Output:
File Name: abc.txt
Counter({' ': 93,
'E': 64,
'N': 45,
'A': 42,
'T': 40,
'I': 36,
'O': 31,
'R': 29,
'H': 25,
'D': 19,
'M': 17,
'Y': 17,
'L': 15,
'F': 15,
'U': 14,
'C': 13,
MREC (A) Page 16
DEPARTMENT OF CSE PYTHON PROGRAMMING LAB
'G': 13,
'S': 12,
',': 7,
'B': 6,
'W': 5,
'9': 5,
'.': 4,
'P': 4,
'1': 3,
'\n': 2,
'0': 2,
'3': 2,
':': 1,
'-': 1,
'K': 1,
'(': 1,
')': 1,
'V': 1})
Program:
textfile=open("a_file.txt")
lines=textfile.readlines()
for line inreversed(lines):
print(line)
Output:
ghi
def
abc
file=open("sample.txt","r")
number_of_lines=0
number_of_words=0
number_of_characters=0
for line infile:
line=line.strip("\n")#won'tcount \n as character
words=line.split()
number_of_lines+=1
number_of_words+=len(words)
number_of_characters+=len(line)
file.close()
print("lines:", number_of_lines, "words:", number_of_words, "characters:",
number_of_characters)
OUTPUT:
lines: 3 words: 5 characters: 29
6.a)Write a function ball _collide that takes two balls as parameters and computes
if they are colliding. Your function should return a Boolean representing whether
or not the balls are colliding.
Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the radius. If
(distance between two balls centers) <= (sum of their radii) then (they are
colliding)
Program:
defball_collide(b1,b2):
if int( b1[2])<=int(b2[2]):
return True
else:
return False
a=int(input(“enter a number”))
b=int(input(“enter a number”))
c=int(input(“enter a number”))
d=int(input(“enter a number”))
e=int(input(“enter a number”))
f=int(input(“enter a number”))
ball1=(a,b,c)
ball2=(d,e,f)
status=ball_collide(ball1,ball2)
if status==True:
print(“balls are collided”)
else:
print(“balls are not collided”);
OUTPUT:
enter a number3
enter a number4
enter a number5
enter a number6
enter a number7
enter a number5
balls are collided
6.b)Find mean, median, mode for the given set of numbers in a list.
Program:
n_num = [1, 2, 3, 4, 5]
n = len(n_num)
get_sum = sum(n_num)
mean = get_sum / n
if n % 2 == 0:
median1 = n_num[n//2]
median2 = n_num[n//2 - 1]
median = (median1 + median2)/2
else:
median = n_num[n//2]
print("Median is: " + str(median))
data = Counter(n_num)
get_mode = dict(data)
mode = [k for k, v in get_mode.items() if v ==
max(list(data.values()))]
if len(mode) == n:
get_mode = "No mode found"
else:
get_mode = "Mode is / are: " + ', '.join(map(str,
mode))
print(get_mode)
OUTPUT:
7(a)Write a function nearly equal to test whether two strings are nearly equal. two
strings a and b are nearly equal when a can be generated by a single mutation on b
Program:
Description:Two strings are said to be nearly equal if a single mutation applied to
one string will result in another string. That means, Given two strings s1 and s2,
find if s1 can be converted to s2 with exactly one edit(mutation). If yes, then the
function should return a True value as the result. Otherwise, it must return a False
value as the result.
defnearly_equal(str1,str2):
count=0
i=j=0
while(i<len(str1) and j<len(str2)):
if(str1[i]!=str2[j]):
count=count+1
if(len(str1)>len(str2)):
i=i+1
elif(len(str1)==len(str2)):
pass
else:
i=i-1
if(count>1):
return False
i=i+1
j=j+1
if(count<2):
return True
OUTPUT:
Description: We need to write a function dups to find all duplicate elements in the
list. If an element is repeated more than once in the list, then add that repeated
element to the resultant list.
Program:
def dups(numlist):
duplicates={}
forele in numlist:
c=numlist.count(ele)
if(c>=2):
duplicates[ele]=c
print("Duplicate elements are:\n",duplicates)
return
numlist=[]
n=int(input("Enter number of elements to be insert:\n"))
fori in range(n):
ele=int(input("Enter element"))
numlist.append(ele)
dups(numlist)
OUTPUT:
Description:We need to write a function unique to find all unique elements in the
list. If an element is found only once in the list, then add that element to the
resultant list.
Program:
def unique(numlist):
uniqueele=[]
forele in numlist:
c=numlist.count(ele)
if(c==1):
uniqueele.append(ele)
print("Unique elements are:\n",uniqueele)
return
numlist=[]
n=int(input("Enter number of elements to be insert:\n"))
fori in range(n):
ele=int(input("Enter element"))
numlist.append(ele)
unique(numlist)
OUTPUT:
OUTPUT:
$python main.py
8 b) Write a function reverse to reverse a list. Without using the reverse function.
[5, 4, 3, 2, 1]
Program:
import re
String1=”hi hitman had you gone for batting”
x = re.findall("bat", String1)
print(x)
String3=”butterfly is colorfull”
x= re.findall("but", String3)
print(x)
String4=”hat is oval in shape”
x= re.findall("hat", String4)
print(x)
String5=”ramana is living in the hut,hits mosquitoes in the evening”
x= re.findall("hut|hit", String5)
print(x)
OUTPUT:
[“batting”]
[“bitten”]
[“butterfly”]
[“hat”]
[“hut”]
9.b)Match any pair of words separated by a single space, i.e., first and last names.
Program:
import re
s1="vamshi krishna is learning java,vamshi krishna is eagerly waiting for learning
python"
s2=re.findall("vamshi krishna",s1)
print(s2)
OUTPUT:
['vamshikrishna', 'vamshikrishna']
9.c)Match any word and single letter separated by a comma and single space, as in
last name, first initial.
Program:
defprintInitials(string: str):
length = len(string)
# to remove any leading or trailing spaces
string.strip()
# to store extracted words
t = ""
fori in range(length):
ch = string[i]
ifch != ' ':
# forming the word
t += ch
# when space is encountered
# it means the name is completed
# and thereby extracted
else:
# printing the first letter
# of the name in capital letters
print(t[0].upper() + ". ", end="")
t = ""
temp = ""
# for the surname, we have to print the entire
# surname and not just the initial
# string "t" has the surname now
for j in range(len(t)):
# first letter of surname in capital letter
if j == 0:
temp += t[0].upper()
# rest of the letters in small
else:
temp += t[j].lower()
# printing surname
print(temp)
# Driver Code
if __name__ == "__main__":
string = "ishitabhuiya"
printInitials(string)
OUTPUT:
I. Bhuiya
import thread
import time
while 1:
pass
OUTPUT:
Program:
class Account:
def_init_(self):
self.balance=0
print('Your Account is Created.')
def deposit(self):
amount=int(input('Enter the amount to deposit:'))
self.balance+=amount
print('Your New Balance =%d' %self.balance)
def withdraw(self):
amount=int(input('Enter the amount to withdraw:'))
if(amount>self.balance):
print('Insufficient Balance!')
else:
MREC (A) Page 31
DEPARTMENT OF CSE PYTHON PROGRAMMING LAB
self.balance-=amount
print('Your Remaining Balance =%d' %self.balance)
def enquiry(self):
print('Your Balance =%d' %self.balance)
account= Account()
account.deposit()
account.withdraw()
account.enquiry()
OUTPUT:
Your Account is Created.
Enter the amount to deposit: 5000
Your New Balance = 5000
Enter the amount to withdraw: 2000
Your Remaining Balance = 3000
Your Balance = 3000
class Stack:
def __init__(self):
self.items=[]
defis_empty(self):
returnself.items==[]
def push(self, data):
self.items.append(data)
def pop(self):
returnself.items.pop()
def display(self):
returnself.items
s= Stack()
while True:
print("push value ")
print("pop")
print("quit")
print("display")
do= input("What would you like to do?").split()
operation= do[0].strip().lower()
if operation== "push":
s.push(int(do[1]))
elif operation== "pop":
ifs.is_empty():
print("Stack is empty")
else:
print("Popped value:", s.pop())
elif operation=="display":
print(s.display())
elif operation=="quit":
break
OUTPUT: