Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
56 views

Python Programming Lab

The document contains code examples demonstrating decision making and looping statements in Python. It includes programs to find the largest of 3 numbers, check if a number is prime, check if a year is a leap year, display the day of the week using a switch statement, check if a number is a palindrome using a while loop, and add two matrices using nested loops. The code samples take user input, apply logical conditions, and display the output of the programs.

Uploaded by

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

Python Programming Lab

The document contains code examples demonstrating decision making and looping statements in Python. It includes programs to find the largest of 3 numbers, check if a number is prime, check if a year is a leap year, display the day of the week using a switch statement, check if a number is a palindrome using a while loop, and add two matrices using nested loops. The code samples take user input, apply logical conditions, and display the output of the programs.

Uploaded by

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

EX-1 a .

LIST
class check():
def __init__(self):
self.n=[]
def add(self,a):
return self.n.append(a)
def remove(self,b):
self.n.remove(b)
def dis(self):
return (self.n)
obj=check()
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Delete")
print("3. Display")
choice=int(input("Enter choice: "))
if choice==1:
n=int(input("Enter number to append: "))
obj.add(n)
print("List: ",obj.dis())
elif choice==2:
n=int(input("Enter number to remove: "))
obj.remove(n)
print("List: ",obj.dis())
elif choice==3:
print("List: ",obj.dis())
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()

Output
0. Exit 0. Exit
1. Add 1. Add
2. Delete 2. Delete
3. Display 3. Display
Enter choice: 1 Enter choice: 2
Enter number to append: 1 Enter number to remove: 3
List: [1] List: [1, 2]
0. Exit 0. Exit
1. Add 1. Add
2. Delete 2. Delete
3. Display 3. Display
Enter choice: 1 Enter choice: 0
Enter number to append: 2 Exiting!
List: [1, 2]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 3
List: [1, 2, 3]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 3
List: [1, 2, 3]

----------------------------------------------------------------------------------------------------------------
EX-1 b1 . TUPLE
def count_digs(tup):

# gets total digits in tuples


return sum([len(str(ele)) for ele in tup ])

# initializing list
test_list = [(3, 4, 6, 723), (1, 2), (12345,), (134, 234, 34)]

# printing original list


print("The original list is : " + str(test_list))

# performing sort
test_list.sort(key = count_digs)

# printing result
print("Sorted tuples : " + str(test_list))

output
The original list is : [(3, 4, 6, 723), (1, 2), (12345,), (134, 234, 34)]
Sorted tuples : [(1, 2), (12345,), (3, 4, 6, 723), (134, 234, 34)]
>>>
----------------------------------------------------------------------------------------------------------------
EX-1 b2 . TUPLE

# Join Tuples if similar initial element


# Using loop

# initializing list
test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]

# printing original list


print("The original list is : " + str(test_list))

# Join Tuples if similar initial element


# Using loop
res = []
for sub in test_list:
if res and res[-1][0] == sub[0]:
res[-1].extend(sub[1:])
else:
res.append([ele for ele in sub])
res = list(map(tuple, res))

# printing result
print("The extracted elements : " + str(res))

