0% found this document useful (0 votes)
141 views

Python Journal

The document outlines a practical journal for Python programming covering topics like basic programs, loops, strings, lists, functions, dictionaries, tuples, file handling, inheritance, regular expressions, GUI programming, and databases. It includes example programs and problems for each topic to help learn and practice various Python concepts.

Uploaded by

cat
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
141 views

Python Journal

The document outlines a practical journal for Python programming covering topics like basic programs, loops, strings, lists, functions, dictionaries, tuples, file handling, inheritance, regular expressions, GUI programming, and databases. It includes example programs and problems for each topic to help learn and practice various Python concepts.

Uploaded by

cat
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Python Programming (PP) Practical Journal

INDEX
Practical 1 - Basic Program
1. Print hello World
2. WAP to accept price and quantity from user and calculate Total Bill.
3. WAP to accept 2 numbers from user and perform swapping of 2 numbers.
4. WAP to accept age from user and check whether user is valid for driving lic or not if user is not
valid for driving lic then also print number of years required to validate.
5. WAP in python to accept number from user and check whether it is positive, negative or zero.

Practical 2 - Loops
1. WAP in Python even numbers n the range 100 to 200.
2. WAP in python to accept number from user and find divisor for number.
3. WAP in python to accept number from user and calculate sum of first n natural numbers.
4. WAP in python to accept number from user and check number is prime number or not.
5. WAP in python to display following pattern 1
22
333
4444
55555
6. WAP in python to count occurrence of even number and odd number between the range (accept
range start and end value from user)
7. WAP in python to accept number from user, calculate and display factorial of any number.
8. WAP in python to display following pattern using do-while loop 1
23
456
7 8 9 10

9. WAP in python to accept numbers from user and check whether it is palindrome or not.

Practical 3 - String
1. WAP in python to count number of vowels from the string
2. WAP in Python to search for specific word from the string
3. WAP in python to check whether the string is palindrome or not
4. WAP in python to find all occurrences of substring in a given string by ignoring the case.

Practical 4 - List
1. Program to find the position of min and max elements of a list in Python
2. Accept 5 integer inputs from the user and store them in a list. Now, copy all the elements in
another list but in reverse order.
3. Write a program in python to display the elements of the list thrice if it is number and display the
element terminated with ‘#’ if it is not a number.
4. Write the program to find at least one common element from the list.
5. Write a program in Python to remove duplicate items from a list.
6. Write a Python program to sum all the items in a list
7. Write a code to convert string into list.
8. Write a program in python to accept 5 integer elements from the list and swap 1st and last
element
9. WAP to accept 10 numbers in the list and separate positive and negative number from the list.

Practical 5 - Function
PAGE 1
Python Programming (PP) Practical Journal

1. Write a function to check the input value is Armstrong and also write the function for
Palindrome.
2. Write a function that returns the maximum of three numbers
3. Write a program to create a function that takes two arguments, name and age of employee and
print their value
4. Write a program to create a function show employee () using the following conditions.
It should accept the employee’s name and salary and display both.
If the salary is missing in the function call, then assign default value 9000 to salary.
5. Write a program that reads a date as an integer in the format MMDDYYYY. The program will
call a function that prints print out the date in the format 
<Month Name> <day>, <year>
12252019 December 25, 2019
6. Write a function called fizz buzz that takes a number.
If the number is divisible by 3, it should return “Fizz”.
If it is divisible by 5, it should return “Buzz”.
If it is divisible by both 3 and 5, it should return “Fizz Buzz”. Otherwise, it should return the
same number.
7. Create a menu driven program using a user defined function to implement a calculator that
performs basic arithmetic operations.
8. Create a program using user defined function named login then accepts userid and password as
parameters - 1) Display message "account blocked" in case of three wrong attempts
2)"Login Successful" if the user enters user id as "ADMIN" and Password as "Password" or
displays "Login Incorrect!!"
9. write a program that uses a user defined function that accepts name and gender (M or F) and
prefix Mr/Mrs on the basis of the gender.
10. Write a program to create user defined function with *args that allows user to pass integer
numbers and perform addition.

Practical 6 - Dictionary
1. Create a dictionary ‘ODD’ of odd numbers between 1 and 10, where the key is the decimal
number and the value is the corresponding number in words.
Display the keys in the dictionary ‘ODD’.
Display the values in the dictionary ‘ODD’.
Display the items from dictionary ‘ODD’
Find the length of the dictionary ‘ODD’.
Check if 7 is present or not in dictionary ‘ODD’
Retrieve the value corresponding to the key 9.
2. Write a program to input your friend’s names and them
phone numbers and store them in the dictionary as the
key-value pair. Perform the following operations on the
dictionary:
a) Display the Name and Phone number for all your
friends.
b) Add a new key-value pair in this dictionary and
display the modified dictionary
c) Delete a particular friend from the dictionary
d) Modify the phone number of an existing friend
e) Check if a friend is present in the dictionary or not
f) Display the dictionary in sorted order of names
3. Write a Python script to concatenate the following dictionaries to create a new one.
Sample Dictionary: dic1= {1:10, 2:20} dic2= {3:30, 4:40} dic3= {5:50,6:60}
PAGE 2
Python Programming (PP) Practical Journal

Expected Result: {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}


4. Write a Python program to sum all the items in a dictionary.
5. Write a Python script to sort (ascending) a dictionary by value.
6. Create dic with all alphabets to display total values of alphabets
dict1= {"A":1,"B":2,"C”: 3, Z}
accept="abc"
uppercase ()
ABC
1+2+3=6

Practical 7 -Tuple
1. Consider the following tuples, tuple1 and tuple2: 
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Perform following:
i)find index of 45 --->            tuple1.index(45)
2)count occurrence of 45 tuple1
3)merge 2 tuples
4)find length of tuple1
5)find max of tuple1
6)find min of tuple1
7)find sum of elements from tuple 2
2. Create the following tuple using for loop
1. a tuple containing the squares of the integer 1 to 10(1,4, 9,100)
2. a tuple ("a","bb","ccc"...) that ends with 5 copies of letter 'e'
3. Perform swapping of 2 numbers
a=int
b-in
before a and b
(a, b) = (b, a)
after a and b
4. Calculate Fibonacci series using tuple - 0 1 1 2 3 5 8
5. Write a program in python to unpack a tuple in several variable
6. Write a program in python to accept the total number of studs from the user.
also marks of 3 subjects. Store that marks in tuple to calculate total of student
and display the same.

Practical 8 -File Handling


1. Write a function in python to read the content from a text file “poem.txt” and display the same on
screen.
2. Write a function in python to count and display the total number of words in a text file.
3. To write the following lines to the text file named hello.txt. Assume that the file is opened in
append mode.
4. Write a program to accept string/sentences from the user till the user enters "END" to save the
data in a text file and then display only those sentences which begin with an uppercase alphabet.
5. Write a function display words () in python to read lines from a text file "story.txt", and display
those words, which are less than 4 characters.

Practical 9 - Inheritance and Regular Expressions


1. WAP to create class number with method get data which will accept 2 numbers from user, create

PAGE 3
Python Programming (PP) Practical Journal

another class multiplication which inherit class number, multiplication class contain method
display mul of 2 numbers.
2. Consider the string=” global warming”. Write the statement in python to implement the
following statement.
1.To display last four characters. 
2.To check whether string has alphanumeric characters or not.
3.To trim the last four characters of strings.
4.To trim the starting four characters of strings.
5.To display the starting index for the substring” wa”.
6.To change the case of the given string.
7.To replace all occurrences of letter ”a” in the stings with”*”. 

Practical 10 - GUI
1. Calculate area and Circumference of the circle.

2. Create bill

Practical 11 – GUI and Database


1. Create a connection with the MySQL Database.
2. WAP in python to create table customers
3. WAP in python to insert inside the table
4. Design a GUI Program to create a student registration form.

Practical 1

PAGE 4
Python Programming (PP) Practical Journal

1. Write a program in python to display hello world message.

Code
print("hello world")

Output

2. Write a program in python to accept price and quantity of product from user and
calculate total price of product.

Code
amt = int(input("Enter the price:"))
quantity = int(input("Enter the quantity:"))
tamt = amt*quantity
print("Total price of the product is:",tamt)

Output

3. Write a program in python to accept 2 numbers from user and perform swapping of
two numbers.

Code
a=int(input("Enter the value for a:"))
b=int(input("Enter the value for b:"))
a=a+b
b=a-b
a=a-b
print("The value of a is:",a)
print("The value of b is:",b)

PAGE 5
Python Programming (PP) Practical Journal

Output

4. Write a program in python to accept age from user and check whether user is valid
for driving or not.

Code
age=int(input("Enter your age:"))
if age>=18:
print("You are eligible for driving license!!!")
else:
print("You have to wait for:",18-age,"years")

Output

5. Write a program in python to accept numbers from user and check whether it is
positive negative and zero.

Code
n =int(input("Enter a number:\n"))
if n>0:
print("Number is positive!")
elif n<0:
print("Number is negative!")
elif n == 0:
print("Number is zero!!")

PAGE 6
Python Programming (PP) Practical Journal

Output

Practical 2
1. Write a program in python to accept even numbers in the range 100to 200.
PAGE 7
Python Programming (PP) Practical Journal

Code
print("Even number are:")
for n in range(100,200,2):
print(n,end=" ")

Output

2. Write a program in python to accept number from user and find divisor for
number.

Code
n=int(input("Enter a number:\n"))
print("Divisors are:")
for a in range(1,int(n / 2)+1):
if n%a==0:
print(a,end=" ")

Output

3. Write a program in python to accept number from user and calculate sum of first n
natural numbers.
Code
n=int(input("Enter a number till which you want to find sum of first n natural
numbers:"))
sum=0
for i in range(0,n+1):
sum=sum+i
print("Sum of first n natural numbers is:",sum)

Output

PAGE 8
Python Programming (PP) Practical Journal

4. Write a program in python to accept number from user and check whether number
is prime or not.

Code
num = int(input('Enter a number:'))
flag = False

if num > 1:
for i in range(2, num):
if (num % i) == 0:
flag = True
break
if flag:
print(num, "is not a prime number !!")
else:
print(num, "is a prime number !!")

Output

5. Write a program in python to display following pattern


1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Code
for a in range (1,6):

PAGE 9
Python Programming (PP) Practical Journal

for b in range(1,a+1):
print(a,end="")

print("\n")

Output

6. Write a program in python to count occurrence of even number and odd number
between the range (accept range start and end value from user).

Code
print("Enter starting no...")
o=0
e=0
a=int(input())
print("Enter ending no..")
b=int(input())
for x in range(a,b+1):
if x%2==0:
e=e+1
else:
o=o+1
print("Odd number=",o)
print("Even number=",e)

Output

PAGE 10
Python Programming (PP) Practical Journal

7. Write a program in python to accept number from user, calculate and display
factorial of any number.

Code
a=int(input("Enter any number:"))
fact=1
while(a>0):
fact=fact*a
a=a-1
print("Factorial:",fact)

Output

8. Write a program in python to display following pattern using do-while loop


1
23
456
78910

Code
n=int(input("Enter number of Rows:"))
count=1
i=1
while(i<=n):
j=1
while(j<=i):
print(count,end="")
count+=1
j+=1
print('\n')
i=i+1

Output

PAGE 11
Python Programming (PP) Practical Journal

9. Write a program in python to accept number from user and check whether it is
palindrome or not.

Code
a=int(input("Enter a Palindrome number:"))
temp=a
rev=0
while (a>0):
dig=a%10
rev=rev*10+dig
a=a//10
if (temp==rev):
print("The number is palindrome")
else:
print("The number is not palindrome")

Output

Practical 3
PAGE 12
Python Programming (PP) Practical Journal

1. Write a program in python to count number of vowels from the string.

Code
mystr=input('Enter Any String:')
count=0
for i in mystr:
if i=='a' or i =='A' or i=='e' or i=='E' or i=='i' or i=='I' or i=='o' or i=='O' or i=='u' or
i=='U':
count+=1

print('From the given string number of vowels are:' , count)

Output

2. Write a program in python to search for specific word from string.

Code
mystr=input('Enter String:')
search=input('Enter keyword:')
my=mystr.lower()
print(my)
if search in my:
print('present')
else:
print('Not present')

Output

3. Write a program in python to check whether the string is palindrome or not.

PAGE 13
Python Programming (PP) Practical Journal

Code
string=input(("Enter a letter:"))
if(string==string[::-1]):
print("The letter is a palindrome")
else:
print("The letter is not a palindrome")

Output

4. Write a program in python to find all occurrences of a sub-string in a given string


by ignoring the case.

Code
a=input("Enter a string to find a substring:")
aa=input("Enter a sub-string:")
a=a.lower()
aa=aa.lower()
print("No. of total occurence is:",a.count(aa))

Output

Practical 4

PAGE 14
Python Programming (PP) Practical Journal

1. Write a program in python to find the position of min and max elements of a list in
python.
Code
l1 = []
for i in range(10):
n =int(input("Enter the number:"))
l1.append(n)

maxNum =max(l1)
minNum =min(l1)
print("Elements in the list",l1)
print("Position of the maximum number is:",l1.index(maxNum))
print("Position of the minimum number is:",l1.index(minNum))

Output

2. Write a program in python to accept 5 integer inputs from the user and store them
in a list. Now, copy all the elements in another list but in reverse order.

Code
l1 = []
l2=[]
revL1=[]
for i in range(5):
n= input("Enter a element:")
l1.append(n)
l2 = l1.copy()
l2.reverse()
print("Elements of l1 are:",l1)
print("Elements of l2 are:",l2)
Output

PAGE 15
Python Programming (PP) Practical Journal

3. Write a program in python to display the elements of the list thrice if it is number
and display the element terminated with’#’ if it is not a number.

Code
l1 = [1,12,56,'abc','lmn',100]
for i in l1:
if(type(i)==int):
print(i,i,i,end=" ")
elif(type(i)==str):
print(i+"#",end=" ")

Output

4. Write a program in python to find at least one common element from the list.

Code
l1 =[1,2,4,25,3,26]
l2 =[4,25,4,26,1]
result=[]
flag=False
for i in l1:
if i in l2:
flag=True
result.append(i)

if(flag):
print(result)
else:
print("No Common numbers:")
Output

PAGE 16
Python Programming (PP) Practical Journal

5. Write a program in python to remove duplicate items from a list.

Code
l1=[]
for i in range(5):
n = int(input('Enter a element:'))
l1.append(n)
l2=[]
for i in range(len(l1)):
if l1[i] not in l2:
l2.append(l1[i])
else:
pass

print("Elements in l1:",l1)
print("Elements in l2:",l2)

Output

6. Write a program in python to sum all the items in a list.

Code
l1 = [10,20,30,40]
print("List is:",l1)
print("Sum of all the elements in the list is:",sum(l1))

Output

7. Write a program in python to convert string into list.

PAGE 17
Python Programming (PP) Practical Journal

Code
s ="hello world abc"
# l1 = s.split(" ")
print(list(s))

Output

8. Write a program in python to accept 5 integer elements from the list and swap 1st
and last element.

Code
l1 =[]
i=0
while i<=5:
n=int(input("Enter a element:"))
l1.append(n)
i+=1
x =l1[0]
l1[0] =l1[-1]
l1[-1] =x
print(l1)

Output

9. Write a program in python to accept 10 numbers in the list and separate positive
and negative number from the list.

PAGE 18
Python Programming (PP) Practical Journal

Code
pos=[]
neg=[]
l1 = []
for i in range(5):
n=int(input("Enter a number:"))
l1.append(n)

for element in l1:


if element>0:
pos.append(element)
elif element in l1:
neg.append(element)

print(pos)
print("list of positive number is:",pos)
print("list of negative number is:",neg)

Output

Practical 5

PAGE 19
Python Programming (PP) Practical Journal

1. Write a function to check the input value is Armstrong and also write the function
for Palindrome.

Code
def armstrong(num):
fnum=0
nstr=str(num)
l=len(str(num))
for x in range(0,1):
t=int(nstr[x])
t=t**l
fnum=fnum+t
if(fnum==num):
print(num,"is an armstrong number")
else:
print(num,"is not an armstrong number")
def palin(num):
s=str(num)
if s==s[::-1]:
print(num,"it's a palindrome number")
else:
print(num,"it's not an palindrome number")

armstrong(7)
palin(151)

Output

2. Write a function that returns the maximum of three numbers.

Code
PAGE 20
Python Programming (PP) Practical Journal

def maxNum(a,b,c):
if a>b and a>c:
return a
elif b>a and b>c:
return b
else:
return c

a= int(input("Enter the first number: "))


b= int(input("Enter the second number: "))
c= int(input("Enter the third number: "))

print("Maximum number from the given nums is:",maxNum(a,b,c))

Output

3. Write a program to create a function that takes two arguments, name and age of
employee and print their value.

Code
def employee(name, age):
print("Name of employee is:",name)
print("Age of employee is:",age)

employee("Rohan","20")

Output

4. Write a program to create a function show employee () using the following


conditions. It should accept the employee’s name and salary and display both. If the
salary is missing in the function call, then assign default value 9000 to salary.

PAGE 21
Python Programming (PP) Practical Journal

Code
def show_employee(name, salary=9000):
print("Name of the employee is:",name)
print("Salary of the employee is:",salary)

show_employee("Rohan")

Output

5. Write a program that reads a date as an integer in the format MMDDYYYY.  The
program will call a function that prints print out the date in the format <Month
Name> <day>, <year> 12252019 December 25, 2019.

Code
def DateFormatter(s):
l=["January","February","March","April","May","June","July","August","September",
"October","November","December"]
month= s[:2]
day = s[2:4]
year = s[4:8]
# print(month,day, year)
print("{}{}, {}".format(l[int(month)-1],day,year))
n=input("Enter a Date in MM/DD/YYY format only: ")
DateFormatter(n)

Output

6. Write a function called fizz buzz that takes a number. If the number is divisible by
3, it should return “Fizz”. If it is divisible by 5, it should return “Buzz”. If it is
divisible by both 3 and 5, it should return “Fizz Buzz”. Otherwise, it should return
the same number.
PAGE 22
Python Programming (PP) Practical Journal

Code
def fizzBuzz(n):
if n%3==0 and n%5 ==0:
print("Number",n,"is Fizzbuzz")
elif n%3==0:
print("Number",n,"is Fizz")
elif n%5==0:
print("Number",n,"is Buzz")

n= int(input("Enter a number:"))
fizzBuzz(n)

Output

7. Create a menu driven program using a user defined function to implement a


calculator that performs basic arithmetic operations.

Code
def calc():
s =""
while(s!="n" or s!="N"):
print("1. Addition")
print("2. Substraction")
print("3. Multiply")
print("4. Division")
operation = int(input("Enter a number from above:"))
if(operation<5 and operation>0):
if(operation ==1 ):
add()
elif(operation == 2):
sub()
elif(operation == 3):
mul()
elif(operation == 4):
div()
s=input("Enter y if you want to continue, else enter n")

def add():
PAGE 23
Python Programming (PP) Practical Journal

a=int(input("Enter first num to add:"))


b=int(input("Enter second num to add:"))
print("Addition is:",a+b)

def sub():
a=int(input("Enter first num to sub:"))
b=int(input("Enter second num to sub:"))
print("Subtraction is:",a-b)
def mul():
a=int(input("Enter first num to mul:"))
b=int(input("Enter second num to mul:"))
print("Multiplication is:",a*b)
def div():
a=int(input("Enter first num to div:"))
b=int(input("Enter second num to div:"))
print("Division is:",a//b)

calc()

Output

8. Create a program using user defined function named login then accepts userid and
password as parameters.

Code
def login():
n=0

PAGE 24
Python Programming (PP) Practical Journal

while(n<=3):
userid =input("Enter userid:")
password =input("Enter password:")
if(userid=="ADMIN" and password=="password"):
# print("Login Successful")
return "Login Successful!!"
else:
n+=1
print("Oops!! Login Incorrect")
# return "Login Incorrect"
return "--Account blocked--"
print(login())

Output

9. Write a program that uses a user defined function that accepts name and gender(M
or F) and prefix Mr/Mrs on the basis of the gender.

Code
def nameFormatter():
name =input("Enter you name")
gender =input("Enter Gender M/F")
if(gender=="M" or gender=="m"):
print("Mr",name)
elif(gender == "F" or gender == "f"):
print("Mrs",name)
nameFormatter()

Output

PAGE 25
Python Programming (PP) Practical Journal

10. Write a program to create user defined function with *args that allows user to
pass integer numbers and perform addition.

Code
def addition(*args):
sum = 0
for arg in args:
temp = int(arg)
sum +=temp
return sum
print(addition(25,26,94))

Output

11. Calculate factorial using recursive function.

Code
def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
print factorial(9)

Output

Practical 6

1. Create a dictionary ‘ODD’ of odd numbers between 1 and 10, where the key is the
decimal number and the value is the corresponding number in words.
Display the keys in the dictionary ‘ODD’.
Display the values in the dictionary ‘ODD’.

PAGE 26
Python Programming (PP) Practical Journal

Display the items from dictionary ‘ODD’


Find the length of the dictionary ‘ODD’.
Check if 7 is present or not in dictionary ‘ODD’
Retrieve the value corresponding to the key 9

Code
ODD={1:"one",3:"three",5:"five",7:"seven",9:"nine"}
print("\nKeys:",end=" ")
for key in ODD.keys():
print(key,end=" ")
print("\nValues:",end=" ")
for value in ODD.values():
print(value,end=" ")

print("\nKey:Values")
for key,value in ODD.items():
print(key,":",value)

print("\nLength of dict ODD is",len(ODD))

for key in ODD.keys():


if key==7:
print("\n7 is present in the dict ODD")

print("\nValue corresponding to the key 9 is",ODD[9])

Output

PAGE 27
Python Programming (PP) Practical Journal

2. Write a program to input your friend’s names and their phone numbers and store
them in the dictionary as the key-value pair. Perform the following operations on
the dictionary:
a) Display the Name and Phone number for all your friends.
b) Add a new key-value pair in this dictionary and display the modified dictionary
c) Delete a particular friend from the dictionary
d) Modify the phone number of an existing friend
e) Check if a friend is present in the dictionary or not
f) Display the dictionary in sorted order of names

