0% found this document useful (0 votes)
131 views35 pages

Python Solved QB

The document provides 12 Python programming questions and solutions. The questions cover topics such as swapping variables, finding digits in a number, calculating simple interest, calculating areas of shapes, finding sums and averages of numbers, Fibonacci series, and determining the greatest of three numbers. The final question involves calculating tax based on income levels by applying different tax rates.

Uploaded by

Jevaa Kharthick
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
131 views35 pages

Python Solved QB

The document provides 12 Python programming questions and solutions. The questions cover topics such as swapping variables, finding digits in a number, calculating simple interest, calculating areas of shapes, finding sums and averages of numbers, Fibonacci series, and determining the greatest of three numbers. The final question involves calculating tax based on income levels by applying different tax rates.

Uploaded by

Jevaa Kharthick
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 35

SOLVED PYTHON PROGRAMMING QUESTIONS FROM THE QUESTION BANK

0. Python program to swap two variables

#Program to swap

x=5
y = 10

# To take inputs from the user


#x = input('Enter value of x: ')
#y = input('Enter value of y: ')

# create a temporary variable and swap the values


temp = x
x=y
y = temp

print('The value of x after swapping: {}'.format(x))


print('The value of y after swapping: {}'.format(y))

Output

The value of x after swapping: 10


The value of y after swapping: 5

1. Find the number of digits of a number

#Program to find number of digits of a number

PYTHON CODE :

#program to find number of digits of a number

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

count=0
while(n>0):

count=count+1

n=n//10

print("The number of digits in the number are:",count)

OUTPUT:

Enter number:1234

The number of digits in the number are: 4

2. Calculate the simple interest using principle, rate of interest and no of


years

#Python program to calculate simple interest

PYTHON CODE:

#Python program to calculate simple interest

P = float(input("Enter the principal amount : "))

N = float(input("Enter the number of years : "))

R = float(input("Enter the rate of interest : "))

#calculate simple interest by using this formula

SI = (P * N * R)/100

#print

print("Simple interest : {}".format(SI))

OUTPUT:

Enter the principal amount : 1000


Enter the number of years : 1

Enter the rate of interest : 2

Simple interest : 20.0

3. Calculate Area of triangle, circle and rectangle

# Program to find area of triangle

PYTHON CODE:

# program to find area of triangle

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

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

area=0.5*base*height

print("The area of triangle:",area)

OUTPUT :

Enter base:3

Enter height:4

The area of triangle: 6.0

PYTHON CODE:

# program to find area of circle

PI = 3.14

r = float(input("Enter the radius of a circle:"))

area = PI * r * r

print("Area of a circle =",area)

OUTPUT:
Enter the radius of a circle:4

Area of a circle = 50.24

PYTHON CODE:

#program to find area of rectangle

width=5

height=10

area=width*height

print("Area of rectangle=",area)

OUTPUT:

Area of rectangle= 50

4. Find the sum of all digits of a number

#Program to find sum of all digits of a number

PYTHON CODE:

#program to find sum of all digits of a number

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

tot=0

while(n>0):

dig=n%10

tot=tot+dig

n=n//10

print("The total sum of digits is:",tot)

OUTPUT:
Enter a number:14

The total sum of digits is: 5

5. Write a python program to calculate the roots of a quadratic equation.

#Python program to calculate the roots of a quadratic equation

PYTHON CODE:

# import complex math module

import cmath

a = float(input('Enter a: '))

b = float(input('Enter b: '))

c = float(input('Enter c: '))

# calculate the discriminant

d = (b**2) - (4*a*c)

# find two solutions

sol1 = (-b-cmath.sqrt(d))/(2*a)

sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))

OUTPUT:

Enter a: 2

Enter b: 4

Enter c: 6

The solution are (-1-1.4142135623730951j) and (-1+1.4142135623730951j)


6. Write a python program to read ‘n’ numbers and count the negatives,
positives, and zeroes entered by the user.

# Python Program to Count Positive and Negative Numbers in a List

PYTHON CODE:

# Python Program to Count Positive and Negative Numbers in a List

NumList = []

Positive_count = 0

Negative_count = 0

j=0

Number = int(input("Please enter the Total Number of List Elements: "))

for i in range(1, Number + 1):

value = int(input("Please enter the Value of %d Element : " %i))

NumList.append(value)

while(j < Number):

if(NumList[j] >= 0):

Positive_count = Positive_count + 1

else:

Negative_count = Negative_count + 1

j=j+1

print("\nTotal Number of Positive Numbers in this List = ", Positive_count)

print("Total Number of Negative Numbers in this List = ", Negative_count)

OUTPUT:
Please enter the Total Number of List Elements: 5

Please enter the Value of 1 Element : 6

Please enter the Value of 2 Element : -9

Please enter the Value of 3 Element : 7

Please enter the Value of 4 Element : 9

Please enter the Value of 5 Element : -7

Total Number of Positive Numbers in this List = 3

Total Number of Negative Numbers in this List = 2

7. Write a python program to find the Fibonacci series for a given length

#Program to find the Fibonacci series for a given length

PYTHON CODE :

#program to find the Fibonacci series for a given length

n_terms = int(input ("How many terms the user wants to print? "))

# First two terms

num1 = 0

num2 = 1

count = 0

# Now, we will check if the number of terms is valid or not

if n_terms <= 0:

print ("Please enter a positive integer, the given number is not valid")

# if there is only one term, it will return num1


elif n_terms == 1:

print ("The Fibonacci sequence of the numbers up to", n_terms, ": ")

print(num1)

# Then we will generate Fibonacci sequence of number

else:

print ("The fibonacci sequence of the numbers is:")

while count < n_terms:

print(num1)

nth = num1 + num2

num1 = num2

num2 = nth

count += 1

OUTPUT:

How many terms the user wants to print? 7

The fibonacci sequence of the numbers is:

8
8. Write a python program to calculate the sum and average of the digits of a
number

#Python program to calculate the sum and average of the digits of a number

PYTHON CODE:

#python program to calculate the sum and average of the digits of a number

inputString =input("Enter the number:");

sumDigits =0

numberDigits=0

# Looping through a string.

for character in inputString:

if (character.isdigit()):

# Calculate the sum of the digits of all numbers that appear in the string

sumDigits+=int(character)

numberDigits+=1

# Calculate the average of the digits of all numbers that appear in the string

average=sumDigits/numberDigits

# Print the sum of all digits(8)

print("The sum of all digit is:",str(sumDigits))

# Print the average of all digits(2.0) in the new line.

print("The average of all digits in number:", average)

OUTPUT:

Enter the number:123


The sum of all digit is: 6

The average of all digits in number: 2.0

9. Write a python program to calculate the sum and average of first n natural
number

#Python program to calculate sum and average of first n natural number

PYTHON CODE:

#sum and average of first n natural number

n =int( input("Enter Number to calculate sum & average:"))

sum = 0

for num in range(0, n+1):

sum = sum+num

average = sum / n

print("sum of", n, "numbers is: ", sum )

print("Average of", n, "natural number is: ", average)

OUTPUT:

Enter Number to calculate sum & average:25

sum of 25 numbers is: 325

Average of 25 natural number is: 13.0

10. Bonus calculation

#Program to give bonus to the employee

1. If a company decides to give bonus to all its employees on Diwali. A 5% bonus on


salary is given to the male workers and 10% bonus on salary to the female workers.
Write a python program to enter the salary of the employee and gender of the
employee. If the salary of the employee is less than Rs.10,000 then the employee gets
an extra 2% bonus on salary. Calculate the bonus that has to be given to the employee
and display the salary that the employee will get.

PYTHON CODE:

ch=input("Enter the gender of the employee(m or f):")

sal=int(input("Enter the salary of the employee:"))

if(ch=='n'):

bonus=0.05*sal

else:

bonus=0.10*sal

amt_to_be_paid=sal+bonus

print("Salary = ",sal)

print("Bonus = ",bonus)

print("************************************")

print("Amount to be paid: ",amt_to_be_paid)

OUTPUT:

Enter the gender of the employee(m or f):f

Enter the salary of the employee:40000

Salary = 40000

Bonus = 4000.0

************************************

Amount to be paid: 44000.0

11.. Write a python program to find the greatest number from three numbers
#Program to find greatest of the numbers

PYTHON CODE:

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

num2=int(input("Enter the second number:"))

num3=int(input("Enter the third number:"))

if(num1>num2):

if(num2>num3):

print(num1,"is greater than",num2,"and",num3)

else:

print(num3,"is greater than",num1,"and",num2)

elif(num2>num3):

print(num2,"is greater than",num1,"and",num3)

else:

print("The three numbers are equal")

OUTPUT:

Enter the first number:13

Enter the second number:43

Enter the third number:25

43 is greater than 13 and 25

12. Write a python program to calculate tax given the following conditions:

If income<1,50,000 then no tax

If taxable income is 1,50,001 – 3,00,000 then charge 10% tax

If taxable income is 3,00,001 – 5,00,000 then charge 20% tax


If taxable income is above 5,00,001 then charge 30% tax

#Program to calculate tax

PYTHON CODE:

MIN1 = 150001

MAX1 = 300000

RATE1 = 0.10

MIN2 = 300001

MAX2 = 500000

RATE2 = 0.20

MIN3 = 500001

RATE3 = 0.30

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

taxable_income= income - 150000

if(taxable_income <=0):

print("No tax")

elif(taxable_income>=MIN1 and taxable_income<MAX1):

tax = (taxable_income - MIN1)*RATE1

elif(taxable_income>=MIN2 and taxable_income<MAX2):

tax = (taxable_income - MIN2)*RATE2

else:

tax = (taxable_income - MIN3)*RATE3

print("TAX = ",tax)

OUTPUT:

Enter the income:2000000


TAX = 404999.7

13. . Write a python program to enter the marks of a student in four subjects. Then
calculate the total and aggregate, and display the grade obtained by the student. If the
student scores an aggregate >75%, then the grade is “Distinction”. If aggregate >=60%
and <75%, then the grade is “First Division”. If aggregate >=50% and <60%, then the
grade is “Second Division”. If aggregate >=40% and <50%, then the grade is “Third
Division” Else the grade is “Fail”.

#Program to find total,average and grade

PYTHON CODE:

marks1=int(input("Enter the marks in mathematics:"))

marks2=int(input("Enter the marks in science:"))

marks3=int(input("Enter the marks in social science:"))

marks4=int(input("Enter the marks in computers:"))

total =marks1+marks2+marks3+marks4

avg =float(total)/4

print("Total = ",total,"\t Aggregate = ",avg)

if(avg>=75):

print("Distinction")

elif(avg>=60 and avg<75):

print("First division")

elif(avg>=50 and avg<60):

print("Second division")

elif(avg>=40 and avg<50):

print("Third division")

else:

print("Fail")

OUTPUT:
Enter the marks in mathematics:98

Enter the marks in science:97

Enter the marks in social science:95

Enter the marks in computers:94

Total = 384 Aggregate = 96.0

Distinction

14. Write a python program to calculate the roots of a quadratic equation.

#Program to calculate the roots of a quadratic equation.

PYTHON CODE:

a=int(input("Enter the values of a:"))

b=int(input("Enter the values of b:"))

c=int(input("Enter the values of c:"))

D=(b*b)-(4*a*c)

deno=2*a

if(D>0):

print("REAL ROOTS")

root1=(-b + D**0.5)/deno

root2=(-b - D**0.5)/deno

print("Root1 = ",root1,"\tRoot2 = ",root2)

elif(D==0):

print("REAL ROOTS")

root1 = -b/deno

print("Root1 and Root2 = ",root1)

else:

print("IMAGINARY ROOTS")
OUTPUT:

Enter the values of a:3

Enter the values of b:4

Enter the values of c:5

IMAGINARY ROOTS

15. Write a python program to read the numbers until -1 is encountered. Also
count the negatives, positives, and zeroes entered by the user.

#Program to count the negatives, positives and zeroes entered until -1 is


encountered

PYTHON CODE:

negatives = positives = zeroes = 0

print("Enter -1 to exit..")

while(1):

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

if(num==-1):

