Python Questions Bank
Python Questions Bank
Functions
1. Which keyword is used to define a function in Python?
a) func
b) def
c) function
d) define
Answer: b) def
2. What is the default return value of a function that does not explicitly return anything?
a) 0
b) None
c) Null
d) False
Answer: b) None
3. Which of the following arguments must be passed in the correct order?
a) Required arguments
b) Keyword arguments
c) Default arguments
d) Variable length arguments
Answer: a) Required arguments
4. Which type of argument allows passing different numbers of values to a function?
a) Required argument
b) Default argument
c) Variable length argument
d) Keyword argument
Answer: c) Variable length argument
5. What is recursion in Python?
a) Function calling another function
b) Function calling itself
c) Multiple functions calling each other
d) None of the above
Answer: b) Function calling itself
Strings
6. Strings in Python are:
a) Mutable
b) Immutable
c) Partially mutable
d) Dynamic
Answer: b) Immutable
7. Which operator is used for string concatenation in Python?
a) *
b) +
c) &
d) %
Answer: b) +
8. Which function returns the length of a string?
a) size()
b) count()
c) len()
d) length()
Answer: c) len()
9. What will "hello".upper() return?
a) Hello
b) HELLO
c) hello
d) error
Answer: b) HELLO
10. Which operator is used for string comparison in Python?
a) ==
b) =
c) :=
d) ===
Answer: a) ==
Modules
11. Which statement is used to include a module in Python?
a) include
b) using
c) import
d) require
Answer: c) import
12. Which function lists all attributes of a module?
a) list()
b) dir()
c) help()
d) show()
Answer: b) dir()
13. In Python, a module is:
a) A built-in class
b) A file containing Python code
c) A package manager
d) A memory block
Answer: b) A file containing Python code
14. Which keyword defines a separate namespace for variables and functions?
a) import
b) module
c) namespace
d) class
Answer: a) import
15. What file extension is used for Python modules?
a) .txt
b) .mod
c) .py
d) .pym
Answer: c) .py
Answer:
A function in Python is a block of reusable code that performs a specific task.
Syntax:
def function_name(parameters):
# block of code
return value
Example:
def greet(name):
return "Hello, " + name
print(greet("Ganesh"))
Answer:
Function Definition: Declares the function using def keyword, specifies its name,
parameters, and body.
Function Call: Executes the function by using its name followed by parentheses ().
Example:
def add(a, b): # Function definition
return a + b
Answer:
Scope: Refers to the region of the program where a variable can be accessed.
o Local scope → inside a function.
o Global scope → outside all functions.
Lifetime: Duration for which the variable exists in memory. Local variables exist
only during the function execution.
Example:
x = 10 # Global variable
def demo():
y = 5 # Local variable
print(y)
demo()
print(x)
Q4. What is the role of the return statement? Can a function return multiple values?
Answer:
The return statement is used to send a value back from a function to the caller.
Yes, a function can return multiple values as a tuple.
Example:
result = calc(10, 5)
print(result) # (15, 5)
Q5. Distinguish between required arguments and default arguments with examples.
Answer:
Required arguments: Must be passed in the correct order when calling a function.
def greet(name):
print("Hello", name)
def greet(name="Guest"):
print("Hello", name)
Answer:
Example:
intro(age=20, name="Meena")
Answer:
Example:
Answer:
Recursion: A function calling itself to solve a problem in smaller parts.
Use: Solving mathematical problems like factorial, Fibonacci, Tower of Hanoi, etc.
Example (factorial):
def fact(n):
if n==0:
return 1
return n * fact(n-1)
print(fact(5)) # 120
Answer:
Strings are immutable, meaning their content cannot be changed after creation.
Any modification creates a new string object.
Example:
s = "Hello"
s[0] = "h" # ❌ Error (not allowed)
s = "h" + s[1:] # ✅ New string created
Answer:
Example:
Q11. How does Python perform string comparison? Explain with examples.
Answer:
Answer:
A module is a file containing Python code (functions, classes, variables) that can be
reused.
Python provides built-in modules (e.g., math, os).
Example:
import math
print(math.sqrt(16)) # 4.0
Answer:
The import statement is used to include and use functions/variables from a module.
Syntax: import module_name
Example:
import random
print(random.randint(1, 10))
Q14. What does the dir() function do? Illustrate with an example.
Answer:
dir() returns a list of all attributes, methods, and variables available in an object or
module.
Example:
import math
print(dir(math))
Answer:
Namespace: A collection of names (variables/functions) mapped to objects.
Types: Local, Global, Built-in.
Example:
x = 10 # Global
def func():
y = 5 # Local
print(y)
func()
print(x)
Answer:
Python functions can take four types of arguments:
Example Program:
# 1. Required Arguments
def add(a, b):
return a + b
print("Required:", add(10, 5))
# 2. Keyword Arguments
def intro(name, age):
print(name, "is", age, "years old")
intro(age=20, name="Ravi")
# 3. Default Arguments
def greet(name="Guest"):
print("Hello", name)
greet()
greet("Ganesh")
Answer:
Recursion is a process where a function calls itself until a base condition is met.
Useful for problems that can be broken into smaller sub-problems (divide-and-
conquer).
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
Output:
011235
Q3. Write a function to find the factorial of a number using both iteration and
recursion. Compare both approaches.
Answer:
Factorial (n!) = n × (n-1) × ... × 1
Iterative Approach:
def fact_iter(n):
result = 1
for i in range(1, n+1):
result *= i
return result
print("Iterative:", fact_iter(5))
Recursive Approach:
def fact_rec(n):
if n == 0:
return 1
return n * fact_rec(n-1)
print("Recursive:", fact_rec(5))
Comparison:
Answer:
Common string operations:
1. Concatenation (+)
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2) # Hello World
2. Repetition (*)
print("Hi " * 3) # Hi Hi Hi
3. Indexing
s = "Python"
print(s[0], s[-1]) # P n
4. Slicing
print(s[0:4]) # Pyth
print(s[::2]) # Pto
print("Py" in s) # True
Q5. Write a Python program that accepts a string and performs various operations.
Answer:
Program:
for ch in text:
if ch in vowels:
v += 1
elif ch.isalpha():
c += 1
elif ch.isdigit():
d += 1
elif ch.isspace():
sp += 1
print("Vowels:", v)
print("Consonants:", c)
print("Digits:", d)
print("Spaces:", sp)
# Convert to upper/lowercase
print("Upper:", text.upper())
print("Lower:", text.lower())
Q6. Discuss immutable nature of strings in Python with examples. Why is immutability
important?
Answer:
Strings in Python are immutable, meaning they cannot be modified after creation.
Any change creates a new object in memory.
Example:
s = "Hello"
print(id(s))
s = s + " World" # New object created
print(id(s)) # Different ID
Importance:
Q7. Explain how to create a Python module, import it, and use its functions.
Answer:
# mymath.py
def add(a, b):
return a + b
def sub(a, b):
return a - b
import mymath
print(mymath.add(10, 5))
print(mymath.sub(10, 5))
Output:
15
5
Answer:
Example:
x = 50 # Global variable
def func():
x = 10 # Local variable
print("Local:", x)
func()
print("Global:", x)
Output:
Local: 10
Global: 50
Q9. Compare and contrast built-in modules and user-defined modules in Python.
Answer:
Example:
import math
print(math.sqrt(16)) # Built-in
# User-defined
import mymath
print(mymath.add(5, 3))
Example:
import math
print(dir(math))
UNIT 4
5 Marks Questions
Lists
Tuples
Dictionaries
🔹 10 Marks Questions
Lists
1. Explain list creation, accessing, updating, and basic operations with suitable
examples.
2. Write short notes on nested lists and list methods with examples.
Tuples
3. Explain tuples with creation, accessing, updating, and deleting elements with
examples.
4. Explain nested tuples and give differences between lists and tuples with examples.
Dictionaries
lst = [1,2,3,4]
print(lst[-1])
a) 1
b) 3
c) 4
d) Error
Answer: c) 4
Tuples
3. Tuples are:
a) Mutable
b) Immutable
c) Dynamic
d) Static but mutable
Answer: b) Immutable
4. Which of the following creates a tuple?
a) t = (1,)
b) t = (1)
c) t = [1]
d) t = {1}
Answer: a) t = (1,)
Dictionaries
d = {"a":1, "b":2}
print(d["b"])
a) a
b) 1
c) 2
d) Error
Answer: c) 2
Answer:
A list is created by placing elements inside square brackets [], separated by commas.
Answer:
Answer:
Lists are mutable, so elements can be updated directly using indices.
nums = [1, 2, 3]
nums[1] = 20
print(nums) # [1, 20, 3]
Answer:
A list inside another list is called a nested list.
Answer:
nums = [3, 1, 2]
nums.append(4) # [3,1,2,4]
nums.sort() # [1,2,3,4]
Answer:
A tuple is created using parentheses (). Access with indexing.
t = (10, 20, 30)
print(t[1]) # 20
Answer:
t = (1, 2, 3)
# t[0] = 10 ❌ Error
t = (10,) + t[1:] # ✅ New tuple
print(t) # (10, 2, 3)
Answer:
A tuple inside another tuple is a nested tuple.
Answer:
Answer:
A dictionary stores key–value pairs inside {}.
Answer:
Answer:
d = {"a":1,"b":2}
print(d.keys())
d.update({"c":3})
print(d)
Answer:
Q1. Explain list creation, accessing, updating, and basic operations with examples.
Answer:
Creating a list:
Accessing values:
print(fruits[0]) # apple
Updating values:
fruits[1] = "mango"
Basic operations:
print(len(fruits)) # Length
print(fruits + ["grape"]) # Concatenation
print(fruits * 2) # Repetition
print("apple" in fruits) # Membership
Q2. Write short notes on nested lists and list methods with examples.
Answer:
matrix = [[1,2],[3,4],[5,6]]
print(matrix[2][1]) # 6
List Methods:
nums = [5,3,8]
nums.append(10) # Add element
nums.remove(3) # Remove element
nums.sort() # Sort
nums.pop() # Remove last
nums.insert(1,20) # Insert
print(nums)
Q3. Explain tuples with creation, accessing, updating, and deleting examples.
Answer:
Creating:
Accessing:
print(t[1]) # 20
t = (100,) + t[1:]
del t
Q4. Explain nested tuples and difference between lists and tuples with examples.
Answer:
Nested tuple:
Difference:
| Feature | List | Tuple |
|------------|-------------|-------------|
| Mutability | Mutable | Immutable |
| Syntax | [] | () |
| Speed | Slower | Faster |
| Use | General use | Fixed data |
Q5. Explain dictionaries: creating, accessing, updating, and deleting elements with
examples.
Answer:
Creating:
student = {"name":"Ravi","age":20}
Accessing:
print(student["name"])
Updating:
student["age"] = 21
Deleting:
del student["name"]
Answer:
d = {"a":1, "b":2}
print(d.keys()) # dict_keys(['a','b'])
print(d.values()) # dict_values([1,2])
print(d.items()) # dict_items([('a',1),('b',2)])
Answer:
Example:
# List
marks = [85, 90, 78]
print(marks[1])
# Dictionary
student = {"name":"Ravi", "marks":90}
print(student["marks"])