Code

from ast import Not


phoneList={"Rohan":1010101010,"Varun":2020202020,"Shyam":3030303030}

def displayPhoneList():
global phoneList
print("Name : Phone Number\n")
for key,value in phoneList.items():
print(key,":",value)

def addNumber():
global phoneList
name=input("Enter the Name of New Contact")
phoneNumber=int(input("Enter Phone Number"))
phoneList[name]=phoneNumber

def deleteNumber():
global phoneList
name=input("Enter the name to delete the Contact")
PAGE 28
Python Programming (PP) Practical Journal

phoneList.pop(name)
print(name,"'s Phone Number is Deleted")

def modifyNumber():
global phoneList
name=input("Enter a number to update")
phoneNumber=int(input("Enter new Number"))
phoneList[name]=phoneNumber

def checkFriend():
global phoneList
name=input("Enter a name to check its availability")
flag1=False
for key in phoneList.keys():
if key == name:
flag1=True
break
if flag1:
print("Name is present in the list")
elif flag1==False:
print("Name is NOT present in the list")

def driverProgram():
flag=True
while(flag):
print("Select one option")
print("1.Display All contacts")
print("2.Add a Contact")
print("3.Delete a Contact")
print("4.Modify a Contact")
print("5.Check Availablitiy of Contact")
num=int(input())
if num==1 :
displayPhoneList()
elif num==2:
addNumber()
elif num==3:
deleteNumber()
elif num==4:
modifyNumber()
elif num==5:
checkFriend()
elif num==6:
flag=False
PAGE 29
Python Programming (PP) Practical Journal

