0% found this document useful (0 votes)
1 views23 pages

Python Questions Bank

This document contains a comprehensive overview of Python programming concepts, focusing on functions, strings, and modules. It includes 5-mark and 10-mark questions with answers, covering topics such as function definitions, variable scope, recursion, string operations, and module usage. Additionally, it features multiple-choice questions to test knowledge on these subjects.

Uploaded by

ssascw.bca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views23 pages

Python Questions Bank

This document contains a comprehensive overview of Python programming concepts, focusing on functions, strings, and modules. It includes 5-mark and 10-mark questions with answers, covering topics such as function definitions, variable scope, recursion, string operations, and module usage. Additionally, it features multiple-choice questions to test knowledge on these subjects.

Uploaded by

ssascw.bca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT -3

5-Mark Questions (Short / Medium Answers)

1. Define a function in Python with syntax and example.


2. Differentiate between function definition and function call.
3. Explain variable scope and its lifetime with an example.
4. What is the role of the return statement? Can a function return multiple values?
5. Distinguish between required arguments and default arguments with examples.
6. What are keyword arguments? Write a small code example.
7. Explain variable-length arguments (*args, **kwargs) with example.
8. Define recursion and mention one practical use of recursion.
9. What do you mean by immutable strings in Python? Give example.
10. List any five built-in string methods with syntax.
11. How does Python perform string comparison? Explain with examples.
12. What is a module in Python? Give an example.
13. Explain the use of the import statement in Python.
14. What does the dir() function do? Illustrate with an example.
15. Define namespace in Python with a suitable example.

10-Mark Questions (Long / Descriptive + Coding)

1. Write a Python program to demonstrate different types of function arguments:


o Required arguments
o Keyword arguments
o Default arguments
o Variable-length arguments
2. Explain recursion with an example. Write a recursive function to generate Fibonacci
series up to n terms.
3. Write a function to find the factorial of a number using both iteration and recursion.
Compare both approaches.
4. Explain string operations in Python with examples (concatenation, repetition, slicing,
indexing).
5. Write a Python program that accepts a string and:
o Counts vowels, consonants, digits, and spaces
o Converts the string to uppercase and lowercase
6. Discuss immutable nature of strings in Python with examples. Why is immutability
important?
7. Explain how to create a Python module, import it, and use its functions in another
program. Show with code.
8. Discuss the concept of namespaces in Python with a suitable example program.
9. Compare and contrast built-in modules and user-defined modules in Python. Give
examples.
10. Write short notes on:
a) Function scope and lifetime of variables
b) return statement and multiple returns
c) dir() function usage

MCQs – Python (Functions, Strings, and Modules)

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

Q1. Define a function in Python with syntax and example.

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"))

Q2. Differentiate between function definition and function call.

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

print(add(3, 5)) # Function call

Q3. Explain variable scope and its lifetime with an example.

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:

def calc(a, b):


return a+b, a-b

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)

greet("Ravi") # Required argument

 Default arguments: Have predefined values. If not passed, default is used.

def greet(name="Guest"):
print("Hello", name)

greet() # Hello Guest

Q6. What are keyword arguments? Write a small code example.

Answer:

 Keyword arguments are passed by explicitly mentioning parameter names during a


function call.
 Order doesn’t matter.

Example:

def intro(name, age):


print(name, "is", age, "years old")

intro(age=20, name="Meena")

Q7. Explain variable-length arguments (*args, **kwargs) with example.

Answer:

 *args: Allows passing variable number of positional arguments (tuple).


 **kwargs: Allows passing variable number of keyword arguments (dictionary).

Example:

def demo(*args, **kwargs):


print(args) # Tuple
print(kwargs) # Dictionary

demo(1, 2, 3, name="Ravi", age=20)

Q8. Define recursion and mention one practical use of recursion.

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

Q9. What do you mean by immutable strings in Python? Give example.

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

Q10. List any five built-in string methods with syntax.

Answer:

1. upper() → Converts string to uppercase


2. lower() → Converts string to lowercase
3. strip() → Removes leading/trailing spaces
4. replace(old, new) → Replaces substring
5. split(delimiter) → Splits string into list

Example:

s = " Hello World "


print(s.upper(), s.lower(), s.strip(), s.replace("World","Python"), s.split())

Q11. How does Python perform string comparison? Explain with examples.

Answer:

 String comparison uses lexicographic (dictionary) order based on Unicode values.


 Operators: ==, !=, <, >, <=, >=.
Example:

print("apple" == "apple") # True


print("apple" < "banana") # True
print("Zebra" > "apple") # False (Z < a in Unicode)

Q12. What is a module in Python? Give an example.

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

Q13. Explain the use of the import statement in Python.

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))

Q15. Define namespace in Python with a suitable example.

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)

Python – 10 Mark Questions with Answers

Q1. Write a Python program to demonstrate different types of function arguments.

Answer:
Python functions can take four types of arguments:

1. Required Arguments → Must be passed in correct order.


2. Keyword Arguments → Passed with parameter name.
3. Default Arguments → Have predefined values.
4. Variable-Length Arguments → Accept multiple values.

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")

# 4. Variable Length Arguments


def demo(*args, **kwargs):
print("Args:", args)
print("Kwargs:", kwargs)
demo(1, 2, 3, name="Meena", age=21)

Q2. Explain recursion with an example. Write a recursive function to generate


Fibonacci series.

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).

Fibonacci Example (Recursive):

def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)

# Print first 6 terms


for i in range(6):
print(fibonacci(i), end=" ")

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:

 Iterative → Faster, memory-efficient.


 Recursive → Easier to understand for mathematical problems but uses more memory
(stack calls).

Q4. Explain string operations in Python with examples.

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

5. Membership (in, not in)

print("Py" in s) # True

Q5. Write a Python program that accepts a string and performs various operations.

Answer:
Program:

text = "Hello World 123"

# Count vowels, consonants, digits, spaces


vowels = "aeiouAEIOU"
v = c = d = sp = 0

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:

1. Ensures security and consistency.


2. Allows safe use of strings in multiple places.
3. Enables internal optimizations like string interning.

Q7. Explain how to create a Python module, import it, and use its functions.

Answer:

 A module is a .py file containing functions, variables, and classes.


 Helps in code reuse and organization.

Step 1: Create mymath.py

# mymath.py
def add(a, b):
return a + b
def sub(a, b):
return a - b

Step 2: Import in another file

import mymath

print(mymath.add(10, 5))
print(mymath.sub(10, 5))

Output:

15
5

Q8. Discuss the concept of namespaces in Python with example.

Answer:

 Namespace: Mapping of variable/function names to objects.


 Types:
1. Local Namespace – Inside a function.
2. Global Namespace – Variables defined in the main program.
3. Built-in Namespace – Predefined names (print, len, etc.).

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:

Feature Built-in Module (e.g., math) User-Defined Module

Availability Pre-installed with Python Created by user

Example Usage import math import mymodule

Functions Provided Standard library functions Custom functions

Purpose General-purpose use Project-specific

Example:

import math
print(math.sqrt(16)) # Built-in

# User-defined
import mymath
print(mymath.add(5, 3))

Q10. Write short notes on:

(a) Function scope and lifetime of variables

 Scope: Defines where a variable can be accessed (local vs global).


 Lifetime: Local variable exists only during function execution.

(b) return statement and multiple returns

 return sends values from function to caller.


 Multiple values are returned as a tuple.

Example:

def calc(a, b):


return a+b, a*b
print(calc(3, 4)) # (7, 12)

(c) dir() function usage

 Returns list of attributes/methods of an object/module.

import math
print(dir(math))
UNIT 4

5 Marks Questions
Lists

1. How do you create a list in Python? Give an example.


2. How can you access values in a list?
3. Explain with an example how to update elements in a list.
4. What are nested lists? Give an example.
5. List any five list methods.

Tuples

6. How do you create and access a tuple?


7. Can tuples be updated? Justify your answer.
8. What are nested tuples? Give an example.
9. Give any two differences between lists and tuples.

Dictionaries

10. How do you create a dictionary in Python?


11. How can you update and delete elements from a dictionary?
12. Write any four dictionary methods.
13. Give any two differences between lists and 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

5. Explain dictionaries: creating, accessing, updating, and deleting elements with


examples.
6. Write short notes on dictionary methods with examples.
7. Discuss the differences between lists and dictionaries with examples.

MCQs with Answers


Lists

1. Which of the following creates a list?


a) {1,2,3}
b) (1,2,3)
c) [1,2,3]
d) <1,2,3>
Answer: c) [1,2,3]
2. What will be the output?

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

5. Which of the following is correct for a dictionary?


a) Indexed by integers
b) Indexed by keys
c) Immutable
d) Cannot be updated
Answer: b) Indexed by keys
6. What is the output?

