Python Question Bank Program solution
UNIT – 1: Introduction and Syntax of Python Programming
1. Write a simple Python program to calculate Simple and Compound Interest. Simple Interest
= P∗R∗T/100 Compound Interest = P ∗ (1+R/100∗n)n∗T
# Taking input from user
P = float(input("Enter Principal Amount: "))
R = float(input("Enter Rate of Interest: "))
T = float(input("Enter Time (in years): "))
n = int(input("Enter Number of times interest is compounded per year: "))
# Simple Interest Formula
SI = (P * R * T) / 100
# Compound Interest Formula
CI = P * (1 + (R / (100 * n))) ** (n * T)
# Display results
print("Simple Interest =", SI)
print("Compound Interest =", CI)
2. Write a simple python program to convert Celsius to Fahrenheit and vice versa.
# Celsius to Fahrenheit
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (9/5) * celsius + 32
print("Temperature in Fahrenheit =", fahrenheit)
# Fahrenheit to Celsius
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5/9
print("Temperature in Celsius =", celsius)
3. Design a program to read name, contact, email and birthdate and print them using
format() function.
name = input("Enter your name: ")
contact = input("Enter your contact number: ")
email = input("Enter your email: ")
birthdate = input("Enter your birthdate (DD/MM/YYYY): ")
print("Name: {}".format(name))
print("Contact: {}".format(contact))
print("Email: {}".format(email))
print("Birthdate: {}".format(birthdate))
4. Write a simple python program to compute the slope of a line between two points (x1,
y1) and (x2, y2). ( Slope = 𝑦2−𝑦1 / 𝑥2−𝑥1).
x1 = float(input("Enter x1: "))
y1 = float(input("Enter y1: "))
x2 = float(input("Enter x2: "))
y2 = float(input("Enter y2: "))
slope = (y2 - y1) / (x2 - x1)
print("Slope of the line =", slope)
5. Write a program to calculate area of a rectangle and circle.
# Area of Rectangle
length = float(input("Enter length of rectangle: "))
breadth = float(input("Enter breadth of rectangle: "))
rectangle_area = length * breadth
print("Area of Rectangle =", rectangle_area)
# Area of Circle
radius = float(input("Enter radius of circle: "))
circle_area = 3.14 * radius * radius
print("Area of Circle =", circle_area)
6. Write a python program to get change values in Quarter, Dime, Nickels and Pennies, and
calculate the value of change in Dollars. Consider Quarter = 0.25 $, Dime = 0.10 $, Nickels =
0.05 $ and Penny = 0.01 $.
quarter = int(input("Enter number of Quarters: "))
dime = int(input("Enter number of Dimes: "))
nickel = int(input("Enter number of Nickels: "))
penny = int(input("Enter number of Pennies: "))
total = (quarter * 0.25) + (dime * 0.10) + (nickel * 0.05) + (penny * 0.01)
print("Total value of change in Dollars = $", total)
7. Write a program to calculate area and volume of Sphere. ( Area=4πr2, Volume=4/3
πr3)
radius = float(input("Enter radius of sphere: "))
area = 4 * 3.14 * radius * radius
volume = (4/3) * 3.14 * radius * radius * radius
print("Area of Sphere =", area)
print("Volume of Sphere =", volume)
8. Write a program to accept two numbers from the user and calculate multiplication.
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 * num2
print("Multiplication =", result)
UNIT 2: Operators and Control Flow Structures
1. Write a Python program to remove all duplicate character from a given string.
s = input("Enter a string: ")
result = ""
for ch in s:
if ch not in result:
result = result + ch
print("String after removing duplicates:", result)
2. Develop a program that displays an ASCII character table from ! to ~. Display the
ASCII value of a character in decimal and hexadecimal. Display five characters per
line.
count = 0
for i in range(33, 127):
print(chr(i), "=", i, hex(i), end="\t")
count += 1
if count % 5 == 0:
print()
3. Develop a program that counts the occurrences of each digit in a string. The
program counts how many times a digit appears in the string. For example, if the
input is "12203AB3", then the output should output 0 (1 time), 1 (1 time), 2 (2
times), 3 (2 times).
s = input("Enter a string: ")
for i in range(10):
count = [Link](str(i))
if count > 0:
print(i, "=", count, "time(s)")
4. Write a Python program to print the sum of all even numbers between 1 to 100.
total = 0
for i in range(2, 101, 2):
total = total + i
print("Sum of even numbers =", total)
5. Write program to display Fibonacci sequence up to n terms.
n = int(input("Enter number of terms: "))
a=0
b=1
for i in range(n):
print(a, end=" ")
c=a+b
a=b
b=c
6. Write a program to check whether given number/string is palindrome or not.
(example- 13231-palindrome 1201-not palindrome)
data = input("Enter a number/String: ")
if data == data[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
7. Write program to check given year is a leap year or not.
year = int(input("Enter year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("Leap Year")
else:
print("Not a Leap Year")
8. Write a program to determine whether input number is prime or not.
num = int(input("Enter a number: "))
count = 0
for i in range(2, num):
if num % i == 0:
count = count + 1
if count == 0:
print("Prime Number")
else:
print("Not Prime Number")
9. Write a program to read n numbers from users and calculate average of those n
numbers.
n = int(input("Enter how many numbers: "))
total = 0
for i in range(n):
num = float(input("Enter number: "))
total = total + num
average = total / n
print("Average =", average)
10. Write a program to find the sum of following series:
n = int(input("Enter number of terms: "))
sum = 0
num = 1
for i in range(n):
sum = sum + (1 / num)
num = num + 2
print("Sum of series =", sum)
11. Write a program that checks whether two words are anagrams. For Example: Silent
and Listen are anagrams.
word1 = input("Enter first word: ")
word2 = input("Enter second word: ")
if sorted([Link]()) == sorted([Link]()):
print("Anagrams")
else:
print("Not Anagrams")
12. Write a Python Program for a Score between 0 and [Link] the Score is out of range
print an error. If the score is between 0 and 100 ,print a grade. Grading system :
A(>=90),B(80-89),C(70-79), D(60-69),E(50-59),F(<50)
score = int(input("Enter score: "))
if score < 0 or score > 100:
print("Error: Score out of range")
elif score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
elif score >= 70:
print("Grade C")
elif score >= 60:
print("Grade D")
elif score >= 50:
print("Grade E")
else:
print("Grade F")
13. Write a python program to sum the following series: 1/3+3/5+5/7+7/9+……….97/99.
total = 0
for i in range(1, 98, 2):
total = total + (i / (i + 2))
print("Sum of series =", total)
14. Write a Program to Check if a Number is Even or Odd Using Bitwise Operator.
num = int(input("Enter a number: "))
if num & 1 == 0:
print("Even Number")
else:
print("Odd Number")
15. Create a Python program to display the following patterns using loop concept.
rows = 5
for i in range(1, rows + 1): *
for j in range(rows - i):
**
print(" ", end="")
***
for k in range(i):
print("* ", end="") ****
print() *****
_________________________________________________________________
rows = 5 1
for i in range(1, rows + 1):
12
for j in range(1, i + 1):
123
print(j, end=" ")
print() 1234
12345
___________________________________________________________________
rows = 5 A
ch = 65 # ASCII value of A
BB
for i in range(1, rows + 1):
CCC
for j in range(i):
print(chr(ch), end=" ")
DDDD
ch = ch + 1 EEEEE
print()
____________________________________________________________________
rows = 5
$
for i in range(1, rows + 1): $$
for j in range(i): $$$
print("$", end=" ") $$$$
print() $$$$$
rows = 5 1
22
for i in range(1, rows + 1): 333
for j in range(i):
4444
print(i, end=" ")
55555
print()
UNIT – 3: Data Structure in Python
1. Write a Python program to concatenate two dictionaries into a new one.
d1 = {"a": 10, "b": 20}
d2 = {"c": 30, "d": 40}
d3 = {}
[Link](d1)
[Link](d2)
print("New Dictionary:", d3)
print("Result list =", result)
2. Write a Python program to check if a key exists in a dictionary.
d = {"name": "Ravi", "age": 20}
key = input("Enter key to check: ")
if key in d:
print("Key exists")
else:
print("Key does not exist")
3. Write a program that is given a dictionary containing the average daily
temperature for each day of the week, and prints all the days on which the
average temperature was between 40 and 50 degrees.
temp = {
"Monday": 45,
"Tuesday": 38,
"Wednesday": 50,
"Thursday": 42,
"Friday": 55,
"Saturday": 48,
"Sunday": 35
}
for day in temp:
if temp[day] >= 40 and temp[day] <= 50:
print(day)
4. Given a two list of numbers, write a program to create a new list such that the
new list should contain even numbers from the first list and odd numbers from
the second list.
- L1=[12,15,30,42,35], L2=[34,23,77,50,32]
- Expected output: Result list=[12,30,42,23,77]
L1 = [12, 15, 30, 42, 35]
L2 = [34, 23, 77, 50, 32]
result = []
for i in L1:
if i % 2 == 0:
[Link](i)
for i in L2:
if i % 2 != 0:
[Link](i)
print("Result list =", result)
5. Develop a program to repeatedly prompt the user to enter the capital of a state.
Upon receiving the user’s input, the program reports whether the answer is
correct. Assume the states and their capitals are stored in dictionaries as key
value pairs.
states = {
"Gujarat": "Gandhinagar",
"Maharashtra": "Mumbai",
"Rajasthan": "Jaipur"
}
state = input("Enter state name: ")
capital = input("Enter capital: ")
if capital == states[state]:
print("Correct Answer")
else:
print("Wrong Answer")
6. Write a Python program to perform the below operations on the List: (1) Create
a list.(2)Add/Remove an item to/from a list. (3) Get the number of elements in the
list.(4)Access elements of the list using the index.(5)Sort the list.(6) Reverse the
list.
mylist = [10, 20, 30]
print("List:", mylist)
[Link](40)
print("After adding:", mylist)
[Link](20)
print("After removing:", mylist)
print("Number of elements:", len(mylist))
print("Element at index 1:", mylist[1])
[Link]()
print("Sorted list:", mylist)
[Link]()
print("Reversed list:", mylist)
7. Write a Python program to perform the below operations on the list:
• Read n numbers from a user
• Find positive numbers and Find negative numbers.
• Find even numbers and Find odd numbers.
n = int(input("Enter how many numbers: "))
numbers = []
for i in range(n):
num = int(input("Enter number: "))
[Link](num)
for i in numbers:
if i > 0:
print("Positive:", i)
if i < 0:
print("Negative:", i)
if i % 2 == 0:
print("Even:", i)
else:
print("Odd:", i)
8. Write a program to perform below operations on set:
• Create two different sets with the data.
• Print set items.
• Add/remove items in/from a set.
• Perform operations on sets : Union,Intersection,difference
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print("Set1:", set1)
print("Set2:", set2)
[Link](6)
print("After add:", set1)
[Link](2)
print("After remove:", set1)
print("Union:", set1 | set2)
print("Intersection:", set1 & set2)
print("Difference:", set1 - set2)
9. Write a program to perform below operations on tuple:
1. Create tuple with different data types.
2. Print tuple items.
3. Convert tuple into a list and add an item.
4. Convert list into a tuple and print tuple items.
t = (10, "Hello", 3.5)
print("Tuple items:", t)
l = list(t)
print("Tuple to List:", l)
[Link]("Python")
t = tuple(l)
print("List to Tuple:", t)
10. Write a program to perform below operations on dictionary :
1. Create a dictionary
2. Print dictionary items.
3. Concatenate multiple dictionaries.
d1 = {"a": 1, "b": 2}
d2 = {"c": 3}
d3 = {"d": 4}
print("Dictionary items:", d1)
[Link](d2)
[Link](d3)
print("After concatenation:", d1)
UNIT – 4: Python Functions and File Handling Functions
1. Give the output of following Python code:
a. myStr = ‘INDIA IS THE BEST’
b. print myStr [15 : : 1]
c. print myStr [-10 : -1 : 2]
d. print myStr [-1: :-1]
Output : ST
STEBS
TSEB EHT SI AIDNI
2. Develop an automated censor program that reads the text from a file and creates
a new file where all of the four-letter words have been replaced by “****”. You
can ignore punctuation, and you may assume that no words in the file are split
across multiple lines.
file = open("[Link]", "r")
text = [Link]()
[Link]()
words = [Link]()
new_text = ""
for word in words:
if len(word) == 4:
new_text = new_text + "**** "
else:
new_text = new_text + word + " "
file = open("[Link]", "w")
[Link](new_text)
[Link]()
print("New file created")
3. Develop a program that reads a text file and calculates the average word length
and sentence length in that file.
file = open("[Link]", "r")
text = [Link]()
[Link]()
words = [Link]()
sentences = [Link](".")
total = 0
for word in words:
total = total + len(word)
avg_word = total / len(words)
avg_sentence = len(words) / len(sentences)
print("Average word length =", avg_word)
print("Average sentence length =", avg_sentence)
4. Write a Python program that reads a text file and counts the occurrences of each
alphabet in the file. The program should prompt the user to enter the filename.
filename = input("Enter file name: ")
file = open(filename, "r")
text = [Link]().lower()
[Link]()
for ch in "abcdefghijklmnopqrstuvwxyz":
count = [Link](ch)
if count > 0:
print(ch, "=", count)
5. Write a Python program to check whether a given string is palindrome or not.
s = input("Enter a string: ")
if s == s[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
6. Write a program that defines a function to return a new list by eliminating the
duplicate values in the list.
def remove_duplicate(lst):
new_list = []
for i in lst:
if i not in new_list:
new_list.append(i)
return new_list
list1 = [1, 2, 2, 3, 4, 4, 5]
print(remove_duplicate(list1))
7. Write a Python program to find Length of string.
s = input("Enter a string: ")
print("Length of string =", len(s))
8. Write a recursive user-defined function to find the factorial of a given number.
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
num = int(input("Enter number: "))
print("Factorial =", factorial(num))
9. Write a recursive user-defined function to find the Fibonacci series up to a given
number.
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
num = int(input("Enter number of terms: "))
for i in range(num):
print(fibonacci(i), end=" ")
UNIT – 5: Python Modules and Packages
1. Write a program to plot sine wave using matplotlib.
import numpy as np
import [Link] as plt
x = [Link](0, 10, 100)
y = [Link](x)
[Link](x, y)
[Link]("Sine Wave")
[Link]()
2. Write Numpy program to create 2D array, perform slicing, find sum & mean.
import numpy as np
arr = [Link]([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
print("2D Array:\n", arr)
print("First two rows:\n", arr[0:2])
print("First two columns:\n", arr[:, 0:2])
print("Sum =", [Link]())
print("Mean =", [Link]())
3. Create simple line plot, bar chart and scatter chart using Matplotlib.
import [Link] as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
# Line plot
[Link](x, y)
[Link]("Line Plot")
[Link]()
# Bar chart
[Link](x, y)
[Link]("Bar Chart")
[Link]()
# Scatter chart
[Link](x, y)
[Link]("Scatter Plot")
[Link]()
4. Develop a program that picks a random integer from 1 to 100, and has players
guess the number. If a player's guess is less than 1 or greater than 100, say
"OUT OF BOUNDS", if their guess is within 10 of the number, return
"WARM!" and if their guess is further than 10 away from the number, return
"COLD!",When the player's guess equals the number, tell them they've guessed
correctly and display how many guesses it took.
import random
number = [Link](1, 100)
count = 0
while True:
guess = int(input("Enter your guess: "))
count = count + 1
if guess < 1 or guess > 100:
print("OUT OF BOUNDS")
elif guess == number:
print("Correct! You guessed in", count, "tries")
break
elif abs(guess - number) <= 10:
print("WARM!")
else:
print("COLD!")
5. Create a user defined module with simple functions for: addition, subtraction,
multiplication, division, modulo, square, factorial. Write a program to import
the module and access functions defined in the module.
# [Link] (module file)
def add(a, b):
return a + b
def sub(a, b): # Main program
return a - b import mymath
def mul(a, b): print([Link](10, 5))
return a * b print([Link](10, 5))
def div(a, b): print([Link](10, 5))
return a / b print([Link](10, 5))
def mod(a, b): print([Link](10, 5))
return a % b print([Link](5))
def square(a): print([Link](5))
return a * a
def factorial(n):
f=1
for i in range(1, n + 1):
f=f*i
return f
6. Create a user-defined module with a simple functions for finding the area of a
square, circle and rectangle. Write a program to import the module and access
functions defined in the module.
# [Link] (module file)
def square(side):
return side * side
def circle(radius):
return 3.14 * radius * radius
def rectangle(length, breadth):
return length * breadth
# Main program for Question 6
import area
print("Square Area =", [Link](4))
print("Circle Area =", [Link](3))
print("Rectangle Area =", [Link](5, 2))
7. Write a program to define module to find sum of two numbers. Import module
to another program.
# sum_module.py (module file)
def add(a, b):
return a + b
# Main program for Question 7
import sum_module
print("Sum =", sum_module.add(10, 20))
8. Write a program to read a date in the format DD/MM/YYYY and print the same
date in MM-DD-YYYY format.
date = input("Enter date (DD/MM/YYYY): ")
d, m, y = [Link]("/")
print("New format =", m + "-" + d + "-" + y)