GE3171 - Python Lab PDF
GE3171 - Python Lab PDF
output:
Enter value of x: 10
Enter value of y: 20
.
The value of x after swapping: 20
The value of y after swapping: 10
Few Other Methods to Swap variables
Without Using Temporary variable
Program:
x=5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)
output:
x = 10
y=5
.
Program:
A=list(input("Enter the list Values:"))
print(A)
for i in range(1,len(A),1):
print(A[i:]+A[:i])
Output:
Enter the list Values: '0123'
['0','1', '2', '3']
['1','2', '3', '0']
['2', '3','0', '1']
['3','0', '1', '2']
Program:
import math
y2 = int(input("y2 = "))
Output:
Enter coordinates for Point 1:
x1 = 2
y1 = 3
Enter coordinates for point 2:
x2 = 3
y2 = 4
Program:
# Fibonacci series
print("Fibonacci series")
Num_of_terms = int(input("Enter number of terms : "))
f1 = -1
f2 = 1
for i in range(0,Num_of_terms,1):
term = f1+f2
print(term, end=" ")
f1 = f2
f2 = term
Output:
Fibonacci series :
Enter number of terms : 5
01123
.
Program:
# list of numbers
list1 = [10, 21, 4, 45, 66, 93]
Output:
21,45,93
.
Program:
rows = int(input('Enter the number of rows'))
for i in range(rows):
for j in range(i+1):
print(j+1, end=' ')
print(' ')
Output:
Enter the number of rows
6
1
22
333
4444
55555
666666
Program:
rows = int(input('Enter the number of rows'))
for i in range(rows):
for j in range(i+1):
print(“*”, end=' ')
print('\n ')
Output:
#creating a list
Library=['OS','OOAD','MPMC']
print(" Books in library are:")
print(Library)
OUTPUT :
Books in library are:
['OS', 'OOAD', 'MPMC']
OUTPUT :
Accessing a element from the
list OS
MPMC
OUTPUT :
Accessing a element from a Multi-Dimensional list OOAD
TOC
#Negative indexing
Library=['OS','OOAD','MPMC']
print("Negative accessing a element from the list")
print(Library[-1])
print(Library[-2])
OUTPUT :
Negative accessing a element from the
list MPMC
OOAD
.
#Slicing
Library=['OS','OOAD','MPMC','TOC','NW']
print(Library[1][:-3])
print(Library[1][:4])
print(Library[2][2:4])
print(Library[3][0:4])
print(Library[4][:])
OUTPUT :
O OOAD MC TOC NW
#append()
Library=['OS','OOAD','MPMC']
Library.append(“DS”)
Library.append(“OOPS”)
Library.append(“NWs”)
print(Library)
OUTPUT :
['OS', 'OOAD', 'MPMC', 'DS', 'OOPS', 'NWs']
#extend()
Library=['OS','OOAD','MPMC']
Library.extend(["TOC","DWDM"])
print(Library)
OUTPUT :
['OS', 'OOAD', 'MPMC', 'TOC', 'DWDM']
#insert()
Library=['OS','OOAD','MPMC']
Library.insert(0,”DS”)
print(Library)
OUTPUT :
['DS', 'OS', 'OOAD', 'MPMC']
#del method
Library=['OS','OOAD','MPMC']
del Library[:2]
print(Library)
OUTPUT :
['MPMC']
.
#remove()
Library=['OS','OOAD','MPMC','OOAD']
Library.remove('OOAD')
print(Library)
OUTPUT :
['OS', 'MPMC', 'OOAD']
#reverse()
Library=['OS','OOAD','MPMC']
Library.reverse()
print(Library)
OUTPUT :
['MPMC', 'OOAD', 'OS']
#sort()
Library=['OS','OOAD','MPMC']
Library.sort()
print(Library)
OUTPUT :
['MPMC', 'OOAD', 'OS']
#+concatenation operator
Library=['OS','OOAD','MPMC']
Books=['DS','TOC','DMDW']
print(Library+Books)
OUTPUT :
['OS', 'OOAD', 'MPMC', 'DS', 'TOC', 'DMDW']
# *replication operator
Library=['OS','OOAD','MPMC','TOC','NW']
print('OS' in Library)
print('DWDM' in Library)
print('OS' not in Library)
.
OUTPUT :
True
False
False
#count()
Library=['OS','OOAD','MPMC','TOC','NW']
x=Library.count("TOC")
print(x)
OUTPUT :
1
.
Program:
bk_list=["OS","MPMC","DS"]
print("Welcome to library”")
while(1):
ch=int(input(" \n 1. add the book to list \n 2. issue a book \n 3. return the book \n 4. view the
book list \n 5. Exit \n"))
if(ch==1):
bk=input("enter the book name")
bk_list.append(bk)
print(bk_list)
elif(ch==2):
ibk=input("Enter the book to issue")
bk_list.remove(ibk)
print(bk_list)
elif(ch==3):
rbk=input("enter the book to return")
bk_list.append(rbk)
print(bk_list)
elif(ch==4):
print(bk_list)
else:
break
.
Output:
Welcome to library”
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
1
enter the book name NW
['OS', 'MPMC', 'DS', ' NW']
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
2
Enter the book to issue
NW ['OS', 'MPMC', 'DS']
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
3
enter the book to return
NW ['OS', 'MPMC', 'DS', '
NW']
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
4
['OS', 'MPMC', 'DS', ' NW']
.
Program:
cc=['Engine','Front xle','Battery','transmision']
com=input('Enter the car components:')
cc.append(com)
print("Components of car :",cc)
print("length of the list:",len(cc))
print("maximum of the list:",max(cc))
print("minimum of the list:",min(cc))
print("indexing(Value at the index 3):",cc[3])
print("Return 'True' if Battery in present in the list")
print("Battery" in cc)
print("multiplication of list element:",cc*2)
.
Output:
Enter the car components:Glass
Components of car : ['Engine', 'Front xle', 'Battery', 'transmision', 'Glass']
length of the list: 5
maximum of the list: transmision
minimum of the list: Battery
indexing(Value at the index 3): transmision
Return 'True' if Battery in present in the list
True
multiplication of list element: ['Engine', 'Front xle', 'Battery', 'transmision', 'Glass',
'Engine', 'Front xle', 'Battery', 'transmision', 'Glass']
.
Program:
cc=['Bricks','Cement','paint','wood']
cc.sort()
print("sorted List")
print(cc)
print("Reverse List")
cc.reverse()
print(cc)
print("Insert a value 'glass' to the list")
cc.insert(0, 'Glass')
print(cc)
print("Delete List")
del cc[:2]
print(cc)
print("Find the index of Cement")
.
print(cc.index('Cement'))
print(“New list”)
new=[]
for i in cc:
if “n” in i:
new append(i)
print(new)
Output:
sorted List
['Bricks', 'Cement', 'paint', 'wood']
Reverse List
['wood', 'paint', 'Cement', 'Bricks']
Insert a value 'glass' to the list
['Glass', 'wood', 'paint', 'Cement', 'Bricks']
Delete List
['paint', 'Cement', 'Bricks']
Find the index of Cement
1
New List
['paint', 'Cement']
.
Program:
book=("OS","MPMC","DS")
book=book+("NW",)
print(book)
print(book[1:2])
print(max(book))
print(min(book))
book1=("OOAD","C++","C")
print(book1)
new=list(book)
print(new)
del(book1)
print(book1)
.
OUTPUT :
('OS', 'MPMC', 'DS', 'NW')
('MPMC',)
OS
DS
('OOAD', 'C++', 'C')
['OS', 'MPMC', 'DS', 'NW']
Traceback (most recent call last):
File "C:/Portable Python 3.2.5.1/3.py", line 12, in <module>
print(book1)
NameError:Book1 is not defined
.
Program:
cc=('Engine','Front axle','Battery','transmision')
y=list(cc)# adding a value to a tuple means we have to convert to a list y[1]="Gear"
cc=tuple(y)
print(cc)
y=list(cc)# removing a value from tuple. y.remove("Gear")
cc=tuple(y)
print(cc)
new=(" Handle",)
print(type(new))
Output :
('Engine', 'Gear', 'Battery', 'transmision')
('Engine', 'Battery', 'transmision')
<class 'tuple'>
.
Program:
cm=('sand','cement','bricks','water')
a,b,c,d = cm
# tuple unpacking
print("\nValues after unpacking: ")
print(a)
print(b)
print(c)
print(d)
print(cm.count('sand'))
print(cm.index('sand'))
new=tuple("sand")
print(new)
print(sorted(cm))
print(type(sorted(cm)))
Output :
Values after unpacking:
sand
cement
bricks
water
1
0
('s', 'a', 'n', 'd')
['bricks', 'cement', 'sand', 'water']
<class 'list'>
.
Program:
Language={}
print(" Empty Dictionary :",Language)
Language=dict({1: "english", "two": "tamil", 3: "malayalam"})
print(" Using dict() the languages are :",Language)
New_Language={4: "hindi",5: "hindi"}#duplicate values can create
Language.update(New_Language)
print(" the updated languages are :",Language)
print(" the length of the languages :",len(Language))
Language.pop(5)
print(" key 5 has been popped with value :",Language)
print(" the keys are :",Language.keys())
print(" the values are :",Language.values())
print(" the items in languages are :",Language.items())
Language.clear()
print(" The items are cleared in dictionary ",Language)
del Language
print(Language)
.
OUTPUT :
Empty Dictionary : {}
Using dict() the languages are : {1: 'english', 3: 'malayalam', 'two': 'tamil'}
the updated languages are : {1: 'english', 3: 'malayalam', 4: 'hindi', 'two': 'tamil', 5: 'hindi'}
key 5 has been popped with value : {1: 'english', 3: 'malayalam', 4: 'hindi', 'two': 'tamil'}
the items in languages are : dict_items([(1, 'english'), (3, 'malayalam'), (4, 'hindi'), ('two',
'tamil')])
print(Language)
.
Program:
auto_mobile={}
print(" Empty dictionary ",auto_mobile)
auto_mobile=dict({1:"Engine",2:"Clutch",3:"Gearbox"})
print(" Automobile parts :",auto_mobile)
print(" The value for 2 is ",auto_mobile.get(2))
auto_mobile['four']="chassis"
print(" Updated auto_mobile",auto_mobile) print(auto_mobile.popitem())
print(" The current auto_mobile parts is :",auto_mobile)
print(" Is 2 available in automobile parts")
print(2 in auto_mobile)
OUTPUT :
Empty dictionary {}
Automobile parts : {1: 'Engine', 2: 'Clutch', 3: 'Gearbox'} The
value for 2 is Clutch
Updated auto_mobile {1: 'Engine', 2: 'Clutch', 3: 'Gearbox', 'four': 'chassis'} (1, 'Engine')
The current auto_mobile parts is : {2: 'Clutch', 3: 'Gearbox', 'four': 'chassis'}
Is 2 available in automobile parts True
.
Program:
civil_ele={}
print(civil_ele)
civil_ele=dict([(1,"Beam"),(2,"Plate")])
print(" the elements of civil structure are ",civil_ele)
print(" the value for key 1 is :",civil_ele[1])
civil_ele['three']='concrete'
print(civil_ele)
new=civil_ele.copy()
print(" The copy of civil_ele",new)
print(" The length is ",len(civil_ele))
for i in civil_ele:
print(civil_ele[i])
.
OUTPUT :
{}
the elements of civil structure are {1: 'Beam', 2: 'Plate'}
the value for key 1 is : Beam
{1: 'Beam', 2: 'Plate', 'three': 'concrete'}
The copy of civil_ele {1: 'Beam', 2: 'Plate', 'three': 'concrete'}
The length is 3
Beam
Plate
Concrete
.
Program:
def factorial(n):
if n==0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n)
OUTPUT :
Input a number to compute the factorial : 5
120
.
Program:
def largest(n):
list=[]
print("Enter list elements one by one")
for i in range(0,n):
x=int(input())
list.append(x)
print("The list elements are")
print(list)
large=list[0]
for i in range(1,n):
if(list[i]>large):
large=list[i]
print("The largest element in the list is",large)
n=int(input("Enter the limit"))
largest(n)
.
OUTPUT :
Enter the limit5
Enter list elements one by one
10
20
30
40
50
The list elements are
[10, 20, 30, 40, 50]
The largest element in the list is 50
.
Program:
def rect(x,y):
return x*y
def circle(r):
PI = 3.142
return PI * (r*r)
def triangle(a, b, c):
Perimeter = a + b + c
s = (a + b + c) / 2
Area = math.sqrt((s*(s-a)*(s-b)*(s-c)))
print(" The Perimeter of Triangle = %.2f" %Perimeter)
print(" The Semi Perimeter of Triangle = %.2f" %s)
print(" The Area of a Triangle is %0.2f" %Area)
def parallelogram(a, b):
return a * b;
# Python program to compute area of rectangle
l = int(input(" Enter the length of rectangle : "))
b = int(input(" Enter the breadth of rectangle : "))
a = rect(l,b)
print("Area =",a)
# Python program to find Area of a circle
num=float(input("Enter r value of circle:"))
print("Area is %.6f" % circle(num))
# python program to compute area of triangle
import math
triangle(6, 7, 8)
# Python Program to find area of Parallelogram
Base = float(input("Enter the Base : "))
Height = float(input("Enter the Height : "))
Area =parallelogram(Base, Height)
print("The Area of a Parallelogram = %.3f" %Area)
.
Output:
Area = 6
Enter r value of
circle:2 Area is
12.568000
Output:
dlroW ,olleH
Program:
string=input(("Enter a
string:")) if(string==string[::-
1]):
print("The string is a
palindrome") else:
print("Not a palindrome")
Output:
Enter a string: madam
The string is a
palindromeEnter a
string: nice
Not a palindrome
Program:
a=input(" enter
thestring") count
= 0;
#Counts each character
except space for i in range(0,
len(a)):
if(a[i] != ' '):
count = count + 1;
#Displays the total number of characters present in the given
stringprint("Total number of characters in a string: " + str(count));
Output:
enter the string hai
Total number of characters in a string: 3
Program:
Output:
String after replacing with given
character: Once in a blue mhhn
Program:
Output:
1 a
2 b
3 c
4 d
5 e
dtype: object
Program:
import numpy as np
#Array without zero value
x = np.array([1, 2, 3, 4,])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
#Array with zero value
x = np.array([0, 1, 2, 3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
Output:
Original array:
[1 2 3 4]
Test if none of the elements of the said array is zero:
True
Original array:
[0 1 2 3]
Test if none of the elements of the said array is zero:
False
Program:
Output:
Program:
Output:
1000.0
8.0
1.0
0.707106781187
Program:
with open("file.txt") as f:
with open("sample.txt", "w") as f1:
for line in f:
f1.write(line)
Output:
Output:
Number of arguments: 4 arguments.
Argument List: ['cmd.py', 'arg1', 'arg2', 'arg3']
Program:
Output:
['hai', 'this', 'is', 'parvathy', 'how', 'are', 'you', 'all', 'read', 'well', 'all', 'best', 'for', 'university',
'exams.']
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)
Output:
Enter First Number: 12.5
Invalid Input Please Input Integer...
def main():
#single try statement can have multiple except statements.
try:
age=int(input("Enter your age"))
if age>18:
print("'You are eligible to vote'")
else:
print("'You are not eligible to vote'")
except ValueError:
print("age must be a valid number")
except IOError:
print("Enter correct value")
#generic except clause, which handles any exception.
except:
print("An Error occured")
main()
Output:
Enter your age20.3
age must be a valid number
def main():
try:
mark=int(input(" Enter your mark:"))
if(mark>=50 and mark<101):
print(" You have passed")
else:
print(" You have failed")
except ValueError:
print(" It must be a valid number")
except IOError:
print(" Enter correct valid number")
except:
print(" an error occured ")
main()
Output:
Enter your mark:50
You have passed
Enter your mark:r
It must be a valid number
Enter your mark:0
You have failed
Program:
pygame.init()
speed = [1, 1]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("'C:\\Users\\parvathys\\Downloads\\ball1.png")
ballrect = ball.get_rect()
while 1:
speed[0] = -speed[0]
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
Output:
Program:
import pygame
pygame.init() #initializes the Pygame
from pygame.locals import* #import all modules from Pygame
screen = pygame.display.set_mode((798,1000))
#changing title of the game window
pygame.display.set_caption('Racing Beast')
#changing the logo
logo = pygame.image.load('C:\\Users\\parvathys\\Downloads\\car game/logo.png')
pygame.display.set_icon(logo)
#defining our gameloop function
def gameloop():
#setting background image
bg = pygame.image.load(''C:\\Users\\parvathys\\Downloads\\car game/bg.png')
# setting our player
maincar = pygame.image.load(''C:\\Users\\parvathys\\Downloads\\car game\car.png')
maincarX = 100
maincarY = 495
maincarX_change = 0
maincarY_change = 0
#other cars
car1 = pygame.image.load(''C:\\Users\\parvathys\\Downloads\\car game\car1.png')
car2 = pygame.image.load(''C:\\Users\\parvathys\\Downloads\\car game\car2.png')
car3 = pygame.image.load(''C:\\Users\\parvathys\\Downloads\\car game\car3.png')
run = True
while run:
for event in pygame.event.get():if
event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
maincarX_change += 5
if event.key == pygame.K_LEFT:
maincarX_change -= 5
if event.key == pygame.K_UP:
maincarY_change -= 5
if event.key == pygame.K_DOWN:
maincarY_change += 5
#CHANGING COLOR WITH RGB VALUE, RGB = RED, GREEN, BLUE
screen.fill((0,0,0))
#displaying the background image
screen.blit(bg,(0,0))
#displaying our main car
screen.blit(maincar,(maincarX,maincarY))
#displaing other cars
screen.blit(car1,(200,100))
screen.blit(car2,(300,100))
screen.blit(car3,(400,100))
#updating the values
maincarX += maincarX_change
maincarY +=maincarY_change
pygame.display.update()
gameloop()
Output: