Programming and Problem Solving Through Python
Programming and Problem Solving Through Python
Solution
Output
——————-
Write a python program that calculate and prints the number of seconds in a
year.
Solution
Output
——————————
Output
—————————
Python program to nd the ASCII Value of entered
character
Write a program to input any Character and nd its ASCII Value.
Solution
Output
—————————————————-
Write python program that display a joke but display the punch line only
when the user presses enter key.
Output
————————————-
5 10 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
———————————-
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)
Output
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
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
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
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
(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
C X 9/5 + 32 = F
Solution
Output
WAP to print the area of circle when radius of the circle is given by user.
Solution
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
Output
Solution
Output
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
Solution
Output
Python program to read a number in n and prints n2 n3
n4
Solution
Output
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
Output
Python program to obtain three numbers and print their
sum
Solution
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
Solution
Output
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
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
Solution
Output
Enter a number : 3
Cube of 3 is : 27
>>>
=====================
Enter a number : 5
Cube of 5 is : 125
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
Output
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
write a program to nd sale price of an item with given price and discount (%)
Solution
Output
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
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
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:
Solution
Solution
Output
Write a program to obtain principal amount, rate of interest and time from
user and compute simple interest.
Solution
si = p * r * t / 100
Output
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
Solution
Output
Program of modulus
Solution
Output
Remainder: 1
fi
Python program convert dollars in Rupee
Output
694.5 Rupees
Solution
Output
conv_fac=0.621371
fl
miles=km*conv_fac
Program to convert the distance (in feet) to inches, yards, and miles
Solution
Output
Solution
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)
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
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.
Solution
mins = totalSecs // 60
secs = totalSecs % 60
Output
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
Output
Reversed Number: 52
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
d1 = x % 10
x //= 10
d2 = x % 10
x //= 10
d3 = x % 10
y = d1 * 100 + d2 * 10 + d3
print("Reversed Number:", y)
Output
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
n = (m - 1) * 30 + d
Output
Enter day: 3
Enter month: 2
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
d = y * 365
h = d * 24
m = h * 60
s = m * 60
Output
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
Output
Solution
import math
r = math.sqrt(area / (4 * math.pi))
Solution
import math
Output
Enter side: 5
Write a program to input the radius of a sphere and calculate its volume (V =
4/3πr3)
Solution
import math
Output
Solution
si = p * r * t / 100
amt = p + si
Output
Enter time: 3
Write a python code to input the time in seconds. Display the time after
converting it into hours, minutes and seconds.
Solution 1:
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”)
Solution 1:
Solution 2:
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
Write a Python program input 3 numbers from user and check these
numbers are Unique are Not.
Solutions 1
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
Solution
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
Output
Leap Year
Write a program to take two numbers and print if the rst number is fully
divisible by second number or not.
Solution
Output
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
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
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
Output
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
Solution
Output
Solution
Output
Write a program that returns True if the input number is an even number,
False otherwise.
Solution
Output
Even
>>>
========================
Odd
Python program to print larger number using swap
Output
>>>
========================
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
WAP to take two numbers and check that the rst number is fully divisible by
second number or not.
Solution
Output
fi
fi
Python program 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.
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
Solution
Output
Solution
Solution
Output
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).
Solution
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
Output
Solution
Output
Output
>>>
========================
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
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
Output
Solution
Output
Solution
Output
Solution
Output
Solution
Output
Solution
Output
Triangle Possible
fi
Python program to input 3 sides of a triangle and print
whether it is an equilateral scalene or isosceles triangle
Solution
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
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:
Output
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.
Output
Given below is a hypothetical table showing rate of income tax for an Indian
citizen, who is below or up to 60 years.
Up to ₹ 5,00,000 Nil
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 age:45
Name : ravi
Age : 45
The volume of solids viz. cuboid, cylinder and cone can be calculated by the
following formulae:
Write a Python code by using user’s choice to perform the above task.
Solution:
Output
1. Volume of Cuboid
2. Volume of Cylinder
3. Volume of Cone
Enter height: 9
Solution
Output
Write a program to input any string and count number of uppercase and
lowercase letters.
Solution
Output
Solution
Output
Write a python program to accept a integer number and count the number of
digits in number.
Sample:
Input: 2223
Solution
Output
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
Solution
Output
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
Solution
Output
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
Output
Greatest Digit : 8
Smallest Digit : 2
Write a python program to accept an integer number and print the frequency
of each digit present in the number .
Solution
Output
Write a program to input any number and to check whether given number is
Armstrong or not.
Example:
Armstrong 153,
Solution
Output
Solution
Output
Solution
Output
Decimal Value : 5
======================
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
while temp != 0 :
digit = temp % 10
count += 1
temp = temp // 10
y = count * 10 + digit
print("Y =", y)
Output
Y = 42
fi
fi
fi
Python program to nd the LCM of two input numbers
Solution
Output
Enter Number 1 : 21
Enter Number 2 : 5
L.C.M. : 105
fi
fi
Python program to nd GCD of 2 number
Solution
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:
Output
========================
Enter any Number : 30
it is not a Special Number
Solution:
Output
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
Solution:
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
Output
Solution
Output
Python program 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
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.
Solution
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
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
Output
fi
fi
Python program to nd the sum of n natural numbers
WAP to nd the sum of n natural numbers.
Solution
Output
The sum is : 10
Solution
Output
Solution
for i in range(1,n+1,2):
s=s+i
print("The sum is : ",s)
Output
Solution
Output
Write a program to input any number and to print all natural numbers up to
given number.
Solution
Output
Write a program to input any number and to nd sum of all natural numbers
up to given number.
Solution
Output
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
Output
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
Solution
Output
Write a Python program to accept a integer number from user and check
number is composite Number or not.
Solution
Output
10 is Composite Number
=========================
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
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
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
Solution
Output
Solution
Output
x
Python program to print ASCII code for entered
message
Solution
Output
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
Output
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
Output
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.
6,28,496,8128
Solution:
Output
Output
Write a Python code to display the rst ten terms of the following series
2, 5, 10, 17,……………………………..
Solution:
Output
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
Write a Python function which takes list of integers as input and nds:
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
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
Output
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
Output
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
Solution
divBy4=[ ]
for i in range(21):
if (i%4==0):
divBy4.append(i)
print(divBy4)
Output
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
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
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
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
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
Solution
Output
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”)
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
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
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
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
Solution
Output
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
Output
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
))
Output
write a program to input a list of numbers and swap elements at the even
location with the elements at the odd location.
Solution
Output
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
Output
Solution
Output
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
Output
Solution
Output
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
Output
[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
Output
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.
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.
Output
Write a python program to move all duplicate values in a list to the end of the
list.
Solution
Write a python program to compare two equal sized list and print the rst
index where they differ
Solution
Output
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
Output
Solution
if mi<len(mylist)-1:
print("Successor of Largest No. ",mylist[mi+1])
else:
print("No Successor Exist")
Output
Solution
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
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
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
Output
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
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
Output
Before SWAPPING
AFTER SWAPPING
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
Output
Before SWAPPING
AFTER SWAPPING
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
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
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
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
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
Output
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
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
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
Solution
Output
{'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
For example, if the input is 876 then the output should be 'Eight Seven Six'.
Solution
Output
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
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.
Solution
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
Write a program that checks if two same values in a dictionary have different
keys.
Solution
e.g., if
d1 = {1:11, 2:12}
Solution
e.g.
Then
Solution
Output
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
Output
Result Dictionary is : {'assets': [3000, 5000, 2000], 'liability ': [4000, 1500,
2000], 'capital': [500, 2000]}
Balanced
------------------------------------------------------------------------------------------
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
Output
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.
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
False
fi
fi
Python program to create a function to calculate
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
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
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
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
>>>
===================
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
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.
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
Solution
Output
0b11001 in binary.
0o31 in octal.
0x19 in hexadecimal.
Python program that generates six random numbers in
a sequence created with start stop step
Solution
import random
import statistics
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)
Enter step: 5
Generated Numbers:
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
Factorial is : 120
fi
Python recursive function to nd the sum of digits
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
Sum of Digit 9
fi
fi
Python recursive function to print the reverse of
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
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
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
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
Day Part : 22
Month Part : 11
Write a Python program which accept the le name from user and print the all
content of le in console.
Solution
Output
Python program to accept le name and data for write on le, create and write
data on le.
Solution
Output
18
fi
fi
fi
fi
fi
fi
fi
Python program to count the number of lines in the le
Solution
Output
Solution
Output
Solution
Output
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
Solution
Output
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
Output
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)
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
Write a python
Solution
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
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
Solution
file=open("myfile.csv","r")
for line in file:
print(line)
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
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
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
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
Solution
import random
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)
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
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
Solution
import numpy as np
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
Solution
Output
Solution
Output
========================
Write a program that inputs a string and then prints it equal to number of
times its length, e.g.,
Result ekaekaeka
Output
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.
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
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
Write a code in Python to enter a sentence and display the longest word
present in the sentence along with its length.
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
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
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
Solution B
NN
FFF
OOOO
MMMMM
AAAAAA
XXXXXXX
INFOMAX
INFOMA
INFOM
INFO
INF
IN