else:
print("Enter a valid Option")

driverProgram()

Output

3. Write a Python script to concatenate the following dictionaries to create a new one.
Sample Dictionary: dic1= {1:10, 2:20} dic2= {3:30, 4:40} dic3= {5:50,6:60}
Expected Result: {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

Code
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}

dic1.update(dic2)
dic1.update(dic3)

print(dic1)

Output

PAGE 30
Python Programming (PP) Practical Journal

4. Write a Python program to sum all the items in a dictionary.

Code
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}

dic1.update(dic2)
dic1.update(dic3)

print(dic1)

Output

5. Write a Python script to sort (ascending) a dictionary by value.

Code
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}

dic1.update(dic2)
dic1.update(dic3)

print(dic1)

Output

6. Create dic with all alphabets to display total values of alphabets


dict1={"A":1,"B":2,"C":3,...Z}
PAGE 31
Python Programming (PP) Practical Journal

accept="abc"
uppercase ()
ABC
1+2+3=6

Code
dict1={"A":1,"B":2,"C":3,"D":4,"E":5,"F":6,"G":7,"H":8,"I":9,"J":10}
accept=input('Enter a string: ')
sum=0
for letter in accept:
letter=letter.upper()
sum+=dict1[letter]
print(sum)

Output

Practical 7
1. Consider the following tuples, tuple1 and tuple2: 
PAGE 32
Python Programming (PP) Practical Journal

tuple1 = (23,1,45,67,45,9,55,45) ,tuple2 = (100,200) perform following:


i)find index of 45 --->            tuple1.index(45)
ii)count occurrence of 45 tuple1
iii)merge 2 tuples
iv)find length of tuple1
v)find max of tuple1
vi)find min of tuple1
vii)find sum of elements from tuple 2

Code
tuple1=(23,1,45,67,45,9,55,45)
tuple2=(100,200)
print("Index of 45 is: ",tuple1.index(45))

count=0
for element in tuple1:
if element ==45:
count+=1
print("Occurance of 45 is:",count)

tupl3=tuple1+tuple2
print("Merged two tuples:",tupl3)

print("Length of tuple1 is:",len(tuple1))

print("Max from the tuple1 is:",max(tuple1))

print("Min from the tuple1 is:",min(tuple1))

print("Sum of tuple1 is:",sum(tuple1))

Output

2. Create the following tuple using for loop


1)= a tuple containing the squares of the integer 1 to 10(1,4,9,...100)
2)= a tuple ("a","bb","ccc"...) that ends with 5 copies of letter 'e.
PAGE 33
Python Programming (PP) Practical Journal

Code
a=()
for i in range(1,10):
a+=(i*i,)
print(a)

a=()
for i in range(1,6):
a+=(chr(i+96)*i,)
print(a)

Output

3. Perform swapping of 2 numbers


a=int
b-in
before a and b
(a,b)=(b,a)
after a and b

Code

a=()
b=()
a=(input("Enter value for a"))
b=(input("Enter value for a"))
print("Value of a before swaping",a)
print("Value of b before swaping",b)
a,b=b,a
print("Value of a after swaping",a)
print("Value of b after swaping",b)

Output

PAGE 34
Python Programming (PP) Practical Journal

4. Calculate Fibonacci series using tuple - 0 1 1 2 3 5 8

Code
fib = (0,1,1)

for i in range(4):
fib+=(fib[i+1]+fib[i+2],)

print(fib)

Output

5. Write a program in python to unpack a tuple in several variable.

Code
t1=(4,5,6,6,7)
(e1,e2,e3,e4,e5)=t1
print(e1,e2,e3,e4,e5)

Output

6. Write a program in python to accept the total number of stud from the user. also
marks of 3 subjects. Store that marks in tuple to calculate total of student and
display the same.

Code
PAGE 35
Python Programming (PP) Practical Journal

n=int(input("Enter the number of students:\n"))


for i in range(n):
marks=()
name=input("Enter your name:\n")
m1=int(input("Enter marks in first subject:\n"))
m2=int(input("Enter marks in second subject:\n"))
m3=int(input("Enter marks in third subject:\n"))
marks+=(m1,m2,m3)
print(name,", Your Total sum of all three subjects is:",sum(marks))

Output

Practical 8

PAGE 36
Python Programming (PP) Practical Journal

1. Write a function in python to read the content from a text file “poem.txt” and
display the same on screen.

Code
file=open("poem.txt","r")
d=file.read()
print(d)
file.close()

Output

2. Write a function in python to count and display the total number of words in a text
file.

Code
def display_count():
file=open("poem.txt","r")
count=0
for line in file:
l=line.split()
count+=len(l)
file.close()
print("Count of words in a text file is: ",count)

display_count()
Output

3. To write the following lines to the text file named hello.txt. Assume that the file is
opened in append mode.

Code
PAGE 37
Python Programming (PP) Practical Journal

file=open("hello.txt","a")
file.write("Hello!! Welcome to the world of python programming.....")
file.close()

Output

4. Write a program to accept string/sentences from the user till the user enters "END"
to save the data in a text file and then display only those sentences which begin with
an uppercase alphabet.

Code
file=open("userinput.txt","r+")
s=""
l=[]
while True:
s=input("Enter something to write in userinput.txt file: ")
if s=="END":
break
if s[0].isupper():
l.append(s)
file.write(s)

for x in l:
print(x)
file.close()

Output

PAGE 38
Python Programming (PP) Practical Journal

5. Write a function display words () in python to read lines from a text file "story.txt",
and display those words, which are less than 4 characters.

Code
def display_words():
file=open("story.txt","r")
for lines in file:
l=lines.split()
for word in l:
if len(word)<4:
print(word,end=" ")
file.close()

display_words()

Output

Practical 9

1. Create a python class named Circle constructed by a radius and two methods which
will compute the area and the perimeter of a circle.

PAGE 39
Python Programming (PP) Practical Journal

Code
class Circle:
def __init__(self,radius):
self.radius=radius

def area(self):
return 3.14*self.radius*self.radius

def peri(self):
return 2*3.14*self.radius

