Python Question Bank Complete 100 Question
Python Question Bank Complete 100 Question
Python Question Bank Complete 100 Question
2 Marks
7) List any two types of functions in Python and give a brief description of each?
• Built-in :- Predefined, e.g., `print()`.
• User-defined :- Created by user, e.g., `def my_func()`.
10) Explain the concept of local and global variables with an example?
• Local is inside functions, global is outside.
11) What is the difference between append () and extend () methods in Python lists?
• append() :- Adds single item.
• extend() :- Adds multiple items.
12) How do you create a function in Python? Write a simple example of a function that
adds two
numbers.
• def add(a, b):
return a + b
4 Marks
5. Write an anonymous function to find the area of a rectangle given its length and width.
• area = lambda length, width: length * width
print(area(5, 3)) # Output: 15
6. Explain the use of control statements (break, continue, pass) with examples.
• break : Exits the loop.
for i in range(5):
if i == 3:
break
print(i)
• continue : Skips to the next iteration.
for i in range(5):
if i == 3:
continue
print(i)
• pass : Placeholder that does nothing.
for i in range(5):
if i == 3:
pass
7. How do you access and manipulate elements in a list? Provide examples of common
list operations.
• Access :- my_list[index].
• Modify :- my_list[index] = new_value.
• Append :- my_list.append(value).
• Remove :- my_list.remove(value).
• Example :-
my_list = [1, 2, 3]
my_list.append(4) # [1, 2, 3, 4]
my_list[0] = 10 # [10, 2, 3, 4]
8. What are the properties of dictionaries in Python? How do you access and modify their
values?
• Mutable, unordered, key-value pairs.
• Access/Modify
my_dict = {"name": "Alice"}
print(my_dict["name"]) # Access
my_dict["name"] = "Bob" # Modify
10. What are the differences between global and local variables in Python? Provide
examples
• Local : Defined inside a function; can’t be accessed outside.
• Global : Defined outside functions; accessible anywhere.
x = 10 # Global
def func():
x = 5 # Local
print(x) # Output: 5
func()
print(x) # Output: 10
12. What is the significance of the if-else statement? Provide an example demonstrating
its use.
• The `if-else` statement allows conditional execution of code.
• Example :-
num = 10
if num > 5:
print("Greater than 5")
else:
print("5 or less")
13. Describe the different types of functions in Python and give examples for each.
• Built-in : Predefined functions (e.g., `len()`, `print()`).
• User-defined : Functions created with `def` (e.g., `def my_func(): pass`).
• Lambda : Anonymous, single-expression functions (e.g., `lambda x: x + 1`).
14. How do you create and use a tuple in Python? Illustrate with examples.
Tuples are immutable, defined with `()` and can hold multiple items.
my_tuple = (1, 2, 3)
print(my_tuple[1]) # Output: 2
15. How do you create and use lists and tuples in Python? Provide examples
• List : Mutable, created with `[]`.
my_list = [1, 2, 3]
my_list.append(4) # [1, 2, 3, 4]
• Tuple : Immutable, created with `()`.
my_tuple = (1, 2, 3)
# Access element
print(my_tuple[1])
4 Marks
1. Write a Python program to accept a string and remove the characters which have odd
index values of the given string using a user-defined function.
def remove_odd_index(s):
return ''.join([s[i] for i in range(len(s)) if i % 2 == 0])
print(remove_odd_index("example"))
# Output: "eape”
5. Write a Python program that accepts a list of numbers and returns a new list
containing only the even numbers.
def filter_even(numbers):
return [num for num in numbers if num % 2 == 0]
6. Write a Python program to demonstrate the use of 'break' and 'continue' statement in a
loop.
for i in range(5):
if i == 3:
break
print(i) # Output: 0 1 2
for i in range(5):
if i == 3:
continue
print(i) # Output: 0 1 2 4
7. Write a Python function that takes two lists and returns a dictionary with elements
from the first list as keys and elements from the second list as values.
def lists_to_dict(keys, values):
return dict(zip(keys, values))
print(lists_to_dict(['a', 'b'], [1, 2]))
# Output: {'a': 1, 'b': 2}
9. Write a Python program to find the largest and smallest numbers in a list.
def min_max(numbers):
return min(numbers), max(numbers)
print(min_max([1, 2, 3, 4])) # (1, 4)
11. Write a Python function to calculate the factorial of a number using recursion.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
14. Write a Python program that accepts a list of integers and returns the sum of all the
odd numbers in that list.
def sum_odd(numbers):
return sum(num for num in numbers if num % 2 != 0)
15. Write a Python program that use while loop to print the numbers from 1 to 10.
i=1
while i <= 10:
print(i)
i += 1
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
17. Write a Python program to add two numbers using an anonymous function. The
program should take two numbers as input and print their sum.
add = lambda a, b: a + b
print(add(3, 5)) # Output: 8
18. Write a Python program to filter out even numbers from a list using an anonymous
function. The program should return a new list containing only the odd numbers.
numbers = [1, 2, 3, 4, 5, 6]
odd_numbers = list(filter(lambda x: x % 2 != 0, numbers))
print(odd_numbers) # Output: [1, 3, 5]
4 Marks
def greet(name):
return f"Hello, {name}!"
class MyClass:
class_variable = 0 # This is a class variable
obj1 = MyClass(1)
obj2 = MyClass(2)
print(MyClass.class_variable) # Output: 0
2. How to create class and object in python?
• Define a class using the `class` keyword.
• Create an object by calling the class as if it were a function.
class Dog:
def __init__(self, name):
self.name = name
def method_name(self):
# Method body
1. Class Method
• A method bound to the class, not instances, defined with `@classmethod` and takes `cls` as
the first parameter.
• Example:
class Dog:
species = "Canis familiaris"
@classmethod
def get_species(cls):
return cls.species
print(Dog.get_species()) # Output: Canis familiaris
2. Benefits of inheritance
• Code Reusability : Reuses code from the parent class.
• Extensibility : Child classes can extend or override parent class behavior.
• Maintainability : Changes in the parent class reflect in child classes.
• Hierarchical Classification : Represents relationships between classes.
• Example:
class Animal:
def speak(self):
return "Animal sound"
class Dog(Animal):
def speak(self):
return "Bark"
dog = Dog()
print(dog.speak()) # Output: Bark
3. Polymorphism
• Allows different classes to use the same method name, with each class providing its own
implementation.
• This enables flexible and dynamic behavior.
• Example:
class Animal:
def speak(self):
return "Animal sound"
class Dog(Animal):
def speak(self):
return "Bark"
class Cat(Animal):
def speak(self):
return "Meow"
def make_animal_speak(animal):
print(animal.speak())
dog = Dog()
cat = Cat()
make_animal_speak(dog) # Output: Bark
make_animal_speak(cat) # Output: Meow
4 Marks
class Car:
def __init__(self):
self.engine = Engine()
class Child(Parent):
# Child class can add or override methods and properties
• Example:
class Animal:
def speak(self):
return "Animal sound"
class Dog(Animal):
def speak(self):
return "Bark"
calc = Calculator()
print(calc.add(5)) # Output: 5
print(calc.add(5, 3)) # Output: 8
4. How does python static method works?
• A static method is a method bound to the class rather than its instances.
• It is defined using the `@staticmethod` decorator and doesn't take `self` or `cls` as the first
argument.
• Example:
class Math:
@staticmethod
def add(a, b):
return a + b
class Printer:
def print(self, text=None):
if text is not None:
print(text)
else:
print("No text to print")
printer = Printer()
printer.print("Hello") # Output: Hello
printer.print() # Output: No text to print
class Dog(Animal):
def speak(self):
return super().speak() + " and Bark"
dog = Dog()
print(dog.speak()) # Output: Animal sound and Bark
4 Marks (Programs)
1. Write the python script using class to reverse the string word by word.
class StringReversal:
def __init__(self, string):
self.string = string
def reverse(self):
return ' '.join(self.string.split()[::-1])
# Usage:
print(StringReversal("Hello World").reverse()) # Output: World Hello
2. Write a program of python to create a class circle and calculate area and
circumference of circle
(Use parameterized constructor).
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def circumference(self):
return 2 * math.pi * self.radius
# Usage:
circle = Circle(5)
print(circle.area(), circle.circumference())
```
3. Write a python program to create class which perform basic calculator operations.
class Calculator:
def add(self, a, b): return a + b
def subtract(self, a, b): return a - b
def multiply(self, a, b): return a * b
def divide(self, a, b): return a / b if b != 0 else "Error"
# Usage:
calc = Calculator()
print(calc.add(10, 5), calc.subtract(10, 5), calc.multiply(10, 5), calc.divide(10, 5))
Unit 4: Exception Handling
2 Marks
try:
# code
except ExceptionType as e:
# handle exception
4. Justify more than one except statement can a try-except block have.
• You can have multiple `except` blocks to handle different types of exceptions separately:
try:
# code
except TypeError:
# handle TypeError
except ValueError:
# handle ValueError
4 Marks
1. Try-Except statement
• The `try-except` statement handles exceptions in Python.
• The code inside the `try` block is executed, and if an exception occurs, the `except` block
handles it.
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!")
2. Raise statement.
• The `raise` statement is used to explicitly raise an exception, either new or re-raising an
existing one.
3. Custom Exception
• A custom exception is created by defining a new class that inherits from the built-in `Exception`
class.
class MyCustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
4 Marks
• Button Widget : A `Button` widget is used to create clickable buttons in the GUI.
• It can trigger actions when clicked.
• Example:
from tkinter import *
def on_click():
print("Button clicked!")
root = Tk()
button = Button(root, text="Click Me", command=on_click)
button.pack()
root.mainloop()
• Entry Widget : An `Entry` widget is used for text input in a single-line field. It allows users to
enter data.
• Example:
from tkinter import *
def show_entry():
print(entry.get())
root = Tk()
entry = Entry(root)
entry.pack()
button = Button(root, text="Submit", command=show_entry)
button.pack()
root.mainloop()
root = Tk()
button = Button(root, text="Click Me", command=on_button_click)
button.pack()
root.mainloop()
root = Tk()
entry = Entry(root)
entry.pack()
button = Button(root, text="Submit", command=show_input)
button.pack()
root.mainloop()
root.mainloop()
b) `entry.insert()`
• The `insert()` method is used to insert text at a specific position in the `Entry` widget.
• Syntax:
entry.insert(index, text)
• Example:
from tkinter import *
root = Tk()
entry = Entry(root)
entry.pack()
entry.insert(0, "Hello World!")
root.mainloop()
Marks (Programs)
1. Write Python GUI program to create back ground with changing colors.
import tkinter as tk
import random
def change_color():
root.config(bg=random.choice(['red', 'green', 'blue', 'yellow', 'purple']))
root.after(1000, change_color)
root = tk.Tk()
root.geometry("400x400")
change_color()
root.mainloop()
2. Write Python GUI program to accept a decimal number and convert and display it to
binary, octal and hexadecimal.
import tkinter as tk
def convert():
num = int(entry.get())
result = f"Binary: {bin(num)[2:]}\nOctal: {oct(num)[2:]}\nHex: {hex(num)[2:].upper()}"
result_label.config(text=result)
root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
tk.Button(root, text="Convert", command=convert).pack()
result_label = tk.Label(root, text="")
result_label.pack()
root.mainloop()
3. Write Python GUI program to accept dimension of a cylinder and display the surface
area and the volume of cylinder.
import tkinter as tk
import math
def calculate():
r = float(radius_entry.get())
h = float(height_entry.get())
area = 2 * math.pi * r * (r + h)
volume = math.pi * r**2 * h
result_label.config(text=f"Area: {area:.2f}\nVolume: {volume:.2f}")
root = tk.Tk()
radius_entry = tk.Entry(root)
radius_entry.pack()
height_entry = tk.Entry(root)
height_entry.pack()
tk.Button(root, text="Calculate", command=calculate).pack()
result_label = tk.Label(root, text="")
result_label.pack()
root.mainloop()
4 Marks