Python Question Bank – Answers with Explanation
1. What is a Variable? Give rules to create a
variable
Definition
A variable is a name used to store data in memory.
Example:
x = 10
name = "Dhavan"
Rules for Creating Variables
1. Variable name must start with a letter or underscore (_).
2. It should not start with a number.
3. Spaces are not allowed.
4. Special symbols except underscore are not allowed.
5. Python keywords cannot be used.
6. Variable names are case-sensitive.
Valid:
age = 20
_student = "Ram"
Invalid:
2age = 20
first name = "Ram"
1
2. Differentiate for and while loops
for loop while loop
Used when number of iterations is known Used when iterations are unknown
Iterates over sequence Executes based on condition
Simple syntax Needs manual update
Less chance of infinite loop Infinite loop possible
Example of for loop
for i in range(5):
print(i)
Example of while loop
i = 0
while i < 5:
print(i)
i += 1
3. Define continue and break statement with
example
Break
Terminates the loop immediately.
for i in range(1, 6):
if i == 3:
break
print(i)
Output:
2
1
2
Continue
Skips current iteration and moves to next iteration.
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
4. Define membership operator
Membership operators are used to check whether a value exists in a sequence.
Operators:
• in
• not in
Example
list1 = [1, 2, 3]
print(2 in list1)
print(5 not in list1)
Output:
3
True
True
5. Define identity operator
Identity operators compare memory locations of two objects.
Operators:
• is
• is not
Example
x = [1, 2]
y = x
print(x is y)
Output:
True
6. What is boxing and unboxing?
Boxing
Converting primitive data into object form.
Unboxing
Extracting primitive value from object.
Example:
x = 10
4
Python automatically handles boxing and unboxing.
7. Explain Boolean operator
Boolean operators are used to combine conditional statements.
Operators:
• and
• or
• not
Example
x = 10
print(x > 5 and x < 20)
print(x > 5 or x < 5)
print(not(x > 5))
8. Program to find factorial using recursion
Explanation
Factorial of n is:
n! = n × (n-1) × (n-2)...1
Program
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
num = int(input("Enter number: "))
print("Factorial:", factorial(num))
5
9. Program to display Fibonacci series using
recursion
Program
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
terms = int(input("Enter terms: "))
for i in range(terms):
print(fibonacci(i), end=" ")
10. What is tuple?
A tuple is an ordered and immutable collection in Python.
Example
t = (1, 2, 3)
print(t)
Features
1. Ordered
2. Immutable
3. Allows duplicate values
4. Faster than list
11. Explain nested dictionary with syntax
A dictionary inside another dictionary is called nested dictionary.
6
Syntax
student = {
"s1": {"name": "Ram", "age": 20},
"s2": {"name": "Sam", "age": 21}
}
Accessing values
print(student["s1"]["name"])
12. Explain list along with methods
A list is an ordered mutable collection.
Example
list1 = [1, 2, 3]
List Methods
Method Description
append() Adds element
insert() Inserts element
remove() Removes element
pop() Removes last element
sort() Sorts list
reverse() Reverses list
clear() Removes all elements
7
Example
[Link](4)
[Link]()
print(list1)
13. Explain lambda expression with example
Lambda is an anonymous function.
Syntax
lambda arguments : expression
Example
square = lambda x: x * x
print(square(5))
Output:
25
14. Define operator overloading with suitable
example
Operator overloading means giving additional meaning to operators.
Example
class Demo:
def __init__(self, x):
self.x = x
def __add__(self, other):
8
return self.x + other.x
obj1 = Demo(10)
obj2 = Demo(20)
print(obj1 + obj2)
15. Program to check vowel or not
ch = input("Enter character: ")
if [Link]() in ['a', 'e', 'i', 'o', 'u']:
print("Vowel")
else:
print("Not a vowel")
16. Program to check right triangle
a = int(input("Enter side1: "))
b = int(input("Enter side2: "))
c = int(input("Enter side3: "))
if a*a + b*b == c*c:
print("Right triangle")
else:
print("Not a right triangle")
17. ATM denomination tuple program
notes = (2, 3, 5)
num_500, num_200, num_100 = notes
total = (num_500 * 500) + (num_200 * 200) + (num_100 * 100)
print("Total amount:", total)
9
18. Program to check perfect number
Explanation
A perfect number is equal to sum of its proper divisors.
Example: 6 = 1 + 2 + 3
Program
num = int(input("Enter number: "))
sum1 = 0
for i in range(1, num):
if num % i == 0:
sum1 += i
if sum1 == num:
print("Perfect number")
else:
print("Not a perfect number")
19. Program to count digits using recursion
def count_digits(n):
if n < 10:
return 1
return 1 + count_digits(n // 10)
num = int(input("Enter number: "))
print("Digits:", count_digits(num))
20. Student marks dictionary program
students = {}
n = int(input("Enter number of students: "))
10
for i in range(n):
name = input("Enter name: ")
mark = int(input("Enter mark: "))
students[name] = mark
search = input("Enter student name to search: ")
if search in students:
print(students[search])
else:
print("Not Found")
21. Course class using constructor and
encapsulation
class Course:
def __init__(self, name, code, duration):
self.__name = name
self.__code = code
self.__duration = duration
def get_name(self):
return self.__name
def get_code(self):
return self.__code
def get_duration(self):
return self.__duration
def display(self):
print("Course Name:", self.__name)
print("Course Code:", self.__code)
print("Duration:", self.__duration)
name = input()
code = input()
duration = input()
c = Course(name, code, duration)
[Link]()
11
22. Operator overloading for addition and
subtraction
class Number:
def __init__(self, value):
[Link] = value
def __add__(self, other):
return [Link] + [Link]
def __sub__(self, other):
return [Link] - [Link]
n1 = Number(20)
n2 = Number(10)
print("Addition:", n1 + n2)
print("Subtraction:", n1 - n2)
23. Multilevel inheritance with example
Definition
When a class inherits from another inherited class.
Program
class Grandfather:
def show1(self):
print("Grandfather class")
class Father(Grandfather):
def show2(self):
print("Father class")
class Son(Father):
def show3(self):
print("Son class")
12
obj = Son()
obj.show1()
obj.show2()
obj.show3()
24. Hierarchical inheritance with example
Definition
Multiple child classes inherit from one parent class.
Program
class Parent:
def display(self):
print("Parent class")
class Child1(Parent):
pass
class Child2(Parent):
pass
obj1 = Child1()
obj2 = Child2()
[Link]()
[Link]()
25. Explain dictionary with example
A dictionary stores data in key-value pairs.
Example
student = {
"name": "Ram",
"age": 20
}
13
print(student["name"])
Features
1. Mutable
2. Key-value structure
3. Fast access
4. No duplicate keys
26. Create dictionary using two lists
names = ["Ram", "Sam", "Tom"]
ages = [20, 21, 22]
result = dict(zip(names, ages))
for k, v in [Link]():
print(k, v)
27. Encapsulation using getter and setter
class Bank:
def __init__(self):
self.__balance = 0
def set_balance(self, amount):
if amount >= 0:
self.__balance = amount
else:
print("Invalid amount")
def get_balance(self):
return self.__balance
obj = Bank()
obj.set_balance(5000)
print("Balance:", obj.get_balance())
14
28. Program to check upper triangular matrix
matrix = [
[1, 3, 5],
[0, 4, 6],
[0, 0, 2]
]
flag = True
for i in range(len(matrix)):
for j in range(i):
if matrix[i][j] != 0:
flag = False
if flag:
print("Upper triangular matrix")
else:
print("Not an upper triangular matrix")
29. Sum of natural numbers using recursion
def natural_sum(n):
if n == 1:
return 1
return n + natural_sum(n - 1)
num = int(input("Enter number: "))
print("Sum:", natural_sum(num))
30. Compare sort() and sorted()
sort() sorted()
Modifies original list Returns new list
Works only with list Works with all iterables
No return value Returns sorted sequence
15
Example
list1 = [3, 1, 2]
[Link]()
print(list1)
list2 = [5, 4, 6]
print(sorted(list2))
31. Fruit shop dictionary program
fruits = {
"apple": 100,
"banana": 40,
"orange": 80,
"grapes": 120,
"mango": 150
}
count = 0
total = 0
while True:
item = input("Enter fruit name or Q to quit: ")
if [Link]() == 'Q':
break
if item in fruits:
total += fruits[item]
count += 1
else:
print("Fruit not available")
print("Total selected fruits:", count)
print("Total bill:", total)
16
32. Multiple inheritance program
class Father:
def show1(self):
print("Father class")
class Mother:
def show2(self):
print("Mother class")
class Child(Father, Mother):
pass
obj = Child()
obj.show1()
obj.show2()
33. Hierarchical inheritance program
class Animal:
def sound(self):
print("Animal makes sound")
class Dog(Animal):
pass
class Cat(Animal):
pass
obj1 = Dog()
obj2 = Cat()
[Link]()
[Link]()
34. Combine two lists and make dictionary
keys = ["name", "age", "city"]
values = ["Ram", 20, "Chennai"]
17
result = dict(zip(keys, values))
print(result)
35. Dictionary for mobile specification
mobile = {
"Brand": "Samsung",
"RAM": "8GB",
"Storage": "128GB",
"Battery": "5000mAh",
"Price": 25000
}
for k, v in [Link]():
print(k, ":", v)
36. Dictionary for grocery shop purchase
items = {
"Rice": 50,
"Sugar": 40,
"Oil": 120
}
bill = 0
for item, price in [Link]():
print(item, price)
bill += price
print("Total Bill:", bill)
18
37. Fibonacci and factorial using recursive
functions
Factorial Program
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n-1)
print(factorial(5))
Fibonacci Program
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
for i in range(6):
print(fibonacci(i), end=" ")
38. Lambda expression for square root and cube
root
square = lambda x: x ** 2
cube = lambda x: x ** 3
num = int(input("Enter number: "))
print("Square:", square(num))
print("Cube:", cube(num))
19
39. Lambda expression for lower, upper and title
case
lower = lambda s: [Link]()
upper = lambda s: [Link]()
title = lambda s: [Link]()
text = input("Enter string: ")
print(lower(text))
print(upper(text))
print(title(text))
40. Student SGPA using classes and constructor
class Student:
def __init__(self, name, marks):
[Link] = name
[Link] = marks
def calculate_sgpa(self):
return sum([Link]) / len([Link])
def display(self):
print("Name:", [Link])
print("SGPA:", self.calculate_sgpa())
marks = []
for i in range(5):
m = int(input("Enter mark: "))
[Link](m)
s = Student("Ram", marks)
[Link]()
20
41. Calculator using class and constructor
class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def sub(self):
return self.a - self.b
def mul(self):
return self.a * self.b
def div(self):
return self.a / self.b
obj = Calculator(10, 5)
print("Addition:", [Link]())
print("Subtraction:", [Link]())
print("Multiplication:", [Link]())
print("Division:", [Link]())
42. Employee database system
employees = {}
n = int(input("Enter number of employees: "))
for i in range(n):
name = input("Enter employee name: ")
age = int(input("Enter age: "))
employees[name] = age
while True:
choice = input("Enter employee name to search or Q to quit: ")
if [Link]() == 'Q':
break
21
if choice in employees:
print("Age:", employees[choice])
else:
print("Employee not found")
def display_all():
print("Employee Details")
for k, v in [Link]():
print(k, v)
def names_by_age():
for k, v in [Link]():
print(v, "-", k)
display_all()
names_by_age()
End of Question Bank Answers
22