c=Circle(2)
print("Area of the circle is:",c.area())
print("Perimeter of the circle is:",c.peri())

Output

2. Create the class SOCIETY with following information: society name, house no, no
of members, flat, income
Methods 1. An init method to assign initial values of society as "ABC apartments",
flat as "A Type", house no as 20, no of members as 3, income as 25000.
Method 2 Input data () - to read data members (society, house no, no of members &
income) and call e allocate flat (). allocate _flat ()-To allocate flat according to
income
Income Flat
>=25000 A Type
>=20000 and <25000 B Type
<15000 C Type
Show data () - to display the details of the entire class 2.

Code
class Society:
def __init__(self):
self.society_name="ABC Apartments"
self.house_no=20

PAGE 40
Python Programming (PP) Practical Journal

self.no_of_members=3
self.flat="A Type"
self.income=25000

def allocate_flat(self):
if self.income>=25000:
self.flat="A Type"
elif self.income>=20000 and self.income<25000:
self.flat="B Type"
else:
self.flat="C Type"

def Inputdata(self,society_name, house_no, no_of_members, income):


self.society_name=society_name
self.house_no=house_no
self.no_of_members=no_of_members
self.income=income
self.allocate_flat()

def showData(self):
print("**********Following are the Details**********")
print("----------------------------------------------")
print("Society Name is:",self.society_name)
print("House no is:",self.house_no)
print("No of Members is:",self.no_of_members)
print("Flat type is:",self.flat)
print("Income is:",self.income)

user=Society()
user.Inputdata("XYZ apartment",19,4,20000)
user.allocate_flat()
user.showData()

Output

PAGE 41
Python Programming (PP) Practical Journal

3. Create class Student with method accept data to accept following info name, class,
Physics, Chemistry, Maths, marks. Create method display to display students details
and also percentage (accept at least 3 stud info).
.
Code
class Student:
def accept_data(self):
self.name=input("Enter your name:")
self.div=input("Enter your class:")
self.phy=int(input("Enter your marks in phy:"))
self.chem=int(input("Enter your marks in chem:"))
self.maths=int(input("Enter your marks in maths:"))

def display(self):
print("Name :",self.name)
print("Class is:",self.div)
print("Marks in Physics:",self.phy)
print("Marks in Chemistry:",self.chem)
print("Marks in Mathematics:",self.maths)

percentage=(self.phy+self.chem+self.maths)/3
print("Your percentage is :",percentage)
s1=Student()
s2=Student()
s3=Student()
l1=[s1,s2,s3]
for i in range(3):
l1[i].accept_data()

print(l1)
for i in range(3):
l1[i].display()

Output

PAGE 42
Python Programming (PP) Practical Journal

4. Wap to create class number with method get data which will accept 2 numbers from
user, create another class multiplication which inherit class number, multiplication
class contain method display mul of 2 numbers.

Code
class Number:
a=0
b=0
def getData(self):
self.a=int(input("Enter first Number"))
self.b=int(input("Enter second Number"))

class Multi(Number):
def display(self):
print("Multipication of two numbers is",(self.a*self.b))

n1 = Multi()
n1.getData()
n1.display()

Output

PAGE 43
Python Programming (PP) Practical Journal

5. Consider the string = ”global warming”. Write the statement in python to


implement the following statement.
1.) To display last four characters.
Code
import re
string="Global Warming"
print("\n")
a=re.search("....$",string)
print("Last four characters are:",a.group())
n1 = Multi()
n1.getData()
n1.display()

Output

2.) To check whether string has alphanumeric characters or not.


Code
import re
string="Global warming"
print("\n")
a=re.search("\d",string)
if(a):
print("string is alphanumeric")
else:
print("string is not alphanumeric")

Output

PAGE 44
Python Programming (PP) Practical Journal

3.) To trim the last four characters of strings.


Code
import re
string="Global Warming"
b=[]
print("\n")
a=re.search("....$",string)
print("\n")
a=re.search("....$",string)
print(string.replace(a.group(),""))

Output

4.) To trim the starting four characters of strings.


Code
import re
string="Global Warming"
b=[]
print("\n")
a=re.search("^....",string)
print("\n")
a=re.search("^....",string)
print(string.replace(a.group(),""))

Output

PAGE 45
Python Programming (PP) Practical Journal

5.) To display the starting index for the substring “WA”.


Code
import re
string="Global Warming"
b=[]
print("\n")
a=re.search("....$",string)
print("\n")
print("\n")
print(string.find("Wa"))

Output

6.) To change the case of the given string.


Code
import re
string="Global Warming"
if string.islower():
print(string.upper())
else:
print(string.lower())

Output

7.) To replace all occurrences of letter “a” in the strings with “*”.
Code
import re
PAGE 46
Python Programming (PP) Practical Journal

string="Global Warming"
x=""
for i in string:
if i=="a":
x+="*"
else:
x+=i
print(x)

Output

Practical 10

1. Calculate area and Circumference of the circle


PAGE 47
Python Programming (PP) Practical Journal

Code
from tkinter import*

def cal():
r=int(e1.get())
area=3.14*r*r
circum=3.14*r*2
e2.insert(0,area)
e3.insert(0,circum)

