Program:
P = int( input("Please enter value for P: "))
Q = int( input("Please enter value for Q: "))
# To swap the value of two variables
# we will user third variable which is a temporary
variable temp= P
P=Q
Q = temp
print ("The Value of P after swapping: ",
P) print ("The Value of Q after
swapping:", Q)
Output:
Please enter value for P: 10
Please enter value for Q: 20
The Value of P after swapping: 20
The Value of Q after swapping: 10
Program:
no_of_terms = int(input("Enter number of
values : "))
#Read values list1 = [] for val in
range(0,no_of_terms,1): ele =
int(input("Enter integer : "))
list1.append(ele)
#Circulate and display values
print("Circulating the elements of list ",
list1) for val in
range(0,no_of_terms,1): ele =
list1.pop(0) list1.append(ele)
print(list1)
Output:
Enter number of values : 5
Enter integer : 10
Enter integer : 20
Enter integer : 25
Enter integer : 15
Enter integer : 5
Circulating the elements of list [10, 20, 25, 15, 5]
[20, 25, 15, 5, 10]
[25, 15, 5, 10, 20]
[15, 5, 10, 20, 25]
[5, 10, 20, 25, 15]
[10, 20, 25, 15, 5]
Program:
import math
x1 [4, 0] x2 =
[6, 6]
distance = math.sqrt( ((x1[0]-x2[0])**2)+((x1[1]-x2[1])**2) )
print(distance)
Output:
6.324555320336759
Program:
print("Enter the range of number:")
n=int(input())
sum=0 for i in
range(1,n+1):
sum+=i*i
print("The sum of the series = ",sum)
Output:
Enter the range of number:
5
The sum of the series = 55
Program:
rows = int(input("Enter the number of
rows: ")) # Outer loop will print number
of rows for i in range(rows+1):
# Inner loop will print the value of i after each
iteration
for j in range(i): print(i, end=" ") # print
number
# line after each row to display pattern
correctly print(" ")
Output:
Enter the number of rows: 5
1
22
333
4444
55555
Program:
print("Print equilateral triangle Pyramid with characters ")
s=5
asciiValue = 65 m
= (2 * s) - 2 for i
in range(0, s):
for j in range(0, m):
print(end=" ")
# Decreased the value of after each iteration
m = m - 1 for j in range(0,
i + 1): alphabate =
chr(asciiValue)
print(alphabate, end=' ')
# Increase the ASCII number after each iteration
asciiValue += 1
print()
Output:
Print equilateral triangle Pyramid with characters
A
BC
DEF
GHIJ
KLMNO
Program:
# Iterative Binary Search Function
# It returns index of x in given array arr if present,
# else returns -1 def
binary_search(arr,
x): low = 0
high = len(arr) -
1 mid = 0 while
low <= high:
mid = (high + low) // 2
# If x is greater, ignore left
half if arr[mid] < se:
low = mid + 1
# If x is smaller, ignore right
half elif arr[mid] > se:
high = mid - 1
# means x is present
at mid else:
return mid
# If we reach here, then the element was not present
return -1 # Test array arr = [] size = int(input("Enter the size
of the array: ")) for i in range(size): x = int(input("Enter the
element at {} position in the array: ".format(i+1)))
arr.append(x)
arr.sort() print("array
elements are: ") for
lists in arr:
print(lists,end="\t")
se = int(input("\nEnter the array element to be searched: "))
result =
binary_search(arr, se) if
result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
Output:
Enter the size of the array: 5
Enter the element at 1 position in the array: 12
Enter the element at 2 position in the array: 2
Enter the element at 3 position in the array: 65
Enter the element at 4 position in the
array: 89 Enter the element at 5 position
in the array: 7 array elements are:
2 7 12 65 89
Enter the array element to be searched: 2
Element is present at index 0
Program:
# Python code for various list
operation # declaring a list of
integers
iList = [10, 20, 30, 40, 50, 60, 70, 80,
90, 100]
# List slicing
operations # printing
the complete list
print('iList: ',iList)
# printing first element
print('first element:
',iList[0]) # printing
fourth element
print('fourth element: ',iList[3])
# printing list elements from 0th index to
4th index print('iList elements from 0 to 4
index:',iList[0: 5]) # printing list -7th or
3rd element from the list print('3rd or -7th
element:',iList[-7])
# appending an element to the list
iList.append(111)
print('iList after
append():',iList)
# finding index of a specified element
print('index of \'80\': ',iList.index(80))
# sorting the elements of iLIst
iList.sort() print('after
sorting: ', iList);
# popping an element
print('Popped elements is: ',iList.pop())
print('after pop(): ', iList);
# removing specified
element iList.remove(80)
print('after removing \'80\':
',iList)
# inserting an element at specified index
# inserting 100 at 2nd
index iList.insert(2,
100) print('after insert:
', iList)
# counting occurances of a specified element
print('number of occurences of \'100\': ',
iList.count(100))
# extending elements i.e. inserting a list
to the list iList.extend([11, 22, 33])
print('after extending:', iList)
#reversing the list
iList.reverse()
print('after reversing:',
iList)
Output:
iList: [10, 20, 30, 40, 50, 60, 70, 80,
90, 100] first element: 10 fourth
element: 40
iList elements from 0 to 4 index: [10, 20, 30, 40, 50]
3rd or -7th element: 40
iList after append(): [10, 20, 30, 40, 50, 60, 70, 80, 90,
100, 111] index of '80': 7
after sorting: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
111] Popped elements is: 111
after pop(): [10, 20, 30, 40, 50, 60, 70, 80,
90, 100] after removing '80': [10, 20, 30, 40,
50, 60, 70, 90, 100] after insert: [10, 20, 100,
30, 40, 50, 60, 70, 90, 100] number of
occurences of '100': 2
after extending: [10, 20, 100, 30, 40, 50, 60, 70, 90, 100,
11, 22, 33] after reversing: [33, 22, 11, 100, 90, 70, 60,
50, 40, 30, 100, 20, 10]
Program:
#Creating an empty Tuple
Tuple1 = ()
print("Initial empty Tuple:
") print (Tuple1)
#Creating a Tuple
#with the use of string Tuple1 =
('Geeks', 'For') print("\nTuple
with the use of String: ")
print(Tuple1)
# Creating a Tuple
with # the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using
List: ")
print(tuple(list1))
#Creating a Tuple
#with the use of built-in
function Tuple1 =
tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)
Output:
Initial empty Tuple: ()
Tuple with the use of String:('Geeks', 'For')
Tuple using List: (1, 2, 4, 5, 6)
Tuple with the use of function:('G', 'e', 'e', 'k', 's')
Program:
readlist = [] # define an empty
list # Set a flag to show that
polling is active. flag = True
# Prompt for the entering library
details while flag:
bname = input("\nEnter name of the book? ") byear = input("Enter
the year of publication? ") bauthor = input("Enter author name")
vno=input("enter volume number")
readlist.append({"bname":bname, "byear":byear, "bauthor":bauthor,
"vnumber":vno})
# To continue adding book details repeat =
input("Please refer another person? (yes/ no)
") if repeat == 'no':
flag = False
print("bnamebauthorbyear bvolume")
print("..... ....... .......
.......") for items in readlist:
bname,bauthor,byear,vno=items.values()
print(bname + " " + byear + " "+bauthor+" "+vno
Output:
Enter name of the book? Think
Python
Enter the year of
publication? 2017 Enter
author nameallen downey
enter volume number1
Please refer another person? (yes/
no) no
bname bauthor byearbvolume
..... ....... ....… ...….
Think Pythonallen downey 2017 1
Program:
readlist = [] # define an empty list
# Set a flag to show that details
are active. flag = True
# Prompt for the entering car
details while flag:
cname = input("\nEnter name of the
car? ") cmodel = input("Enter the model
of the car ")
cprice = input("Enter car price")
cyear=input("enter year of
manufacturing")
readlist.append({"carname":cname, "car model":cmodel, "carprice":cprice,
"cyear":cyear})
# To continue adding book details repeat =
input("Please refer another person? (yes/ no)
") if repeat == 'no':
flag = False
print("carnamecarmodelcarpricecaryear")
print("....... ........ ........
.......") for items in readlist:
cname,cmodel,cprice,cyear=items.values()
print(cname + " " + cmodel + " "+cprice+" "+cyear)
Output:
Enter name of the car? indica
Enter the model of the car DLE
Enter car price350000 enter year
of manufacturing1997 Please
refer another person? (yes/ no)
no carname carmodel
carprice caryear ....... ....…
........ ....... indica DLE 350000
1997
Program:
# Creating a car set literal
# A set in python programming is a collection which is unordered
and un-indexed cars = {'BMW', 'Honda', 'Audi', 'Mercedes',
'Honda', 'Toyota', 'Ferrari', 'Tesla'}
# 2. Accessing the values from the set
# Approach1
print('Approach #1= ',
cars)
print('========
==') # Approach2
-
print('Approach #2') for car
in cars: print('Car name =
{}'.format(car))
print('==========')
# 3. Adding an element to the set and
accessing it # There is no specific index
attached cars.add('Tata')
print('New cars set =
{}'.format(cars)) # 4.
Removing an element from the
set # There is no specific index
attached
cars.discard('Mercedes')
print('discard() method =
{}'.format(cars))
# 5. Basic functions over set
oddDays = {"Mon", "Wed",
"Fri"}
allDays = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
# 5(a). Union of sets
# Union operation produces a new set containing all the distinct
elements from both the sets union = oddDays | allDays print("Union of
sets = {}".format(union)) print('==========') # 5(b). Intersection of
sets
# Intersection operation produces a new set containing only common elements
from both the sets intersection = oddDays & allDays
print("Intersection of sets = {}".format(intersection))
print('==========
') # 5(c). Difference
of sets
# Difference operation produces a new set containing only the elements from the
first set and none from the second set
difference = allDays - oddDays
print("Difference of sets = {}".format(difference))
print('==========')
# 5(d). Compare sets
# Compare operation checks if a given set is a subset or superset
of the another set # The result is true or false depending on the
elements present in the sets subset = oddDays <= allDays
superset = allDays >= oddDays print("Subset result =
{}".format(subset)) print("Superset result =
{}".format(superset))
Output:
Approach #1= {'Tesla', 'BMW', 'Audi', 'Mercedes', 'Toyota', 'Ferrari', 'Honda'}
==========
Approach #2
Car name = Tesla
Car name = BMW
Car name = Audi
Car name = Mercedes
Car name = Toyota
Car name = Ferrari
Car name = Honda
==========
New cars set = {'Tesla', 'BMW', 'Audi', 'Tata', 'Mercedes', 'Toyota',
'Ferrari', 'Honda'} discard() method = {'Tesla', 'BMW', 'Audi', 'Tata',
'Toyota', 'Ferrari', 'Honda'}
Union of sets = {'Thu', 'Sat', 'Sun', 'Wed', 'Fri', 'Mon', 'Tue'}
==========
Intersection of sets = {'Fri', 'Mon', 'Wed'}
==========
Difference of sets = {'Sun', 'Sat', 'Thu', 'Tue'}
==========
Subset result = True
Superset result = True
>>>
Program:
#Creating a tuple
count=0 T1 =
(101, "Peter", 22)
T2 = ("Apple", "Banana", "Orange")
T3 = 10,20,30,40,50
#To display elements
print("To display tuples
T1,T2,T3")
print("T1",T1)
print("T2",T2)
print("T3",T3)
#To know type of element
print("element type")
print(type(T1))
print(type(T2))
print(type(T3))
#tuple indexing
print("indexing")
count = 0
#tuple iteration print("tuple
iteration") for i in T3:
print("tuple1[%d] =
%d"%(count, i)) count =
count+1
#slicing
print("indexing and
slicing") print(T1[1:])
print(T2[1:])
print(T3[1:])
print("negative
indexing") print(T1[:-
1])
#to repeat tuple
print("tuple
repetation")
print(T1*2)
#to concatenate tuple
print("tuple
Concatenation")
print(T1+T2)
#to return membership
operator
print("membership")
print(2 in T1)
#to delete tuple
print("delete entire
tuple") del T1
#tuple indexing error
print("indexing error")
print(T1[8])
Output:
To display tuples T1,T2,T3
T1 (101, 'Peter', 22)
T2 ('Apple', 'Banana',
'Orange') T3 (10, 20, 30,
40, 50)
element type
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
indexing
tuple
iteration
tuple1[0] =
10
indexing and slicing
('Peter', 22)
('Banana',
'Orange') (20, 30,
40, 50)
negative indexing
(101, 'Peter')
tuple repetation
(101, 'Peter', 22, 101, 'Peter', 22)
tuple Concatenation
(101, 'Peter', 22, 'Apple', 'Banana', 'Orange')
membership
False delete
entire tuple
indexing error
Traceback (most recent call last):
File "C:\Python34\New Folder\tupleope.py", line 55, in
<module> print(T1[8])
NameError: name 'T1' is not defined
Program:
def fact(n): print("fact has been called
with n="+str(n)) if n==1:
return 1 else:
res = n * fact(n-1)
print("intermediate result for",n,"*fact(",n-1,"):
",res) return res
n=int(input("enter the number to find its fatorial:"))
print(fact(n))
Output:
enter the number to find its fatorial:5
fact has been called with n=5 fact
has been called with n=4 fact has
been called with n=3 fact has been
called with n=2 fact has been called
with n=1 intermediate result for 2
*fact( 1 ): 2 intermediate result for 3
*fact( 2 ): 6 intermediate result for 4
*fact( 3 ): 24 intermediate result for
5 *fact( 4 ): 120 120
Program:
def max_num_in_list( list ):
max = list[ 0 ]
for a in list: if a
> max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))
Output:
2
Program:
def calculate_area(name):
name = name.lower()
# calculate area of rectangle
if name == "rect":
l = int(input("Enter rectangle's length:
")) b = int(input("Enter rectangle's
breadth: "))
rect = l * b
print("The area of rectangle is {rect_area}.",rect)
# calculate area of square elif name ==
"square": s = int(input("Enter square
length: ")) square=s*s
print("The area of rectangle is {square}.",square)
# calculate area of triangle elif
name == "tri": b =
int(input("Enter height: ")) h =
int(input("Enter breadth: "))
tri=0.5*b*h
print("The area of triangle is {triangle}.",tri)
# calculate area of circle elif name ==
"circle": r = int(input("Enter circle radius
length: "))
pi=3.14
cir=pi*r*r
print("The area of rectangle is {circle}.",cir)
# calculate area of parallelogram elif name ==
"para": base = int(input("Enter parallelogram
base length: ")) height = int(input("Enter
parallelogram height length: "))
paral=base*height
print("The area of rectangle is {parallelogram}.",paral)
else:
print("Sorry! This shape is not available")
if __name__ == "__main__" :
print("Calculate Shape Area")
shape_name = input("Enter the name of shape whose area you want to find: ")
calculate_area(shape_name)
Output:
Calculate Shape Area
Enter the name of shape whose area you want to find: para
Enter parallelogram base length: 20
Enter parallelogram height length: 10
The area of rectangle is {parallelogram}.
200
Program:
def
reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]
s = "Geeksforgeeks"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using recursion) is :
",end="") print (reverse(s))
Output:
enter stringmass The
original string is : mass
The reversed string(using recursion) is : ssam
Program:
def ispal(w):
if len(w)==1: print("string
is palindrome")
return True
elif len(w)==2:
if w[0]==w[1]:
return True
else: return
False
else:
if w[0]==w[-1]:
return ispal(w[1:-1])
else:
return False
str=input("enter the string")
print(ispal(str))
repeat = input("Please refer another person? (yes/
no) ") while repeat:
if repeat == 'yes':
str=input("enter the
string")
print(ispal(str))
repeat = input("Enter another string (yes/ no) ")
else :
break
Output:
enter the stringmam
string is palindrome
True
Enter another string? (yes/ no)
yes enter the stringmadam
string is palindrome
True
Enter another string(yes/
no) yes enter the stringsas
string is palindrome
True
Enter another string(yes/ no)
yes enter the stringsa
False
Enter another string (yes/ no) no
Program:
def count_o(text):
count=0 for c in
text:
if c=="p":
count+=1
return(count)
test=input("enter the character")
print("total character length
is",len(test))
#count_o(test)==4
test=count_o("problem solving and python programming")==3
print(test)
Output:
enter the character:
Parbhuram
total character length is 9
True
Program:
str1 = input("Please Enter your Own String :
") ch = input("Please Enter your Own
Character : ") newch = input("Please Enter
the New Character : ")
str2 = '' for i in
str1:
if(i == ch):
str2 = str2 + newch
else:
str2 = str2 + i
print("\nOriginal String : ", str1)
print("Modified String : ", str2)
Output:
Please Enter your Own String : python programming examples
Please Enter your Own Character : o
Please Enter the New Character : G
Original String : python programming examples
Modified String : pythGn prGgramming examples
Program:
import numpy as np arrSumList = [] number =
int(input("Enter the Total Array Items = ")) for i
in range(1, number + 1): value =
int(input("Enter the %d Array value = " %i))
arrSumList.append(value)
intarrSum = np.array(arrSumList) total =
sum(intarrSum) print("The Sum of Total
Array Item = ", total)
Output:
Enter the Total Array Items = 4
Enter the 1 Array value = 20
Enter the 2 Array value = 5090
Enter the 3 Array value = 20
Enter the 4 Array value = 54 The
Sum of Total Array Item = 5184
Program:
def main(): fname=input("enter a
filename:").strip()
infile=open(fname,"r")
wordcounts={} for line in
infile: processline(line.lower(),
wordcounts)
pairs=list(wordcounts.items())
items=[[x,y] for (y,x) in pairs]
items.sort() for i in
range(len(items)-1,len(items)-11,-
1):
print(items[i][1]+"\t"+str(items[i][0]))
def
processline(line,wordco
unts):
line=replacePunctuation
s(line) words=line.split()
for word in words:
if word in wordcounts:
wordcounts[word]+=
1 else:
wordcounts[word]=1
def replacePunctuations(line):
for ch in line:
if ch in "~$%^&*()-_=+|\;:[]{},.<>/?":
line=line.replace(ch," ")
return line
main()
Output:
enter a filename: wordfreq.txt
world 2
will 2 in
2u 1
soon 1
real 1
only 1
not 1
nice 1
mvp 1
Program:
def longest_word(filename):
with open(filename, 'r') as
infile: words =
infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print(longest_word('wordfreq.txt'))
Text file: wordfreq.txt
Hi
H6:06 AM 12/27/2021
Hru
"
:
have a nice day u will
bercome billionaremvp soon
it will happen in real world
not only in dream world
Output:
['billionaremvp']
Program:
with open("wordfreq.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)
Output:
wordfreq.txt
Hi
H6:06 AM 12/27/2021
Hru
"
:
have a nice day
Out.txt:
Hi
H6:06 AM 12/27/2021
Hru
" have a nice
day
Program:
flag=True
while flag:
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)
repeat = input("Please enter (yes/
no) ") if repeat == 'no':
flag = False
Output:
Enter First Number: 10
Enter Second Number: 2
5.0
Please enter (yes/ no) yes
Enter First Number: 10
Enter Second Number: 20
0.5
Please enter (yes/ no) yes
Enter First Number:
10
Enter Second
Number: 0 division
by zero Please enter
(yes/ no) yes
Enter First Number: 1
Enter Second
Number: 0 division
by zero Please enter
(yes/ no) yes
Enter First Number: 0
Enter Second Number: 1
0.0
Program:
flag=True
while flag:
try:
# input age
age = int(input("Enter Age :
")) # condition to check voting
eligibility if age>=18:
status="Eligible"
else:
status="Not Eligible"
print("You are ",status," for Vote.")
except ValueError as e:
print("Invalid Input Please Input Integer...")
repeat = input("Please enter (yes/
no) ") if repeat == 'no':
flag = False
Output:
Enter Age : 19
You are Eligible for Vote.
Please enter (yes/ no) yes
Enter Age : 19.0
Invalid Input Please Input Integer...
Please enter (yes/ no) yes
Enter Age : 18
You are Eligible for Vote.
Please enter (yes/ no) yes
Enter Age : 17
You are Not Eligible for Vote.
Please enter (yes/ no) no
Program:
flag=True
while flag:
try:
sub1=int(input("Enter marks of the first
subject: ")) sub2=int(input("Enter marks of
the second subject: ")) avg=(sub1+sub2)/2
if(avg>=90):
print("Grade: A")
elif(avg>=80 and avg<90):
print("Grade: B")
elif(avg>=70 and avg<80):
print("Grade: C")
elif(avg>=60 and avg<70):
print("Grade: D")
else:
print("Grade: F")
except ValueError as e:
print("Invalid Input Please Input Integer...")
repeat = input("Please enter (yes/
no) ") if repeat == 'no':
flag = False
Output:
Enter marks of the first subject: 90
Enter marks of the second subject: 60
Grade: C
Please enter (yes/ no) yes
Enter marks of the first subject: 90
Enter marks of the second subject:
90.0 Invalid Input Please Input
Integer... Please enter (yes/ no)
Program:
import pygame
pygame.init() white
= (255, 255, 255)
# assigning values to height and width variable
height = 400
width = 400
# creating the display surface object # of specific
dimension..e(X, Y). display_surface =
pygame.display.set_mode((height, width))
# set the pygame window name
pygame.display.set_caption('Image')
# creating a surface object, image is drawn on it.
image =
pygame.image.load(r'C:\Users\Intel\Downloads\niru.
png')
# infinite loop
while True:
display_surface.fill(white)
display_surface.blit(image, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() #
quit the
program.
quit()
# Draws the surface object to the screen.
pygame.display.update()
Output:
Program:
import sys, pygame pygame.init()
size = width, height = 800, 400
speed = [1, 1] background = 255,
255, 255 screen =
pygame.display.set_mode(size)
pygame.display.set_caption("Bounci
ng ball") ball =
pygame.image.load("ball.png")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
ballrect = ballrect.move(speed) if
ballrect.left < 0 or ballrect.right >
width: speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom >
height: speed[1] = -speed[1]
screen.fill(background) screen.blit(ball, ballrect) pygame.display.flip()
Output: