You are on page 1of 245

Topic : Introduction to Python

Python program to input a welcome message and print


it
Write a python program to input a welcome message and print it

Solution

message=input("Enter welcome message : ")


print("Hello, ",message)

Output

Enter welcome message : Good morning

Hello, Good morning

——————-

Python program to print number of seconds in year

Write a python program that calculate and prints the number of seconds in a
year.

Solution

#Python program to print the Number of seconds in


Year
days=365
hours=24
minutes=60
seconds=60
print("Number of seconds in a year :
",days*hours*minutes*seconds)

Output

Number of seconds in a year : 31536000

——————————

Python program to calculate GST Goods and Service


Tax

Program to calculate GST


Solution

item=input("Enter item name :")


sp_cost=float(input("How much is selling price of
item"))
gst_rate=float(input("What is GST rate %"))
cgst=sp_cost*((gst_rate/2)/100)
sgst=cgst
amt=sp_cost+cgst*sgst
print("CGST (@",(gst_rate/2),"%) :",(cgst))
print("SGST(@",(gst_rate/2),"%) :",(sgst))
print("Amount payable: ",(amt))

Output

Enter item name :mobile


How much is selling price of item12600
What is GST rate %18
CGST (@ 9.0 %) : 1134.0
SGST(@ 9.0 %) : 1134.0
Amount payable: 1298556.0

—————————
Python program to nd the ASCII Value of entered
character
Write a program to input any Character and nd its ASCII Value.

Solution

ch=input("Enter any Character : ")


ans=ord(ch) # ord is predefined function to find
ascii value
print("ASCII Value of ",ch," is : ",ans)

Output

Enter any Character : A


ASCII Value of A is : 65
>>>
=========================
Enter any Character : a
ASCII Value of a is : 97
>>>
=========================
Enter any Character : 0
ASCII Value of 0 is : 48

—————————————————-

Python program that display a joke but display the


punch line only when the user presses enter key

Write python program that display a joke but display the punch line only
when the user presses enter key.

Hint: you may use input()


fi
fi
print("Why does Waldo wear stripes?")
input()
print("Because he doesn’t want to be spotted.")

Output

Why does Waldo wear stripes?

Because he doesn’t want to be spotted.

————————————-

Python program to generate the following output 5 10 9

Write a program to generate the following output :

5 10 9

Assign value 5 to a variable using assignment operator (=) Multiply it with 2 to


generate 10 and subtract 1 to generate 9

a=5
print(a)
a=a*2
print(a)
a=a-1
print(a)

Output

5
10
9

—————————————-
Python program to print 5@10@9
Assign value 5 to a variable using assignment operator (=) Multiply it with 2 to
generate 10 and subtract 1 to generate 9

a=5
print(a,end='@')
a=a*2
print(a,end='@')
a=a-1
print(a)

Output

5@10@9

———————————-

Topic : Operators Expressions and Python


Statements

Python program to nd a side of a right angled triangle


whose two sides and an angle is given

Write a program to nd a side of a right angled triangle whose two sides and
an angle is given.

Solution

import math
fi
fi
a = float(input("Enter base: "))
b = float(input("Enter height: "))
x = float(input("Enter angle: "))

c = math.sqrt(a ** 2 + b ** 2)

print("Hypotenuse =", c)Enter base: 10.5


Enter height: 5.5
Enter angle: 60
Hypotenuse = 11.853269591129697

Output

Enter base: 10.5


Enter height: 5.5
Enter angle: 60
Hypotenuse = 11.853269591129697

Write a Python code to calculate and display the value


of Sine 45° and Cosine 30°

Write a Python code to calculate and display the value of Sine 45° and
Cosine 30°

import math
a=45;b=60
x = 22/(7*180)*a
y = 22/ (7*180)*b
sn= math.sin(x)
cs= math.cos(y)
print("The value of Sine 45 degree =",sn)
print("The value of Cosine 60 degree =",cs)
Output

The value of Sine 45 degree = 0.7073302780849811


The value of Cosine 60 degree = 0.4996349289865546

Python program to accept the Base and Perpendicular


and nd the Hypotenuse

Write a python program to accept the Base and Perpendicular for


right angled triangle from user and nd the Hypotenuse

Hint: h2=b2+p2

import math
base=float(input("Enter the length of base "))
per=float(input("Enter the length of Perpendicular
"))
hyp=math.sqrt(base*base+per*per)
print("Length of Hypotenuse is : ",hyp)

Output

Enter the length of base 4


Enter the length of Perpendicular 3
Length of Hypotenuse is : 5.0

Python program to obtain the marks in computer of


some student and nd mean median and mode
fi
fi
fi
The Computer marks obtained by some students are given below:

89,91,96,94,96,88,91,92,95,99,91,97,91

Write a python code to calculate and display mean, median and mode.

import statistics
mn=statistics.mean([89,91,96,94,96,88,91,92,95,99,91
,97,91])
mid=statistics.median([89,91,96,94,96,88,91,92,95,99
,91,97,91])
md=statistics.mode([89,91,96,94,96,88,91,92,95,99,91
,97,91])
print("Mean ",mn)
print("Median ",mid)
print("Mode “,md)
Python program to accept three side of triangle and
nd its area by using Herons Formula

Write a python program to accept 3 side of triangle and nd its area by using
Heron’s Formula

where s=(a+b+c)/2

import math
a=float(input("Enter the Side 1 "))
b=float(input("Enter the Side 2 "))
c=float(input("Enter the Side 3 "))
s=(a+b+c)/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
print("Area of Triangle is : ",area)

Output

Enter the Side 1 5

Enter the Side 2 4

Enter the Side 3 3

Area of Triangle is : 6.0


fi
fi
Python program to accept side of Equilateral Triangle
and nd its area

Write a Python program to accept the side of Equilateral Triangle and nd its
area

A = (√3)/4 × side2

import math
a=float(input("Enter the Length of Side"))
area=(math.sqrt(3)/4)*(a**a)
print("Area of Triangle is : ",area)

Output

Enter the Length of Side5

Area of Triangle is : 1353.1646934131852

Python program to check whether dart hit inside board


or outside
fi
fi
A dartboard of radius 10 units and the wall it is hanging on are represented
using a two-dimensional coordinate system, with the boards center at
coordinate (0,0). Variables x and y store the x-coordinate and the y-
coordinate of a dart that hits the dartboard. Write a Python expression using
variables x and y that evaluates to True if the dart hits (is within) the
dartboard, and then evaluate the expression for these dart coordinates:

(a) (0,0)

(b) (10,10)

(c) (6,6)

(d) (7,8)
Solutions:

import math
x=int(input("Enter the Coordinate x : "))
y=int(input("Enter the Coordinate y : "))
distance=math.sqrt(math.pow(x,2)+math.pow(y,2))
if distance<=10:
print("Within Board")
else:
print("Outside Board ")

Output

Enter the Coordinate x : 6


Enter the Coordinate y : 6
Within Board
>>>
=================
Enter the Coordinate x : 10
Enter the Coordinate y : 10
Outside Board

Python Program to obtain temperature in Celsius and


convert it into Fahrenheit

Write a Program to obtain temperature in Celsius and convert it into


Fahrenheit using formula –

C X 9/5 + 32 = F

Solution

c=int(input("Enter the temperature in Celsius:"))


f=(c*9/5)+32
print("Temperature in Fahrenheit: ",f)

Output

Python program to print the area of circle when radius


of the circle is given by user

WAP to print the area of circle when radius of the circle is given by user.

Solution

r=int(input("Enter the radius: "))


area=3.14*r*r
print("Area of circle is : ",area)

Output
Python program to print the volume of a cylinder when
radius and height of the cylinder is given by user

WAP to print the volume of a cylinder when radius and height of the cylinder
is given by user.

area =πr2h

Solution

r=int(input("Enter the radius : "))


h=int(input("Enter the height : "))
vol=3.14*r*r*h
print("Volume of Cylinder is : ",vol)

Output

Python program that asks your height in centimeters


and converts it into foot and inches
WAP that asks your height in centimeters and converts it into foot and inches.

Solution

cm=int(input("Enter height in Centimeters : "))


foot=cm//30
rcm=cm%30
inches=rcm*0.393701
print("Height is : ",foot," Foot ",inches," Inches
")

Output

WAP to accept 3 side of triangle and nd area of a triangle.

Solution

import math
a=int(input("Enter side 1 of triangle : "))
b=int(input("Enter side 2 of triangle : "))
c=int(input("Enter side 3 of triangle : "))
s=(a+b+c)/2
area=s*math.sqrt((s-a)*(s-b)*(s-c))
print("Area of Triangle is : ",area)
fi
Output

Python program to input principle amount,rate time and


calculate simple interes

WAP to input principle amount,rate time and calculate simple interest.

Solution

p=int(input("Enter Principal : "))


r=int(input("Enter Rates : "))
t=int(input("Enter Time : "))
si=(p*r*t)/100
print("Simple Interest is : ",si)

Output
Python program to read a number in n and prints n2 n3
n4

WAP to read a number in n and prints n^2, n^3, n^4

Solution

n=int(input("Enter the value of n : "))


print("n^2 : ",n*n)
print("n^3 : ",n*n*n)
print("n^4 : ",n*n*n*n)

Output

Enter the value of n : 5

n^2 : 25

n^3 : 125

n^4 : 625
Python program which take value of x y z from the user
and calculate the equation

WAP to take value of x,y,z from the user and calculate the

equation

Solution

x=int(input("Enter x : "))
y=int(input("Enter y : "))
z=int(input("Enter z : "))
fx=4*pow(x,4)+3*pow(y,3)+9*pow(z,2)+6*3.14
print("The Answer is : ",fx)

Output
Python program to take the temperatures of all 7 days
of the week and displays the average temperature of
that week

WAP to take the temperatures of all 7 days of the week and displays the
average temperature of that week.

Solution

d1=int(input("Temperature of day 1 : "))


d2=int(input("Temperature of day 2 : "))
d3=int(input("Temperature of day 3 : "))
d4=int(input("Temperature of day 4 : "))
d5=int(input("Temperature of day 5 : "))
d6=int(input("Temperature of day 6 : "))
d7=int(input("Temperature of day 7 : "))
avg=(d1+d2+d3+d4+d5+d6+d7)/7
print("The average Temperature is : ",avg)

Output
Python program to obtain three numbers and print their
sum

Python program to obtain three numbers and print their sum.

Solution

num1=int(input("Enter Number 1 : "))


num2=int(input("Enter Number 2 : "))
num3=int(input("Enter Number 3 : "))
sum=num1+num2+num3
print("Three Numbers are : ",num1,num2,num3)
print("Sum is : ",sum)

Output

Enter Number 1 : 5
Enter Number 2 : 4
Enter Number 3 : 3
Three Numbers are : 5 4 3
Sum is : 12

Python program to obtain length and breath of a


rectangle and calculate its area

Python program to obtain length and breath of a rectangle and calculate its
area

Solution

length=float(input("Enter the length of rectangle :


"))
breadth=float(input("Enter the breadth of
rectangle : "))
area=length*breadth
print("Rectangle specifications ")
print("Length : ",length," Breadth : ",breadth,"
Area : ",area)

Output

Enter the length of rectangle : 6


Enter the breadth of rectangle : 5
Rectangle speci cations
Length : 6.0 Breadth : 5.0 Area : 30.0

Python program to calculate body mass index of a


person

Python program to calculate (BMI) body mass index of a person

Body Mass Index is a simple calculation using a person's height and weight.
The formula is BMI=kg/m^2 where kg is a person's weight in kilogram and
m^2 is the height in meter squared.

Solution

weight=float(input("Enter the weight of person in KG


: "))
height=float(input("Enter the height of person in
meter : "))
bmi=weight/(height*height)
print("BMI of person is : ",bmi)

Output
fi
Enter the weight of person in KG : 60
Enter the height of person in meter : 1.6
BMI of person is : 23.437499999999996

Python program to input a number and print its cube

Write a program to input a number and print its cube.

Solution

num=int(input("Enter a number : "))


cube=num**3
print("Cube of ",num," is : ",cube)

Output

Enter a number : 3
Cube of 3 is : 27
>>>
=====================
Enter a number : 5
Cube of 5 is : 125

Python program to input a single digit and print a 3 digit


number

Write a program to input a single digit(n) and print a 3 digit number created as
<n(n+1)(n+2)> e.g., if you input 7, then it should print 789. Assume that the
input digit is in range 1-7.
Solution

n=int(input("Enter a digit in range 1-7 : "))


num=n*100+(n+1)*10+(n+2)
print(" New 3 Digit Number : ",num)

Output

Enter a digit in range 1-7 : 5

New 3 Digit Number : 567

Python program to calculate the compound interest

Write a program to Calculate the Compound Interest

Solution

import math
prin=float(input("Enter the Principal Amount : "))
rate=float(input("Enter the Rate : "))
time=float(input("Enter the Time (in year) : "))
amt=prin*(math.pow((1+rate/100),time))
ci=amt-prin
print("Compound Interest is",ci)

Output

Enter the Principal Amount : 4000


Enter the Rate : 7.6
Enter the Time (in year) : 3
Compound Interest is 983.0679040000014
Python program to nd sale price of an item with given
price and discount

write a program to nd sale price of an item with given price and discount (%)

Solution

price=float(input("Enter Price : "))


dp=float(input("Enter discount % : "))
discount=price*dp/100
sp=price-discount
print("Cost Price : ",price)
print("Discount: ",discount)
print("Selling Price : ",sp)

Output

Enter Price : 4500


Enter discount % : 12
Cost Price : 4500.0
Discount: 540.0
Selling Price : 3960.0

Python Program to Calculate the Area of a Triangle

Write a Python program to accept 3 sides of triangle and nd the area of


triangle.

s = (a+b+c)/2

area = √(s(s-a)*(s-b)*(s-c))

Solution
fi
fi
fi
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Output

Enter rst side: 4


Enter second side: 5
Enter third side: 6
The area of the triangle is 9.92

Python program for addition of two times in hour and


minute format

Write a python program which accept two times as input and displays the
total time after adding both the entered times.

Sample Input :

Enter Time 1 :
Hour : 3
Minute : 40
Enter Time 2 :
Hour : 2
Minute : 35

Output:
fi
Time 1 : 3 Hour & 40 Minute
Time 2 : 2 Hour & 35 Minute
Total Time : 6 Hour & 15 Minute

Solution

print("Enter Time 1 :")


h1=int(input("Hour : "))
m1=int(input("Minute : "))
print("Enter Time 2 :")
h2=int(input("Hour : "))
m2=int(input("Minute : "))
h3=h1+h2+(m1+m2)//60
m3=(m1+m2)%60
print("Time 1 :",h1," Hour &",m1," Minute")
print("Time 2 :",h2," Hour &",m2," Minute")
print("Total Time :",h3," Hour &",m3," Minute”)

Python program for addition of two times in hour minute


and second format

Write a python program which accept two times (HH:MM:SS) as input and
displays the total time after adding both the entered times.

Sample :

Input:

Enter Time 1 :
Hour : 2
Minute : 40
Second : 45
Enter Time 2 :
Hour : 1
Minute : 35
Second : 40
Output:

Time 1 : 2 Hour, 40 Minute and 45 Second


Time 2 : 1 Hour, 35 Minute and 40 Second
Total Time : 4 Hour & 16 Minute and 25 Second

Solution

print("Enter Time 1 :")


h1=int(input("Hour : "))
m1=int(input("Minute : "))
s1=int(input("Second : "))
print("Enter Time 2 :")
h2=int(input("Hour : "))
m2=int(input("Minute : "))
s2=int(input("Second : "))
h3=h1+h2+(m1+m2+(s1+s2)//60)//60
m3=(m1+m2+(s1+s2)//60)%60
s3=(s1+s2)%60
print("Time 1 :",h1," Hour,",m1," Minute and ",s1,"
Second")
print("Time 2 :",h2," Hour,",m2," Minute and ",s2,"
Second")
print("Total Time :",h3," Hour &",m3," Minute and
“,s3,"Second")
Python program to print quotient

Program to print quotient.

Solution

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


b=int(input("Enter second number :"))
print ("Quotient :" , a/b)

Output

Enter the rst number :5


Enter second number :2
Quotient : 2.5

Python program to calculate simple interest

Write a program to obtain principal amount, rate of interest and time from
user and compute simple interest.

Solution

p = float(input("Enter principal: "))


r = float(input("Enter rate: "))
t = float(input("Enter time: "))

si = p * r * t / 100

print("Simple Interest =", si)

Output

Enter any principal amount:3000


Enter rate of interest:10
Enter time:12
fi
Simple Interest= 3600.0

Python program to calculate area and perimeter of a


parallelogram

Program to calculate area and perimeter of a parallelogram

Solution

l=float(input("Enter length"))
w=float(input("Enter width"))
h=float(input("Enter height:"))
area_parallelogram=l*h
peri_parallalogram=2*l+2*w
print ("The area of the parallelogram is",
area_parallelogram)
print(" The perimeter of the parallelogram is",
peri_parallalogram)

Output

Enter length5.2
Enter width2.0
Enter height:1.5
The area of the parallelogram is 7.800000000000001
The perimeter of the parallelogram is 14.4

Python program demonstrating working with power


operator
Program demonstrating working with power operator

Solution

x=int(input("Please enter an integer:"))


print('value of x=',x)
print('x**2=',x**2)
print('x**3=',x**3)
print('x**4',x**4)

Output

Please enter an integer:2


value of x= 2
x**2= 4
x**3= 8
x**4 16

Python program of modulus

Program of modulus

Solution

num1=int(input("Enter first number:"))


num2=int(input(" Enter second number"))
remainder=num1%num2
print("Remainder:",remainder)

Output

Enter rst number:7

Enter second number2

Remainder: 1
fi
Python program convert dollars in Rupee

Program convert dollars in Rupee


Solution

dollars=float(input("Please enter dollars :"))


rupees=dollars*69.45
print(rupees,"Rupees")

Output

Please enter dollars :10

694.5 Rupees

Python program to convert kilometres to miles

Program to convert kilometres to miles

Solution

km=float(input("Enter the value in kilometres :"))


conv_fac=0.621371
miles=km*conv_fac
print("The entered value in Miles :",miles)

Output

km= oat(input("Enter the value in kilometres :"))

conv_fac=0.621371
fl
miles=km*conv_fac

print("The entered value in Miles :",miles)

Python program to convert the distance in feet to


inches yards and miles

Program to convert the distance (in feet) to inches, yards, and miles

Solution

dis_ft=int(input("Input distance in feet :"))


dis_inches=dis_ft*12
dis_yards=dis_ft/3.0
dis_miles=dis_ft/5280.0
print(" The distance in inches is %i inches." %
dis_inches)
print("The distance in inches in yards is %.2f
yards." % dis_yards)
print("The distance in miles is %.2f miles."
%dis_miles)

Output

Input distance in feet :200

The distance in inches is 2400 inches.

The distance in inches in yards is 66.67 yards.

The distance in miles is 0.04 miles.


Python program to display menu to calculate area of
square or rectangle

Program to display menu to calculate are of square or rectangle

Solution

print("1. Calculate area of square")


print("2. Calculate area of rectangle ")
choice= int(input(" Enter your choice (1 or 2):"))
if(choice==1):
side=float(input("Enter side of a
square :"))
area_square=side*side
print("Area of square is:",area_square)
else:
length=float(input(" Enter length of
a rectangle:"))
breadth=float(input("Enter breadth
of a rectangle:"))
area_rectangle=length*breadth
print("Area of a rectangle is :",
area_rectangle)

Output

Output 1:
1. Calculate area of square
2. Calculate area of rectangle
Enter your choice (1 or 2):1
Enter side of a square :2.5
('Area of square is:', 6.25)

Output 2:
1. Calculate area of square
2. Calculate area of rectangle
Enter your choice (1 or 2):2
Enter length of a rectangle:8
Enter breadth of a rectangle:4
('Area of a rectangle is :', 32.0)

Python program to obtain x y z from user and calculate


expression

Write a program to obtain x, y, z from user and calculate expression : 4x4 +


3y3 + 9z + 6π

Solution

import math

x = int(input("Enter x: "))
y = int(input("Enter y: "))
z = int(input("Enter z: "))

res = 4 * x ** 4 + 3 * y ** 3 + 9 * z + 6 * math.pi

print("Result =", res)

Output

Enter x: 2

Enter y: 3

Enter z: 5

Result = 208.84955592153875
Python program that reads a number of seconds and
prints it in form mins and seconds

Write a program that reads a number of seconds and prints it in form : mins
and seconds, e.g., 200 seconds are printed as 3 mins and 20 seconds.

[Hint. use // and % to get minutes and seconds]

Solution

totalSecs = int(input("Enter seconds: "))

mins = totalSecs // 60
secs = totalSecs % 60

print(mins, "minutes and", secs, "seconds")

Output

Enter seconds: 200

3 minutes and 20 seconds

Python program to take a 2 digit number and then print


the reversed number

Write a program to take a 2-digit number and then print the reversed number.
That is, if the input given is 25, the program should print 52.
Solution

Solution

x = int(input("Enter a two digit number: "))


y = x % 10 * 10 + x // 10
print("Reversed Number:", y)

Output

Enter a two digit number: 25

Reversed Number: 52

Python program to take a 3 digit number and then print


the reversed number

Write a program to take a 3-digit number and then print the reversed number.
That is, if you input 123, the program should print 321.

Solution

x = int(input("Enter a three digit number: "))

d1 = x % 10
x //= 10
d2 = x % 10
x //= 10
d3 = x % 10
y = d1 * 100 + d2 * 10 + d3

print("Reversed Number:", y)
Output

Enter a three digit number: 123

Reversed Number: 321

Python program to take two inputs for day month and


then calculate which day of the year

Write a program to take two inputs for day, month and then calculate which
day of the year, the given date is. For simplicity, take 30 days for all months.
For example, if you give input as: Day3, Month2 then it should print "Day of
the year : 33".

Solution

d = int(input("Enter day: "))


m = int(input("Enter month: "))

n = (m - 1) * 30 + d

print("Day of the year:", n)

Output

Enter day: 3

Enter month: 2

Day of the year: 33


Python program that asks a user for a number of years
and then prints out the number of days hours minutes
and seconds

Write a program that asks a user for a number of years, and then prints out
the number of days, hours, minutes, and seconds in that number of years.

Solution

y = float(input("How many years? "))

d = y * 365
h = d * 24
m = h * 60
s = m * 60

print(y, "years is:")


print(d, "days")
print(h, "hours")
print(m, "minutes")
print(s, "seconds")

Output

How many years? 10

10.0 years is:

3650.0 days

87600.0 hours

5256000.0 minutes

315360000.0 seconds
Python program that inputs an age and print age after
10 years

Write a program that inputs an age and print age after 10 years as shown
below:

Solution

age = int(input("What is your age? "))


print("In ten years, you will be", age + 10, "years
old!")

Output

What is your age? 17

In ten years, you will be 27 years old!

Python program to calculate the radius of a sphere


whose area is given

Write a program to calculate the radius of a sphere whose area (4πr2) is


given.

Solution

import math

area = float(input("Enter area of sphere: "))

r = math.sqrt(area / (4 * math.pi))

print("Radius of sphere =", r)


Output

Enter area of sphere: 380.14

Radius of sphere = 5.50005273006328

Python program to calculate the area of an equilateral


triangle

Write a program to calculate the area of an equilateral triangle. (area = (√3 /


4) * side * side).

Solution

import math

side = float(input("Enter side: "))


area = math.sqrt(3) / 4 * side * side

print("Area of triangle =", area)

Output

Enter side: 5

Area of triangle = 10.825317547305481


Python program to input the radius of a sphere and
calculate its volume

Write a program to input the radius of a sphere and calculate its volume (V =
4/3πr3)

Solution

import math

r = float(input("Enter radius of sphere: "))


v = 4 / 3 * math.pi * r ** 3

print("Volume of sphere = ", v)

Output

Enter radius of sphere: 3.5

Volume of sphere = 179.59438003021648


Python program to calculate amount payable after
simple interest

Write a program to calculate amount payable after simple interest.

Solution

p = float(input("Enter principal: "))


r = float(input("Enter rate: "))
t = float(input("Enter time: "))

si = p * r * t / 100
amt = p + si

print("Amount Payable =", amt)

Output

Enter principal: 55000.75

Enter rate: 14.5

Enter time: 3

Amount Payable = 78926.07625


Python program to input the time in second and convert
into hours minute and seconds

Write a python code to input the time in seconds. Display the time after
converting it into hours, minutes and seconds.

Sample Output: Time in Second 5420

Sample Output: 1 Hour 30 Minutes 20 Seconds

Solution 1:

sec=int(input("Enter time in Second : "))


hour=sec//3600
rem=sec%3600
min=rem//60
sec=rem%60
print(hour," hour ",min," minute and ",sec,"
second")

Solution 2:
sec=int(input("Enter time in Second : "))
hour=sec//3600
min=(sec%3600)//60
sec=(sec%3600)%60
print(hour," hour ",min," minute and ",sec,"
second”)

Python program to input 3 numbers and check all are


same or not
Write a Python program to input 3 Integer Number and check al numbers are
same or not.

Solution 1:

n1=int(input("Enter Number 1 "))


n2=int(input("Enter Number 2 "))
n3=int(input("Enter Number 3 "))
if n1==n2==n3:
print("All 3 Numbers are same ")
else:
print("All 3 Numbers are not same")

Solution 2:

n1=int(input("Enter Number 1 "))


n2=int(input("Enter Number 2 "))
n3=int(input("Enter Number 3 "))
if n1==n2 and n2==n3:
print("All 3 Numbers are same ")
else:
print("All 3 Numbers are not same")
Output

Enter Number 1 5
Enter Number 2 7
Enter Number 3 4
All 3 Numbers are not same
>>>
========================
Enter Number 1 4
Enter Number 2 4
Enter Number 3 4
All 3 Numbers are same

Python program to input 3 numbers from user and


check these are unique numbers are not

Write a Python program input 3 numbers from user and check these
numbers are Unique are Not.

Solutions 1

n1=int(input("Enter Number 1 : "))


n2=int(input("Enter Number 2 : "))
n3=int(input("Enter Number 3 : "))
if n1!=n2!=n3!=n1:
print("All Numbers are Unique ")
else:
print("Two or All are same Numbers")
Output

Enter Number 1 : 1
Enter Number 2 : 2
Enter Number 3 : 2
Two or All are same Numbers

==========================
Enter Number 1 : 1
Enter Number 2 : 2
Enter Number 3 : 1
Two or All are same Numbers

==========================
Enter Number 1 : 2
Enter Number 2 : 3
Enter Number 3 : 4
All Numbers are Unique

==========================
Enter Number 1 : 1
Enter Number 2 : 3
Enter Number 3 : 3
Two or All are same Numbers

Python program of modulus


Program of modulus

Solution

num1=int(input("Enter first number:"))


num2=int(input(" Enter second number"))
remainder=num1%num2
print("Remainder:",remainder)

Output
Enter rst number:7
Enter second number2
Remainder: 1
fi
Python program to take year as input and check if it is
a leap year or not

Write a program to take year as input and check if it is a leap year or not.

Solution

y = int(input("Enter year to check: "))


print(y % 4 and "Not a Leap Year" or "Leap Year")

Output

Enter year to check: 2020

Leap Year

Python program to take two numbers and print if the


rst number is fully divisible by second number or not

Write a program to take two numbers and print if the rst number is fully
divisible by second number or not.

Solution

x = int(input("Enter first number: "))


y = int(input("Enter second number: "))
print(x % y and "Not Fully Divisible" or "Fully
Divisible")

Output

Enter rst number: 4


Enter second number: 2
Fully Divisible
fi
fi
fi
Python program to input two number and swap them

Write a program to input two number and swap them.

Solution 1: Using Multiple Assignment

n1=int(input("Enter number 1 : "))


n2=int(input("Enter number 2 : "))
print("Original Number : ",n1,n2)
n1,n2=n2,n1
print("After Swapping : ",n1,n2)

Solution 2: Swapping by using 3rd variable

n1=int(input("Enter number 1 : "))


n2=int(input("Enter number 2 : "))
print("Original Number : ",n1,n2)
n3=n1
n1=n2
n2=n3
print("After Swapping : ",n1,n2)
Solution 3: Swapping by using Arithmetic Addition and Subtraction

n1=int(input("Enter number 1 : "))


n2=int(input("Enter number 2 : "))
print("Original Number : ",n1,n2)
n1=n1+n2
n2=n1-n2
n1=n1-n2
print("After Swapping : ",n1,n2)

Solution 4: Swapping by using Arithmetic Multiplication and Division

n1=int(input("Enter number 1 : "))


n2=int(input("Enter number 2 : "))
print("Original Number : ",n1,n2)
n1=n1*n2
n2=n1/n2
n1=n1/n2
print("After Swapping : ",n1,n2)

Output

Enter number 1 : 45

Enter number 2 : 30

Original Number : 45 30

After Swapping : 30 45
Python program to input three number and swap 3
numbers

Write a program to input three numbers and swap them as this : 1st number
becomes the 2nd number, 2nd number becomes the 3rd number and 3rd
number becomes the rst number.

Solution

n1=int(input("Enter number 1 : "))


n2=int(input("Enter number 2 : "))
n3=int(input("Enter number 3 : "))
print("Original Number : ",n1,n2,n3)
n1,n2,n3=n2,n3,n1
print("After Swapping : ",n1,n2,n3)

Output

Enter number 1 : 4

Enter number 2 : 5

Enter number 3 : 6

Original Number : 4 5 6

After Swapping : 5 6 4
fi
Python program to read 3 numbers in 3variables and
swap rst two variables with the sums of rst and
second

Write a program to read three numbers in three variables and swap rst two
variables with the sums of rst and second ,second and third number
respectively.

Solution

n1=int(input("Enter number 1 : "))


n2=int(input("Enter number 2 : "))
n3=int(input("Enter number 3 : "))
print("Original Number : ",n1,n2,n3)
n1,n2,n3=(n1+n2),(n2+n3),(n3+n1)
print("After Swapping : ",n1,n2,n3)

Output

Enter number 1 : 4

Enter number 2 : 3

Enter number 3 : 5

Original Number : 4 3 5

After Swapping : 7 8 9
fi
fi
fi
fi
Python credit card program
Credit Card Program

Solution

amount=int(input("Enter the amount:"))


if(amount<=1000):
print("Your charge is accepted.")
if(amount>1000):
print("The amount exceeds your credit
limit.")

Output

Enter the amount:1000


Your charge is accepted.
Enter the amount:1200
The amount exceeds your credit limit.

Python program to print absolute value of number


provided by the user

Program to print absolute value of number provided by the user.

Solution

num=eval(input("Enter a number:"))
print('|',num,'|=',(-num if num<0 else num),sep='')

Output

Enter a number:-9

|-9|=9
Python program to check divisibility of a number

Program to check divisibility of a number

Solution

num1=int(input("Enter first number :"))


num2=int(input(" Enter second number"))
remainder=num1%num2
if remainder==0:
print(" First number is divsible by
second number")
else:
print(" First number is not
divisible by second number")

Output

Enter rst number :100

Enter second number2

First number is divsible by second number


fi
Python program to print the largest number

Program to print the largest number

Solution

num1=int(input("Enter the first number"))


num2=int(input("Enter the second number"))
num3=int(input("Enter the third number"))
max=num1
if num2>max:
max=num2
if num3>max:
max=num3
print("Largest number is:",max)

Output

Enter the rst number27

Enter the second number37

Enter the third number17

('Largest number is:', 37)


fi
Python program to check number is even or odd

Write a program that returns True if the input number is an even number,
False otherwise.

Solution

#Python program to check number is Even or Odd


num=int(input("Enter any Integer Number : "))
if num%2==0:
print("Even")
else:
print("Odd")

Output

Enter any Integer Number : 4

Even

>>>

========================

Enter any Integer Number : 5

Odd
Python program to print larger number using swap

Write a python program to print larger number using swap

x=int(input("Enter the first Number : "))


y=int(input("Enter the second Number : "))
if x>y:
x,y=y,x
print("The Larger Number is : ",y)
print("The smaller Number is : ",x)

Output

Enter the rst Number : 45

Enter the second Number : 34

The Larger Number is : 45

The smaller Number is : 34

>>>

========================

Enter the rst Number : 33

Enter the second Number : 90

The Larger Number is : 90

The smaller Number is : 33


fi
fi
Python program to input three unequal numbers and
display the greatest and the smallest number

Write a Python code to input three unequal numbers. Display the greatest
and the smallest numbers.

Solution:

max=min=0
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
c=int(input("Enter third number:"))
if((a>b) and (a>c)):
max=a
if((b>a) and (b>c)):
max=b
if((c>a) and (c>b)):
max=c
if((a<b) and (a<c)):
min=a
if((b<a) and (b<c)):
min=b
if((c<a) and (c<b)):
min=c
print("Greatest Number :",max)
print("Smallest Number :",min)

Output

Enter rst number:5


Enter second number:9
Enter third number:4
Greatest Number : 9
Smallest Number : 4
fi
Python program to take two numbers and check that
the rst number is fully divisible by second number or
not

WAP to take two numbers and check that the rst number is fully divisible by
second number or not.

Solution

a=int(input("Enter First Number : "))


b=int(input("Enter Second Number : "))
if a%b==0:
print(a," is fully divisible by ",b)
else:
print(a," is not fully divisible by ",b)

Output
fi
fi
Python program to check the given year is leap year or
not

WAP to check the given year is leap year or not.

Solution

year=int(input("Enter year"))
if year%4==0:
if year%100==0:
if year%400==0:
print(year,"is a leap year")
else:
print(year,"is a not leap year")
else:
print(year,"is a leap year")
else:
print(year,"is a not leap year")

Output
Python program to calculate the roots of a given
quadratic equation.

WAP to calculate the roots of a given quadratic equation.

Solution

import math
a=int(input("Enter a"))
b=int(input("Enter b"))
c=int(input("Enter c"))
d=(b*b)-(4*a*c)
if d>=0:
print("roots are : ")
x1=-b+math.sqrt(d)/(2*a)
x2=-b-math.sqrt(d)/(2*a)
print(" x1 = ",x1)
print(" x2 = ",x2)
else:
print(" roots are imaginary.")

Output
Python program to nd simple interest based upon
number of years

Program to nd the simple interest based upon number of years. If number of


years is more than 12 rate of interest is 10 otherwise 15.

Solution

p = input("Enter any principle amount")


t = input("Enter any time")
if (t>10):
si = p*t*10/100
else:
si = p*t*15/100
print ("Simple Interest = ",si)

Output

Enter any principle amount 3000


Enter any time12
Simple Interest = 3600

Python program to check where is pro t or loss


Write a python program to input cost price, selling price of product from user
and check whether is pro t or loss and also print the Pro t/loss amount

Solution

cp=float(input("Enter the Cost Price : "));


sp=float(input("Enter the Selling Price : "));
if cp==sp:
print("No Profit No Loss")
else:
if sp>cp:
print("Profit of ",sp-cp)
else:
print("Loss of ",cp-sp)
fi
fi
fi
fi
fi
Output

Enter the Cost Price : 300


Enter the Selling Price : 450
Pro t of 150.0
>>>
=========================
Enter the Cost Price : 500
Enter the Selling Price : 379
Loss of 121.0
>>>
=========================
Enter the Cost Price : 400
Enter the Selling Price : 400
No Pro t No Loss

Python program to check number is buzz number or not


Write a python program to input a number form user and check whether
number is buzz number or not.

A number is said to be Buzz Number if it ends with 7 or is divisible by 7.

Solution

#python program to check number is buzz number or


not.
num=int(input("Enter any Number : "))
if num%7==0 or num%10==7:
print(num, "is a Buzz Number")
else:
print(num, "is a not a Buzz Number")

Output

Enter any Number : 14


14 is a Buzz Number
fi
fi
>>>
=========================
Enter any Number : 77
77 is a Buzz Number
>>>
=========================
Enter any Number : 10
10 is a not a Buzz Number

Python program to input assets liabilities and capital


then check accounting equation means balanced or not

Write a program to input assets, liabilities and capital of a company and test if
accounting equation holds true for the given value (i.e., balanced or not).

Hint : assets == liabilities + capital

Solution

capital = float(input("Enter capital : "))


assets = float(input("Enter assets : "))
liabilities = float(input("Enter liabilities : "))
if assets == liabilities + capital :
print("Balanced")
else :
print("Not balanced")
Output

Enter capital : 5000


Enter assets : 15000
Enter liabilities : 20000
Not balanced
>>>
========================
Enter capital : 5000
Enter assets : 20000
Enter liabilities : 15000
Balanced
Python program to input total debt and total assets and
calculate total debt to total assets ratio and check
whether major funded by assets or equity

Write a program to input total debt and total assets and calculate total-debt-
to-total-assets ratio (TD/TA) as Total Debt/Total Assets. Then print if the major
portion of the debt is funded by assets (when TD/TA > 1) or greater portion of
assets is funded by equity (when TD/TA < 1).

Solution

total_debt = float(input("Enter total debt : "))


total_assets = float(input("Enter total assets :
"))
ratio = total_debt / total_assets
if ratio > 1 :
print("the major portion of the debt is funded
by assets ")
else :
print("greater portion of assets is funded by
equity ")

Output

Enter total debt : 4000


Enter total assets : 2000
the major portion of the debt is funded by assets
>>>
========================
Enter total debt : 5000
Enter total assets : 12000
greater portion of assets is funded by equity
Python program to calculate debt to equity check
whether it is risky scenario for investor or not

Write a program to calculate Debt-to-equity (D/E) ratio as [ Total Liabilities /


Total shareholders' ] equity after inputting total liabilities and total
shareholders' equity. And then print if an investor should invest in the
company or not. A D/E ratio greater than 2.0 indicates a risky scenario for an
investor.

Solution

total_Liabilities = float(input("Enter Total


Liabilities : "))
Total_equity = float(input("Enter Total
shareholders' equity : "))
ratio = total_Liabilities / Total_equity
if ratio > 2 :
print("a risky scenario for an investor")
else :
print("investor should invest in the company ")

Output

Enter Total Liabilities :4000


Enter Total shareholders' equity :5000
investor should invest in the company
>>>
========================
Enter Total Liabilities :60000
Enter Total shareholders' equity :2000
a risky scenario for an investor
Python program to input 2 integer number and check
where they are same of different number

Write a Python program which accept 2 integer number and check


where they are same number or different number.

num1=int(input("Enter First Number : "))


num2=int(input("Enter Second Number : "))
if num1==num2:
print("Both are same Number")
else:
print("These are Different Number")

Output

Enter First Number : 7

Enter Second Number : 6

These are Different Number

>>>

========================

Enter First Number : 4

Enter Second Number : 4

Both are same Number


Python program to read todays date only date Part
from user Then display how many days are left in the
current month

WAP to read todays date (only date Part) from user. Then display how
many days are left in the current month.

import datetime
td=0
day=int(input("Enter current date(only date part)"))
now=datetime.datetime.now()
if now.month==2:
td=28
elif now.month in(1,3,4,7,8,10,12):
td=31
else:
td=30
print("Total remaining days in the current month are
: ",td-day)

Output

Enter current date(only date part)6

Total remaining days in the current month are : 25


Python program to compute the result when two numbers and
one operator is given by user
WAP to compute the result when two numbers and one operator is given by
user.

Solution
#WAP to compute the result when two numbers and one
operator is given by user.
a=int(input("Enter 1st number : "))
b=int(input("Enter 2nd number : "))
c=input("Enter the Operator +,-,*,/ : ")
if c=='+':
print("The Result is : ",a+b)
elif c=='-':
print("The Result is : ",a-b)
elif c=='*':
print("The Result is : ",a*b)
elif c=='/':
print("The Result is : ",a/b)
else:
print("Wrong Operator Entered")

Output
Python program to input a digit and print it in words
WAP to input a digit and print it in words.

Solution
n=int(input("Enter the digit form 0 to 9 : "))
print("Entered Digit is : ",end='')
if n==0:
print("Zero")
elif n==1:
print("One")
elif n==2:
print("Two")
elif n==3:
print("Three")
elif n==4:
print("Four")
elif n==5:
print("Five")
elif n==6:
print("Six")
elif n==7:
print("Seven")
elif n==8:
print("Eight")
elif n==9:
print("Nine")
else:
print("Not a Digit")

Output
Python program to input any choice and to implement
the following
Write a program to input any choice and to implement the following.

Choice Find
1. Area of square
2. Area of rectangle
3. Area of triangle
Solution

c = input ("Enter any Choice")


if(c==1):
s = input("enter any side of the square")
a = s*s
print"Area = ",a
elif(c==2):
l = input("enter length")
b = input("enter breadth")
a = l*b
print"Area = ",a
elif(c==3):
x = input("enter first side of triangle")
y = input("enter second side of triangle")
z = input("enter third side of triangle")
s = (x+y+z)/2
A = ((s-x)*(s-y)*(s-z))**0.5
print"Area=",A
else:
print "Wrong input"

Output

Enter any Choice2


enter length4
enter breadth6
Area = 24
Python program to check number is positive negative
or zero
write a program to print one of the words negative, zero or positive, according
to whether variable x is less than zero, zero, or greater than zero,
respectively.

Solution

x=int(input("Enter any Integer Number : "))


if x==0:
print("Number is Zero")
elif x>0:
print("It is Positive Number")
else:
print("It is Negative Number")

Output

Enter any Integer Number : 4


It is Positive Number
>>>
======================== R
Enter any Integer Number : -9
It is Negative Number
>>>
========================
Enter any Integer Number : 0
Number is Zero
Python program to calculate electricity bill

Write Python program to calculate Electricity Bill

Solution

tuc=int(input("Enter the number of units consumed :


"))
if tuc>500:
amount=tuc*9.25
surcharge=80
elif tuc>300:
amount=tuc*7.75
surcharge=70
elif tuc>200:
amount=tuc*5.25
surcharge=50
elif tuc>100:
amount=tuc*3.75
surcharge=30
else:
amount=tuc*2.25
surcharge=20
billTotal=amount+surcharge
print("Electricity Bill : ",billTotal)

Output

Enter the number of units consumed : 345

Electricity Bill : 2743.75


Python program to input three number and print in
ascending order
Write Python program to input three number and print in ascending order

Solution

num1=int(input("Enter First number : "))


num2=int(input("Enter Second number : "))
num3=int(input("Enter Third number : "))
if num1<num2 and num1<num3:
if num2<num3:
x,y,z=num1,num2,num3
else:
x,y,z=num1,num3,num2
elif num2<num1 and num2<num3:
if num1<num3:
x,y,z=num2,num1,num3
else:
x,y,z=num2,num3,num1
else:
if num1<num2:
x,y,z=num3,num1,num2
else:
x,y,z=num3,num2,num1
print("Numbers in ascending order are : ",x,y,z)

Output

Enter First number : 50


Enter Second number : 45
Enter Third number : 100
Numbers in ascending order are : 45 50 100
>>>
========================
Enter First number : 30
Enter Second number : 20
Enter Third number : 10
Numbers in ascending order are : 10 20 30
Python program to check character is alphabetic
character or not

Write a Python program to check character is alphabetic character or not

Solution

ch=input("Enter any alphabetic character : ")


if ch>='A' and ch<='Z':
print("The Character is an upper case letter")
elif ch>='a' and ch<='z':
print("The Character is an lower case letter")
else:
print("This is not an alphabetic character!")

Output

Enter any alphabetic character : f


The Character is an lower case letter
>>>
========================
Enter any alphabetic character : R
The Character is an upper case letter
>>>
========================
Enter any alphabetic character : 4
This is not an alphabetic character!
>>>
========================
Enter any alphabetic character : #
This is not an alphabetic character!
Python program to input length of three sides of a
triangle Then check if these sides will form a triangle or
not

Write a program to input length of three sides of a triangle. Then check if


these sides will form a triangle or not.

(Rule is: a+b>c;b+c>a;c+a>b)

Solution

a = int(input("Enter first side : "))


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

if a + b > c and b + c > a and a + c > b :


print("Triangle Possible")
else :
print("Triangle Not Possible")

Output

Enter rst side : 3

Enter second side : 5

Enter third side : 6

Triangle Possible
fi
Python program to input 3 sides of a triangle and print
whether it is an equilateral scalene or isosceles triangle

Write a program to input 3 sides of a triangle and print whether it is an


equilateral, scalene or isosceles triangle.

Solution

a = int(input("Enter first side : "))


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

if a == b and b == c :
print("Equilateral Triangle")
elif a == b or b == c or c == a:
print("Isosceles Triangle")
else :
print("Scalene Triangle")

Output

Enter rst side : 10

Enter second side : 5

Enter third side : 10

Isosceles Triangle
fi
Python program using if Elif else statement to nd the
number of days present in a month

Write a Python program using if Elif else statement to nd the number of days
present in a month:

month=eval(input("Enter Month Sr. No (ex: for Jan


enter - 1 ): "))
if month==1 or month==3 or month==5 or month==7 or
month==8 or month==10 or month==10 :
print("Number of days in Month are 31")
elif month==4 or month==6 or month==9 or month==11:
print("Number of days in Month are 30")
else:
print("Number of days in Month are 28 or 29")

Output

Enter Month Sr. No (ex: for Jan enter - 1 ): 4

Number of days in Month are 30


fi
fi
Python program to accept marks of English math and
science and display the appropriate stream allotted to
the candidate
A school display a notice on the school notice board regarding admission in
Class XI for choosing streams according to the marks obtained in English,
Maths and Science in Class X Council Examination.

Marks obtained in different subjects Stream

Eng., Maths and Science >=80% Pure Science

Eng. And Science >=80%, Maths>=60% Bio. Science

Otherwise Commerce

Write a Python code to accept marks in English, Maths and Science from the
console and display the appropriate stream allotted to the candidate.

e=int(input("Enter marks in English: "))


m=int(input("Enter marks in Marks: "))
s=int(input("Enter marks in Science: "))
if(e>=80 and m>=80 and s>=80):
print("Stream: Pure Science ")
elif(e>=80 and m>=60 and s>=80):
print("Stream: Bio Science")
else:
print("Stream: Commerce")

Output

Enter marks in English: 67


Enter marks in Marks: 45
Enter marks in Science: 67
Stream: Commerce
Python program to calculate income tax based on
condition

Given below is a hypothetical table showing rate of income tax for an Indian
citizen, who is below or up to 60 years.

Taxable Income (TI) in ₹ Income Tax in ₹

Up to ₹ 5,00,000 Nil

More than ₹5,00,000 and less than or equal (TI-5,00,000)* 10%


to ₹7,50,000
More than ₹7,50,000 and less than or equal (TI-7,50,000)* 20% +
to ₹10,00,000 30,000
More than ₹10,00,000 (TI-10,00,000) * 30% +
90,000

Write a Python code to input the name, age and taxable income of a person.
If the age more than 60 years then display a message “Wrong Category”. IF
the age is less than or equal to 60 years then compute and display the
payable income tax along with the name of tax payer, as per the table given
above.

Solution:

tax=0
name=input("Enter name :")
age=int(input("Enter age:"))
sal=int(input("Enter annual salary:"))
if(age>60):
print("Wrong Category!")
else:
if sal<=500000:
tax=0
elif sal<=750000:
tax=(sal-500000)*10/100
elif sal<=1000000:
tax=30000+(sal-750000)*20/100
elif sal>1000000:
tax=90000+(sal-750000)*30/100
print("Name :",name)
print("Age :",age)
print("Tax Payable =₹",tax)

Output

Enter name :ravi

Enter age:45

Enter annual salary:650000

Name : ravi

Age : 45

Tax Payable =₹ 15000.0


Python program to calculate volume of cuboid cylinder
and cone based on user choice

The volume of solids viz. cuboid, cylinder and cone can be calculated by the
following formulae:

1. Volume of a cuboid (V= 1*b*h)

2. Volume of a cylinder (V=*π*r2*h)

3. Volume of a cone (V=1/3*π*r2h) [π= 22/7 ]

Write a Python code by using user’s choice to perform the above task.

Solution:

print("1. Volume of Cuboid");


print("2. Volume of Cylinder");
print("3. Volume of Cone");
c=int(input("Enter your choice: "))
if(c==1):
print("Enter three sides of a cuboid:")
I= float(input("Enter length: "))
b=float(input("Enter breath: "))
h=float(input("Enter height: "))
vol= l*b*h
print("Volume of Cuboid =",vol)
elif(c==2):
print("Enter radius and height of a cylinder")
r=float(input("Enter radius: "))
h=float(input("Enter height: "))
vol=(22*r*r*h)/7
print("Volume of Cylinder =",vol);
elif(c==3):
print("Enter radius and height of a cone")
r= float(input("Enter radius: "))
h= float(input("Enter height: " ))
vol=(22*r*r*h)/(3*7)
print("Volume of cone =",vol);
else:
print("Wrong Choice!!")

Output

1. Volume of Cuboid

2. Volume of Cylinder

3. Volume of Cone

Enter your choice: 2

Enter radius and height of a cylinder

Enter radius: 5.6

Enter height: 9

Volume of Cylinder = 887.0399999999998


Python program to input any number and to nd
reverse of that number

Write a program to input any number and to nd reverse of that number.

Solution

num = int(input("Enter any number"))


rev = 0
while(num>0):
digit=num%10
rev = rev*10+digit
num = num//10
print ("reverse number is", r)

Output

Enter any number 345


reverse number is 543

Python program to input any string and count number


of uppercase and lowercase letters

Write a program to input any string and count number of uppercase and
lowercase letters.

Solution

s=raw_input("Enter any String")


rint s
u=0
fi
fi
l=0
i=0
while i<len(s):
if (s[i].islower()==True):
l+=1
if (s[i].isupper()==True):
u+=1
i+=1
print "Total upper case letters :", u
print "Total Lower case letters :", l

Output

Enter any String Python PROG


Python PROG
Total upper case letters: 5
Total Lower case letters: 5

Python program to accept a integer number and nd its


sum of digit
Write a program to accept a integer number from user and nd its sum of
digit.

Solution

num=int(input("Enter any Number : "))


sum=0
while num>0:
digit=num%10
sum=sum+digit
num=num//10
print("Sum of Digit : ",sum)

Output

Enter any Number : 123


Sum of Digit : 6
fi
fi
Python program to count the number of digits in given
number

Write a python program to accept a integer number and count the number of
digits in number.

Sample:

Input: 2223

Output: Number of Digits: 4

Solution

num=int(input("Enter any Number : "))


count=0
while num>0:
count+=1
num=num//10
print("Number of Digit : ",count)

Output

Enter any Number : 2342

Number of Digit : 4
Python program to nd the largest digit of a given
number

Write a python program to accept a integer number form user and nd the
largest digit of number.

Sample:

Input : 12341

Output : Largest Digit is : 4

Solution

num=int(input("Enter any Number : "))


max=0
while num>0:
digit=num%10
if max<digit:
max=digit
num=num//10
print("Largest Digit is : ",max)

Output

Enter any Number : 23241

Largest Digit is : 4
fi
fi
Python program to nd the smallest digit of a given
number

Write a python program to accept a integer number form user and nd the
smallest digit of number.

Sample:

Input : 12341

Output : Smallest Digit is : 1

Solution

num=int(input("Enter any Number : "))


min=9
while num>0:
digit=num%10
if min>digit:
min=digit
num=num//10
print("Smallest Digit is : ",min)

Output

Enter any Number : 2315

Smallest Digit is : 1
fi
fi
Python program to nd the difference between greatest
and smallest digits presents in the number

Write a python program to accept an integer number to nd out and print the
difference between greatest and smallest digits presents in the number .

Solution

number=int(input("Enter any Number"))


min=9
max=0
while(number>0):
digit=number%10;
if(min>digit):
min=digit;
if(max<digit):
max=digit;
number=number//10;
diff=max-min
print("Greatest Digit : ",max);
print("Smallest Digit : ",min);
print("Difference Between Greatest and Smallest
Digit : ",diff);

Output

Enter any Number34528

Greatest Digit : 8

Smallest Digit : 2

Difference Between Greatest and Smallest Digit : 6


fi
fi
Python program to print the frequency of digits present
in given number

Write a python program to accept an integer number and print the frequency
of each digit present in the number .

Solution

number=int(input("Enter any Number"))


print("Digit\tFrequency")
for i in range(0,10):
count=0;
temp=number;
while temp>0:
digit=temp%10
if digit==i:
count=count+1
temp=temp//10;
if count>0:
print(i,"\t",count)

Output

Enter any Number3148472


Digit Frequency
1 1
2 1
3 1
4 2
7 1
8 1
Python program to check whether given number is
Armstrong or not

Write a program to input any number and to check whether given number is
Armstrong or not.

Example:

Armstrong 153,

1^3+5^3 +3^3 =(1+125+27)=153

Solution

num=int(input("Enter any Number"))


sum=0
tmp=num
while num>0:
digit=(num%10)
sum=sum+digit**3
num=num//10
if sum==tmp:
print(tmp, " is Armstrong Number")
else:
print(tmp, " is not Armstrong Number")

Output

Enter any Number153


153 is Armstrong Number
>>>
========================
Enter any Number123
123 is not Armstrong Number
Python program to convert decimal number to binary

Write a program to convert decimal number to binary.

Solution

num=int(input("Enter Any Number : "))


binary=""
while num>0:
digit=num%2
binary=str(digit)+binary
num=num//2
print("Binary Value : ",binary)

Output

Enter Any Number : 12

Binary Value : 1100


Python program to convert binary to decimal

Write a program to convert binary to decimal.

Solution

num=int(input("Enter Any Binary Number : "))


decimal=0
count=0
while num>0:
digit=num%10
decimal=decimal+digit*(2**count)
num=num//10
count=count+1
print("Decimal Value : ",decimal)

Output

Enter Any Binary Number : 101

Decimal Value : 5

======================

Enter Any Binary Number : 1001

Decimal Value : 9
Python program to input list of numbers and nd those
which are palindromes
Given a list of integers, write a program to nd those which are palindromes.
For example, the number 4321234 is a palindrome as it reads the same from
left to right and from right to left.

Solution

print("Enter numbers:")
print("(Enter 'q' to stop)")

while True :
n = input()
if n == 'q' or n == 'Q' :
break
n = int(n)
t = n
r = 0
while (t != 0) :
d = t % 10
r = r * 10 + d
t = t // 10
if (n == r) :
print(n, "is a Palindrome Number")
else :
print(n, "is not a Palindrome Number")

Output
Enter numbers:
(Enter 'q' to stop)
67826
67826 is not a Palindrome Number
4321234
4321234 is a Palindrome Number
256894
256894 is not a Palindrome Number
122221
122221 is a Palindrome Number
fi
fi
Python program to place and the most signi cant digit
of number
Write a complete Python program to do the following :
(i) read an integer X.
(ii) determine the number of digits n in X.
(iii) form an integer Y that has the number of digits n at ten's place and
the most signi cant digit of X at one's place.
(iv) Output Y.
(For example, if X is equal to 2134, then Y should be 42 as there are 4
digits and the most signi cant number is 2).
Solution

x = int(input("Enter an integer: "))


temp = x
count = 0
digit = -1

while temp != 0 :
digit = temp % 10
count += 1
temp = temp // 10

y = count * 10 + digit

print("Y =", y)

Output

Enter an integer: 2134

Y = 42
fi
fi
fi
Python program to nd the LCM of two input numbers

Write a Python program to input 2 numbers and n the LCM.

Solution

n1=int(input("Enter Number 1 : "))


n2=int(input("Enter Number 2 : "))
if n1 > n2:
greater = n1
else:
greater = n3
while(True):
if((greater % n1 == 0) and (greater % n2 == 0)):
lcm = greater
break
greater += 1
print("L.C.M. : ",lcm)

Output

Enter Number 1 : 21

Enter Number 2 : 5

L.C.M. : 105
fi
fi
Python program to nd GCD of 2 number

Write a Python program to input two number and nd the G.C.D

Solution

n1=int(input("Enter Number 1 : "))


n2=int(input("Enter Number 2 : "))
while(n2):
n1, n2 = n2, n1 % n2
print("G.C.D. : ",n1)

Output

Enter Number 1 : 21

Enter Number 2 : 14

H.C.F. : 7
fi
fi
Python program to check number is special or not

Write a Python Program which accept a number form user and check
number is Special or Not.

Special number is a integer number which where addition of sum of digit and
product of digits are same to number.

Solution:

num=int(input("Enter any Number : "))


sum=0
product=1
temp=num
while num>0:
digit=num%10
sum=sum+digit
product=product*digit
num=num//10
if (product+sum)==temp:
print("it is Special Number ")
else:
print("it is not a Special Number ")

Output

Enter any Number : 29


it is Special Number

========================
Enter any Number : 30
it is not a Special Number

Python program to nd the smallest digit of the input


number
Write a Python code to input a number and nd the smallest digit of the input
number.

Solution:

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


min=n%10
while(n>0):
r=n%10
if(r<min):
min=r
n=n//10
print("Smallest digit : ",min)

Output

Enter a number :4925

Smallest digit : 2
fi
fi
Python program to check whether it is a prime number
or not If it is not a prime then display the next number
that is prime

Write a Python code to input a number and check whether it is a prime


number or not. If it is not a prime then display the next number that is prime.

Solution:

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


c=c1=m=0
for a in range(1, n+1):
if(n%a==0):
c=c+1
if(c==2):
print(n, "is a prime number")
else:
a=n
m=n
while(c1!=2):
a=a+1
c1=0
for p in range(1,a+1):
if(a%p==0):
c1=c1+1
print("Next prime number to ", m , " is ",a)
Output

Enter a number: 11
11 is a prime number
>>>
==========================
Enter a number: 24
Next prime number to 24 is 29
Python program to calculate compound simple interest
after taking the principle rate and time

WAP to calculate compound simple interest after taking the principle, rate and
time.

Solution

p=int(input("Enter the Principal"))


r=int(input("Enter the Interest Rate"))
t=int(input("Enter the Tenure"))
temp=1+r/100
f=1
for i in range(1,t+1):
f=f*temp
Amount=p*f
interest=Amount-p
print("The interest on ",p," with rate ",r," is
",interest)

Output

Enter the Principal500

Enter the Interest Rate4

Enter the Tenure7

The interest on 500 with rate 4 is 157.9658896179202


Python program that searches for prime numbers from
15 through 25

WAP that searches for prime numbers from 15 through 25.

Solution

#WAP that searches for prime numbers from 15 through


25.
for a in range(15,25):
k=0
for i in range(2,a//2+1):
if a%i==0:
k=k+1
if k==0:
print(a)

Output
Python program to test if given number is prime or not

WAP to test if given number is prime or not.

Solution

a=int(input("Enter Number"))
k=0
for i in range(2,a//2+1):
if a%i==0:
k=k+1
if k<=0:
print(a," is Prime Niumber")
else:
print(a," is not a prime Number")

Output
Python program to check whether square root of a
given number is prime or not

WAP to check whether square root of a given number is prime or not.

Solution

import math
n=int(input("Enter a number "))
m=int(math.sqrt(n))
k=0
for i in range(2,m//2+1):
if m%i==0:
k=k+1
if k==0:
print(m,", which square root of ",n," , is Prime
Number.")
else:
print(m,", which square root of ",n," , is NOt
Prime Number.")

Output
Python program to print rst n odd numbers in
descending order.

WAP to print rst n odd numbers in descending order.

Solution

n=int(input("Enter the Limit"))


if n%2==0:
for i in range(n-1,0,-2):
print(i)
else:
for i in range(n,0,-2):
print(i)

Output
fi
fi
Python program to nd the average of the list of the
numbers entered through keyboard

WAP to nd the average of the list of the numbers entered through keyboard.

Solution

#WAP to find the average of the list of the numbers


entered through keyboard.
n=int(input("Enter the Limit "))
s=0
for i in range(1,n+1):
print("Enter ",i,end='')
a=int(input(" the Number : "))
s=s+a
avg=s/n
print("The Sum of entered numbers : ",s)
print("The Average of entered numbers : ",avg)

Output
fi
fi
Python program to nd the largest number from the list
of the numbers entered through keyboard

WAP to nd the largest number from the list of the numbers entered through
keyboard.

Solution

n=int(input("Enter the Limit less than


99999999999"))
small=99999999999
for i in range(1,n+1):
print("Enter ",i,end='')
a=int(input("th number : "))
if a<small:
small=a
print("Smallest no is : ",small)

Output
fi
fi
Python program to nd the sum of n natural numbers
WAP to nd the sum of n natural numbers.

Solution

#WAP to find the sum of n natural numbers.


n=int(input("Enter the Limit : "))
s=0
for i in range(1,n+1):
s=s+i
print("The sum is : ",s)

Output

Enter the Limit : 4

The sum is : 10

Python program to nd the sum of rst n even numbers

WAP to nd the sum of rst n even numbers.

Solution

n=int(input("Enter the Limit : "))


s=0
for i in range(0,n+1,2):
s=s+i
print("The sum is : ",s)

Output

Enter the Limit : 20

The sum is : 110


fi
fi
fi
fi
fi
fi
Python program to nd the sum of rst n odd numbers.
WAP to nd the sum of rst n odd numbers.

Solution

n=int(input("Enter the Limit : "))


s=0

for i in range(1,n+1,2):
s=s+i
print("The sum is : ",s)

Output

Enter the Limit : 10


The sum is : 25

Python program to generate a list of elements of


Fibonacci Series
WAP a program to generate a list of elements of Fibonacci Series.

Solution

n=int(input("Enter the limit : "))


a=-1
b=1
for i in range(1,n+1):
c=a+b
print(c,end=' ')
a=b
b=c

Output

Enter the limit : 20


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
fi
fi
fi
fi
Python program to input any number and to print all
natural numbers up to given number

Write a program to input any number and to print all natural numbers up to
given number.

Solution

n = input("enter any number")


for i in range(1,n+1):
print i

Output

enter any number 10


1 2 3 4 5 6 7 8 9 10

Python program to input any number and to nd sum of


all natural numbers up to given number

Write a program to input any number and to nd sum of all natural numbers
up to given number.

Solution

n = input("Enter any number")


sum= 0
for i in range(1,n+1):
sum = sum+i
print "sum=",sum

Output

Enter any number 5


sum = 15
fi
fi
Python program to nd the factorial value of given
number

Write a Python program to accept a integer number form user and nd the
factorial value of input number.

The factorial of a number is the product of all the integers from 1 to that
number. For example, the factorial of 6 is 1*2*3*4*5*6 = 720 . Factorial is not
de ned for negative numbers, and the factorial of zero is one, 0! = 1 .

Sample:

Input : 5

Output : 120

Solution

num=int(input("Enter any Number : "))


fact=1
for a in range(1,num+1):
fact=fact*a
print("Factorial of ",a," is : ",fact)

Output

Enter any Number : 5

Factorial of 5 is : 120
fi
fi
fi
Python program to print factor of given number

Write a Python program to input any number and print all factors of input
number.

A factor is a number that divides into another number exactly and without
leaving a remainder.

Sample:

Input : 12

Output : Factor of 12 are : 1,2,3,4,6 ,12

Solution

num=int(input("Enter any Number : "))


print("Factor of ",num," are : ",end='')
for a in range(1,num):
if num%a==0:
print(a,end=',')
print(num)

Output

Enter any Number : 12

Factor of 12 are : 1,2,3,4,6,12


Python program to check given number is composite
number or not

Write a Python program to accept a integer number from user and check
number is composite Number or not.

Composite number is a whole numbers that have on 1 or more than 1 factors


excluding 1 and itself.

Solution

num=int(input("Enter any Number : "))


count=0
for a in range(2,num):
if num%a==0:
count+=1
if count>=1:
print(num, "is Composite Number")
else:
print(num, "is Prime Number")

Output

Enter any Number : 10

10 is Composite Number

=========================

Enter any Number : 11

11 is Prime Number
Python program to print table of entered number

write a program to print the table of a given number. The number has to be
entered by the user.

Solution

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


for i in range(1,11):
print(n,'x',i,'=',(n*i))

Output

Enter number : 5

5x1=5

5 x 2 = 10

5 x 3 = 15

5 x 4 = 20

5 x 5 = 25

5 x 6 = 30

5 x 7 = 35

5 x 8 = 40

5 x 9 = 45

5 x 10 = 50
Python program to calculate the sum of odd numbers
divisible by 5 from the range 1 to 100

write a program to calculate the sum of odd numbers divisible by 5 from the
range 1..100

Solution

sum=0
for i in range (1,101,2):
if i%5==0:
sum=sum+i
print("Sum of odd numbers divisible by 5 from range
1 to 100 is : ",sum)

Output

Sum of odd numbers divisible by 5 from range 1 to 100 is : 500


Python program to print Floyds triangle

Write a program to print Floyd's triangle as shown below:

2 3

4 5 6

7 8 9 10

11 12 13 14 15

Solution

x=1
for a in range(1,6):
for b in range(1,a+1):
print(x,end=' ')
x=x+1
print()

Output

2 3

4 5 6

7 8 9 10

11 12 13 14 15
Python program to nd all prime numbers up to given
number

Write a program to nd all prime numbers up to given number

Solution

num=int(input("Enter any Number (Upper Limit) : "))


for a in range(1,num+1):
k=0
for i in range(2,a//2+1):
if a%i==0:
k=k+1
if k==0:
print(a)

Output

Enter any Number (Upper Limit) : 20


1
2
3
5
7
11
13
17
19
fi
fi
Python program to print letters of word

Write Python program to print letters of entered word

Solution

word=input("Enter any word : ")


for letter in word:
print(letter)

Output

Enter any word : infomax

x
Python program to print ASCII code for entered
message

Write a Python program to print ASCII code for entered message

Solution

message=input("Enter Message to encode : ")


print("ASCII code for message : ")
for ch in message:
print(ord(ch),end=" ") # ord function return the
ascii value of char

Output

Enter Message to encode : infomax

ASCII code for message :

105 110 102 111 109 97 120


Python program to print rst ten mersenne numbers

Write Python program to print rst ten mersenne numbers. Numbers in the
form 2n-1 are called Mersenne numbers.

For example, the rst Mersenne number is 21-1=1, the second Mersenne
number is 22-1=3 etc.

Solution

print("First Ten Mersenne numbers are : ")


for n in range(1,11):
num=2**n-1
print(num,end=" ")

Output

First Ten Mersenne numbers are :

1 3 7 15 31 63 127 255 511 1023


fi
fi
fi
Python program to Print numbers from 11 to N When the
number is a multiple of 3 print Tipsy when it is a multiple of 7
print Topsy
Write a program to take N (N > 20) as an input from the user. Print numbers
from 11 to N. When the number is a multiple of 3, print "Tipsy", when it is a
multiple of 7, print "Topsy". When it is a multiple of both, print "TipsyTopsy".

Solution
n = int(input("Enter a number greater than 20: "))
if n <= 20 :
print("Invalid Input")
else :
for i in range(11, n + 1) :
print(i)
if i % 3 == 0 and i % 7 == 0 :
print("TipsyTopsy")
elif i % 3 == 0 :
print("Tipsy")
elif i % 7 == 0 :
print("Topsy")
Output
Enter a number greater than 20: 25
11
12
Tipsy
13
14
Topsy
15
Tipsy
16
17
18
Tipsy
19
20
21
TipsyTopsy
22
23
24
Tipsy
25
Python program to input N numbers and then print the
second largest number
Write a program to input N numbers and then print the second largest
number.

Solution

n = int(input("How many numbers you want to enter?


"))
if n > 1 :
l = int(input()) # Assume first input is
largest
sl = int(input()) # Assume second input is
second largest
if sl > l :
t = sl
sl = l
l = t
for i in range(n - 2) :
a = int(input())
if a > l :
sl = l
l = a
elif a > sl :
sl = a
print("Second Largest Number =", sl)
else :
print("Please enter more than 1 number")

Output

How many numbers you want to enter? 5


55
25
36
12
18
Second Largest Number = 36
Python program to print every integer between 1 and n
divisible by m Also report whether the number that is
divisible by m is even or odd

Write a Python program to print every integer between 1 and n divisible


by m. Also report whether the number that is divisible by m is even or
odd.

m = int(input("Enter m: "))
n = int(input("Enter n: "))
for i in range(1, n) :
if i % m == 0 :
print(i, "is divisible by", m)
if i % 2 == 0 :
print(i, "is even")
else :
print(i, "is odd")
Output

Enter m: 3
Enter n: 20
3 is divisible by 3
3 is odd
6 is divisible by 3
6 is even
9 is divisible by 3
9 is odd
12 is divisible by 3
12 is even
15 is divisible by 3
15 is odd
18 is divisible by 3
18 is even
Python program to check number is perfect number or
not

Write a Python program which accept a integer number form user and
check number is perfect or Not.

A perfect number is a positive integer that is equal to the sum of its


positive divisors, excluding the number itself.

For instance, 6 has divisors 1, 2 and 3, and 1 + 2 + 3 = 6, so 6 is a


perfect number.

Perfect Numbers between 1 to 10000 are:

6,28,496,8128

Solution:

num=int(input("Enter any Number : "))


sum=0
for a in range (1,num):
if num%a==0:
sum=sum+a
if sum==num:
print(num ," is Perfect Number")
else:
print(num ," is not a Perfect Number”)

Output

Enter any Number : 7


7 is not a Perfect Number
========================
Enter any Number : 6

Python program to print all buzz numbers between 1 to n


Write a Python program which accept the value of n and Print all the buzz
numbers between 1 to N.

n=int(input("Enter the value of n: "))


print("Buzz Numbers between 1 to ",n," are: ")
for a in range(1,n+1):
if a%7==0 or n%10==7:
print(a,end='\t')

Output

Enter the value of n: 200


Buzz Numbers between 1 to 200 are:
7 14 21 28 35 42 49 56 63 70 77 84 91
98 105 112 119 126 133 140 147 154 161 168 175 182
189 196
Python program to display the rst ten terms of the
following series 2 5 10 17

Write a Python code to display the rst ten terms of the following series

2, 5, 10, 17,……………………………..

Solution:

print("The first ten terms of the series:")


for a in range(1, 11):
p=a*a+1
print(p, end=' ')

Output

The rst ten terms of the series:

2 5 10 17 26 37 50 65 82 101
fi
fi
fi
Python program to nd the sum of rst ten terms of the
series
Write a Code in Python to display the rst ten terms of the series:

import math
sum=0
n=int(input("Enter the value of n : "))
a=int(input("Enter the value of a : "))
for p in range(1, n+1):
sum=sum+1/math.pow(a,p)
print("Sum of the series=",sum)

Write a code in Python to compute and display the sum of the series:
Solution:

Solution
sum=0
s1=s2=1
n=int(input("Enter the value of n : "))
for p in range(1, n+1):
s1=s1+(p+1)
s2=s2*(p+1)
s=s1/s2
sum=sum+s
print("Sum of the series=",sum)

Output

Enter the value of n : 5

Enter the value of a : 2

Sum of the series= 0.96875


fi
fi
fi
Python function which takes list of integers as input and
nds the followings

Write a Python function which takes list of integers as input and nds:

(a) The largest positive number in the list

(b) The smallest negative number in the list

(c) Sum of all positive numbers in the list

Solution

def calculate(*arg):
print("Largest Number : ",max(arg))
print("Smallest Number : ",min(arg))
s=0
for a in arg:
if a>0:
s=s+a
print("Sum of all Positive Number : ",s)
calculate(1,-2,4,3)

Output

Largest Number : 4

Smallest Number : -2

Sum of all Positive Number : 8


fi
fi
Python program to print all the prime numbers in the
given range

Write a Python program to print all the prime numbers in the given range. an
Interval. A prime number is a natural number greater than 1 that has no
positive divisors other than 1 and itself.

Solution

start=int(input("Enter the Start value"))


end=int(input("Enter the End value"))
print("Prime numbers between ",start," and ",end)
for a in range(start,end+1):
n=a
flag=True
for b in range(2,(n//2)+1):
if n%b==0:
flag=False
if flag==True and n>1:
print(n,end=',')

Output

Enter the Start value11

Enter the End value50

Prime numbers between 11 and 50

11,13,17,19,23,29,31,37,41,43,47
Python program to print the sum of series
Write a Python program to print the sum of series 1^3 + 2^3 + 3^3 + 4^3 +
…….+ n^3 till n-th term. N is the value given by the user.

Solution

n=int(input("Enter the value of n : "))


sum=0
for a in range(1,n+1):
sum=sum+a**3
print("sum of Series : ",sum)

Output

Enter the value of n : 10


sum of Series : 3025

Python program to print rst n perfect numbers


Write a Python program which accept the value of n from user and print
rst n Perfect Numbers.

n=int(input("Enter the value of N : "))


count=0
a=1;
while count<=n:
sum=0
for b in range (1,(a//2)+1):
if a%b==0:
sum=sum+b
if sum==a:
print(a ,end=' ')
count+=1
a+=1
Output

Enter the value of N : 4


6 28 496 8128
fi
fi
Topic : Sequence data types in python

Python program to nd the 2nd largest number from


the list of the numbers entered through keyboard.

WAP to nd the 2nd largest number from the list of the numbers entered
through keyboard.

Solution

a=[]
n=int(input("Enter the number of elements : "))
for i in range(1,n+1):
b=int(input("Enter element : "))
a.append(b)
a.sort()
print("Second largest element is : ",a[n-2])

Output

Enter the number of elements : 5


Enter element : 23
Enter element : 45
Enter element : 2
Enter element : 34
Enter element : 1
Second largest element is : 34
fi
fi
Python program that creates a list of numbers from 1 to
20 that are divisible by 4
Write a python program that creates a list of numbers from 1 to 20 that are
divisible by 4

Solution
divBy4=[ ]
for i in range(21):
if (i%4==0):
divBy4.append(i)
print(divBy4)
Output

[0, 4, 8, 12, 16, 20]

Python program to de ne a list of countries that are a


member of BRICS Check whether a county is member
of BRICS or not
Write a python program to de ne a list of countries that are a member
of BRICS. Check whether a county is member of BRICS or not

Solution
country=["India", "Russia", "Srilanka", "China",
"Brazil"]
is_member = input("Enter the name of the country: ")
if is_member in country:
print(is_member, " is the member of BRICS")
else:
print(is_member, " is not a member of BRICS")

Output

Enter the name of the country: India


India is the member of BRICS
----------------------------------------------
Enter the name of the country: Japan
Japan is not a member of BRICS
fi
fi
Python program to read marks of six subjects and to
print the marks scored in each subject and show the
total marks

Python program to read marks of six subjects and to print the marks scored
in each subject and show the total marks

Solution

marks=[]
subjects=['Tamil', 'English', 'Physics',
'Chemistry', 'Comp. Science', 'Maths']
for i in range(6):
m=int(input("Enter Mark = "))
marks.append(m)
for j in range(len(marks)):
print("{ }. { } Mark = { }
".format(j1+,subjects[j],marks[j]))
print("Total Marks = ", sum(marks))
Output

Enter Mark = 45
Enter Mark = 98
Enter Mark = 76
Enter Mark = 28
Enter Mark = 46
Enter Mark = 15

1. Tamil Mark = 45
2. English Mark = 98
3. Physics Mark = 76
4. Chemistry Mark = 28
5. Comp. Science Mark = 46
6. Maths Mark = 15
Total Marks = 308
Python program to read prices of 5 items in a list and
then display sum of all the prices product of all the
prices and nd the average
Python program to read prices of 5 items in a list and then display sum of
all the prices, product of all the prices and nd the average

Solution
items=[]
prod=1
for i in range(5):
print ("Enter price for item { } :
".format(i+1))
p=int(input())
items.append(p)
for j in range(len(items)):
print("Price for item { } = Rs.
{ }".format(j+1,items[j]))
prod = prod * items[j]
print("Sum of all prices = Rs.", sum(items))
print("Product of all prices = Rs.", prod)
print("Average of all prices = Rs.",sum(items)/
len(items))

Output
Enter price for item 1 : 5
Enter price for item 2 : 10
Enter price for item 3 : 15
Enter price for item 4 : 20
Enter price for item 5 : 25
Price for item 1 = Rs. 5
Price for item 2 = Rs. 10
Price for item 3 = Rs. 15
Price for item 4 = Rs. 20
Price for item 5 = Rs. 25
Sum of all prices = Rs. 75
Product of all prices = Rs. 375000
Average of all prices = Rs. 15.0
fi
fi
Python program to count the number of employees
earning more than 1 lakh per annum
Python program to count the number of employees earning more than 1
lakh per annum. The monthly salaries of n number of employees
are given

Solution

count=0
n=int(input("Enter no. of employees: "))
print("No. of Employees",n)
salary=[]
for i in range(n):
print("Enter Monthly Salary of Employee { } Rs.:
".format(i+1))
s=int(input())
salary.append(s)
for j in range(len(salary)):
annual_salary = salary[j] * 12
print ("Annual Salary of Employee { } is:Rs.
{ }".format(j+1,annual_salary))
if annual_salary >= 100000:
count = count + 1
print("{ } Employees out of { } employees are
earning more than Rs. 1 Lakh per
annum".format(count, n))

Output

Enter no. of employees: 5


No. of Employees 5
Enter Monthly Salary of Employee 1 Rs.:
3000
Enter Monthly Salary of Employee 2 Rs.:
9500
Enter Monthly Salary of Employee 3 Rs.:
12500
Enter Monthly Salary of Employee 4 Rs.:
5750
Enter Monthly Salary of Employee 5 Rs.:
8000
Annual Salary of Employee 1 is:Rs. 36000
Annual Salary of Employee 2 is:Rs. 114000
Annual Salary of Employee 3 is:Rs. 150000
Annual Salary of Employee 4 is:Rs. 69000
Annual Salary of Employee 5 is:Rs. 96000
2 Employees out of 5 employees are earning more than Rs. 1 Lakh per
annum

Python program to create a list of numbers in the range


1 to 10 Then delete all the even numbers from the list
and print the nal list
Write a program to create a list of numbers in the range 1 to 10. Then
delete all the even numbers from the list and print the nal list.

Solution

Num = []
for x in range(1,11):
Num.append(x)
print("The list of numbers from 1 to 10 = ", Num)
for index, i in enumerate(Num):
if(i%2==0):
del Num[index]
print("The list after deleting even numbers = ",
Num)
Output

The list of numbers from 1 to 10 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


The list after deleting even numbers = [1, 3, 5, 7, 9]
fi
fi
Python program to generate in the Fibonacci series
and store it in a list Then nd the sum of all values

Write a program to generate in the Fibonacci series and store it in a list.


Then nd the sum of all values.

Solution

a=-1
b=1
n=int(input("Enter no. of terms: "))
i=0
sum=0
Fibo=[]
while i<n:
s = a + b
Fibo.append(s)
sum+=s
a = b
b = s
i+=1
print("Fibonacci series upto "+ str(n) +" terms is :
" + str(Fibo))
print("The sum of Fibonacci series: ",sum)

Output

Enter no. of terms: 10

Fibonacci series upto 10 terms is : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

The sum of Fibonacci series: 88


fi
fi
Python program to nd minimum element from a list of
elements along with its index in the list

WAP to nd minimum element from a list of elements along with its index in
the list.

Solution

L=[2,58,95,999,65,32,15,1,7,45]
print(L)
m=min(L)
print("The Minimum element is : ",m)
print("Index of minimum element is : ",L.index(m))

Output

The Minimum element is : 1


Index of minimum element is : 7

Python program to calculate mean of a given list of


numbers
WAP to calculate mean of a given list of numbers.

Solution

from statistics import mean


L=[2,58,95,999,65,32,15,1,7,45]
m=mean(L)
print("Mean of List is : ",m)

Output

Mean of List is : 131.9


fi
fi
Python program to search for an element in a given list
of numbers
WAP to search for an element in a given list of numbers.

Solution 1:

L=[2,58,95,999,65,32,15,1,7,45]
n=int(input("Enter the number to be searched : "))
if n in L:
print("Item found at the Position : ",L.index(n)
+1)
else:
print("Item not found in list”)

Hear we use in operator of list which is used to check where an element is


parent in list or not, and index function help to nd the index of given
element.

Solution 2:

L=[2,58,95,999,65,32,15,1,7,45]
n=int(input("Enter the number to be searched : "))
found=0
for x in L:
if x==n:
print("Item found at the Position : ",L.index(n)
+1)
found=1
if found==0:
print("Item not found in list")
Output

Enter the number to be searched : 6


Item not found in list
===============================
Enter the number to be searched : 15
Item found at the Position : 7
fi
Python program to count frequency of a given element
in a list of numbers
WAP to count frequency of a given element in a list of numbers.

Solution

L=[2,58,95,999,65,32,15,1,7,45]
n=int(input("Enter the number : "))
print("The frequency of number ",n," is
",L.count(n))

Output

Enter the number : 3


The frequency of number 3 is 0
--------------------------------------------------------

Enter the number : 58


The frequency of number 58 is 1

Python program to calculate the sum of integers of the list


WAP to calculate the sum of integers of the list

Solution

L=[1,2,"Two",3,4,"four",5]
s=0
for x in L:
if type(x)==int:
s=s+x
print("The sum of integers is : ",s)

Output

The sum of integers is : 15


Python program to reverses an array of integers

WAP that reverses an array of integers (in place)

Solution

L=[1,2,3,4,5,6]
end=len(L)-1
limit=int(end/2)+1
for i in range(limit):
L[i],L[end]=L[end],L[i]
end=end-1
print(L)

Output

[6, 5, 4, 3, 2, 1]
Python program to creates a third list after adding two
lists

WAP that creates a third list after adding two lists.

Solution

list1=eval(input("Enter list 1 : "))


list2=eval(input("Enter list 2 : "))
list3=list1+list2
print("Given List are : ",list1," and ",list2)
print("The sum of list are : ",list3)

Output

Enter list 1 : 3,4,5


Enter list 2 : 2,5,6,4
Given List are : (3, 4, 5) and (2, 5, 6, 4)
The sum of list are : (3, 4, 5, 2, 5, 6, 4)
Python program that input a list, replace it twice and
then prints the sorted list in ascending and descending
order

write a program that input a list, replace it twice and then prints the sorted list
in ascending and descending order.

Solution

val=eval(input("Enter a list:"))
print("Original List :",val)
val=val*2
print("Replaced List :",val)
val.sort()
print("Sorted in ascending order :",val)
val.sort(reverse=True)
print("Sorted in Descending order :",val)

Output

Enter a list:[4,5,6,6,75,5]
Original List : [4, 5, 6, 6, 75, 5]
Replaced List : [4, 5, 6, 6, 75, 5, 4, 5, 6, 6, 75, 5]
Sorted in ascending order : [4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 75, 75]
Sorted in Descending order : [75, 75, 6, 6, 6, 6, 5, 5, 5, 5, 4, 4]
Python program to check if the maximum element of
the list lies in the rst half of the list or in the second
half

write a program to check if the maximum element of the list lies in the rst half
of the list or in the second half.

Solution

lst=eval(input("Enter a list :"))


ln=len(lst)
mx=max(lst)
ind=lst.index(mx)
if ind<=(ln/2):
printf("The maximum element ",mx,"lies in the
1st half.")
else:
print("The maximum element ",mx,"lies in the 2nd
half.")

Output

Enter a list :[4,5,6,7,5,6,12]

The maximum element 12 lies in the 2nd half.


fi
fi
Python program to display the maximum elements from
the two list along with its index in its list

write a program to input two lists and display the maximum elements from the
elements of both the list combined, along with its index in its list.

Solution

lst1=eval(input("Enter List 1"))


lst2=eval(input("Enter List 2"))
mx1=max(lst1)
mx2=max(lst2)
if mx1>=mx2:
print(mx1,"the maximum value in is in the list 1
at index ",lst1.index(mx1))
else:
print(mx2,"the maximum value in is in the list 2
at index ",lst2.index(mx2

))

Output

Enter List 1[4,5,6,2,3]

Enter List 2[8,3,4,2]

8 the maximum value in is in the list 2 at index 0


Python program to swap list elements with even and
locations

write a program to input a list of numbers and swap elements at the even
location with the elements at the odd location.

Solution

val=eval(input("Enter a list "))


print("Original List is:",val)
s=len(val)
if s%2!=0:
s=s-1
for i in range(0,s,2):
val[i],val[i+1]=val[i+1],val[i]
print("List after swapping :",val)

Output

Enter a list [3,4,5,6]

Original List is: [3, 4, 5, 6]

List after swapping : [4, 3, 6, 5]


Python program to rotate list elements with next
elements

Write a program rotates the elements of a list so that the elements at the rst
index moves to the second index , the element in the second index moves to
the third index, etc., and the element at the last index moves to the rst index.

Solution

lst=eval(input("Enter a list : "))


print("List before Rotation :",lst)
a=lst[0]
s=len(lst)
for i in range(1,s):
lst[i-1]=lst[i]
lst[s-1]=a
print("List after Rotate :",lst)

Output

Enter a list : [3,4,5,6]

List before Rotation : [3, 4, 5, 6]

List after Rotate : [4, 5, 6, 3]


fi
fi
Python program to increment the elements of list

Write a python program to increment the elements of a list with a number.

Solution

mylist=eval(input("Enter any List"))


print("Before increment list is ",mylist)
a=0
for b in mylist:
mylist[a]=b+1
a=a+1
print("After increment list is ",mylist)

Output

Enter any List[5,7,8,4]

Before increment list is [5, 7, 8, 4]

After increment list is [6, 8, 9, 5]


Python program to enter a list containing number
between 1 and 12 then replace all the entries in the list
that are greater than 10 with 10

Ask the use to enter a list containing number between 1 and 12, then replace
all the entries in the list that are greater than 10 with 10

Solution

mylist=eval(input("Enter any List"))


print("Before Replace list is ",mylist)
a=0
for b in mylist:
if b>10:
mylist[a]=10
a=a+1
print("After Replace list is ",mylist)

Output

Enter any List[4,12,5,10,11,7]

Before Replace list is [4, 12, 5, 10, 11, 7]

After Replace list is [4, 10, 5, 10, 10, 7]


Python program that reverse the list of integers in place

Write a Python program that reverse a list of integers (in place)

Solution

mylist=eval(input("Enter any List"))


print("Before Reverse list is ",mylist)
mylist.reverse()
print("After Replace list is ",mylist)

Output

Enter any List[5,7,8,9]

Before Reverse list is [5, 7, 8, 9]

After Replace list is [9, 8, 7, 5]


Python program to input two list and create third list
which contains all elements of the rst elements
followed by all elements of second list

Write a python program that inputs two lists and creates a third, that contains
all elements of the rst followed by all elements of the second.

Solution

list1=eval(input("Enter List 1 : "))


list2=eval(input("Enter List 2 : "))
list3=list1+list2
print(list3)

Output

Enter List 1 : [4,5,6,7]

Enter List 2 : [1,2,3]

[4, 5, 6, 7, 1, 2, 3]
fi
fi
Python program to inter list of string and create a new
list that consist of those strings with their rst
characters removed

Ask the user to inter list of string. Create a new list that consist of those
strings with their rst characters removed.

Solution

mylist=eval(input("Enter List with string elements :


"))
print('Original List ',mylist)
a=0
for b in mylist:
mylist[a]=b[1:len(b)]
a=a+1
print('Result List ',mylist)

Output

Enter List with string elements : ['infomax','computer','academy']

Original List ['infomax', 'computer', 'academy']

Result List ['nfomax', 'omputer', ‘cademy']


fi
fi
Python program to create a list using for loop which
consist of integers 0 through 49

Write a Python program to Create a list using for loop which consist of
integers 0 through 49

Solution

mylist=list()
for a in range(0,50):
mylist.append(a)
print("Result List is: ",mylist)

Output

Result List is: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
Python program to create a list using for loop which
consist square of the integers 1 through 50

Write a Python program to create a list using for loop which consist square of
the integers 1 through 50

Solution

mylist=list()
for a in range(1,51):
mylist.append(a**2)
print("Result List is: ",mylist)

Output

Result List is: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225,
256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900,
961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764,
1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500]
Python program to create a list using for loop which
consist a bb ccc dddd that ends with 26 copies of the
letter z.

Write a Python program to create a list using for loop which consist
['a','bb','ccc','dddd',....] that ends with 26 copies of the letter z.

Solution

mylist=list()
for a in range(1,27):
mylist.append(chr(a+96)*a)
print("Result List is: ",mylist)

Output

Result List is: ['a', 'bb', 'ccc', 'dddd', 'eeeee', 'ffffff', 'ggggggg', 'hhhhhhhh',
'iiiiiiiii', 'jjjjjjjjjj', 'kkkkkkkkkkk', 'llllllllllll', 'mmmmmmmmmmmmm',
'nnnnnnnnnnnnnn', 'ooooooooooooooo', 'pppppppppppppppp',
'qqqqqqqqqqqqqqqqq', 'rrrrrrrrrrrrrrrrrr', 'sssssssssssssssssss', 'tttttttttttttttttttt',
'uuuuuuuuuuuuuuuuuuuuu', 'vvvvvvvvvvvvvvvvvvvvvv',
'wwwwwwwwwwwwwwwwwwwwwww', 'xxxxxxxxxxxxxxxxxxxxxxxx',
'yyyyyyyyyyyyyyyyyyyyyyyyy', ‘zzzzzzzzzzzzzzzzzzzzzzzzzz']
Python program that takes any two list L and M of the
same size and adds their elements together in another
third list

Write a python program that takes any two list L and M of the same size and
adds their elements together to from a new list N whose elements are sums
of the corresponding elements in L and M.

For instance, if L=[3,1,4] and M= [1,5,9] the N should equal [4,6,13].

print("Enter Two list of same Size")


L=eval(input("Enter List 1 : "))
M=eval(input("Enter list 2 : "))
N=[]
if len(L)!=len(M):
print("The size of both list are not same : ")
else:
for a in range(0,len(M)):
N.append(L[a]+M[a])
print("Result List :",N)
Output
Enter Two list of same Size
Enter List 1 : [4,5,3,5,6]
Enter list 2 : [3,2,3,4,5]
Result List : [7, 7, 6, 9, 11]
>>>
========================
Enter Two list of same Size
Enter List 1 : [1,2,3,4]
Enter list 2 : [1,2,4]
The size of both list are not same :
Python program to rotates the elements of list so that
st elements move to second and second to the third

Write a python program to rotates the elements of a list so that the elements
at the rst index moves to the second index, the element in the second index
moves to the third index, etc. and the elements in the last index moves to the
rst index.

mylist=eval(input("Enter any List of Integer : "))


temp=mylist[len(mylist)-1]
for a in range(len(mylist)-1,0,-1):
mylist[a]=mylist[a-1]
mylist[0]=temp
print("After Shift List is : ",mylist)

Output

Enter any List of Integer : [3,5,8,9,6]

After Shift List is : [6, 3, 5, 8, 9]


fi
fi
fi
Python program to move all duplicate element to the
end of list

Write a python program to move all duplicate values in a list to the end of the
list.

Solution

mylist=eval(input("Enter any List : "))


for a in range(0,len(mylist)):
for b in range(a-1,-1,-1):
if mylist[a]==mylist[b]:
mylist.append(mylist[b])
mylist.pop(b)
print(mylist)

Python program to compare two equal sized list and


print the rst index where they differ

Write a python program to compare two equal sized list and print the rst
index where they differ

Solution

list1=eval(input("Enter list 1 : "))


list2=eval(input("Enter list 2 : "))
index=-1
if(len(list1)!=len(list2)):
print("Length of both list are not same")
else:
fi
fi
for a in range(0,len(list1)):
if list1[a]!=list2[a]:
index=a
break
if index>=0:
print("the elements are differ and the first
index where it differ is :",index)
else:
print("The list elements are same")

Output

Enter list 1 : [1,2,3,4]


Enter list 2 : [1,2,3]
Length of both list are not same
>>>
========================
Enter list 1 : [1,2,3,4,5]
Enter list 2 : [1,2,5,6,7]
the elements are di er and the rst index where it di er is : 2
>>>
========================
Enter list 1 : [1,2,3]
Enter list 2 : [1,2,3]
The list elements are same
ff
fi
ff
Python program that receives a Fibonacci series term
and returns a number telling which term it is

Write a Python program that receives a Fibonacci series term and returns a
number telling which term it is . for instance, if you pass 3, it return 5, telling it
is 5th term; for 8, it returns 7.

Solution

fib=[]
a,b=-1,1
c=0
ind=int(input("Enter any Element : "))
while c<=ind:
c=a+b
fib.append(c)
a,b=b,c
#print(fib)
print("Element ",ind," Found at :",fib.index(ind)
+1,"Position")

Output

Enter any Element : 8

Element 8 Found at : 7 Position


Python Program to accept three distinct digits and print
all possible combinations from the digits

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


b=int(input("Enter second number:"))
c=int(input("Enter third number:"))
d=[]
d.append(a)
d.append(b)
d.append(c)
for i in range(0,3):
for j in range(0,3):
for k in range(0,3):
if(i!=j&j!=k&k!=i):
print(d[i],d[j],d[k])

Output

Enter rst number:4


Enter second number:3
Enter third number:5
435
453
345
354
543
534
fi
Python Program to nd the successor and predecessor
of the largest element in list

Python Program to nd the successor and predecessor of the largest element


in list

Solution

mylist=eval(input("Enter any List : "))


m=max(mylist)
mi=mylist.index(m)
#print(m," -> ",mi)
if mi>0:
print("Predecessor of Largest No.
",mylist[mi-1])
else:
print("No Predecessor Exist")

if mi<len(mylist)-1:
print("Successor of Largest No. ",mylist[mi+1])
else:
print("No Successor Exist")

Output

Enter any List : [1,2,3,5,2,1]


Predecessor of Largest No. 3
Successor of Largest No. 2
>>>
======================
Enter any List : [1,2,3,4]
Predecessor of Largest No. 3
No Successor Exist
>>>
======================
Enter any List : [4,3,2,1]
No Predecessor Exist
Successor of Largest No. 3
fi
fi
Python program to swap two values using tuple
assignment

Write a program to swap two values using tuple assignment

Solution

a = int(input("Enter value of A: "))


b = int(input("Enter value of B: "))
print("Value of A = ", a, "\n Value of B = ", b)
(a, b) = (b, a)
print("Value of A = ", a, "\n Value of B = ", b)

Output

Enter value of A: 54

Enter value of B: 38

Value of A = 54

Value of B = 38

Value of A = 38

Value of B = 54
Python program using a function that returns the area
and circumference of a circle whose radius is passed
as an argument

Write a python program using a function that returns the area


and circumference of a circle whose radius is passed as an
argument.two values using tuple assignment

Solution

pi = 3.14
def Circle(r):
return (pi*r*r, 2*pi*r)
radius = float(input("Enter the Radius: "))
(area, circum) = Circle(radius)
print ("Area of the circle = ", area)
print ("Circumference of the circle = ", circum)

Output

Enter the Radius: 5

Area of the circle = 78.5

Circumference of the circle = 31.400000000000002


Python program that has a list of positive and negative
numbers Create a new tuple that has only positive
numbers from the list

Write a program that has a list of positive and negative numbers. Create a
new tuple that has only positive numbers from the list

Solution

Numbers = (5, -8, 6, 8, -4, 3, 1)


Positive = ( )
for i in Numbers:
if i > 0:
Positive += (i, )
print("Positive Numbers: ", Positive)

Output

Positive Numbers: (5, 6, 8, 3, 1)


Python program to nd maximum and minimum values
in tuple

Write a program to input ‘n’ numbers and store it in a tuple and nd maximum
& minimum values in the tuple.

Solution

t=tuple()
n=int(input("Total number of values in tuple"))
for i in range(n):
a=input("enter elements")
t=t+(a,)
print ("maximum value=",max(t))
print ("minimum value=",min(t))

Output

Total number of values in tuple5

enter elements3

enter elements4

enter elements5

enter elements6

enter elements2

maximum value= 6

minimum value= 2
fi
fi
Python program to interchange the values of two tuple
Write a program to input any two tuples and interchange the tuple values.
Solution

t1=tuple()
n=int(input("Total number of values in first
tuple"))
for i in range(n):
a=input("enter elements")
t1=t1+(a,)
t2=tuple()
m=int(input("Total number of values in second
tuple"))
for i in range(m):
a=input("enter elements")
t2=t2+(a,)
print ("Before SWAPPING")
print ("First Tuple",t1)
print ("Second Tuple",t2)
t1,t2=t2,t1
print ("AFTER SWAPPING")
print ("First Tuple",t1)
print ("Second Tuple",t2)

Output
Total number of values in rst tuple3
enter elements10
enter elements20
enter elements30
Total number of values in second tuple4
enter elements100
enter elements200
enter elements300
enter elements400
Before SWAPPING
First Tuple ('10', '20', '30')
Second Tuple ('100', '200', '300', '400')
AFTER SWAPPING
First Tuple ('100', '200', '300', '400')
Second Tuple ('10', '20', '30')
fi
Write a program to input any two tuples and
interchange the tuple values.
Solution

t1=eval(input("Enter Tuple 1"))


t2=eval(input("Enter Tuple 2"))
print ("Before SWAPPING")
print ("First Tuple",t1)
print ("Second Tuple",t2)
t1,t2=t2,t1
print ("AFTER SWAPPING")
print ("First Tuple",t1)
print ("Second Tuple",t2)

Output

Enter Tuple 1(1,2,3)

Enter Tuple 2(5,6,7,8)

Before SWAPPING

First Tuple (1, 2, 3)

Second Tuple (5, 6, 7, 8)

AFTER SWAPPING

First Tuple (5, 6, 7, 8)

Second Tuple (1, 2, 3)


Python program to interchange the values of two tuple
Write a program to input any two tuples and interchange the tuple values.

Solution

t1=tuple()
n=int(input("Total number of values in first
tuple"))
for i in range(n):
a=input("enter elements")
t1=t1+(a,)
t2=tuple()
m=int(input("Total number of values in second
tuple"))
for i in range(m):
a=input("enter elements")
t2=t2+(a,)
print ("Before SWAPPING")
print ("First Tuple",t1)
print ("Second Tuple",t2)
t1,t2=t2,t1
print ("AFTER SWAPPING")
print ("First Tuple",t1)
print ("Second Tuple",t2)

Output
Total number of values in rst tuple3
enter elements10
enter elements20
enter elements30
Total number of values in second tuple4
enter elements100
enter elements200
enter elements300
enter elements400
Before SWAPPING
First Tuple ('10', '20', '30')
Second Tuple ('100', '200', '300', '400')
AFTER SWAPPING
First Tuple ('100', '200', '300', '400')
Second Tuple ('10', '20', '30')
fi
Write a program to input any two tuples and
interchange the tuple values.
Solution

t1=eval(input("Enter Tuple 1"))


t2=eval(input("Enter Tuple 2"))
print ("Before SWAPPING")
print ("First Tuple",t1)
print ("Second Tuple",t2)
t1,t2=t2,t1
print ("AFTER SWAPPING")
print ("First Tuple",t1)
print ("Second Tuple",t2)

Output

Enter Tuple 1(1,2,3)

Enter Tuple 2(5,6,7,8)

Before SWAPPING

First Tuple (1, 2, 3)

Second Tuple (5, 6, 7, 8)

AFTER SWAPPING

First Tuple (5, 6, 7, 8)

Second Tuple (1, 2, 3)


Python program that create a tuple storing rst 9 terms
of Fibonacci series

Write a Python program that create a tuple storing rst 9 terms of Fibonacci
series

Solution

fib=[]
a,b=-1,1
for i in range(1,10):
c=a+b
fib.append(c)
a,b=b,c
fib_tup=tuple(fib)
print(fib_tup)

Output

(0, 1, 1, 2, 3, 5, 8, 13, 21)


fi
fi
Python program that receives the index and return the
corresponding value

write a python program that receives the index and return the corresponding
value

Solution

t1=(45,3,2,3,5,6,9,3,2)
ind=int(input("Enter any Index : "))
print("Value at ",ind," index is ",t1[ind])

Output

Enter any Index : 4

Value at 4 index is 5
Python program to create a nested tuple to store roll
number name and marks of students
write a program to create a nested tuple to store roll number, name and
marks of students.

Solution

tup= ()
while True :
roll = int(input("Enter a roll number : "))
name = input("Enter name :")
mark = input("Enter marks :")
tup += ( (roll,name,mark ),)
flag = input("Do you want add another record
(if yes the pres Y ) :")
if flag not in ['y','Y']:
break
print(tup)

Output

Enter a roll number : 101


Enter name :sam
Enter marks :567
Do you want add another record (if yes the pres Y ) :y
Enter a roll number : 102
Enter name :zaq
Enter marks :400
Do you want add another record (if yes the pres Y ) :n
((101, 'sam', '567'), (102, 'zaq', ‘400'))
Python program that interactively creates a nested
tuple to store the marks in three subjects for ve
students

Write a program that interactively creates a nested tuple to store the


marks in three subjects for ve students.

i.e., tuple will look somewhat like: marks((45,45,40),(35,40,38),(36,30,38),


(25,27,20),(10,15,20))

tup= ()
for a in range(1,6):
print("Enter the Marks for student ",a)
sub1= int(input("Enter Marks for Sub 1 : "))
sub2= int(input("Enter Marks for Sub 2 : "))
sub3= int(input("Enter Marks for Sub 3 : "))
tup += ( (sub1,sub2,sub3 ),)
print(tup)

Output

Enter the Marks for student 1


Enter Marks for Sub 1 : 34
Enter Marks for Sub 2 : 23
Enter Marks for Sub 3 : 45
Enter the Marks for student 2
Enter Marks for Sub 1 : 56
Enter Marks for Sub 2 : 34
Enter Marks for Sub 3 : 45
Enter the Marks for student 3
Enter Marks for Sub 1 : 34
Enter Marks for Sub 2 : 56
Enter Marks for Sub 3 : 67
Enter the Marks for student 4
Enter Marks for Sub 1 : 34
Enter Marks for Sub 2 : 34
Enter Marks for Sub 3 : 45
Enter the Marks for student 5
Enter Marks for Sub 1 : 56
Enter Marks for Sub 2 : 67
Enter Marks for Sub 3 : 44
((34, 23, 45), (56, 34, 45), (34, 56, 67), (34, 34, 45), (56, 67, 44))
fi
fi
Python Program that generate a set of prime numbers
and another set of even numbers

Python Program that generate a set of prime numbers and another set of
even numbers. Demonstrate the result of union, intersection,
difference and symmetirc difference operations.

Solution

even=set([x*2 for x in range(1,11)])


primes=set()
for i in range(2,20):
j=2
f=0
while j<i/2:
if i%j==0:
f=1
j+=1
if f==0:
primes.add(i)
print("Even Numbers: ", even)
print("Prime Numbers: ", primes)
print("Union: ", even.union(primes))
print("Intersection: ", even.intersection(primes))
print("Difference: ", even.difference(primes))
print("Symmetric Difference: ",
even.symmetric_difference(primes))

Output

Even Numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}


Prime Numbers: {2, 3, 4, 5, 7, 11, 13, 17, 19}
Union: {2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20}
Intersection: {2, 4}
Di erence: {6, 8, 10, 12, 14, 16, 18, 20}
Symmetric Di erence: {3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20}
ff
ff
Python program to store the product information in
dictionary

WAP that repeatedly asks the user to enter product names and prices. Store
all of them in a dictionary whose keys are product names and values are
prices. And also write a code to search an item from the dictionary.

Solution

dict={}
ch='y'
while ch=='y' or ch=='Y':
name=input("Enter name of product : ")
price=eval(input("Enter the price of product :
"))
dict[name]=price
ch=input("Want to add more items (Y/N) : ")
print(dict)
nm=input("Enter the product you want to search : ")
for x in dict:
if x==nm:
print("Product found and the price of
product ",x," is ",dict[x])

Output

Enter name of product : pen


Enter the price of product : 45
Want to add more items (Y/N) : y
Enter name of product : notebook
Enter the price of product : 40
Want to add more items (Y/N) : y
Enter name of product : pencil
Enter the price of product : 10
Want to add more items (Y/N) : n
{'pen': 45, 'notebook': 40, 'pencil': 10}
Enter the product you want to search : notebook
Product found and the price of product notebook is 40
Python program to create a dictionary whose keys are
month names and values are their corresponding
number of days

WAP to create a dictionary named year whose keys are month names and
values are their corresponding number of days.

Solution

dict={}
ch='y'
while ch=='y' or ch=='Y':
month=input("Enter name of month : ")
days=eval(input("Enter no. of days of month :
"))
dict[month]=days
ch=input("Want to add more months (Y/N) : ")
print(dict)

Output

Enter name of month : january


ENter no. of days of month : 31
Want to add more months (Y/N) : y
Enter name of month : February
ENter no. of days of month : 28
Want to add more months (Y/N) : n
{'january': 31, 'February': 28}
Python program to enter names of employees and their
salaries as input and store them in a dictionary

Write a Python program to enter names of employees and their salaries as


input and store them in a dictionary

Solution

emp_dic = { }
while True :
name = input("Enter employee name : ")
sal = int(input("Enter employee salary : "))
emp_dic[ name] = sal
choice = input("Do you want to Enter another
record Press 'y' if yes : ")
if choice != "y" :
break
print(emp_dic)

Output

Enter employee name : amit


Enter employee salary : 4000
Do you want to Enter another record Press 'y' if yes : y
Enter employee name : sumit
Enter employee salary : 5000
Do you want to Enter another record Press 'y' if yes : y
Enter employee name : mohit
Enter employee salary : 4500
Do you want to Enter another record Press 'y' if yes : n
{'amit': 4000, 'sumit': 5000, 'mohit': 4500}
Python program to count the number of times a
character appears in a given string

Write a program to count the number of times a character appears in a given


string

Solution

mystr = input("Enter any String : ")


mydic = { }
for i in mystr :
mydic [ i ] = mystr.count( i )
print(mydic)

Output

Enter any String : infomax computer academy

{'i': 1, 'n': 1, 'f': 1, 'o': 2, 'm': 3, 'a': 3, 'x': 1, ' ': 2, 'c': 2, 'p': 1, 'u': 1, 't': 1, 'e': 2, 'r':
1, 'd': 1, 'y': 1}
Python program to convert a number entered by the
user into its corresponding number in words

Write a program to convert a number entered by the user into its


corresponding number in words.

For example, if the input is 876 then the output should be 'Eight Seven Six'.

Solution

num = input ("enter a number = ")


dic = { "0" : "zero" , "1":"one " , "2" : "two" ,
"3" : "three" , "4" : "four" , "5" : "five" , "6" :
"six" , "7" : "seven" , "8" : "eight" , "9" :
"nine"}
for i in num :
print( dic[ i ], end = " ")

Output

enter a number = 456

four ve six
fi
Python program Repeatedly ask the user to enter a
team name

Repeatedly ask the user to enter a team name and how many games the
team has won and how many they lost. Store this information in a dictionary
where the keys are the team names and the values are a list of the form
[wins, losses ].

(i) using the dictionary created above, allow the user to enter a team name
and print out the team’s winning percentage.

(ii) using dictionary create a list whose entries are the number of wins for
each team.

(iii) using the dictionary, create a list of all those teams that have winning
records.

Solution

dic ={}
lstwin = []
lstrec = []
while True :
name = input ("Enter the name of team (enter q
for quit)=")
if name == "Q" or name == "q" :
break
else :
win = int (input("Enter the no.of win match
="))
loss = int(input("Enter the no.of loss match
="))
dic [ name ] = [ win , loss ]
lstwin += [ win ]
if win > 0 :
lstrec += [ name ]
nam = input ("Enter the name of team those you are
entered =")
print ("Winning percentage =",dic [ nam ][0] *100 /
(dic [nam ][0] + dic[nam ][1] ))
print("wining list of all team = ",lstwin)
print("team who has winning records are “,lstrec)
Python program that repeatedly asks the user to enter
product names and prices

Write a program that repeatedly asks the user to enter product names and
prices. Store all of these in a dictionary whose keys are the product names
and whose values are the price .

When the user is done entering products and price, allow them to repeatedly
enter a product name and print the corresponding price or a message if the
product is not in dictionary.

Solution

dic = { }
while True :
product = input("enter the name of product
(enter q for quit )= ")
if product == "q" or product == "Q" :
break
else :
price = int(input("enter the price of
product = "))
dic [ product ] = price
while True :
name = input("enter the name of product those
you are entered (enter q for quit )= ")
if name == "q" or name == "Q" :
break
else :
if name not in dic :
print("name of product is invaild")
else :
print("price of product = “,
Python Program to Create a dictionary whose keys are
month name and whose values are number of days in
the corresponding month

Create a dictionary whose keys are month name and whose values are
number of days in the corresponding month:
(a) ask the user to enter the month name and use the dictionary to tell how
many days are in month .
(b) print out all of the keys in alphabetical order .
(c) print out all of the month with 31 days.
(d) print out the (key - value) pair sorted by the number of the days in each
month.

Solution

month = { "jan" : 31 , "feb" : 28 , "march" : 31 ,


"april" : 30 , "may" : 31 , "june" : 30 , "july" :
31 , "aug" : 31 , "sept" : 30 , "oct" : 31 , "nov" :
30 , "dec" : 31}
mon = input("enter the mounth name in short form =
")
print("number of days in ",mon,"=",month [ mon ])
lst = list ( month . keys() )
lst.sort()
print( lst )
print( "month which have 31 days --- ")
for i in month :
if month [ i ] == 31 :
print( i )
print("month according to number of days ---")
print("feb")
for i in month :
if month [ i ] == 30 :
print(i)
for i in month :
if month [ i ] == 31 :
print( i)
Python program to store the detail of 10 students in a
dictionary at the same time

Can you store the detail of 10 students in a dictionary at the same time?
details include – rollno, name ,marks ,grade etc. Give example to support
your answer.

Solution

dic = { }
while True :
roll = input("enter the roll no. of student
(enter Q for quit )= ")
if roll == "Q" or roll == "q" :
break
else :
name = input("enter the name of student =
")
mark = input("enter the marks of student =
")
grade = input("enter the grade of stucent =
")
dic[roll] = [ name , mark , grade ]
print(dic)
Python program to Create a dictionary with the
opposite mapping
Given the dictionary x = {‘k1’: ‘v1’, ‘k2’ : ‘v2’, ‘k3’ : ‘v3’} ,create a dictionary
with the opposite mapping.

Write a program to create the dictionary .

Solution

x = { "k1" : "v1" , "k2" : "v2", "k3" : "v3"}


dic = { }
for i in x :
dic [ x[ i ] ] = i
print(dic)
Python program that lists the over lapping keys of the
two dictionaries if a key of d1 is also a key of d2 the list
it

Given two dictionaries say d1 and d2

Write a program that lists the over lapping keys of the two dictionaries if a key
of d1 is also a key of d2 , the list it .

Solution

d1 = eval(input("enter first dictionary = "))


d2 = eval(input("enter second dictionary = "))
lst1 = (d1.keys() )
lst2 = (d2.keys() )
lst = [ ]
for i in lst1 :
for j in lst2 :
if i == j :
lst += [ i ]
print("over lapping keys are “,lst)
Python program that checks if two same values in a
dictionary have different keys

Write a program that checks if two same values in a dictionary have different
keys.

Solution

dic = eval(input("Enter a dictionar = "))


count = 0
lst = list (dic.values())
for i in lst :
a = lst.count(i)
if a > 1 :
count += a
for j in lst :
if i == j :
lst.remove( j )
if count == 0 :
print( "no values are same " )
else :
print( count,"values are same “)
Python program to check if a dictionary is contained in
another dictionary

Write a program to check if a dictionary is contained in another dictionary.

e.g., if

d1 = {1:11, 2:12}

d2 = {1:11, 2:12, 3:13, 4:15}

Then d1 is contained in d2.

Solution

dic1 = eval(input("Enter first dictionary :-"))


dic2 = eval(input("Enter second dictionary :-"))
count = 0
for i in dic1 :
for j in dic2 :
if i == j :
count += 1
if count == len(dic1):
print("Then d1 is contained in d2.")
else :
print("Then d1 is not contained in d2.”)
Python program to create a new dictionary D2 having
same keys as D1 but values as the sum of the list
elements

A dictionary D1 has values in the form of lists of numbers. Write a program to


create a new dictionary D2 having same keys as D1 but values as the sum of
the list elements.

e.g.

D1 = {'A': [1, 2, 3], 'B': [4, 5, 6]}

Then

D2 is {'A':6, 'B': 15}

Solution

dic1 = eval(input("Enter dictionary : "))


dic2 = {}
for i in dic1 :
lst = dic1[ i ]
sum_of_num = sum( lst )
dic2 [ i ] = sum_of_num
print(dic2)

Output

Enter dictionary : {"list 1":[1,2,3,4],"list 2":[4,5,6,7],"list 3":[4,2,3]}

{'list 1': 10, 'list 2': 22, 'list 3': 9}


Python program to create a dictionary has three keys
assets liabilities and capital

A dictionary has three keys: 'assets', 'liabilities' and 'capital'. Each of these
keys store their value in form of a list storing various values of 'assets',
liabilities' and 'capital' respectively. Write a program to create a dictionary in
this form and print. Also test if the accounting equation holds true.

Solution

assets = eval(input("Enter assets list : "))


liability = eval(input("Enter liability list : "))
capital = eval(input("Enter capital list : "))
dic = { "assets" : assets , "liability" :
liability , "capital" : capital }
print("Result Dictionary is :",dic)
total_assets=0
total_liability=0
total_capital=0
for i in range( len( dic[ "assets" ] ) ) :
total_assets=total_assets+dic [ "assets" ][ i ]
for i in range( len( dic[ "liability" ] ) ) :
total_liability=total_liability+dic
[ "liability" ][ i ]
for i in range( len( dic[ "capital" ] ) ) :
total_capital=total_capital+dic [ "capital" ][ i
]
if total_assets == total_liability+ total_capital:
print("Balanced")
else:
print("Not Balanced")

Output

Enter assets list : [3000,5000,2000]


Enter liability list : [4000,1500,2000]

Enter capital list : [500,2000]

Result Dictionary is : {'assets': [3000, 5000, 2000], 'liability ': [4000, 1500,
2000], 'capital': [500, 2000]}

Balanced

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

Enter assets list : [3000,4000,4000]

Enter liability list : [5000,9000]

Enter capital list : [3000,5000]

Result Dictionary is : {'assets': [3000, 4000, 4000], 'liability': [5000, 9000],


'capital': [3000, 5000]}

Not Balanced
Python function that takes a string as parameter and
returns a string with every successive repetitive
character replaced

Write a Python function that takes a string as parameter and returns a string
with every successive repetitive character replaced by & e.g. Parameter may
become Par&met&r.

Solution

def str_encode(s):
ans=""
for a in s:
if a not in ans:
ans=ans+a
else:
ans=ans+'&'
return ans

st1=input("Enter any String :")


output=str_encode(st1)
print("Output is : ",output)

Output

Enter any String :Parameter

Output is : Par&met&
Topic : Functions in Python

Write a function with name divideby ve which generate


and prints a random integer number from the range 0
to 100 and then return True if the randomly generated
number is divisible by 5, and False otherwise.

Write a function with name divideby ve which generate and prints a random
integer number from the range 0 to 100 and then return True if the randomly
generated number is divisible by 5, and False otherwise.

Solution

import random
def divbyfive():
num=random.randint(1,100)
print("Random genrated Number :",num)
if num%5==0:
return True
else:
return False

x=divbyfive()
print(x)

Output

Random genrated Number : 42

False
fi
fi
Python program to create a function to calculate
factorial value

Write a Python program to create a function for factorial value

Solution

def factorial(num):
fact=1
while(num>0):
fact=fact*num
num=num-1
return(fact)
num=int(input("Enter any Number : "))
f=factorial(num)
print("Factorial value of ",num," is : ",f)

Output

Enter any Number : 5

Factorial value of 5 is : 120


Python program to nd the sum of factorial upto n
terms using function

Write program to nd the sum of factorial upto n terms

Solution

def factorial(num):
fact=1
while(num>0):
fact=fact*num
num=num-1
return(fact)
n=int(input("Enter Value of n : "))
sum=0
for a in range(1,n+1):
sum=sum+factorial(a)
print("Sum of Factorials : ",sum)

Output

Enter Value of n : 5

Sum of Factorials : 153


fi
fi
Python program to create a function for reverse the
number

Write a python program to create a function which reverse the given number

Solution

def reverse(num):
rev=0
while num>0:
rev=rev*10+(num%10)
num=num//10
return rev
num=int(input("Enter any Number "))
ans=reverse(num)
print("Reverse of Number is : ",ans)

Output

Enter any Number 2345

Reverse of Number is : 5432


Python program to check number is Palindrome or not
using function

Write a Python program to input any number and check number is


Palindrome or Not using Function

Solution

def reverse(num):
rev=0
while num>0:
rev=rev*10+(num%10)
num=num//10
return rev
num=int(input("Enter any Number "))
ans=reverse(num)
if num==ans:
print("Number is Palindrome ")
else:
print("Number is Not Palindrome")

Output

Enter any Number 5245

Number is Not Palindrome

>>>

===================

Enter any Number 10001

Number is Palindrome
Python program to create a function for calculating sum
of digit

Write a Python program to input any number from user and nd its sum of
digit

Solution

def sumOfDigit(num):
sum=0
while num>0:
sum=sum+(num%10)
num=num//10
return sum
num=int(input("Enter any Number : "))
sum=sumOfDigit(num)
print("Sum of Digit : ",sum)

Output

Enter any Number : 2342

Sum of Digit : 11
fi
Python function to get two matrices and multiply them

Write a Python function to get two matrices and multiply them. Make sure that
number of columns of rst matrix = number of rows of second.

Python program to illustrate the global variable

Write a Python program to show the application of Global variable.

Solution

x="global"
def check():
global x
print(x)
x="Local"
#x="Local"
check()
print(x)

Output

global

Local
fi
Python program to convert decimal into other number
systems

Python program to convert decimal into other number systems

Solution

num = int(input("Enter any Decimal Number : "))


print("The decimal value of", num, "is:")
print(bin(num), "in binary.")
print(oct(num), "in octal.")
print(hex(num), "in hexadecimal.")

Output

Enter any Decimal Number : 25

The decimal value of 25 is:

0b11001 in binary.

0o31 in octal.

0x19 in hexadecimal.
Python program that generates six random numbers in
a sequence created with start stop step

Write a program that generates six random numbers in a sequence created


with (start, stop, step). Then print the mean, median and mode of the
generated numbers.

Solution

import random
import statistics

start = int(input("Enter start: "))


stop = int(input("Enter stop: "))
step = int(input("Enter step: "))

a = random.randrange(start, stop, step)


b = random.randrange(start, stop, step)
c = random.randrange(start, stop, step)
d = random.randrange(start, stop, step)
e = random.randrange(start, stop, step)
f = random.randrange(start, stop, step)

print("Generated Numbers:")
print(a, b, c, d, e, f)

seq = (a, b, c, d, e, f)

mean = statistics.mean(seq)
median = statistics.median(seq)
mode = statistics.mode(seq)

print("Mean =", mean)


print("Median =", median)
print("Mode =", mode)
Output

Enter start: 100

Enter stop: 500

Enter step: 5

Generated Numbers:

235 255 320 475 170 325

Mean = 296.6666666666667

Median = 287.5

Mode = 235
Python program to create recursive function to nd
factorial

Write a Python function to calculate the factorial value of given number using
recursion.

Solution

def fact(n):
if n==1:
return 1
else:
return n*fact(n-1)
num=int(input("Enter any Number "))
ans=fact(num)
print("Factorial is : ",ans);

Output

Enter any Number 5

Factorial is : 120
fi
Python recursive function to nd the sum of digits

Write a recursive function in python to nd the sum of digit of given number.

Solution:

def sod(num):
if num<10:
return num
else:
return num%10+sod(num//10)
n=int(input("Enter any Number : "))
sum=sod(n)
print("Sum of Digit ",sum)

Output

Enter any Number : 342

Sum of Digit 9
fi
fi
Python recursive function to print the reverse of
number

Write a recursive function to print the reverse of given number.

Solution:

def reverse(num):
if num<10:
print(num)
else:
print(num%10,end='')
reverse(num//10)
n=int(input("Enter any Number : "))
reverse(n)

Output

Enter any Number : 576

675
Python function to accept 2 number and return addition
subtraction multiplication and division

Write a Python program to create a function which accept two number and
return addition subtraction multiplication and division.

Solution:

def calculate(n1,n2):
a=n1+n2
b=n1-n2
c=n1*n2
d=n1/n2
return a,b,c,d
x=int(input("Enter First No :"))
y=int(input("Enter Second No :"))
#t1=calculate(x,y)
#print(t1)
add,sub,mul,div=calculate(x,y)
print("Sum is ",add)
print("Sub is ",sub)
print("Mul is ",mul)
print("Div is ",div)

Output

Enter First No :10


Enter Second No :7
Sum is 17
Sub is 3
Mul is 70
Div is 1.4285714285714286
Python function to accept number of days and return
week and days to its equivalent

Write a python function which accept number of days and return week and
days to its equivalent

Solution:

def convert(days):
week=days//7
day=days%7
return week,day
d=int(input("Enter the Number of Days "))
w,d=convert(d)
print("Week = ",w," and days=",d)

Output

Enter the Number of Days 10

Week = 1 and days= 3


Python function to extract the day month year from
given date

Write a Python function which accept the date 'DD-MM-YYYY' format as an


argument and return date, month nd year part.

Solution:

def extract_date(date):
l1=date.split("-")
return l1[0],l1[1],l1[2]
dt=input("Enter any Date in 'DD-MM-YYYY' format : ")
d,m,y=extract_date(dt)
print("Day Part : ",d)
print("Month Part : ",m)
print("Year Part : ",y)

Output

Enter any Date in 'DD-MM-YYYY' format : 22-11-2012

Day Part : 22

Month Part : 11

Year Part : 2012


Topic : File Processing in Python

Python program to read the full content of speci ed txt


le

Write a Python program which accept the le name from user and print the all
content of le in console.

Solution

fname=input("Enter the file name : ")


fp=open(fname,"r")
print(fp.read())
fp.close()

Output

Enter the le name : my le.txt

Infomax Computer Academy


fi
fi
fi
fi
fi
fi
Python program to accept le name and data from user
and write data on le

Python program to accept le name and data for write on le, create and write
data on le.

Solution

fname=input("Enter the file name : ")


fp=open(fname,"w")
data=input("Enter the data for Write : ")
print(fp.write(data))
fp.close()

Output

Enter the le name : mynew le.txt

Enter the data for Write : ram is a good boy.

18
fi
fi
fi
fi
fi
fi
fi
Python program to count the number of lines in the le

Write a Python program to display the number of lines in the le

Solution

fname=input("Enter the file name : ")


fp=open(fname,"r")
data=fp.readlines()
count=len(data)
print("Number of Lines in File Are : ",count)
fp.close()

Output

Enter the le name : my le.txt

Number of Lines in File Are : 5


fi
fi
fi
fi
Python program to display the size of a le in byte

Write a program to display the size of a le in byte

Solution

fname=input("Enter the file name : ")


fp=open(fname,"r")
data=fp.read()
size=len(data)
print("Size of file in Byte : ",size)
fp.close()

Output

Enter the le name : my le.txt

Size of le in Byte : 124


fi
fi
fi
fi
fi
Python program to display all the records in a le along
with line number

Write a program to display all the records in a le along with line/record


number

Solution

fname=input("Enter the file name : ")


fp=open(fname,"r")
sr=1
while True:
data=fp.readline()
if data=="":
break
print(sr,". ",data)
sr=sr+1
fp.close()

Output

Enter the le name : my le.txt


1 . java

2 . php

3 . python

4 . o level

5 . dca

6 . ccc
fi
fi
fi
fi
Python program to display only last line of a text le

Write a program to display only last line of a text le

Solution

fname=input("Enter the file name : ")


fp=open(fname,"r")
data=fp.readlines()
print("Last Line : ",data[-1])
fp.close()

Output

Enter the le name : my le.txt

Last Line : ccc


fi
fi
fi
fi
Python program that reads a text le and creates
another le that is identical except that every sequence
of consecutive blank spaces is replaced by single
space

Write a program that reads a text le and creates another le that is identical
except that every sequence of consecutive blank spaces is replaced by single
space.

Solution

fname1=input("Enter the File Name 1 : ")


fname2=input("Enter the File Name 2 : ")
fp1 = open(fname1,"r")
fp2 = open(fname2,"w")
lines = fp1.readlines()
for line in lines :
word = line.split()
fp2.write( " ".join(word) )
fp2.write("\n")
fp1.close()
fp2.close()

Output

Enter the File Name 1 : le1.txt

Enter the File Name 2 : le2.txt


fi
fi
fi
fi
fi
fi
Write Python code to display sentence starting with
given character from abc.txt le

fp=open("data.txt","r")
data=fp.read()
sen=data.split(".")
ch=input("Enter any Start Char : ")
for line in sen:
line=line.strip()
if line.startswith(ch):
print(line)

Python code to display digits from abc.txt le

Write a Python Program which read only digits from a abc.txt le

fp=open("abc.txt","r")
data=fp.read()
for a in data:
if a.isdigit():
print(a)
fi
fi
fi
Python program to copy the one contents to another

Write a python program to copy all the contents of text le Mango.txt into a
empty le Orange.txt

Solution

fp=open("mango.txt","r")
data=fp.read()
fp1=open("orange.txt","w")
fp1.write(data)
print("data copied")
fp.close()
fp1.close()
fi
fi
Python program to copy the all word which start with
constant in another le

Write a python program to copy the words from text le Lily.txt into an empty
le Rose.txt which start with a consonant.

Solution

fp=open("Lily.txt","r")
data=fp.read()
fp1=open("Rose.txt","w")
output=""
str1=data.split()
for word in str1:
if word[0].lower() not in ['a','e','i','o','u']:
output=output+word+" "
fp1.write(output)
print("data copied")
fp.close()
fp1.close()
fi
fi
fi
Python program to write rst n prime number in text le

Write a Python program which write a rst n prime in txt le (each line contain
one prime no.)

Solution:

prime=[]
limit=int(input("How many prime numnbers you want to
write : "))
n=2
count=0
while count<=limit:
flag=True
for a in range(2,n):
if n%a==0:
flag=False
if flag==True:
count=count+1
prime.append(str(n)+"\n")
n=n+1
fp=open("prime.txt","w")
fp.writelines(prime)
fp.close()
fi
fi
fi
fi
Python program to marge the content of target le into
source le

Write a Python program to accept two le name (source and Target) and copy
and append the content of target le into source le.

Solution

fname1=input("Enter the Source File Name : ")


fname2=input("Enter the Target File Name : ")
fp1=open(fname1,"a")
fp2=open(fname2,"r")
data=fp2.read()
fp1.write(data)
fp1.close()
fp2.close()
fi
fi
fi
fi
fi
Python program to read txt le data from speci ed
index to speci ed length

Write a python

Solution

fname=input("Enter the Source File Name : ")


pos=int(input("Enter the start index : "))
size=int(input("Enter the length to read no of
char : "))
fp=open(fname,"r")
fp.seek(pos)
data=fp.read(size)
print(data)
fp.close()

Python program to delete the speci ed le from


computer

Python program to delete a speci ed le from Computer

Solution

import os
fname=input("Enter the File Name : ")
os.remove(fname)
print("file deleted”)
fi
fi
fi
fi
fi
fi
fi
Python program to create a function that would read
contents from the sports.dat and creates a le named
Atheletic.dat

A le sports.dat contains information in the following format : Event ~


Participant

Write a function that would read contents from the sports.dat and creates a
le named Atheletic.dat copying only those records from sports.dat where the
event name is "Atheletics".

Solution

def filter( ) :
file1 = open("sports.dat","r")
file2 = open("Atheletics.dat","w")
lst = file1.readlines()
for i in lst :
print(i [ : 9 ])
if i [ : 9 ] == "atheletic" or i [ : 9 ] ==
"Atheletic" :
file2.write(i)
file1.close()
file2.close()
filter()
fi
fi
fi
Python program to add delete and display all record of
binary le

Write a Python program to Perform Add, Delete and Display Record operation
on binary le

import pickle
def showData():
stu={}
fp=open("stu.dat","rb")
print("Roll\tName\tCity")
flag=False
try:
while True:
stu=pickle.load(fp)
#print(emp1)

print(stu['roll'],'\t',stu['name'],'\t',stu['city'])
except EOFError:
fp.close()
def deleteData():
stu={}
fp=open("stu.dat","rb")
r=int(input("Enter the Roll No. for Delete : "))
l1=[]
flag=False
try:
while True:
stu=pickle.load(fp)
#print(emp1)
if stu['roll']!=r:

#print(stu['roll'],'\t',stu['name'],'\t',stu['city']
)
l1.append(stu)
fi
fi
flag=True
except EOFError:
fp.close()
if flag==False:
print("Record Not Found " )
else:
print("Record Deleted" )
fp=open("stu.dat","wb")
for a in l1:
pickle.dump(a,fp)
fp.close()

def searchData():
stu={}
fp=open("stu.dat","rb")
r=int(input("Enter the Roll No. for Search : "))
flag=False
try:
while True:
stu=pickle.load(fp)
#print(emp1)
if stu['roll']==r:

print(stu['roll'],'\t',stu['name'],'\t',stu['city'])
flag=True
break
except EOFError:
fp.close()
if flag==False:
print("Record Not Found " )
def addData():
stu={}
fp=open("stu.dat","ab")
while True:
r=int(input("Enter Roll No : "))
n=input("Enter name")
c=input("Enter City")
stu['roll']=r
stu['name']=n
stu['city']=c
pickle.dump(stu,fp)
a=input("if you want to add more data press
Y")
if a not in ['Y','y']:
break
fp.close()
while True:
print("1. Add New Student\n2.Print List of
Student\n 3.Search any Student\n4.Delete Record
\n5.Exit")
ch=int(input("Enter Your Choice : "))
if ch==1:
addData()
elif ch==2:
showData()
elif ch==3:
searchData()
elif ch==4:
deleteData()
elif ch==5:
break
else:
print("Invalid Choice “)
Python program to read csv le content line by line

Write a pyton program to read csv le content

Solution

file=open("myfile.csv","r")
for line in file:
print(line)

Python program to read data from csv le

Write a python program to read data from CSV File

import csv
fp=open("data1.csv","r",)
obj=csv.reader(fp)
for a in obj:
#print(a)
for b in a:
print(b,end=' ')
print()
fp.close()
fi
fi
fi
Python program to write data on csv le

Write a python program which accept data from user and write in csv le.

import csv
fp=open("data1.csv","w",newline="")
obj=csv.writer(fp)
stu=['roll','name','city']
obj.writerow(stu)
for a in range(1,3):
r=int(input("Enter the Roll "))
n=input("Enter any name")
c=input("Enter any City")
stu=[r,n,c]
obj.writerow(stu)
fp.close()
fi
fi
Topic : Modules in Python

Python program to print the calendar of given month


and year

Write a python program which accept the year and month from user and
print the calendar for that month and year

import calendar
year = int(input("Enter Year 'YYYY' : "))
month = int(input("Enter Month 'MM' : "))
print(calendar.month(year, month))

Output

Enter Year 'YYYY' : 2021


Enter Month 'MM' : 08
August 2021
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Python program to print the calendar of given year

Write a Python program which accept a year from user and print the
calendrer of all months in that year.

import calendar
year = int(input("Enter Year 'YYYY' : "))
print ("The calendar of year ",year," is : ")
print (calendar.calendar(year, 2, 1, 6))

Output

Enter Year 'YYYY' : 2022


Python program to generate 3 random integers
between 100 and 999 which is divisible by 5

Write a program to generate 3 random integers between 100 and 999 which
is divisible by 5.

Solution

import random

a = random.randrange(100, 999, 5)
b = random.randrange(100, 999, 5)
c = random.randrange(100, 999, 5)

print("Generated Numbers:", a, b, c)

Output

Generated Numbers: 885 825 355


Python program to generate 6 digit random secure
OTP between 100000 to 999999

Write a program to generate 6 digit random secure OTP between 100000 to


999999.

Solution

import random

otp = random.randint(100000, 999999);

print("OTP:", otp);

Output

OTP: 544072
Python program to generate 6 random numbers and
then print their mean median and mode
Write a program to generate 6 random numbers and then print their mean,
median and mode

Solution

import random
import statistics

a = random.random()
b = random.random()
c = random.random()
d = random.random()
e = random.random()
f = random.random()

print("Generated Numbers:")
print(a, b, c, d, e, f)

seq = (a, b, c, d, e, f)

mean = statistics.mean(seq)
median = statistics.median(seq)
mode = statistics.mode(seq)

print("Mean =", mean)


print("Median =", median)
print("Mode =", mode)

Output

Generated Numbers:
0.47950245404109626 0.6908539320958872 0.12445888663826654
0.13613724999684718 0.37709141355821396 0.6369609321575742
Mean = 0.40750081141464756
Median = 0.4282969337996551
Mode = 0.47950245404109626
Topic : NumPy Basics

Create a numpy array having two dimensions and


shape(3,3) and perform the following operations on
array elements:
Create a numpy array having two dimensions and shape(3,3) and perform the
following operations on array elements:

a) Calculate sum of all the columns of the array


b) Calculate product of all the rows of the array.
c) Retrieve only the last two columns and last two rows form the array.
d) Create another two dimensional array having same shape and carry out
element wise addition of two arrays and display the result.
Create a new array by multiplying every element of original array with value 2
and display the new array.

Solution

import numpy as np
arr=np.array([[3,4,9],[3,4,2],[1,2,3]])
print("Array is : \n",arr)
print("Sum of All Column ",np.sum(arr, axis=0))
print("Product of All Column ",np.prod(arr, axis=0))
print("Last Two Column \n",arr[:, -2:])
print("Last Two Rows \n",arr[-2:, :])
arr1=np.array([[4,5,6],[7,8,3],[2,2,1]])
print("Second Array is : \n",arr1)
print("Addition of 2 Array is : \n",(arr+arr1))
arr3=arr * 2
print("Third Array (Muliply by 2) : \n",arr3)

Output

Array is :
[[3 4 9]
[3 4 2]
[1 2 3]]
Sum of All Column [ 7 10 14]
Product of All Column [ 9 32 54]
Last Two Column
[[4 9]
[4 2]
[2 3]]
Last Two Rows
[[3 4 2]
[1 2 3]]
Second Array is :
[[4 5 6]
[7 8 3]
[2 2 1]]
Addition of 2 Array is :
[[ 7 9 15]
[10 12 5]
[ 3 4 4]]
Third Array (Muliply by 2) :
[[ 6 8 18]
[ 6 8 4]
[ 2 4 6]]
Write a program to nd the intersection of two arrays

Write a program to nd the intersection of two arrays?

Solution

import numpy as np

# Create two arrays


array1 = np.array([1, 2, 3, 4, 5])
array2 = np.array([3, 4, 5, 6, 7])

# Find the intersection of the two arrays


intersection_result = np.intersect1d(array1, array2)

print("Array 1:", array1)


print("Array 2:", array2)

print("\nIntersection of the two arrays:")


print(intersection_result)
fi
fi
Topic : String Handling in Python

Python program input string and prints its characters in


different lines two characters per line

Write a python script that traverses through an input string and prints its
characters in different lines – two characters per line.

Solution

s=input("Enter a String")
l=len(s)
j=0
for i in range(0,1):
print(s[i],end='')
j+=1
if j%2==0:
print('')

Output

Enter a String infomaxacademy


in
fo
ma
xa
ca
de
my
Python to print the number of occurrences of a sub
string into a line

WAP to print the number of occurrences of a substring into a line.

Solution

#WAP to print the number of occurrences of a


substring into a line.
s=input("Enter a String : ")
substr=input("Enter a sub String : ")
l=len(s)
lsub=len(substr)
start=count=0
end=l
while True:
position=s.find(substr,start,end)
if position!=-1:
count+=1
start=position+lsub
else:
break
if start>=l:
break;
print("No. of Occurrence of : ",substr," : ",count)

Output

Enter a String : infomax computer academy


Enter a sub String : max
No. of Occurrence of : max : 1
__________________________________________________
Enter a String : printer print the paper
Enter a sub String : print
No. of Occurrence of : print : 2
Python program to check the given string is palindrome
or not

WAP to check the given string is palindrome or not.

Solution

s=input("Enter a String : ")


mid=len(s)//2
rev=-1
for a in range(mid):
if s[a]==s[rev]:
rev-=1
else:
print(s," is not Palindrome String");
break;
else:
print(s," is Palindrome String ")

Output

Enter a String : nitin

nitin is Palindrome String

========================

Enter a String : infomax

infomax is not Palindrome String


Python program that inputs a string and then prints it
equal to number of times its length

Write a program that inputs a string and then prints it equal to number of
times its length, e.g.,

Enter string : "eka"

Result ekaekaeka

str = input("Enter string: ")


len = len(str)
opStr = str * len
print("Result", opStr)

Output

Enter string: infomax

Result infomaxinfomaxinfomaxinfomaxinfomaxinfomaxinfomax
Python program to form a word by joining rst
character of each word

Write a Python code to enter a sentence. Form a word by joining all the rst
characters of each word of the sentence. Display the word.

Sample Input: Read Only Memory

Solution:

wd=""
str=input("Enter a string in mixed case : ")
str=" "+str
p=len(str)
for i in range(0,p):
if(str[i]==' '):
wd=wd+str[i+1]
print("New Word:",wd)

Output

Enter a string in mixed case : Read Only Memory

New Word: ROM


fi
fi
Python program to reverse order of its words in given
sentence

Write a Python code to accept a sentence. Display the sentence in reverse


order of its words.

Sample Input: Computer is fun

Sample Output: Fun is Computer

wd="";rwd=""
str=input("Enter a string :")
str=str+" "
p=len(str)
for i in range(0,p):
if(str[i]==" "):
rwd=wd+" "+rwd
wd=""
else:
wd=wd+str[i]
print("Words in reversed order:",rwd)

Output

Enter a string :Infomax Computer Academy

Words in reversed order: Academy Computer Infomax


Python program to nd the longest word present in the
sentence along with its length

Write a code in Python to enter a sentence and display the longest word
present in the sentence along with its length.

Sample Input: WE ARE LEARNING PYTHON

Sample Output: The longest word : LEARNING

The length of the word : 8

wd='';nwd='';c=a=0
str=input("Enter a String :")
str=str+' '
p=len(str)
for i in range(0,p):
if(str[i]==' '):
a=len(wd)
if(a>c):
nwd=wd
c=a
a=0
wd=""
else:
wd=wd+str[i]
print("Longest Word:",nwd)
print("Length of the Word:",c)

Output

Enter a String :python is very easy language

Longest Word: language

Length of the Word: 8


fi
Python program to nd the frequency of vowels in each
word

Write a Python code to accept a sentence in lowercase. Find the frequency of


vowels in each word and display the words along with frequency of vowels.

Solution:

wd="";nwd="";b=v=0
str=input("Enter a string in lowercase: ")
str=str+" "
p=len(str)
print("Word\t\t\t No. of vowels")
for i in range(0,p):
if(str[i]==' '):
b=len(wd)
v=0
for j in range(0,b):
if(wd[j]=='a' or wd[j]=='e' or
wd[j]=='i' or wd[j]=='o'or wd[j]=='u'):
v=v+1
print(wd,"\t\t\t",v)
wd=""
else:
wd=wd+str[i]

Output

Enter a string in lowercase: python is very easy language


Word No. of vowels
python 1
is 1
very 1
easy 2
language 4
fi
Python program to input a word and display the pattern
as shown below

Write a Python code to input a word (say, PYTHON) and display the pattern
as shown below:

(a) (b)

P P Y T H O N

Y Y P Y T H O

T T T P Y T H

H H H H P Y T

O O O O O P Y

N N N N N N P

Solution A

word=input("Enter a word :")


for a in range(0,len(word)):
for b in range(0,a+1):
print(word[a],end='')
print()

Solution B

word=input("Enter a word :")


for a in range(len(word)-1,-1,-1):
for b in range(0,a+1):
print(word[b],end='')
print()
Output

Enter a word :INFOMAX

NN

FFF

OOOO

MMMMM

AAAAAA

XXXXXXX

Enter a word :INFOMAX

INFOMAX

INFOMA

INFOM

INFO

INF

IN

You might also like