def clear():
e1.delete(0,END)
e2.delete(0,END)
e3.delete(0,END)

window=Tk()
l1=Label(window,text="Radius").grid(row=0,column=1)
l2=Label(window,text="area").grid(row=1,column=1)
l3=Label(window,text="circumference").grid(row=2,column=1)

e1=Entry(window)
e1.grid(row=0,column=2)
e2=Entry(window)
e2.grid(row=1,column=2)
e3=Entry(window)
e3.grid(row=2,column=2)

b1=Button(window,text="Clear",command=clear)
b1.grid(row=3,column=0)
b2=Button(window,text="Calculate",command=cal)
b2.grid(row=3,column=1)
mainloop()

Output

PAGE 48
Python Programming (PP) Practical Journal

2. Create bill

Code
import tkinter
from tkinter import *

def calculate():
sum=0
if(var1.get()==1):
sum+=250
if(var2.get()==1):
sum+=300
if(var3.get()==1):
sum+=1000
if(var4.get()==1):
sum+=10
r1.delete('0',END)
r1.insert('0',sum)
discount=0
if(var.get()==1):
discount=0
if(var.get()==2):
discount=sum * 0.05
if(var.get()==3):
discount=sum * 0.1
r2.delete('0',END)
r2.insert('0',discount)
fa=sum-discount
r3.insert('0',fa)
def clear():
r1.delete('0',END)
r2.delete('0',END)
r3.delete('0',END)
c1.deselect()

PAGE 49
Python Programming (PP) Practical Journal

rad = Tk()
canvas_width = 500
canvas_height = 500
w=
Canvas(rad,width=canvas_width,height=canvas_height,bg='green',highlightbackgroun
d='red',
highlightthickness='5',cursor='trek')
rad.title("Jay's Sandwich")
Label(rad,text="Operations").grid(row=0, column=0)
Label(rad,text="Discount").grid(row=0, column=3)
Label(rad,text="Total cost:::").grid(row=7, column=0)
Label(rad,text="Discount:::").grid(row=8, column=0)
Label(rad,text="Net Payable Amount:::").grid(row=9, column=0)
r1 = Entry(rad,bd=5)
r1.grid(row=7,column=1)
r2= Entry(rad,bd=5)
r2.grid(row=8,column=1)
r3= Entry(rad,bd=5)
r3.grid(row=9,column=1)
Button(rad,text="Calculate",command=calculate).grid(row=5,column=1,sticky="NW"
)
Button(rad,text="Clear",command=clear).grid(row=5,column=1,sticky="NE")
var1=IntVar()
Checkbutton(rad,text="Grilled Cheese = 250",variable=var1).grid(row=1,sticky='W')
var2=IntVar()
Checkbutton(rad,text="BLT Sandwich = 300",variable=var2).grid(row=2,sticky='W')
var3=IntVar()
Checkbutton(rad,text="McNuggets = 1000",variable=var3).grid(row=3,sticky='W')
var4=IntVar()
Checkbutton(rad,text="Takeaway = 10",variable=var4).grid(row=4,sticky='W')
var=IntVar()
Radiobutton(rad,text="None",padx=2,variable=var,value=1).grid(row=1,column=3)
Radiobutton(rad,text="5%",padx=2,variable=var,value=2).grid(row=2,column=3)
Radiobutton(rad,text="10%",padx=2,variable=var,value=3).grid(row=3,column=3)
mainloop( )

Output

PAGE 50
Python Programming (PP) Practical Journal

Practical 11
PAGE 51
Python Programming (PP) Practical Journal

3. Create a connection with the MySQL Database.

Code
import mysql.connector
con =mysql.connector.connect(host="localhost",user="root",passwd="")
mycursor=con.cursor()
print("Successfully Connected")
con.close()

Output

4. WAP in python to create table customers


Code
import mysql.connector
mydb1=mysql.connector.connect(host="localhost",user="root",password="",database
="mydb")
mycursor=mydb1.cursor()
mycursor.execute("CREATE TABLE customers(name VARCHAR(255),address
VARCHAR(255))")
print("Table Created Success")

Output

5. WAP in python to Insert inside the table.


Code
import mysql.connector
mydb1 =
mysql.connector.connect(host="localhost",user="root",passwd="",database="mydb")
mycursor = mydb1.cursor()
sql = "INSERT INTO customer(name, address) VALUES ('John','Highway')"
mycursor.execute(sql)
mydb1.commit()

print(mycursor.rowcount,"Record inserted.")
Output

PAGE 52
Python Programming (PP) Practical Journal

6. Design a GUI Program to create a student registration form.

Code
import mysql.connector
mydb1 =
mysql.connector.connect(host="localhost",user="root",passwd="",database="mydb")
mycursor = mydb1.cursor()
sql = "INSERT INTO customer(name, address) VALUES ('John','Highway')"
mycursor.execute(sql)
mydb1.commit()

print(mycursor.rowcount,"Record inserted.")

Output

PAGE 53
Python Programming (PP) Practical Journal

THANK YOU

PAGE 54

You might also like