What You'll Practice
- Python Fundamentals — basics, syntax, data types, I/O
- Core Concepts — operators, loops, conditional statements
- Data Structures — lists, tuples, sets, dictionaries, strings
- Advanced Topics — OOPs, threads, regular expressions, MySQL
- Interview Preparation — 400+ questions with detailed answers
- Self Assessment — check your knowledge and track progress
1. Introduction to Python — 20 MCQs
1. Who developed the Python programming language?
Answer: B) Guido van Rossum
Guido van Rossum created Python in 1991. He designed it to be simple, readable, and beginner-friendly.
Guido van Rossum created Python in 1991. He designed it to be simple, readable, and beginner-friendly.
2. Python is a ________ programming language.
Answer: B) Interpreted
Python is an interpreted language, meaning the source code is executed line-by-line by the Python interpreter.
Python is an interpreted language, meaning the source code is executed line-by-line by the Python interpreter.
3. Which of the following is NOT a Python data type?
Answer: D) char
Python does not have a char data type. Single characters are treated as strings of length 1.
Python does not have a char data type. Single characters are treated as strings of length 1.
4. What is the extension of Python files?
Answer: A) .py
Python source files use the .py extension. Compiled files use .pyc.
Python source files use the .py extension. Compiled files use .pyc.
5. Which of the following is used to create a comment in Python?
Answer: C) #
The # symbol is used for single-line comments. Python doesn't support multi-line comments directly.
The # symbol is used for single-line comments. Python doesn't support multi-line comments directly.
6. Python supports which type of programming?
Answer: D) All of the above
Python is a multi-paradigm language supporting procedural, object-oriented, and functional programming.
Python is a multi-paradigm language supporting procedural, object-oriented, and functional programming.
7. What is the correct way to print "Hello World" in Python?
Answer: B) print("Hello World")
print() is the built-in function used to display output in Python.
print() is the built-in function used to display output in Python.
8. What is the output of: print(type(10))?
Answer: A) <class 'int'>
type() returns the data type of the object. 10 is an integer.
type() returns the data type of the object. 10 is an integer.
9. Which of the following is a valid variable name in Python?
Answer: C) _var2
Variable names can start with a letter or underscore, contain letters, digits, and underscores.
Variable names can start with a letter or underscore, contain letters, digits, and underscores.
10. What is the output of: bool(0)?
Answer: B) False
0 is considered False in Python. All other numbers are True.
0 is considered False in Python. All other numbers are True.
11. Which of the following is NOT a keyword in Python?
Answer: C) function
"function" is not a keyword. "def" is used to define functions.
"function" is not a keyword. "def" is used to define functions.
12. What is the output of: print(10 / 3)?
Answer: C) 3.333...
In Python 3, / always returns a float.
In Python 3, / always returns a float.
13. Which of the following is used for multi-line strings?
Answer: A) """ """
Triple quotes are used for multi-line strings and docstrings.
Triple quotes are used for multi-line strings and docstrings.
14. What is the output of: print(2 ** 3)?
Answer: B) 8
** is the exponentiation operator (2 to the power of 3).
** is the exponentiation operator (2 to the power of 3).
15. Which of the following is true about Python?
Answer: C) Both A and B
Python is case-sensitive and uses indentation to define code blocks.
Python is case-sensitive and uses indentation to define code blocks.
16. Which of the following is a Python interpreter?
Answer: D) All of the above
CPython, PyPy, and Jython are all Python interpreters.
CPython, PyPy, and Jython are all Python interpreters.
17. What is the output of: len("Python")?
Answer: B) 6
len() returns the length of the string. "Python" has 6 characters.
len() returns the length of the string. "Python" has 6 characters.
18. Which of the following is NOT a Python built-in function?
Answer: D) compile()
compile() is also a built-in function. Actually all are built-in functions in Python.
compile() is also a built-in function. Actually all are built-in functions in Python.
19. What is the output of: print(10 // 3)?
Answer: B) 3
// is floor division, which returns the integer part of the division.
// is floor division, which returns the integer part of the division.
20. Which of the following is used to check Python version?
Answer: C) Both A and B
Both --version and -v flags show the Python version.
Both --version and -v flags show the Python version.
2. Python Operators — 20 MCQs
1. What is the result of 10 // 3 in Python?
Answer: B) 3
Floor division (//) returns the integer part of the division.
Floor division (//) returns the integer part of the division.
2. Which operator is used for exponentiation in Python?
Answer: B) **
** is the exponentiation operator in Python.
** is the exponentiation operator in Python.
3. What is the result of 5 % 2?
Answer: A) 1
% is the modulo operator, giving the remainder of the division.
% is the modulo operator, giving the remainder of the division.
4. Which operator is used for logical AND in Python?
Answer: B) and
Python uses "and", "or", "not" for logical operations.
Python uses "and", "or", "not" for logical operations.
5. What is the output of 2 ** 3 ** 2?
Answer: A) 512
Exponentiation is right-associative: 3**2=9, then 2**9=512.
Exponentiation is right-associative: 3**2=9, then 2**9=512.
6. Which operator checks if two values are NOT equal?
Answer: A) !=
!= is the not-equal operator in Python.
!= is the not-equal operator in Python.
7. What is the output of: 10 + 3 * 2?
Answer: B) 16
Multiplication has higher precedence than addition: 3*2=6, then 10+6=16.
Multiplication has higher precedence than addition: 3*2=6, then 10+6=16.
8. Which operator is used for identity comparison?
Answer: B) is
"is" checks if two objects are the same object in memory.
"is" checks if two objects are the same object in memory.
9. What is the output of: 5 | 3 (bitwise OR)?
Answer: A) 7
5 (101) | 3 (011) = 111 (7).
5 (101) | 3 (011) = 111 (7).
10. Which operator is used for membership testing?
Answer: A) in
"in" checks if an element exists in a sequence.
"in" checks if an element exists in a sequence.
11. What is the output of: 15 >> 2 (right shift)?
Answer: A) 3
15 >> 2 = 15 // 2**2 = 15 // 4 = 3.
15 >> 2 = 15 // 2**2 = 15 // 4 = 3.
12. What is the output of: not (5 > 3)?
Answer: B) False
5 > 3 is True, so not True is False.
5 > 3 is True, so not True is False.
13. What is the output of: 10 % 3?
Answer: B) 1
10 divided by 3 gives remainder 1.
10 divided by 3 gives remainder 1.
14. Which operator is used for string concatenation?
Answer: A) +
The + operator concatenates strings.
The + operator concatenates strings.
15. What is the output of: 5 & 3 (bitwise AND)?
Answer: A) 1
5 (101) & 3 (011) = 001 (1).
5 (101) & 3 (011) = 001 (1).
16. What does the // operator do?
Answer: B) Floor division
// returns the integer part of division.
// returns the integer part of division.
17. What is the output of: 2 << 3 (left shift)?
Answer: B) 16
2 << 3 = 2 * 2**3 = 2 * 8 = 16.
2 << 3 = 2 * 2**3 = 2 * 8 = 16.
18. Which operator has the highest precedence?
Answer: C) ()
Parentheses have the highest precedence.
Parentheses have the highest precedence.
19. What is the output of: 5 ^ 2 (bitwise XOR)?
Answer: A) 7
5 (101) ^ 2 (010) = 111 (7).
5 (101) ^ 2 (010) = 111 (7).
20. What is the output of: ~5 (bitwise NOT)?
Answer: A) -6
~x = -x - 1. ~5 = -6.
~x = -x - 1. ~5 = -6.
3. Python Input/Output — 15 MCQs
1. Which function is used to take input from the user in Python?
Answer: A) input()
input() reads a line from the user and returns it as a string.
input() reads a line from the user and returns it as a string.
2. What is the default data type of input() function in Python 3?
Answer: C) string
input() always returns a string in Python 3.
input() always returns a string in Python 3.
3. Which function is used to display output in Python?
Answer: C) print()
print() is the built-in function for displaying output.
print() is the built-in function for displaying output.
4. Which of the following is NOT a valid way to format strings?
Answer: D) sprintf()
Python does not have sprintf(). It uses f-strings, .format(), and % formatting.
Python does not have sprintf(). It uses f-strings, .format(), and % formatting.
5. What is the output of: print("Hello", end=" "); print("World")?
Answer: B) Hello World
end=" " replaces the default newline with a space.
end=" " replaces the default newline with a space.
6. Which function reads a file in Python?
Answer: A) read()
read() reads file content. open() opens the file.
read() reads file content. open() opens the file.
7. What is the output of: print("Python" * 3)?
Answer: A) PythonPythonPython
The * operator repeats strings.
The * operator repeats strings.
8. Which method is used to write to a file?
Answer: A) write()
write() is used to write data to a file.
write() is used to write data to a file.
9. What is the output of: print(1, 2, 3, sep="-")?
Answer: A) 1-2-3
sep defines the separator between values.
sep defines the separator between values.
10. Which of the following is a valid way to take integer input?
Answer: A) int(input())
int(input()) converts the string input to integer.
int(input()) converts the string input to integer.
11. What is the output of: print(f"{10:02d}")?
Answer: A) 10
02d formats with at least 2 digits.
02d formats with at least 2 digits.
12. Which of the following is NOT a valid print parameter?
Answer: C) format
format is not a print parameter. print() has sep, end, and file.
format is not a print parameter. print() has sep, end, and file.
13. What is the output of: print("A", "B", sep="", end="")?
Answer: B) AB
sep="" removes spaces, end="" removes newline.
sep="" removes spaces, end="" removes newline.
14. Which method reads one line from a file?
Answer: B) readline()
readline() reads a single line from a file.
readline() reads a single line from a file.
15. What is the output of: print("{:.2f}".format(3.14159))?
Answer: A) 3.14
{:.2f} formats to 2 decimal places.
{:.2f} formats to 2 decimal places.
4. Python Conditional Statements — 20 MCQs
1. Which keyword is used for decision making in Python?
Answer: A) if
if is the primary conditional statement in Python.
if is the primary conditional statement in Python.
2. What is the correct syntax for if-else in Python?
Answer: C) if x > 5: else: ...
Correct syntax uses colons and proper indentation.
Correct syntax uses colons and proper indentation.
3. Which statement is used for multiple conditional checks?
Answer: A) elif
elif (else if) checks multiple conditions.
elif (else if) checks multiple conditions.
4. What is the output of: print("A") if 5 > 3 else print("B")?
Answer: A) A
5 > 3 is True, so "A" is printed.
5 > 3 is True, so "A" is printed.
5. What is the output of: if 0: print("True") else: print("False")?
Answer: B) False
0 is False, so the else block executes.
0 is False, so the else block executes.
6. Which of the following is NOT a valid logical operator?
Answer: D) &&
Python uses 'and', 'or', 'not' instead of symbols.
Python uses 'and', 'or', 'not' instead of symbols.
7. What is the output of: if (5 > 3 and 2 < 4): print("Yes")?
Answer: A) Yes
Both conditions are True, so "Yes" is printed.
Both conditions are True, so "Yes" is printed.
8. What is the output of: x = 10; if x: print("True") else: print("False")?
Answer: A) True
Non-zero numbers are True in Python.
Non-zero numbers are True in Python.
9. Which statement is used to handle multiple conditions?
Answer: A) if-elif-else
Python uses if-elif-else for multiple conditions.
Python uses if-elif-else for multiple conditions.
10. What is the output of: print(3 > 2 > 1)?
Answer: A) True
Python supports chained comparisons: 3>2 is True AND 2>1 is True.
Python supports chained comparisons: 3>2 is True AND 2>1 is True.
11. What is the output of: if []: print("A") else: print("B")?
Answer: B) B
Empty lists are False in Python.
Empty lists are False in Python.
12. Which of the following checks if a number is positive?
Answer: A) if num > 0
num > 0 checks for positive numbers.
num > 0 checks for positive numbers.
13. What is the output of: if (5 > 3) or (2 > 4): print("Yes") else: print("No")?
Answer: A) Yes
At least one condition is True (5>3).
At least one condition is True (5>3).
14. What is the output of: x = 5; if x > 3: print("A") elif x > 4: print("B") else: print("C")?
Answer: A) A
The first true condition executes, even if others would also be true.
The first true condition executes, even if others would also be true.
15. What is the output of: if not False: print("A")?
Answer: A) A
not False evaluates to True.
not False evaluates to True.
16. Which of the following is a ternary operator in Python?
Answer: A) if-else
Python uses if-else as the ternary operator: x if condition else y.
Python uses if-else as the ternary operator: x if condition else y.
17. What is the output of: (5 > 3) and print("A")?
Answer: A) A
and evaluates both expressions. print() returns None.
and evaluates both expressions. print() returns None.
18. What is the output of: if "": print("A") else: print("B")?
Answer: B) B
Empty strings are False in Python.
Empty strings are False in Python.
19. What is the output of: if 5: print("A") else: print("B")?
Answer: A) A
Non-zero numbers are True.
Non-zero numbers are True.
20. Which condition checks if x is between 5 and 10?
Answer: C) Both A and B
Both forms are valid in Python.
Both forms are valid in Python.
5. Python Loops — 25 MCQs
1. Which loop in Python repeats a block of code while a condition is true?
Answer: B) while
while loop continues as long as the condition is true.
while loop continues as long as the condition is true.
2. Which loop is used to iterate over a sequence in Python?
Answer: B) for
for loop iterates over sequences like lists, tuples, strings.
for loop iterates over sequences like lists, tuples, strings.
3. Which statement is used to exit a loop prematurely?
Answer: C) break
break immediately exits the loop.
break immediately exits the loop.
4. What is the output of: for i in range(3): print(i, end=" ")?
Answer: A) 0 1 2
range(3) generates 0, 1, 2.
range(3) generates 0, 1, 2.
5. Which statement skips the rest of the loop iteration?
Answer: B) continue
continue skips the rest and goes to the next iteration.
continue skips the rest and goes to the next iteration.
6. What is the output of: for i in range(2, 5): print(i, end=" ")?
Answer: A) 2 3 4
range(2,5) generates 2, 3, 4 (5 is exclusive).
range(2,5) generates 2, 3, 4 (5 is exclusive).
7. What is the output of: for i in range(1, 10, 2): print(i, end=" ")?
Answer: A) 1 3 5 7 9
range(start, stop, step) with step=2 gives odd numbers.
range(start, stop, step) with step=2 gives odd numbers.
8. Which loop does Python NOT support?
Answer: C) do-while
Python doesn't have a do-while loop, but while loop can simulate it.
Python doesn't have a do-while loop, but while loop can simulate it.
9. What is the output of: i = 0; while i < 3: print(i, end=" "); i += 1?
Answer: A) 0 1 2
while loop executes until i < 3 is false.
while loop executes until i < 3 is false.
10. Which statement is used to do nothing in Python?
Answer: C) pass
pass is a null operation that does nothing.
pass is a null operation that does nothing.
11. What is the output of: for i in [1, 2, 3]: print(i, end=" ")?
Answer: A) 1 2 3
for loop iterates over list elements.
for loop iterates over list elements.
12. What is the output of: for i in range(3): pass; print(i)?
Answer: A) 0 1 2
pass doesn't affect the loop; print(i) executes each iteration.
pass doesn't affect the loop; print(i) executes each iteration.
13. Which loop uses an iterator?
Answer: B) for
for loop automatically uses iterators.
for loop automatically uses iterators.
14. What is the output of: for i in "ABC": print(i, end="")?
Answer: A) ABC
for loop iterates over string characters.
for loop iterates over string characters.
15. What is the output of: while True: print("A"); break?
Answer: A) A
break exits the infinite loop after one iteration.
break exits the infinite loop after one iteration.
16. Which loop is more efficient for iterating over a sequence?
Answer: B) for
for loop is generally more efficient and Pythonic.
for loop is generally more efficient and Pythonic.
17. What is the output of: for i in range(3): if i == 2: break; print(i)?
Answer: A) 0 1
break exits when i is 2.
break exits when i is 2.
18. What is the output of: for i in range(3): if i == 1: continue; print(i)?
Answer: A) 0 2
continue skips printing 1.
continue skips printing 1.
19. Which of the following is true about while loops?
Answer: B) They can create infinite loops
while True: creates an infinite loop.
while True: creates an infinite loop.
20. What is the output of: for i in range(3): print(i, end="") else: print("Done")?
Answer: A) 012Done
The else clause executes after the loop completes normally.
The else clause executes after the loop completes normally.
21. What is the output of: for i in range(3): if i == 1: break; else: print("Done")?
Answer: A) 0
break prevents else from executing.
break prevents else from executing.
22. Which method is used to iterate with both index and value?
Answer: A) enumerate()
enumerate() returns index and value pairs.
enumerate() returns index and value pairs.
23. What is the output of: list(enumerate(['a','b','c']))?
Answer: A) [(0,'a'),(1,'b'),(2,'c')]
enumerate returns tuples of (index, value).
enumerate returns tuples of (index, value).
24. Which of the following creates an infinite loop?
Answer: D) Both A and C
while True: and while 1: both create infinite loops.
while True: and while 1: both create infinite loops.
25. What is the output of: for i in range(3, 0, -1): print(i, end=" ")?
Answer: A) 3 2 1
Negative step counts downward.
Negative step counts downward.
6. Python Lists — 20 MCQs
1. How do you create a list in Python?
Answer: A) []
Square brackets are used to create lists.
Square brackets are used to create lists.
2. What is the index of the first element in a list?
Answer: A) 0
Python uses zero-based indexing.
Python uses zero-based indexing.
3. Which method adds an element to the end of a list?
Answer: B) append()
append() adds a single element to the end of a list.
append() adds a single element to the end of a list.
4. What is the output of: [1,2,3] + [4,5]?
Answer: A) [1,2,3,4,5]
The + operator concatenates lists.
The + operator concatenates lists.
5. Which method removes the last element from a list?
Answer: A) pop()
pop() removes and returns the last element.
pop() removes and returns the last element.
6. What is the output of: [1,2,3] * 2?
Answer: A) [1,2,3,1,2,3]
* repeats the list.
* repeats the list.
7. How do you access the last element of a list?
Answer: A) list[-1]
Negative index -1 accesses the last element.
Negative index -1 accesses the last element.
8. Which method sorts a list?
Answer: C) Both A and B
sort() sorts in-place, sorted() returns a new sorted list.
sort() sorts in-place, sorted() returns a new sorted list.
9. What is the output of: len([1,2,3,4])?
Answer: B) 4
len() returns the number of elements.
len() returns the number of elements.
10. Which method removes a specific element from a list?
Answer: A) remove()
remove() removes the first occurrence of a value.
remove() removes the first occurrence of a value.
11. What is the output of: [1,2,3].index(2)?
Answer: B) 1
index() returns the first index of the value.
index() returns the first index of the value.
12. What is the output of: [1,2,3,2,4].count(2)?
Answer: B) 2
count() returns the number of occurrences.
count() returns the number of occurrences.
13. Which method reverses a list?
Answer: C) Both A and B
reverse() reverses in-place, reversed() returns an iterator.
reverse() reverses in-place, reversed() returns an iterator.
14. What is the output of: [1,2][0:1]?
Answer: A) [1]
Slicing [0:1] gets element at index 0.
Slicing [0:1] gets element at index 0.
15. Which method inserts an element at a specific position?
Answer: A) insert()
insert(index, value) adds an element at the specified position.
insert(index, value) adds an element at the specified position.
16. What is the output of: [1,2,3].pop(1)?
Answer: B) 2
pop(1) removes and returns the element at index 1.
pop(1) removes and returns the element at index 1.
17. Which method removes all elements from a list?
Answer: A) clear()
clear() removes all elements from the list.
clear() removes all elements from the list.
18. What is the output of: [1,2,3] + [4,5] * 2?
Answer: A) [1,2,3,4,5,4,5]
Multiplication happens before addition.
Multiplication happens before addition.
19. Which method extends a list with another list?
Answer: A) extend()
extend() adds all elements from another iterable.
extend() adds all elements from another iterable.
20. What is the output of: [1,2,3][-2]?
Answer: B) 2
Negative index -2 accesses the second last element.
Negative index -2 accesses the second last element.
7. Python Tuples — 15 MCQs
1. How do you create a tuple in Python?
Answer: B) ()
Parentheses are used to create tuples.
Parentheses are used to create tuples.
2. Which of the following is true about tuples?
Answer: B) Tuples are immutable
Tuples cannot be modified after creation.
Tuples cannot be modified after creation.
3. What is the output of: len((1,2,3,4))?
Answer: B) 4
len() returns the number of elements in a tuple.
len() returns the number of elements in a tuple.
4. How do you create a tuple with a single element?
Answer: A) (1,)
A trailing comma is needed for a single-element tuple.
A trailing comma is needed for a single-element tuple.
5. Can you append to a tuple?
Answer: B) No
Tuples are immutable, so they don't have append.
Tuples are immutable, so they don't have append.
6. What is the output of: (1,2,3) + (4,5)?
Answer: A) (1,2,3,4,5)
+ concatenates tuples.
+ concatenates tuples.
7. What is the output of: (1,2,3) * 2?
Answer: A) (1,2,3,1,2,3)
* repeats the tuple.
* repeats the tuple.
8. Which method is available for tuples?
Answer: C) Both A and B
Tuples have count() and index() methods.
Tuples have count() and index() methods.
9. What is the output of: (1,2,3).count(2)?
Answer: B) 1
count() returns the number of occurrences.
count() returns the number of occurrences.
10. Can a tuple contain mutable elements?
Answer: A) Yes
Tuples can contain lists, which are mutable.
Tuples can contain lists, which are mutable.
11. What is the output of: (1,2,3)[1]?
Answer: B) 2
Index 1 accesses the second element.
Index 1 accesses the second element.
12. What is tuple unpacking?
Answer: A) Assigning tuple elements to variables
a, b = (1, 2) unpacks tuple into variables.
a, b = (1, 2) unpacks tuple into variables.
13. What is the output of: (1,2,3) == [1,2,3]?
Answer: B) False
Tuples and lists are different types.
Tuples and lists are different types.
14. Which of the following converts a list to a tuple?
Answer: A) tuple(list)
tuple() constructor converts a list to a tuple.
tuple() constructor converts a list to a tuple.
15. What is the output of: type((1,2,3))?
Answer: B) <class 'tuple'>
type() returns the correct data type.
type() returns the correct data type.
8. Python Sets — 15 MCQs
1. How do you create a set in Python?
Answer: D) set() or C) {}
Sets are created using {} or set() (empty set uses set()).
Sets are created using {} or set() (empty set uses set()).
2. Which of the following is true about sets?
Answer: C) Sets are unordered and unique
Sets contain only unique elements and are unordered.
Sets contain only unique elements and are unordered.
3. What is the output of: len({1,2,3,3,4})?
Answer: B) 4
Duplicate 3 is removed, so set has {1,2,3,4}.
Duplicate 3 is removed, so set has {1,2,3,4}.
4. Which method adds an element to a set?
Answer: A) add()
add() adds a single element to a set.
add() adds a single element to a set.
5. Which method removes an element from a set?
Answer: D) All of the above
remove(), discard(), and pop() all remove elements.
remove(), discard(), and pop() all remove elements.
6. What is the output of: {1,2,3} & {2,3,4} (intersection)?
Answer: B) {2,3}
& operator performs set intersection.
& operator performs set intersection.
7. What is the output of: {1,2,3} | {3,4,5} (union)?
Answer: B) {1,2,3,4,5}
| operator performs set union.
| operator performs set union.
8. What is the output of: {1,2,3} - {2,3} (difference)?
Answer: A) {1}
- operator removes elements present in the second set.
- operator removes elements present in the second set.
9. Which method removes all elements from a set?
Answer: A) clear()
clear() removes all elements from the set.
clear() removes all elements from the set.
10. Can a set contain a list?
Answer: B) No
Sets can only contain hashable (immutable) elements.
Sets can only contain hashable (immutable) elements.
11. What is the output of: set([1,2,2,3,3,3])?
Answer: A) {1,2,3}
set() removes duplicates from the list.
set() removes duplicates from the list.
12. What is the output of: {1,2,3} == {3,2,1}?
Answer: A) True
Sets are equal regardless of order.
Sets are equal regardless of order.
13. Which method returns a copy of a set?
Answer: A) copy()
copy() returns a shallow copy of the set.
copy() returns a shallow copy of the set.
14. What is the output of: {1,2,3}.issubset({1,2,3,4})?
Answer: A) True
issubset() checks if set is a subset.
issubset() checks if set is a subset.
15. What is the output of: type({})?
Answer: B) <class 'dict'>
{} creates a dictionary, not a set.
{} creates a dictionary, not a set.
9. Python Dictionaries — 20 MCQs
1. How do you create a dictionary in Python?
Answer: C) {} with key-value pairs
Dictionaries use key:value pairs inside {}.
Dictionaries use key:value pairs inside {}.
2. How do you access a value in a dictionary?
Answer: B) dict[key]
Dictionary values are accessed using keys.
Dictionary values are accessed using keys.
3. Which method removes all items from a dictionary?
Answer: B) clear()
clear() removes all key-value pairs.
clear() removes all key-value pairs.
4. What is the output of: len({'a':1, 'b':2, 'c':3})?
Answer: A) 3
len() returns the number of key-value pairs.
len() returns the number of key-value pairs.
5. Which method returns all keys of a dictionary?
Answer: A) keys()
keys() returns all keys as a view object.
keys() returns all keys as a view object.
6. What is the output of: {'a':1, 'b':2}.get('a', 0)?
Answer: B) 1
get() returns the value for key 'a'.
get() returns the value for key 'a'.
7. Which method removes a specific key from a dictionary?
Answer: A) pop()
pop(key) removes and returns the value for key.
pop(key) removes and returns the value for key.
8. Can dictionary keys be any data type?
Answer: B) No, must be immutable
Dictionary keys must be hashable/immutable.
Dictionary keys must be hashable/immutable.
9. What is the output of: {'a':1, 'b':2}.items()?
Answer: A) dict_items([('a',1), ('b',2)])
items() returns key-value pairs as tuples.
items() returns key-value pairs as tuples.
10. Which method updates a dictionary with another dictionary?
Answer: A) update()
update() merges another dictionary or iterable.
update() merges another dictionary or iterable.
11. What is the output of: {'a':1, 'b':2} == {'b':2, 'a':1}?
Answer: A) True
Dictionaries are equal if they have the same key-value pairs.
Dictionaries are equal if they have the same key-value pairs.
12. Which method creates a dictionary from keys and values?
Answer: A) dict.fromkeys()
fromkeys() creates a dictionary from a sequence of keys.
fromkeys() creates a dictionary from a sequence of keys.
13. What is the output of: list({'a':1, 'b':2}.keys())?
Answer: A) ['a', 'b']
keys() returns a view, list() converts it.
keys() returns a view, list() converts it.
14. Can a dictionary have duplicate keys?
Answer: B) No
Dictionary keys must be unique.
Dictionary keys must be unique.
15. Which method returns the value for a key or a default if key doesn't exist?
Answer: D) Both A and C
Both get() and setdefault() can return a default value.
Both get() and setdefault() can return a default value.
16. What is the output of: {'a':1, 'b':2}.pop('a', 0)?
Answer: A) 1
pop('a') removes and returns the value for key 'a'.
pop('a') removes and returns the value for key 'a'.
17. Which method returns all values of a dictionary?
Answer: A) values()
values() returns all values as a view object.
values() returns all values as a view object.
18. What is the output of: dict(a=1, b=2)?
Answer: A) {'a':1, 'b':2}
dict() can be called with keyword arguments.
dict() can be called with keyword arguments.
19. Which of the following is a valid dictionary key?
Answer: B) tuple
Tuples are hashable and can be dictionary keys.
Tuples are hashable and can be dictionary keys.
20. What is the output of: {'a':1, 'b':2}.get('c', 'Not Found')?
Answer: C) Not Found
get() returns the default when key doesn't exist.
get() returns the default when key doesn't exist.
10. Python Strings — 20 MCQs
1. Which method converts a string to uppercase?
Answer: A) upper()
upper() converts all characters to uppercase.
upper() converts all characters to uppercase.
2. What is the output of: "Hello".replace("e", "a")?
Answer: B) Hallo
replace() replaces all occurrences.
replace() replaces all occurrences.
3. Which method splits a string into a list?
Answer: A) split()
split() divides a string into a list of substrings.
split() divides a string into a list of substrings.
4. What is the output of: "Python".find("t")?
Answer: C) 2
find() returns the index of the first occurrence.
find() returns the index of the first occurrence.
5. Which method removes whitespace from the beginning and end?
Answer: A) strip()
strip() removes leading and trailing whitespace.
strip() removes leading and trailing whitespace.
6. What is the output of: "Python"[::-1]?
Answer: B) nohtyP
[::-1] reverses the string.
[::-1] reverses the string.
7. Which method joins list elements into a string?
Answer: A) join()
join() concatenates list elements with a separator.
join() concatenates list elements with a separator.
8. What is the output of: "Python".lower()?
Answer: B) python
lower() converts all characters to lowercase.
lower() converts all characters to lowercase.
9. Which method capitalizes the first letter of a string?
Answer: A) capitalize()
capitalize() capitalizes only the first character.
capitalize() capitalizes only the first character.
10. What is the output of: "Hello World".startswith("Hello")?
Answer: A) True
startswith() checks if the string starts with the prefix.
startswith() checks if the string starts with the prefix.
11. What is the output of: "Python".index("o")?
Answer: C) 4
"Python": P-0, y-1, t-2, h-3, o-4, n-5.
"Python": P-0, y-1, t-2, h-3, o-4, n-5.
12. Which method counts occurrences of a substring?
Answer: A) count()
count() returns the number of non-overlapping occurrences.
count() returns the number of non-overlapping occurrences.
13. What is the output of: " Python ".strip()?
Answer: B) "Python"
strip() removes leading and trailing spaces.
strip() removes leading and trailing spaces.
14. Which method checks if all characters are digits?
Answer: D) All of the above
isdigit(), isnumeric(), and isdecimal() all check for digits.
isdigit(), isnumeric(), and isdecimal() all check for digits.
15. What is the output of: "Hello" + "World"?
Answer: A) HelloWorld
+ concatenates strings without spaces.
+ concatenates strings without spaces.
16. Which method checks if all characters are letters?
Answer: A) isalpha()
isalpha() returns True if all characters are letters.
isalpha() returns True if all characters are letters.
17. What is the output of: "Python".endswith("on")?
Answer: A) True
endswith() checks if the string ends with the suffix.
endswith() checks if the string ends with the suffix.
18. Which method creates a string from a list with a separator?
Answer: A) join()
join() joins list elements with a string separator.
join() joins list elements with a string separator.
19. What is the output of: "Python".isupper()?
Answer: B) False
isupper() checks if all characters are uppercase.
isupper() checks if all characters are uppercase.
20. What is the output of: "Python".swapcase()?
Answer: A) pYTHON
swapcase() swaps uppercase to lowercase and vice versa.
swapcase() swaps uppercase to lowercase and vice versa.
11. Python Functions — 25 MCQs
1. Which keyword is used to define a function in Python?
Answer: B) def
def is the keyword for function definition.
def is the keyword for function definition.
2. What is a function that calls itself called?
Answer: B) Recursive function
Recursive functions call themselves.
Recursive functions call themselves.
3. What is a lambda function in Python?
Answer: B) An anonymous function
Lambda functions are anonymous, one-line functions.
Lambda functions are anonymous, one-line functions.
4. Which keyword returns a value from a function?
Answer: A) return
return sends a value back to the caller.
return sends a value back to the caller.
5. What is the output of: def func(): return 5; print(func())?
Answer: A) 5
func() returns 5, which is printed.
func() returns 5, which is printed.
6. Which of the following is a built-in function?
Answer: D) All of the above
print(), len(), type() are all built-in functions.
print(), len(), type() are all built-in functions.
7. What is the output of: def func(x=5): return x; func(10)?
Answer: B) 10
Default parameter is overridden by the argument.
Default parameter is overridden by the argument.
8. Which of the following is true about function parameters?
Answer: D) All of the above
All statements are true about function parameters.
All statements are true about function parameters.
9. What is the output of: lambda x: x * 2 (3)?
Answer: B) 6
Lambda function multiplies x by 2.
Lambda function multiplies x by 2.
10. Which keyword defines a generator function?
Answer: A) yield
yield makes a function a generator.
yield makes a function a generator.
11. What is the output of: def func(): pass; print(func())?
Answer: A) None
Functions without return statement return None.
Functions without return statement return None.
12. Which of the following is a decorator syntax?
Answer: A) @decorator
@ symbol is used for decorators.
@ symbol is used for decorators.
13. What is the output of: def func(a, b): return a + b; func(1,2,3)?
Answer: C) Error
Too many arguments are passed.
Too many arguments are passed.
14. Which of the following collects variable number of arguments?
Answer: C) Both A and B
*args collects positional, **kwargs collects keyword arguments.
*args collects positional, **kwargs collects keyword arguments.
15. What is the output of: def func(*args): return sum(args); func(1,2,3)?
Answer: B) 6
*args collects 1,2,3 and sum returns 6.
*args collects 1,2,3 and sum returns 6.
16. Which keyword is used to import modules?
Answer: A) import
import is used to include modules.
import is used to include modules.
17. What is the output of: def func(x): return x > 5; func(3)?
Answer: B) False
3 > 5 is False.
3 > 5 is False.
18. Which of the following creates a function with default argument?
Answer: A) def func(x=5): return x
Default arguments are assigned using = in parameter list.
Default arguments are assigned using = in parameter list.
19. What is the output of: def func(): global x; x = 10; x = 5; func(); print(x)?
Answer: B) 10
func() changes x to 10 using global.
func() changes x to 10 using global.
20. Which function returns the length of an object?
Answer: A) len()
len() is the built-in function for length.
len() is the built-in function for length.
21. What is the output of: def func(): yield 1; yield 2; list(func())?
Answer: A) [1, 2]
Generator yields values that are collected into a list.
Generator yields values that are collected into a list.
22. Which of the following is NOT a built-in function?
Answer: C) average()
average() is not a built-in function.
average() is not a built-in function.
23. What is the output of: map(lambda x: x*2, [1,2,3])?
Answer: B) <map object>
map() returns an iterator, not a list.
map() returns an iterator, not a list.
24. Which of the following filters a list?
Answer: A) filter()
filter() filters elements based on a condition.
filter() filters elements based on a condition.
25. What is the output of: sorted([3,1,2])?
Answer: A) [1,2,3]
sorted() returns a new sorted list.
sorted() returns a new sorted list.
12. Python Modules — 15 MCQs
1. Which statement is used to import a module in Python?
Answer: B) import
import is used to bring in modules.
import is used to bring in modules.
2. Which of the following is a built-in module in Python?
Answer: D) All of the above
sys, os, and math are all built-in modules.
sys, os, and math are all built-in modules.
3. What is the output of: import math; math.sqrt(16)?
Answer: A) 4.0
math.sqrt() returns the square root as a float.
math.sqrt() returns the square root as a float.
4. Which keyword is used to import specific functions from a module?
Answer: C) from ... import
from module import function imports specific items.
from module import function imports specific items.
5. What is the output of: import random; random.randint(1,10)?
Answer: C) Random number between 1 and 10
randint() returns a random integer inclusive of both endpoints.
randint() returns a random integer inclusive of both endpoints.
6. Which module provides time-related functions?
Answer: B) time
time module provides time-related functions.
time module provides time-related functions.
7. Which module provides operating system functionality?
Answer: D) All of the above
os, sys, and platform all provide OS-related functions.
os, sys, and platform all provide OS-related functions.
8. What is the output of: import sys; sys.version?
Answer: B) Python version string
sys.version returns the Python version.
sys.version returns the Python version.
9. Which of the following is a way to install Python packages?
Answer: C) Both A and B
pip and conda are both package managers.
pip and conda are both package managers.
10. What is the output of: import datetime; datetime.datetime.now()?
Answer: A) Current date and time
datetime.now() returns the current date and time.
datetime.now() returns the current date and time.
11. Which module is used for working with JSON?
Answer: A) json
json module handles JSON data.
json module handles JSON data.
12. What is the output of: import math; math.pi?
Answer: B) 3.141592653589793
math.pi contains the value of π.
math.pi contains the value of π.
13. Which statement imports all functions from a module?
Answer: B) from module import *
This imports all names from the module.
This imports all names from the module.
14. Which module is used for regular expressions?
Answer: A) re
re module handles regular expressions.
re module handles regular expressions.
15. What is the output of: import os; os.getcwd()?
Answer: A) Current working directory
os.getcwd() returns the current working directory.
os.getcwd() returns the current working directory.
13. Python File Handling — 20 MCQs
1. Which function is used to open a file in Python?
Answer: A) open()
open() is used to open files.
open() is used to open files.
2. Which mode is used to read a file in Python?
Answer: B) 'r'
'r' is the read mode.
'r' is the read mode.
3. Which method is used to read all lines of a file?
Answer: C) readlines()
readlines() returns all lines as a list.
readlines() returns all lines as a list.
4. Which mode is used to write to a file (overwrites)?
Answer: C) 'w'
'w' creates a new file or overwrites existing.
'w' creates a new file or overwrites existing.
5. Which mode is used to append to a file?
Answer: C) 'a'
'a' appends to the end of the file.
'a' appends to the end of the file.
6. Which method writes a string to a file?
Answer: A) write()
write() writes a string to the file.
write() writes a string to the file.
7. What is the output of: with open('file.txt', 'r') as f: ...?
Answer: B) File is automatically closed
with statement automatically closes the file.
with statement automatically closes the file.
8. Which mode creates a file exclusively (fails if exists)?
Answer: C) 'x'
'x' creates a new file and raises error if exists.
'x' creates a new file and raises error if exists.
9. Which method closes a file?
Answer: A) close()
close() closes the file.
close() closes the file.
10. Which module is used for working with CSV files?
Answer: A) csv
csv module handles CSV file operations.
csv module handles CSV file operations.
11. What is the output of: file.read()?
Answer: A) Entire file content
read() reads the entire file.
read() reads the entire file.
12. Which mode opens a file for both reading and writing?
Answer: D) All of the above
All these modes allow both read and write.
All these modes allow both read and write.
13. Which method checks if a file exists?
Answer: C) Both A and B
Both check for file existence.
Both check for file existence.
14. Which method is used to rename a file?
Answer: A) os.rename()
os.rename() renames files.
os.rename() renames files.
15. What is the output of: os.remove('file.txt')?
Answer: A) Deletes the file
os.remove() deletes the file.
os.remove() deletes the file.
16. Which mode is used for binary files?
Answer: A) 'b'
'b' is used with other modes for binary files (e.g., 'rb').
'b' is used with other modes for binary files (e.g., 'rb').
17. Which module is used for file/directory path operations?
Answer: C) Both A and B
Both os.path and pathlib handle paths.
Both os.path and pathlib handle paths.
18. What is the output of: file.tell()?
Answer: A) Current file position
tell() returns the current file pointer position.
tell() returns the current file pointer position.
19. Which method moves the file pointer?
Answer: A) seek()
seek() moves the file pointer to a specific position.
seek() moves the file pointer to a specific position.
20. Which module is used for serialization?
Answer: C) Both A and B
pickle and json both handle serialization.
pickle and json both handle serialization.
14. Python Exception Handling — 20 MCQs
1. Which block is used to handle exceptions in Python?
Answer: A) try-except
Python uses try-except for exception handling.
Python uses try-except for exception handling.
2. Which block is always executed regardless of exception?
Answer: B) finally
finally block executes regardless of exception.
finally block executes regardless of exception.
3. Which keyword is used to raise an exception?
Answer: B) raise
raise is used to throw exceptions.
raise is used to throw exceptions.
4. What is the output of: try: 1/0 except ZeroDivisionError: print("Error")?
Answer: A) Error
ZeroDivisionError is caught and "Error" is printed.
ZeroDivisionError is caught and "Error" is printed.
5. Which of the following is a built-in exception?
Answer: D) All of the above
All are built-in exceptions in Python.
All are built-in exceptions in Python.
6. Which block handles multiple exceptions?
Answer: A) except (Exception1, Exception2):
Multiple exceptions can be handled in one except block.
Multiple exceptions can be handled in one except block.
7. What is the output of: try: raise ValueError finally: print("Done")?
Answer: C) Done and Error
finally executes first, then the exception is raised.
finally executes first, then the exception is raised.
8. Which exception is raised when a file is not found?
Answer: C) Both A and B
FileNotFoundError and IOError both handle file errors.
FileNotFoundError and IOError both handle file errors.
9. Which exception is raised for invalid operations?
Answer: D) All of the above
All are exceptions for invalid operations.
All are exceptions for invalid operations.
10. What is the output of: try: print(1/0) except: print("Error") else: print("No Error")?
Answer: A) Error
Exception occurs, so except block executes.
Exception occurs, so except block executes.
11. Which block is executed when no exception occurs?
Answer: B) else
else executes only if no exception occurs.
else executes only if no exception occurs.
12. What is the output of: try: print(10/2) except ZeroDivisionError: print("Error")?
Answer: A) 5.0
No exception occurs, so 5.0 is printed.
No exception occurs, so 5.0 is printed.
13. Which exception is raised when a list index is out of range?
Answer: A) IndexError
IndexError is raised for invalid list indices.
IndexError is raised for invalid list indices.
14. Which exception is raised for dictionary key errors?
Answer: A) KeyError
KeyError is raised for missing dictionary keys.
KeyError is raised for missing dictionary keys.
15. What is the output of: try: 10/2 except Exception: print("Error") else: print("Ok")?
Answer: B) Ok
No exception, else block executes.
No exception, else block executes.
16. Which of the following is a valid exception handling structure?
Answer: D) All of the above
All combinations are valid in Python.
All combinations are valid in Python.
17. Which exception is raised when a variable is not defined?
Answer: A) NameError
NameError is raised for undefined variables.
NameError is raised for undefined variables.
18. What is the output of: try: print("A") finally: print("B")?
Answer: A) A B
try executes first, then finally.
try executes first, then finally.
19. Which exception is raised for invalid type operations?
Answer: A) TypeError
TypeError is raised for type mismatches.
TypeError is raised for type mismatches.
20. How do you create a custom exception?
Answer: A) class MyError(Exception):
Custom exceptions are created by subclassing Exception.
Custom exceptions are created by subclassing Exception.
15. Python OOPs — 30 MCQs
1. What is the basic unit of Object-Oriented Programming?
Answer: B) Class
Classes are the fundamental building blocks of OOP.
Classes are the fundamental building blocks of OOP.
2. Which concept hides the internal details of an object?
Answer: D) Abstraction
Abstraction hides implementation details.
Abstraction hides implementation details.
3. Which keyword is used to create a class in Python?
Answer: A) class
class is the keyword for class definition.
class is the keyword for class definition.
4. What is the constructor method in Python?
Answer: A) __init__
__init__ is the constructor method.
__init__ is the constructor method.
5. What is inheritance in Python?
Answer: A) Creating a new class from an existing class
Inheritance allows a class to inherit from another class.
Inheritance allows a class to inherit from another class.
6. Which of the following is NOT a pillar of OOP?
Answer: C) Compilation
Compilation is not an OOP pillar.
Compilation is not an OOP pillar.
7. What is polymorphism in Python?
Answer: A) Multiple forms of a function
Polymorphism means many forms of the same function.
Polymorphism means many forms of the same function.
8. Which keyword is used to refer to the current object?
Answer: A) self
self refers to the current instance.
self refers to the current instance.
9. What is the output of: class A: pass; type(A())?
Answer: A) <class '__main__.A'>
type() returns the class of the object.
type() returns the class of the object.
10. Which method is called when an object is deleted?
Answer: A) __del__
__del__ is the destructor method.
__del__ is the destructor method.
11. What is multiple inheritance?
Answer: B) Inheriting from multiple classes
Multiple inheritance allows a class to inherit from multiple parents.
Multiple inheritance allows a class to inherit from multiple parents.
12. Which method returns a string representation of an object?
Answer: C) Both A and B
Both __str__ and __repr__ return string representations.
Both __str__ and __repr__ return string representations.
13. What is encapsulation in OOP?
Answer: A) Hiding internal details
Encapsulation wraps data and methods and hides internal details.
Encapsulation wraps data and methods and hides internal details.
14. Which of the following is true about class variables?
Answer: A) Shared by all instances
Class variables are shared across all instances.
Class variables are shared across all instances.
15. What is the output of: class A: def __init__(self): self.x = 5; a = A(); print(a.x)?
Answer: A) 5
Instance variable x is set to 5.
Instance variable x is set to 5.
16. Which of the following is a private attribute in Python?
Answer: A) __attr
Double underscore indicates name mangling for privacy.
Double underscore indicates name mangling for privacy.
17. What is method overriding?
Answer: A) Redefining a method in child class
Override provides a new implementation in the child class.
Override provides a new implementation in the child class.
18. Which function is used to check if an object is an instance of a class?
Answer: A) isinstance()
isinstance() checks object class membership.
isinstance() checks object class membership.
19. What is the output of: class A: x = 5; print(A.x)?
Answer: A) 5
Class variable x is accessed using the class name.
Class variable x is accessed using the class name.
20. Which of the following supports method overloading in Python?
Answer: B) No
Python does not support method overloading directly.
Python does not support method overloading directly.
21. What is the output of: class A: def __init__(self): self.x = 5; a = A(); a.x = 10; print(a.x)?
Answer: B) 10
Instance variable x is changed to 10.
Instance variable x is changed to 10.
22. Which method is used to compare two objects?
Answer: A) __eq__
__eq__ defines equality comparison.
__eq__ defines equality comparison.
23. What is the purpose of the super() function?
Answer: A) Call parent class methods
super() calls methods from parent classes.
super() calls methods from parent classes.
24. What is the output of: class A: pass; print(isinstance(A(), A))?
Answer: A) True
isinstance() returns True for instance of the class.
isinstance() returns True for instance of the class.
25. Which of the following is a type of polymorphism?
Answer: C) Both A and B
Both compile-time and runtime polymorphism exist in Python.
Both compile-time and runtime polymorphism exist in Python.
26. What is the output of: class A: def __init__(self): self.__x = 5; a = A(); print(a.__x)?
Answer: B) Error
Private attribute __x cannot be accessed directly.
Private attribute __x cannot be accessed directly.
27. Which of the following creates an abstract class?
Answer: A) ABCMeta
ABCMeta is used to create abstract classes.
ABCMeta is used to create abstract classes.
28. What is the purpose of the __call__ method?
Answer: A) Make object callable
__call__ allows an object to be called like a function.
__call__ allows an object to be called like a function.
29. Which of the following is true about abstract methods?
Answer: A) Must be implemented in child class
Abstract methods must be implemented by subclasses.
Abstract methods must be implemented by subclasses.
30. What is the output of: class A: def __len__(self): return 5; print(len(A()))?
Answer: A) 5
__len__ defines length, so len() returns 5.
__len__ defines length, so len() returns 5.
16. Python Regular Expressions — 15 MCQs
1. Which module is used for regular expressions in Python?
Answer: B) re
re module provides regex functionality.
re module provides regex functionality.
2. Which method is used to find all matches of a pattern?
Answer: C) findall()
findall() returns all matches as a list.
findall() returns all matches as a list.
3. What is the output of: re.findall(r'\d+', 'a1b2c3')?
Answer: A) ['1', '2', '3']
\d+ matches one or more digits.
\d+ matches one or more digits.
4. Which method searches for a pattern anywhere in the string?
Answer: B) search()
search() finds pattern anywhere in the string.
search() finds pattern anywhere in the string.
5. What is the output of: re.sub(r'\d', 'X', 'a1b2c3')?
Answer: A) aXbXcX
sub() replaces digits with 'X'.
sub() replaces digits with 'X'.
6. Which pattern matches any whitespace character?
Answer: A) \s
\s matches whitespace characters.
\s matches whitespace characters.
7. What is the output of: re.match(r'\d+', '123abc')?
Answer: A) <re.Match object>
match() returns a match object if pattern matches.
match() returns a match object if pattern matches.
8. Which pattern matches any character except newline?
Answer: A) .
Dot matches any character except newline.
Dot matches any character except newline.
9. What is the output of: re.split(r'\s+', 'Hello World Python')?
Answer: A) ['Hello', 'World', 'Python']
split() splits on whitespace.
split() splits on whitespace.
10. Which pattern matches any word character?
Answer: A) \w
\w matches letters, digits, and underscore.
\w matches letters, digits, and underscore.
11. What is the output of: re.findall(r'\w+', 'Hello World!')?
Answer: A) ['Hello', 'World']
\w+ matches word characters only.
\w+ matches word characters only.
12. Which method returns an iterator over matches?
Answer: A) finditer()
finditer() returns an iterator of match objects.
finditer() returns an iterator of match objects.
13. What is the output of: re.compile(r'\d+').search('abc123def')?
Answer: A) <re.Match object>
search() returns match object for '123'.
search() returns match object for '123'.
14. Which pattern matches the start of a string?
Answer: A) ^
^ matches the start of the string.
^ matches the start of the string.
15. Which pattern matches the end of a string?
Answer: B) $
$ matches the end of the string.
$ matches the end of the string.
17. Advanced Python — 25 MCQs
1. What is a generator in Python?
Answer: B) A function that yields values lazily
Generators yield values one at a time.
Generators yield values one at a time.
2. What is a decorator in Python?
Answer: A) A function that modifies another function
Decorators modify or enhance function behavior.
Decorators modify or enhance function behavior.
3. What is the output of: [x**2 for x in range(3)]?
Answer: A) [0, 1, 4]
List comprehension squares elements of range(3).
List comprehension squares elements of range(3).
4. Which of the following is a context manager syntax?
Answer: C) Both A and B
with and try-finally both handle context management.
with and try-finally both handle context management.
5. What is the output of: (lambda x: x**2)(3)?
Answer: B) 9
Lambda squares 3 to get 9.
Lambda squares 3 to get 9.
6. Which of the following is true about async/await?
Answer: C) Both A and B
async/await enables asynchronous, non-blocking code.
async/await enables asynchronous, non-blocking code.
7. What is the output of: sum(range(5))?
Answer: A) 10
sum of 0+1+2+3+4 = 10.
sum of 0+1+2+3+4 = 10.
8. Which of the following is used for type hints?
Answer: A) typing
typing module provides type hint support.
typing module provides type hint support.
9. What is the output of: dict([(1, 'a'), (2, 'b')])?
Answer: A) {1: 'a', 2: 'b'}
dict() creates a dictionary from key-value pairs.
dict() creates a dictionary from key-value pairs.
10. Which of the following is a mutable data type?
Answer: B) list
Lists are mutable; tuples, frozensets, and strings are immutable.
Lists are mutable; tuples, frozensets, and strings are immutable.
11. What is the output of: zip([1,2], ['a','b'])?
Answer: D) zip object
zip() returns an iterator of tuples.
zip() returns an iterator of tuples.
12. Which of the following is used for shallow copy?
Answer: A) copy.copy()
copy() creates a shallow copy.
copy() creates a shallow copy.
13. What is the output of: any([0, 1, 2])?
Answer: A) True
any() returns True if any element is True.
any() returns True if any element is True.
14. Which of the following is used for deep copy?
Answer: B) copy.deepcopy()
deepcopy() creates a recursive copy.
deepcopy() creates a recursive copy.
15. What is the output of: all([1, 2, 3])?
Answer: A) True
all() returns True if all elements are True.
all() returns True if all elements are True.
16. Which of the following is true about Python's GIL?
Answer: D) Both A and C
GIL limits thread execution in CPython.
GIL limits thread execution in CPython.
17. What is the output of: sorted(['b','a','c'])?
Answer: A) ['a', 'b', 'c']
sorted() returns a sorted list.
sorted() returns a sorted list.
18. Which of the following is used for parallel processing?
Answer: D) All of the above
All three provide concurrency mechanisms.
All three provide concurrency mechanisms.
19. What is the output of: list(map(str, [1,2,3]))?
Answer: A) ['1', '2', '3']
map() converts each number to string.
map() converts each number to string.
20. Which of the following is a frozen data type?
Answer: D) All of the above
frozenset, tuple, and str are all immutable.
frozenset, tuple, and str are all immutable.
21. What is the output of: reduce(lambda x, y: x+y, [1,2,3,4])?
Answer: A) 10
reduce() applies the function cumulatively.
reduce() applies the function cumulatively.
22. Which of the following is true about Python's memory management?
Answer: C) Both A and B
Python uses both reference counting and garbage collection.
Python uses both reference counting and garbage collection.
23. What is the output of: list(enumerate(['a','b','c']))?
Answer: A) [(0,'a'),(1,'b'),(2,'c')]
enumerate() adds index to items.
enumerate() adds index to items.
24. Which of the following is a design pattern in Python?
Answer: D) All of the above
All are common design patterns.
All are common design patterns.
25. What is the output of: list(filter(lambda x: x%2==0, [1,2,3,4,5]))?
Answer: A) [2,4]
filter() keeps even numbers.
filter() keeps even numbers.
18. Python Standard Library — 20 MCQs
1. Which module provides time-related functions?
Answer: B) time
time module provides time functions.
time module provides time functions.
2. Which module provides random number generation?
Answer: C) random
random module generates random numbers.
random module generates random numbers.
3. Which module is used for mathematical functions?
Answer: D) Both A and C
math and cmath handle mathematical functions.
math and cmath handle mathematical functions.
4. Which module provides system-specific parameters?
Answer: D) All of the above
All provide system-related information.
All provide system-related information.
5. Which module is used for working with dates?
Answer: A) datetime
datetime module handles dates and times.
datetime module handles dates and times.
6. Which module is used for working with JSON?
Answer: A) json
json module handles JSON data.
json module handles JSON data.
7. Which module is used for file I/O operations?
Answer: C) Both A and B
os and io handle file I/O.
os and io handle file I/O.
8. Which module is used for regular expressions?
Answer: A) re
re module provides regex support.
re module provides regex support.
9. Which module is used for data serialization?
Answer: C) Both A and B
Both pickle and json serialize data.
Both pickle and json serialize data.
10. Which module is used for working with compressed files?
Answer: D) All of the above
All handle compressed file formats.
All handle compressed file formats.
11. Which module is used for working with paths?
Answer: C) Both A and B
Both handle path operations.
Both handle path operations.
12. Which module is used for working with collections?
Answer: D) All of the above
All handle collections and functional operations.
All handle collections and functional operations.
13. Which module provides advanced iterators?
Answer: A) itertools
itertools provides iterator tools.
itertools provides iterator tools.
14. Which module is used for working with sockets?
Answer: C) Both A and B
socket and ssl handle network communication.
socket and ssl handle network communication.
15. Which module is used for working with email?
Answer: C) Both A and B
email and smtplib handle email operations.
email and smtplib handle email operations.
16. Which module is used for working with XML?
Answer: C) Both A and B
xml and xml.etree handle XML.
xml and xml.etree handle XML.
17. Which module is used for working with HTML?
Answer: C) Both A and B
html and html.parser handle HTML.
html and html.parser handle HTML.
18. Which module is used for working with CSV files?
Answer: A) csv
csv module handles CSV files.
csv module handles CSV files.
19. Which module is used for working with temporary files?
Answer: A) tempfile
tempfile creates temporary files.
tempfile creates temporary files.
20. Which module is used for working with logging?
Answer: A) logging
logging module provides logging functionality.
logging module provides logging functionality.
19. Python Testing — 15 MCQs
1. Which module is used for unit testing in Python?
Answer: D) All of the above
unittest, pytest, and nose are testing frameworks.
unittest, pytest, and nose are testing frameworks.
2. Which class is used in the unittest module?
Answer: A) TestCase
unittest uses the TestCase class.
unittest uses the TestCase class.
3. Which method is used to set up test fixtures?
Answer: A) setUp()
setUp() runs before each test method.
setUp() runs before each test method.
4. Which method is used to tear down test fixtures?
Answer: A) tearDown()
tearDown() runs after each test method.
tearDown() runs after each test method.
5. Which assertion checks for equality?
Answer: A) assertEqual()
assertEqual() checks if two values are equal.
assertEqual() checks if two values are equal.
6. Which assertion checks if a value is True?
Answer: A) assertTrue()
assertTrue() checks if value is True.
assertTrue() checks if value is True.
7. Which assertion checks if a value is False?
Answer: A) assertFalse()
assertFalse() checks if value is False.
assertFalse() checks if value is False.
8. Which assertion checks if a value is in a collection?
Answer: A) assertIn()
assertIn() checks membership.
assertIn() checks membership.
9. Which tool is used for test coverage?
Answer: C) Both A and B
coverage and pytest-cov measure test coverage.
coverage and pytest-cov measure test coverage.
10. Which assertion checks if two objects are the same?
Answer: A) assertIs()
assertIs() checks identity.
assertIs() checks identity.
11. Which method is used to run tests in unittest?
Answer: A) unittest.main()
unittest.main() runs the test suite.
unittest.main() runs the test suite.
12. Which of the following is a testing framework?
Answer: D) All of the above
All are Python testing frameworks.
All are Python testing frameworks.
13. Which assertion checks if an exception is raised?
Answer: A) assertRaises()
assertRaises() checks for expected exceptions.
assertRaises() checks for expected exceptions.
14. Which tool is used for mocking in tests?
Answer: C) Both A and B
unittest.mock and mock provide mocking.
unittest.mock and mock provide mocking.
15. Which decorator is used for test fixtures in pytest?
Answer: A) @pytest.fixture
@pytest.fixture defines test fixtures.
@pytest.fixture defines test fixtures.
20. Python Best Practices — 15 MCQs
1. Which style guide is recommended for Python?
Answer: A) PEP 8
PEP 8 is the Python style guide.
PEP 8 is the Python style guide.
2. Which indentation is recommended in Python?
Answer: B) 4 spaces
PEP 8 recommends 4 spaces for indentation.
PEP 8 recommends 4 spaces for indentation.
3. Which naming convention is used for variables?
Answer: A) snake_case
Variables use snake_case in Python.
Variables use snake_case in Python.
4. Which naming convention is used for classes?
Answer: C) PascalCase
Classes use PascalCase in Python.
Classes use PascalCase in Python.
5. What is the Python Zen?
Answer: A) PEP 20
PEP 20 is the Zen of Python.
PEP 20 is the Zen of Python.
6. Which of the following is a Python principle?
Answer: C) Both A and B
Both are principles from the Zen of Python.
Both are principles from the Zen of Python.
7. Which tool is used for code linting?
Answer: C) Both A and B
flake8 and pylint are linters.
flake8 and pylint are linters.
8. Which tool is used for code formatting?
Answer: C) Both A and B
black, autopep8, and yapf are formatters.
black, autopep8, and yapf are formatters.
9. Which of the following is a good practice?
Answer: D) All of the above
All are good programming practices.
All are good programming practices.
10. Which of the following is NOT a best practice?
Answer: C) Using global variables unnecessarily
Global variables should be avoided.
Global variables should be avoided.
11. Which of the following is a docstring convention?
Answer: A) PEP 257
PEP 257 covers docstring conventions.
PEP 257 covers docstring conventions.
12. Which tool is used for type checking?
Answer: C) Both A and B
mypy and pytype are type checkers.
mypy and pytype are type checkers.
13. Which of the following is important for code readability?
Answer: D) All of the above
All contribute to code readability.
All contribute to code readability.
14. Which tool is used for dependency management?
Answer: C) Both A and B
pip, poetry, and conda manage dependencies.
pip, poetry, and conda manage dependencies.
15. Which of the following is a security best practice?
Answer: D) All of the above
All are security best practices.
All are security best practices.
21. MySQL with Python — 25 MCQs
1. Which module is used to connect MySQL with Python?
Answer: D) All of the above
All are MySQL connectors for Python.
All are MySQL connectors for Python.
2. Which method is used to execute a SQL query?
Answer: B) execute()
execute() runs SQL queries.
execute() runs SQL queries.
3. Which method fetches all rows from a query?
Answer: A) fetchall()
fetchall() returns all rows.
fetchall() returns all rows.
4. Which method commits changes to the database?
Answer: A) commit()
commit() saves changes to the database.
commit() saves changes to the database.
5. Which method rolls back changes?
Answer: A) rollback()
rollback() undoes uncommitted changes.
rollback() undoes uncommitted changes.
6. Which function creates a connection to MySQL?
Answer: D) Both A and C
connect() is used in both modules.
connect() is used in both modules.
7. Which method creates a cursor in MySQL?
Answer: A) cursor()
cursor() creates a cursor object.
cursor() creates a cursor object.
8. Which SQL statement is used to insert data?
Answer: A) INSERT INTO
INSERT INTO adds data to a table.
INSERT INTO adds data to a table.
9. Which SQL statement is used to retrieve data?
Answer: B) SELECT
SELECT retrieves data from a table.
SELECT retrieves data from a table.
10. Which SQL statement is used to update data?
Answer: C) UPDATE
UPDATE modifies existing data.
UPDATE modifies existing data.
11. Which SQL statement is used to delete data?
Answer: C) DELETE FROM
DELETE FROM removes data from a table.
DELETE FROM removes data from a table.
12. Which SQL clause is used to filter results?
Answer: B) WHERE
WHERE filters query results.
WHERE filters query results.
13. Which SQL clause is used to sort results?
Answer: B) ORDER BY
ORDER BY sorts query results.
ORDER BY sorts query results.
14. Which SQL keyword is used to prevent SQL injection?
Answer: C) Both A and B
Parameterized queries/prepared statements prevent SQL injection.
Parameterized queries/prepared statements prevent SQL injection.
15. Which exception is raised for MySQL errors?
Answer: C) Both A and B
Both modules have their own Error classes.
Both modules have their own Error classes.
16. Which method checks if a connection is open?
Answer: A) is_connected()
is_connected() checks connection status.
is_connected() checks connection status.
17. Which method closes a MySQL connection?
Answer: C) Both A and B
close() and disconnect() close connections.
close() and disconnect() close connections.
18. Which method returns the last inserted ID?
Answer: C) Both A and B
Both return the last inserted ID.
Both return the last inserted ID.
19. Which SQL statement creates a table?
Answer: B) CREATE TABLE
CREATE TABLE creates a new table.
CREATE TABLE creates a new table.
20. Which SQL statement drops a table?
Answer: A) DROP TABLE
DROP TABLE deletes a table.
DROP TABLE deletes a table.
21. Which SQL keyword is used for joining tables?
Answer: C) Both A and B
JOIN and UNION combine tables.
JOIN and UNION combine tables.
22. Which function returns the number of rows affected?
Answer: C) Both A and B
Both return the number of affected rows.
Both return the number of affected rows.
23. Which type of join returns all rows from both tables?
Answer: C) FULL OUTER JOIN
FULL OUTER JOIN returns all rows from both tables.
FULL OUTER JOIN returns all rows from both tables.
24. Which SQL function is used for counting rows?
Answer: A) COUNT()
COUNT() counts rows.
COUNT() counts rows.
25. Which SQL function is used for calculating average?
Answer: A) AVG()
AVG() calculates the average.
AVG() calculates the average.
22. Python Threads — 20 MCQs
1. Which module is used for threading in Python?
Answer: B) threading
threading module provides thread support.
threading module provides thread support.
2. Which method starts a thread in Python?
Answer: B) start()
start() begins thread execution.
start() begins thread execution.
3. Which method waits for a thread to finish?
Answer: B) join()
join() waits for thread completion.
join() waits for thread completion.
4. Which of the following is true about threads?
Answer: A) Threads share memory
Threads within a process share memory.
Threads within a process share memory.
5. What is a daemon thread?
Answer: A) A thread that runs in the background
Daemon threads run in the background.
Daemon threads run in the background.
6. Which method checks if a thread is alive?
Answer: A) is_alive()
is_alive() checks if thread is running.
is_alive() checks if thread is running.
7. Which function returns the current thread?
Answer: A) current_thread()
current_thread() returns the current thread.
current_thread() returns the current thread.
8. Which function returns the number of active threads?
Answer: A) active_count()
active_count() returns the number of active threads.
active_count() returns the number of active threads.
9. Which lock prevents race conditions?
Answer: D) All of the above
All are synchronization primitives.
All are synchronization primitives.
10. What is the GIL in Python?
Answer: A) Global Interpreter Lock
GIL prevents multiple threads from executing Python bytecode.
GIL prevents multiple threads from executing Python bytecode.
11. Which of the following is NOT affected by GIL?
Answer: B) I/O-bound threads
I/O-bound threads release GIL during I/O operations.
I/O-bound threads release GIL during I/O operations.
12. Which method is used to acquire a lock?
Answer: A) acquire()
acquire() locks the resource.
acquire() locks the resource.
13. Which method is used to release a lock?
Answer: A) release()
release() unlocks the resource.
release() unlocks the resource.
14. Which of the following is a thread-safe data structure?
Answer: A) queue.Queue
Queue is thread-safe by default.
Queue is thread-safe by default.
15. What is a deadlock?
Answer: A) Two or more threads waiting for each other
Deadlock occurs when threads wait for each other.
Deadlock occurs when threads wait for each other.
16. Which function lists all active threads?
Answer: A) enumerate()
enumerate() returns a list of active threads.
enumerate() returns a list of active threads.
17. Which of the following is a thread pool executor?
Answer: C) Both A and B
Both are pool executors from concurrent.futures.
Both are pool executors from concurrent.futures.
18. Which module provides thread pools?
Answer: A) concurrent.futures
concurrent.futures provides thread and process pools.
concurrent.futures provides thread and process pools.
19. Which of the following is true about thread-local data?
Answer: A) Unique to each thread
Thread-local data is unique per thread.
Thread-local data is unique per thread.
20. Which class is used for thread-local data?
Answer: D) Both A and C
threading.local and local provide thread-local storage.
threading.local and local provide thread-local storage.
23. Python Code Output — 30 MCQs
1. What is the output of: print(2 * 3 // 4 + 5)?
Answer: A) 6
2*3=6, 6//4=1, 1+5=6.
2*3=6, 6//4=1, 1+5=6.
2. What is the output of: print("Python"[-1])?
Answer: B) n
Index -1 accesses the last character.
Index -1 accesses the last character.
3. What is the output of: print(type([]))?
Answer: A) <class 'list'>
[] creates a list.
[] creates a list.
4. What is the output of: [1,2,3][1:2]?
Answer: B) [2]
Slicing [1:2] gets the element at index 1.
Slicing [1:2] gets the element at index 1.
5. What is the output of: bool([])?
Answer: B) False
Empty lists are False.
Empty lists are False.
6. What is the output of: set([1,2,2,3,3,3])?
Answer: A) {1,2,3}
set() removes duplicates.
set() removes duplicates.
7. What is the output of: print(3 > 2 > 1)?
Answer: A) True
Chained comparison: 3>2 AND 2>1.
Chained comparison: 3>2 AND 2>1.
8. What is the output of: print(5 // 2)?
Answer: B) 2
Floor division returns the integer part.
Floor division returns the integer part.
9. What is the output of: print(2 ** 3 ** 2)?
Answer: A) 512
Right associativity: 3**2=9, 2**9=512.
Right associativity: 3**2=9, 2**9=512.
10. What is the output of: print("Hello" + "World")?
Answer: A) HelloWorld
+ concatenates strings without spaces.
+ concatenates strings without spaces.
11. What is the output of: print(list(range(3)))?
Answer: A) [0,1,2]
range(3) generates 0,1,2.
range(3) generates 0,1,2.
12. What is the output of: print("Python".upper())?
Answer: A) PYTHON
upper() converts to uppercase.
upper() converts to uppercase.
13. What is the output of: print(10 % 3)?
Answer: B) 1
10 divided by 3 gives remainder 1.
10 divided by 3 gives remainder 1.
14. What is the output of: print(5 & 3)?
Answer: A) 1
5(101) & 3(011) = 1(001).
5(101) & 3(011) = 1(001).
15. What is the output of: print(2 << 3)?
Answer: B) 16
2 << 3 = 2 * 8 = 16.
2 << 3 = 2 * 8 = 16.
16. What is the output of: print(15 >> 2)?
Answer: A) 3
15 >> 2 = 15 // 4 = 3.
15 >> 2 = 15 // 4 = 3.
17. What is the output of: print(not 5 > 3)?
Answer: B) False
5 > 3 is True, not True is False.
5 > 3 is True, not True is False.
18. What is the output of: print(len("Python"))?
Answer: B) 6
"Python" has 6 characters.
"Python" has 6 characters.
19. What is the output of: print("Hello"[1:3])?
Answer: A) el
Index 1 to 3 (exclusive): e, l.
Index 1 to 3 (exclusive): e, l.
20. What is the output of: print("A" * 3)?
Answer: A) AAA
* repeats strings.
* repeats strings.
21. What is the output of: print(1, 2, 3, sep="-")?
Answer: A) 1-2-3
sep defines the separator.
sep defines the separator.
22. What is the output of: print(3 + 4 * 2)?
Answer: B) 11
4*2=8, 3+8=11.
4*2=8, 3+8=11.
23. What is the output of: print((3 + 4) * 2)?
Answer: A) 14
3+4=7, 7*2=14.
3+4=7, 7*2=14.
24. What is the output of: print("Python".replace("t", "p"))?
Answer: A) Pypython
replaces 't' with 'p'.
replaces 't' with 'p'.
25. What is the output of: print(5 ^ 2)?
Answer: A) 7
5(101) ^ 2(010) = 7(111).
5(101) ^ 2(010) = 7(111).
26. What is the output of: print(~5)?
Answer: A) -6
~x = -x - 1.
~x = -x - 1.
27. What is the output of: print(5 ^ 2 ^ 3)?
Answer: A) 4
5^2=7, 7^3=4.
5^2=7, 7^3=4.
28. What is the output of: print("Python".count("t"))?
Answer: B) 2
"Python" has 2 't's.
"Python" has 2 't's.
29. What is the output of: print("Python".find("o"))?
Answer: C) 4
Index of 'o' is 4.
Index of 'o' is 4.
30. What is the output of: print("Python".index("n"))?
Answer: B) 5
Index of 'n' is 5.
Index of 'n' is 5.
Where to Go From Here
Continue your Python learning journey with these resources:
Interview Questions
Prepare for Python interviews with common questions and answers.
Learn More →Case Studies
Apply your Python skills to real-world projects and scenarios.
Learn More →