break

if(num==0):

zeros = zeroes+1

elif(num>0):

positives = positives+1

else:

negatives = negatives+1

print("Count of positive numbers entered : ",positives)

print("Count of negative numbers entered : ",negatives)


print("Count of zeroes entered : ",zeroes)

OUTPUT:

-1 to exit..

Enter any number : 7

Enter any number : 9

Enter any number : 1

Enter any number : 2

Enter any number : -3

Enter any number : -6

Enter any number : -7

Enter any number : 4

Enter any number : 5

Enter any number : 0

Enter any number : -1

Count of positive numbers entered : 6

Count of negative numbers entered : 3

Count of zeroes entered : 1

16. Write a python program to find whether the given number is an Armstrong
number or not

#Program to check armstrong number

PYTHON CODE:

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

s=0

num=n
while (n>0):

r=n%10

s=s+(r**3)

n=n/10

if (s==num):

print(num,"is an armstrong number")

else:

print(num,"is not an armstrong number")

OUTPUT:

Enter a number: 432

432 is not an armstrong number

17. Write a python program to read a character until a * is encountered and


count the number of uppercase, lowercase and numbers entered

#Program to count uppercase, lowercase, numbers entered

PYTHON CODE:

def Count(str):

upper, lower, number, special = 0, 0, 0, 0

for i in range(len(str)):

if str[i].isupper():

upper += 1

elif str[i].islower():

lower += 1

elif str[i].isdigit():

number += 1

else:
special += 1

print('Upper case letters:', upper)

print('Lower case letters:', lower)

print('Number:', number)

print('Special characters:', special)

str = input("Ënter the string:")

Count(str)

OUTPUT:

Enter the string: Happy Learning 23456

Upper case letters: 2

Lower case letters: 11

Number: 5

Special characters: 2

18. Write a python program to generate a calendar month given the start
day(Sunday (1), Monday (2), etc.) and the number of days in that month

#Program to generate a calendar

PYTHON CODE:

startDay=int(input("Enter the start day of the month:"))

num_of_days=int(input("Enter the number of days:"))

print("Sun Mon Tues Wed Thurs Fri Sat")

print("--------------------------------")

for i in range(startDay-1):

print(end=" ")

i=startDay-1

for j in range(1,num_of_days+1):
if(i>6):

print()

i=1

else:

i=i+1

print(str(j)=" ",end=" ")

OUTPUT:

Enter the start day of month:5

Enter number of days:31

Sun Mon Tues Wed Thurs Fri Sat

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

01 02 03

04 05 06 07 08 09 10

11 12 13 14 15 16 17

18 19 20 21 22 23 24

25 26 27 28 29 30 31

TEAM C

19. Write a python program to print the following pattern

Program:

#python program to print asterisk pattern

rows=int(input("enter the number rows: "))

for i in range(0,rows):
print("*******")

Output:

enter the number rows 3

*******

*******

*******

20. Write a python program to print the following patt+ern

**

***

****

*****

Program:

#program to print the following asterisk pattern

rows=int(input("ENTER THE NUMBER OF ROWS"))

for i in range(0,rows):

for j in range(0,i+1):

print("*",end="")

print("\n")

Output:

ENTER THE NUMBER OF ROWS5


*

**

***

****

*****

21. Write a python program to print the following pattern

12

123

1234

12345

Program:

#python program to print numbers in increasing pattern

row=int(input("enter the number of rows:"))

for i in range (0,row+1):

for j in range(1,i+1):

print(j,end=" ")

print()

Output:

enter the number of rows: 5

12
123

1234

12345

22. Write a python program to print the following pattern

22

333

4444

55555

Program:

#program to print the following numbers pattern

rows=int(input("ENTER THE NUMBER OF ROWS"))

for i in range(1,rows+1):

for j in range(0,i):

print(i,end="")

print("\n")

Output:

ENTER THE NUMBER OF ROWS5

22

333

4444
55555

23. Write a python program to print the following pattern

12

345

6789

Program:

#program to print the following number pattern

rows=int(input("ENTER THE NUMBER OF ROWS"))

num=0

for i in range(0,rows):

for j in range(0,i):

print(num,end=" ")

num=num+1

print("\n")

Output:

ENTER THE NUMBER OF ROWS5

12

345

6789
24. Write a python program to print the following pattern

12

123

1234

Program:

#python program to print asterisk pattern

row=int(input("enter the number of rows: "))

for i in range (1,row+1):

for j in range(1,(row-i)+1):

print(" ",end="")

for k in range(1,i+1):

print("{0}".format(k),end="")

print()

Output:

enter the number of rows: 4

12

123
1234

25. Write a python program to print the following pattern

121

12321

1234321

123454321

Program:

#program to create a pyramid

def pyramid():

odd = 1

row = int(input("enter the row:"))

space = row-2

for i in range(1, row):

k=0

for j in range(1, space+1):

print(" ",end = "")

for j in range(1, odd+1):

if j <= i:

k=k+1

else:
k =k-1

print(k, end = "")

print()

odd = odd + 2

space = space - 1

pyramid()

Output:

enter the row:7

121

12321

1234321

123454321

12345654321

26. Write a python program to make a simple calculator by providing choice for
operations

#calculator program

Program:

print("********CALCULATOR*********")
print("Menu \n 1.Add \n 2.Subtract \n 3.Multiply \n 4.Division \n 5.Modulus")
choice = input("enter your choice:").lower()
num1 = int(input("enter number 1:"))
num2 = int(input("enter number 2:"))
if choice == '1' or choice == "add":
print(num1, "+", num2, "=", num1 + num2)
elif choice == '2' or choice == "subtract":
print(num1, "-", num2, "=", num1 - num2)
elif choice == '3' or choice == "multiply":
print(num1, "*", num2, "=", num1 * num2)
elif choice == '4' or choice == "division":
print(num1, "/", num2, "=", num1 / num2)
elif choice == '5' or choice == 'modulus':
print(num1, "%", num2, "=", num1 % num2)
else:
print("enter a valid operation!")

OUTPUT:

********CALCULATOR*********
Menu
1.Add
2.Subtract
3.Multiply
4.Division
5.Modulus
enter your choice:multiply
enter number 1:3
enter number 2:3
3*3=9

********CALCULATOR*********
Menu
1.Add
2.Subtract
3.Multiply
4.Division
5.Modulus
enter your choice:1
enter number 1:2
enter number 2:4
2+4=6
27. Write a python program to compute F(x,y) where F(x,y)=F(x-y,y)+1 if y<=x

Program:

1. Write a python program to display all leap years between 1900 to 2100

PROGRAM:

#Leap Years between 1900 to 2100


def CheckLeap(Year):

if((Year % 400 == 0) or (Year % 100 != 0) and (Year % 4 == 0)):


print( Year,"is a leap Year");

else:
return

for Year in range(1900,2001):


CheckLeap(Year)

OUTPUT:

1904 is a leap Year


1908 is a leap Year
1912 is a leap Year
1916 is a leap Year
1920 is a leap Year
1924 is a leap Year
1928 is a leap Year
1932 is a leap Year
1936 is a leap Year
1940 is a leap Year
1944 is a leap Year
1948 is a leap Year
1952 is a leap Year
1956 is a leap Year
1960 is a leap Year
1964 is a leap Year
1968 is a leap Year
1972 is a leap Year
1976 is a leap Year
1980 is a leap Year
1984 is a leap Year
1988 is a leap Year
1992 is a leap Year
1996 is a leap Year
2000 is a leap Year

28. Write a python program to sum the series : 1 + ½ + 1/3 +….+1/n

PROGRAM:

#Sum of series 1+½+⅓+.....+1/n


n=int(input("Enter the number of terms: "))
sum1=0
for i in range(1,n+1):
sum1=sum1+(1/i)
print("The sum of series is",round(sum1,4))

n=int(input("Enter the number of terms: "))


sum1=0
for i in range(1,n+1):
sum1=sum1+(1/i)
print("The sum of series is",round(sum1,4))

OUTPUT:

1.Enter the number of terms: 5


The sum of series is 2.2833

2.Enter the number of terms: 6


The sum of series is 2.45