d = {"a":1, "b":2}
print(d["b"])

a) a
b) 1
c) 2
d) Error
Answer: c) 2

5 Mark Questions with Answers

Q1. How do you create a list in Python? Give an example.

Answer:
A list is created by placing elements inside square brackets [], separated by commas.

fruits = ["apple", "banana", "cherry"]


print(fruits)
Q2. How can you access values in a list?

Answer:

 Using indexing (positive or negative).


 Using slicing for a range of elements.

numbers = [10, 20, 30, 40]


print(numbers[0]) # 10
print(numbers[-1]) # 40
print(numbers[1:3]) # [20, 30]

Q3. How can you update values in a list?

Answer:
Lists are mutable, so elements can be updated directly using indices.

nums = [1, 2, 3]
nums[1] = 20
print(nums) # [1, 20, 3]

Q4. What are nested lists? Give an example.

Answer:
A list inside another list is called a nested list.

matrix = [[1, 2], [3, 4], [5, 6]]


print(matrix[1][0]) # 3

Q5. List any five list methods with examples.

Answer:

1. append() – Add element


2. insert() – Insert at position
3. remove() – Remove element
4. pop() – Remove by index
5. sort() – Sort elements

nums = [3, 1, 2]
nums.append(4) # [3,1,2,4]
nums.sort() # [1,2,3,4]

Q6. How do you create and access a tuple?

Answer:
A tuple is created using parentheses (). Access with indexing.
t = (10, 20, 30)
print(t[1]) # 20

Q7. Can tuples be updated? Explain.

Answer:

 No, tuples are immutable.


 But a new tuple can be created.

t = (1, 2, 3)
# t[0] = 10 ❌ Error
t = (10,) + t[1:] # ✅ New tuple
print(t) # (10, 2, 3)

Q8. What are nested tuples? Give an example.

Answer:
A tuple inside another tuple is a nested tuple.

t = (1, (2, 3), (4, 5))


print(t[1][0]) # 2

Q9. Give two differences between lists and tuples.

Answer:

1. Mutability: Lists are mutable, tuples are immutable.


2. Syntax: Lists use [], tuples use ().

Q10. How do you create a dictionary in Python?

Answer:
A dictionary stores key–value pairs inside {}.

student = {"name": "Ravi", "age": 20}


print(student["name"]) # Ravi

Q11. How can you update and delete dictionary elements?

Answer:

d = {"name": "Ravi", "age": 20}


d["age"] = 21 # Update
del d["name"] # Delete
print(d) # {'age': 21}
Q12. Write any four dictionary methods with examples.

Answer:

1. keys() – Returns keys


2. values() – Returns values
3. items() – Returns key–value pairs
4. update() – Updates dictionary

d = {"a":1,"b":2}
print(d.keys())
d.update({"c":3})
print(d)

Q13. Give two differences between lists and dictionaries.

Answer:

1. Indexing: Lists are indexed by numbers, dictionaries are indexed by keys.


2. Ordering: Lists maintain order, dictionaries store key–value pairs (since Python 3.7
dictionaries preserve insertion order).

10 Mark Questions with Answers

Q1. Explain list creation, accessing, updating, and basic operations with examples.

Answer:

 Creating a list:

fruits = ["apple", "banana", "cherry"]

 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:

 Nested Lists: A list inside another list.

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:

t = (10, 20, 30)

 Accessing:

print(t[1]) # 20

 Updating: Not possible (immutable), but new tuple can be made.

t = (100,) + t[1:]

 Deleting: Entire tuple can be deleted using del.

del t

Q4. Explain nested tuples and difference between lists and tuples with examples.

Answer:
 Nested tuple:

t = (1, (2, 3), (4, 5))


print(t[1][1]) # 3

 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"]

Q6. Write short notes on dictionary methods with examples.

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)])

d.update({"c":3}) # Add new key


print(d.get("a")) # 1
d.pop("b") # Remove key
print(d)
Q7. Discuss the differences between lists and dictionaries with examples.

Answer:

Feature List Example Dictionary Example

Syntax [10,20,30] {"a":10,"b":20}

Access By index → list[0] By key → dict["a"]

Order Maintains order Key–value pairs (insertion order)

Mutability Mutable Mutable

Use case Sequence of items Key–value mapping

Example:

# List
marks = [85, 90, 78]
print(marks[1])

# Dictionary
student = {"name":"Ravi", "marks":90}
print(student["marks"])

You might also like