output
The original list is : [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
The extracted elements : [(5, 6, 7), (6, 8, 10), (7, 13)]
----------------------------------------------------------------------------------------------------------------
EX-1 C . BOOK MAINTENANCE USING Dictionary
print("********** Book Maintenance*********")
dict1={'1':'C Programming','2':'Python Programming','3':'Web Programming','4':'Softwre
Engineering'}
print("1. Access the Book....")
print("2. Delete the Book....")
print("3. Add the New Book......")

def get_book():
bid=input("Enter the Book ID....:")
print("Name of the book.......:",end='')
print(dict1.get(bid))
print("--------SUCCESS Book Found--------")
def del_book():
bookid=input("\n\nEnter the Book ID to delete....")
newlist=dict1.pop(bookid)
print("--------SUCCESSFULLY BOOK REMOVED -----")
print("Now the Avaialable books are.....")
print(dict1)
def add_book():
bid1=input("Enter the Book Id....:")
bname1=input("Enter the Book Name to insert....:")
dict1.update({bid1:bname1})
#global dict1
while True:
ch=int(input("Enter your Choice[1/2/3/4]:"))
if(ch==1):
print("\n\n************ ACCESS THE BOOK **********")
print("The Availabe Books.........:")
print(dict1)
get_book()
elif(ch==2):
print("\n\n*********** REMOVE THE BOOK ********")
del_book()
elif(ch==3):
add_book()
else:
print("Program goes to terminate......:")
break
Output:
********** Book Maintenance*********
1. Access the Book....
2. Delete the Book....
3. Add the New Book......
Enter your Choice[1/2/3]:1
************ ACCESS THE BOOK **********
The Availabe Books.........:
{'1': 'C Programming', '2': 'Python Programming', '3': 'Web Programming', '4': 'Softwre
Engineering'}
Enter the Book ID....:3
Name of the book.......:Web Programming
--------SUCCESS Book Found--------
Enter your Choice[1/2/3]:2
*********** REMOVE THE BOOK ********
Enter the Book ID to delete....4
--------SUCCESSFULLY BOOK REMOVED -----
Now the Avaialable books are.....
{'1': 'C Programming', '2': 'Python Programming', '3': 'Web Programming'}
Enter your Choice[1/2/3]:3
Enter the Book Id....:5
Enter the Book Name to insert....:Oracle Data Base
Enter your Choice[1/2/3]:1
************ ACCESS THE BOOK **********
The Availabe Books.........:
{'1': 'C Programming', '2': 'Python Programming', '3': 'Web Programming', '5': 'Oracle
Data Base'}
Enter the Book ID....:5
Name of the book.......:Oracle Data Base
--------SUCCESS Book Found--------
Enter your Choice[1/2/3]:6
Program goes to terminate......:

EX- 2 : a1 . DECISION MAKING –CONTROL STATEMENTS


1.Program to find the largest among 3 numbers (if...elif...else...)
print("To find the largest among 3 numbers")
print("*****************************")
num1=float(input("Enter the 1st number: "))
num2=float(input("Enter the 2nd number: "))
num3=float(input("Enter the 3rd number: "))
print('Numbers Entered Are')
print(" Number1: ",num1)
print(" Number2: ",num2)
print(" Number13: ",num3)
if((num1>num2) and (num1>num3)):
largest = num1
elif((num2>num1)and (num2>num3)):
largest = num2
else:
largest = num3
print("The largest num is:",largest)

-----------------------------------------------------------------
OUTPUT

To find the largest among 3 numbers


*****************************
Enter the 1st number: 21
Enter the 2nd number: 67
Enter the 3rd number: 44
Numbers Entered Are
Number1: 21.0
Number2: 67.0
Number13: 44.0
The largest num is: 67.0

Ex - 2 : a2. Program to find whether the given is prime number or not (if...else...)
print("To find whether the given is prime number or not")
print("****************************************")
num=int(input("Enter the Number:"))
print("you have Entered ",num)
if num>1:
for i in range(1,num):
if(num%i)==0:
f=0
break
else:
f=1
if(f==0):
print(num,"is not a Prime Number")
else:
print(num,"is a Prime Number")
else:
print(num,"is not a Integer or a Positive Number")

-----------------------------------------------------------------

OUTPUT:
To find whether the given is prime number or not
****************************************
Enter the Number:7
you have Entered 7
7 is a Prime Number
>>>
To find whether the given is prime number or not
****************************************
Enter the Number:8
you have Entered 8
8 is not a Prime Number
>>>

Ex 2:a3 . Program to find whether the given year is leap or not (Nested if...)
print("To find whether the given year is leap or not")
print("************************************")
year=int(input("Enter the year....:"))
if(year%100==0):
if(year%400==0):
print("Given",year," is a Leap year...")
else:
print("Given",year,"is not a Leap year")
elif(year%4==0):
print("Given",year," is a Leap year...")
else:
print("Given",year,"is not a Leap year")

OUTPUT:

To find whether the given year is leap or not


************************************
Enter the year....:1900
Given 1900 is not a Leap year

To find whether the given year is leap or not


************************************
Enter the year....:2022
Given 2022 is not a Leap year

To find whether the given year is leap or not


************************************
Enter the year....:2024
Given 2024 is a Leap year...
-----------------------------------------------------------------------------
#4. Program using switch statement to display Sunday to Saturday
def switch(num):
dict={
1: 'Sunday',
2: 'Monday',
3: 'Tuesday',
4: 'Wednesday',
5: 'Thursday',
6: 'Friday',
7: 'Saturday'
}
return dict.get(num, 'Invalid Day')
num= int(input("Enter the Option"))
print(' The number is:', num, 'and the day is:',switch(num))

OUTPUT:
Enter the Option2
The number is: 2 and the day is: Monday
>>>
Enter the Option5
The number is: 5 and the day is: Thursday
-------------------------------------------------------------------------------

EX-2 b. DECISION MAKING –LOOPING STATEMENTS


2:b1. To check whether a given is a Palindrome using while statement
print("Find the given number is Palindrome")
n=int(input("Enter the number"))
sum=0
a=n
while(n>0):
m=n%10
sum=sum*10+m
n=n//10
if(sum==a):
print("The given number is Palindrome")
else:
print("The given number is not Palindrome")

OUTPUT:

Find the given number is Palindrome


Enter the number121
The given number is Palindrome
>>>
Enter the number125
The given number is not Palindrome

2:b2. Program to add two matrices using nested loop


X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

for r in result:
print(r)
OUTPUT:
[17, 15, 4]
[10, 12, 9]
[11, 13, 18]

2:b2 . Program to find the sum of n numbers


number = int(input("Enter the Number: "))
sum = 0
for value in range(1, number + 1):
sum = sum + value
print(sum)
OUTPUT:

Enter the Number: 10


55
----------------------------------------------------------------------------------------------------------------

EX-3 REGULAR EXPRESSION

Python program to check whether the password is valid or not with the help of few
conditions.

Primary conditions for password validation :

1. Minimum 8 characters.
2. The alphabets must be between [a-z]
3. At least one alphabet should be of Upper Case [A-Z]
4. At least 1 number or digit between [0-9].
5. At least 1 character from [ _ or @ or $ ].

Program:
# Python program to check validation of password
# Module of regular expression is used with search()
import re
print("--------PASSWORD VALIDATION USING REGUALR EXPRESSION-----")
print(" *********************************************")
password=input("Enter the Password......:")
#password = "R@m@_f0rtu9e$"
flag = 0
while True:
if (len(password)<8):
flag = -1
break
elif not re.search("[a-z]", password):
flag = -1
break
elif not re.search("[A-Z]", password):
flag = -1
break
elif not re.search("[0-9]", password):
flag = -1
break
elif not re.search("[_@$]", password):
flag = -1
break
elifre.search("\s", password):
flag = -1
break
else:
flag = 0
print("You entered :",password,"Valid Password")
break
if flag ==-1:
print("You entered ",password," Not a Valid Password")

Output:
>>>
RESTART:
C:/Users/Admin/AppData/Local/Programs/Python/Python37/passvaliditysun.py
--------PASSWORD VALIDATION USING REGUALR EXPRESSION-----
*********************************************
Enter the Password......:As_r@$76
You entered : As_r@$76 Valid Password
>>>
RESTART:
C:/Users/Admin/AppData/Local/Programs/Python/Python37/passvaliditysun.py
--------PASSWORD VALIDATION USING REGUALR EXPRESSION-----
*********************************************
Enter the Password......:mynati@86ch
You entered mynati@86ch Not a Valid Password

4. CALENDAR FUNCTIONS
Program:

import calendar
def dispcal():
year=int(input("Enter the year........:"))
calendar.prcal(year)
def dispmonth():
year1=int(input("Enter the year........"))
mon1=int(input("Enter the month........"))
print(calendar.month(year1,mon1))
print("----------CALENDAR FUNCTIONS-------")
print("1.DISPLAY THE CALENDAR....")
print("2.DISPLAY THE MONTH.....")
while True:
choice = int(input("Enter your choice :"))
if choice == 1:
dispcal()
elif choice == 2:
dispmonth()
else:
print("program goes to terminate.......:")
break
print("Bye.....")
Output:
>>>
>>> ============ RESTART =====================
>>>
-------CALENDAR FUNCTIONS-------
1.DISPLAY THE CALENDAR....
2.DISPLAY THE MONTH....
Enter your choice :1
Enter the year.....:2020
5. SIMPLE CALCULATION USING TKINTER
from tkinter import *
class MyWindow:
def __init__(self, win):
self.lbl1=Label(win, text='First number')
self.lbl2=Label(win, text='Second number')
self.lbl3=Label(win, text='Result')
self.t1=Entry(bd=3)
self.t2=Entry()
self.t3=Entry()
self.btn1 = Button(win, text='Add')
self.btn2=Button(win, text='Subtract')
self.lbl1.place(x=100, y=50)
self.t1.place(x=200, y=50)
self.lbl2.place(x=100, y=100)
self.t2.place(x=200, y=100)
self.b1=Button(win, text='Add', command=self.add)
self.b2=Button(win, text='Subtract')
self.b2.bind('<Button-1>', self.sub)
self.b1.place(x=100, y=150)
self.b2.place(x=200, y=150)
self.lbl3.place(x=100, y=200)
self.t3.place(x=200, y=200)
def add(self):
self.t3.delete(0, 'end')
num1=int(self.t1.get())
num2=int(self.t2.get())
result=num1+num2
self.t3.insert(END, str(result))
def sub(self, event):
self.t3.delete(0, 'end')
num1=int(self.t1.get())
num2=int(self.t2.get())
result=num1-num2
self.t3.insert(END, str(result))

window=Tk()
mywin=MyWindow(window)
window.title('Hello Python')
window.geometry("400x300+10+10")
window.mainloop()

You might also like