3.Enter the number of terms: 7


The sum of series is 2.5929

29.. Write a python program to sum the series : 1/1 2 + 1/22 + 1/32 +…+ 1/n2

PROGRAM:
#Sum of the Series 1/1^+½^+⅓^+....+1/n^
n=int(input("Enter the number of terms: "))
sum1=0
for i in range(1,n+1):
sum1=sum1+(1/(i**2))
print("The sum of series is",round(sum1,4))
OUTPUT:

1.Enter the number of terms: 7


The sum of series is 1.5118

2.Enter the number of terms: 8


The sum of series is 1.5274

3.Enter the number of terms: 12


The sum of series is 1.565

30. Write a python program to find the sum of first 10 natural numbers using lambda
function

#PROGRAM
#sum of first 10 natural numbers using lambda function
x=lambda: sum(range(1,11))
print(x())

#OUTPUT

55

31. .Write a program using functions in python to convert the hours:minutes format to
minutes. Eg. input: 2 hrs, 20 minutes output: 140 minutes

# PROGRAM
#To Convert Hours to Minutes

def convert_time(hrs, min):

min= hrs*60+min
return min
h=int(input("Enter the hours:"))
m=int(input("Enter the minutes:"))
m=convert_time(h,m)
print("Total Minutes=",m)
#OUTPUT

Enter the hours : 2


Enter the minutes : 25
Total Minutes = 145 minutes

32. Write a program using recursive functions in python


to find factorial of a number

#PROGRAM:
#To Find factorial of a number using recursive function

def recur_factorial(n):

if n == 1:
return n
else:
return n*recur_factorial(n-1)

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

if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

#OUTPUT
Enter a number:7
The factorial of 7 is 5040

33. Write a program using recursive functions in python to calculate GCD of two
numbers

#PROGRAM:

#Calculate GCD of numbers using Recursive function

def GCD(x,y):
r=x%y
if(r==0):
return y
else:
return GCD(y,r)
n= int(input("Enter the First Number :"))
m= int(input("Enter the Second Number :"))
print("The GCD of Two Numbers is:", GCD(n,m))

#OUTPUT:

Enter the First Number :9


Enter the Second Number :36
The GCD of Two Numbers is: 9

34. Write a program using recursive functions in python to find exp(x,y)

#PROGRAM:

#To Find exp(x,y) using recursive function


def exp(x,y):
if(y==0):
return 1
else:
return(x*exp(x,y-1))
x=int(input("Enter the first number:"))
y=int(input("Enter the second number:"))
print("Result=",exp(x,y))

#OUTPUT:

Enter the first number:9


Enter the second number:8
Result= 43046721

35. Write a Python program to create a lambda function that adds 15 to a given number
passed in as an argument, also create a lambda function that multiplies argument x with
argument y and print the result.

# PROGRAM
#To create a lambda function to add 15 to a given number as an argument
& multiplies argument x with argument y
l = lambda add : add + 15
print(l(20))
l = lambda x, y : x * y
print(l(10, 3))

# OUTPUT
35
30

36. Explain the use of packages in python

#Python program to calculate the roots of a quadratic equation

PACKAGES:

A python package is a collection of modules. Modules that are related


to each other are mainly put in the same package.Any Python file, whose name is the
module’s name property without the .py extension, is a module.A package is a directory
of Python modules that contains an additional __init__.py file,which distinguishes a
package from a directory that is supposed to contain multiple Python scripts.Packages
can be nested to multiple depths if each corresponding directory contains its own
__init__.py file.

USES OF PACKAGES:

Packages helps importing any modules, individually or whole.While


importing a package or sub packages or modules,python searches the whole tree of
directories looking for the particular package and proceeds systematically as
programmed by the python.

Python packages allow you to break down large


systems and organize their modules in a consistent way that you and other people can
use and reuse efficiently. Python's motto of "Batteries Included" means that it comes
preloaded with lots of useful packages in the standard library.

BENEFITS

Naming conflicts can be solved easilly

We can identify our components uniquely.

Improves the Modularity of the application.

The readability of the application will be improved.


Maintainability of the application will be improved.

You might also like