Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python Multiple Choice Questions (MCQs) with Answers

Python Multiple Choice Questions - 400+ MCQs with Answers

400+ Python MCQs covering 23 topics with detailed answers.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Test your Python programming knowledge with these 400+ multiple choice questions and answers. This comprehensive collection covers 23 topics from basics to advanced concepts, perfect for interview preparation, exams, and self-assessment.
Read Time: 45 minutes Level: All Levels Topic: Assessment Questions: 400+ Topics: 23
Introduction: 20 Operators: 20 Input/Output: 15 Conditionals: 20 Loops: 25 Lists: 20 Tuples: 15 Sets: 15 Dictionaries: 20 Strings: 20 Functions: 25 Modules: 15 File Handling: 20 Exception: 20 OOPs: 30 Regex: 15 Advanced: 25 Standard Library: 20 Testing: 15 Best Practices: 15 MySQL: 25 Threads: 20 Code Output: 30
Jump to Topic:
  • Introduction (20)
  • Operators (20)
  • Input/Output (15)
  • Conditionals (20)
  • Loops (25)
  • Lists (20)
  • Tuples (15)
  • Sets (15)
  • Dictionaries (20)
  • Strings (20)
  • Functions (25)
  • Modules (15)
  • File Handling (20)
  • Exception (20)
  • OOPs (30)
  • Regex (15)
  • Advanced (25)
  • Std Library (20)
  • Testing (15)
  • Best Practices (15)
  • MySQL (25)
  • Threads (20)
  • Code Output (30)
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
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?
A) Dennis Ritchie
B) Guido van Rossum
C) James Gosling
D) Bjarne Stroustrup
Answer: B) Guido van Rossum
Guido van Rossum created Python in 1991. He designed it to be simple, readable, and beginner-friendly.
2. Python is a ________ programming language.
A) Compiled
B) Interpreted
C) Hybrid
D) Machine
Answer: B) Interpreted
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?
A) int
B) float
C) string
D) char
Answer: D) char
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?
A) .py
B) .python
C) .p
D) .pyth
Answer: A) .py
Python source files use the .py extension. Compiled files use .pyc.
5. Which of the following is used to create a comment in Python?
A) //
B) /* */
C) #
D) --
Answer: C) #
The # symbol is used for single-line comments. Python doesn't support multi-line comments directly.
6. Python supports which type of programming?
A) Procedural
B) Object-Oriented
C) Functional
D) All of the above
Answer: D) All of the above
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?
A) echo "Hello World"
B) print("Hello World")
C) printf("Hello World")
D) console.log("Hello World")
Answer: B) print("Hello World")
print() is the built-in function used to display output in Python.
8. What is the output of: print(type(10))?
A) <class 'int'>
B) <class 'float'>
C) <class 'str'>
D) <class 'bool'>
Answer: A) <class 'int'>
type() returns the data type of the object. 10 is an integer.
9. Which of the following is a valid variable name in Python?
A) 2var
B) var-2
C) _var2
D) var 2
Answer: C) _var2
Variable names can start with a letter or underscore, contain letters, digits, and underscores.
10. What is the output of: bool(0)?
A) True
B) False
C) Error
D) None
Answer: B) False
0 is considered False in Python. All other numbers are True.
11. Which of the following is NOT a keyword in Python?
A) def
B) class
C) function
D) if
Answer: C) function
"function" is not a keyword. "def" is used to define functions.
12. What is the output of: print(10 / 3)?
A) 3
B) 3.0
C) 3.333...
D) 4
Answer: C) 3.333...
In Python 3, / always returns a float.
13. Which of the following is used for multi-line strings?
A) """ """
B) '' ''
C) // //
D) /* */
Answer: A) """ """
Triple quotes are used for multi-line strings and docstrings.
14. What is the output of: print(2 ** 3)?
A) 6
B) 8
C) 9
D) 12
Answer: B) 8
** is the exponentiation operator (2 to the power of 3).
15. Which of the following is true about Python?
A) It is case-sensitive
B) It uses indentation for blocks
C) Both A and B
D) None of the above
Answer: C) Both A and B
Python is case-sensitive and uses indentation to define code blocks.
16. Which of the following is a Python interpreter?
A) CPython
B) PyPy
C) Jython
D) All of the above
Answer: D) All of the above
CPython, PyPy, and Jython are all Python interpreters.
17. What is the output of: len("Python")?
A) 5
B) 6
C) 7
D) 4
Answer: B) 6
len() returns the length of the string. "Python" has 6 characters.
18. Which of the following is NOT a Python built-in function?
A) print()
B) input()
C) type()
D) compile()
Answer: D) compile()
compile() is also a built-in function. Actually all are built-in functions in Python.
19. What is the output of: print(10 // 3)?
A) 3.33
B) 3
C) 4
D) 3.0
Answer: B) 3
// is floor division, which returns the integer part of the division.
20. Which of the following is used to check Python version?
A) python --version
B) python -v
C) Both A and B
D) None of the above
Answer: C) Both A and B
Both --version and -v flags show the Python version.

2. Python Operators — 20 MCQs

1. What is the result of 10 // 3 in Python?
A) 3.33
B) 3
C) 4
D) 3.0
Answer: B) 3
Floor division (//) returns the integer part of the division.
2. Which operator is used for exponentiation in Python?
A) ^
B) **
C) *
D) ++
Answer: B) **
** is the exponentiation operator in Python.
3. What is the result of 5 % 2?
A) 1
B) 2
C) 2.5
D) 0
Answer: A) 1
% is the modulo operator, giving the remainder of the division.
4. Which operator is used for logical AND in Python?
A) &&
B) and
C) &
D) AND
Answer: B) and
Python uses "and", "or", "not" for logical operations.
5. What is the output of 2 ** 3 ** 2?
A) 512
B) 64
C) 256
D) 128
Answer: A) 512
Exponentiation is right-associative: 3**2=9, then 2**9=512.
6. Which operator checks if two values are NOT equal?
A) !=
B) <>
C) !==
D) is not
Answer: A) !=
!= is the not-equal operator in Python.
7. What is the output of: 10 + 3 * 2?
A) 26
B) 16
C) 20
D) 24
Answer: B) 16
Multiplication has higher precedence than addition: 3*2=6, then 10+6=16.
8. Which operator is used for identity comparison?
A) ==
B) is
C) =
D) !=
Answer: B) is
"is" checks if two objects are the same object in memory.
9. What is the output of: 5 | 3 (bitwise OR)?
A) 7
B) 15
C) 8
D) 6
Answer: A) 7
5 (101) | 3 (011) = 111 (7).
10. Which operator is used for membership testing?
A) in
B) contains
C) exists
D) has
Answer: A) in
"in" checks if an element exists in a sequence.
11. What is the output of: 15 >> 2 (right shift)?
A) 3
B) 60
C) 7
D) 15
Answer: A) 3
15 >> 2 = 15 // 2**2 = 15 // 4 = 3.
12. What is the output of: not (5 > 3)?
A) True
B) False
C) Error
D) None
Answer: B) False
5 > 3 is True, so not True is False.
13. What is the output of: 10 % 3?
A) 3
B) 1
C) 2
D) 0
Answer: B) 1
10 divided by 3 gives remainder 1.
14. Which operator is used for string concatenation?
A) +
B) &
C) .
D) concat()
Answer: A) +
The + operator concatenates strings.
15. What is the output of: 5 & 3 (bitwise AND)?
A) 1
B) 2
C) 3
D) 4
Answer: A) 1
5 (101) & 3 (011) = 001 (1).
16. What does the // operator do?
A) Division with remainder
B) Floor division
C) Modulo division
D) Integer division
Answer: B) Floor division
// returns the integer part of division.
17. What is the output of: 2 << 3 (left shift)?
A) 8
B) 16
C) 4
D) 12
Answer: B) 16
2 << 3 = 2 * 2**3 = 2 * 8 = 16.
18. Which operator has the highest precedence?
A) +
B) *
C) ()
D) **
Answer: C) ()
Parentheses have the highest precedence.
19. What is the output of: 5 ^ 2 (bitwise XOR)?
A) 7
B) 3
C) 8
D) 10
Answer: A) 7
5 (101) ^ 2 (010) = 111 (7).
20. What is the output of: ~5 (bitwise NOT)?
A) -6
B) -5
C) 4
D) 6
Answer: A) -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?
A) input()
B) raw_input()
C) scan()
D) read()
Answer: A) input()
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?
A) int
B) float
C) string
D) list
Answer: C) string
input() always returns a string in Python 3.
3. Which function is used to display output in Python?
A) output()
B) display()
C) print()
D) echo()
Answer: C) print()
print() is the built-in function for displaying output.
4. Which of the following is NOT a valid way to format strings?
A) f-strings
B) .format()
C) % formatting
D) sprintf()
Answer: D) sprintf()
Python does not have sprintf(). It uses f-strings, .format(), and % formatting.
5. What is the output of: print("Hello", end=" "); print("World")?
A) HelloWorld
B) Hello World
C) Hello\nWorld
D) Hello World
Answer: B) Hello World
end=" " replaces the default newline with a space.
6. Which function reads a file in Python?
A) read()
B) read_file()
C) file_read()
D) open()
Answer: A) read()
read() reads file content. open() opens the file.
7. What is the output of: print("Python" * 3)?
A) PythonPythonPython
B) Python3
C) P y t h o n
D) Error
Answer: A) PythonPythonPython
The * operator repeats strings.
8. Which method is used to write to a file?
A) write()
B) read()
C) append()
D) insert()
Answer: A) write()
write() is used to write data to a file.
9. What is the output of: print(1, 2, 3, sep="-")?
A) 1-2-3
B) 1 2 3
C) 1,2,3
D) 123
Answer: A) 1-2-3
sep defines the separator between values.
10. Which of the following is a valid way to take integer input?
A) int(input())
B) input(int())
C) float(input())
D) input() + 1
Answer: A) int(input())
int(input()) converts the string input to integer.
11. What is the output of: print(f"{10:02d}")?
A) 10
B) 010
C) 010
D) 10.0
Answer: A) 10
02d formats with at least 2 digits.
12. Which of the following is NOT a valid print parameter?
A) sep
B) end
C) format
D) file
Answer: C) format
format is not a print parameter. print() has sep, end, and file.
13. What is the output of: print("A", "B", sep="", end="")?
A) A B
B) AB
C) A
B
D) A-B
Answer: B) AB
sep="" removes spaces, end="" removes newline.
14. Which method reads one line from a file?
A) read()
B) readline()
C) readlines()
D) readall()
Answer: B) readline()
readline() reads a single line from a file.
15. What is the output of: print("{:.2f}".format(3.14159))?
A) 3.14
B) 3.142
C) 3.141
D) 3.1
Answer: A) 3.14
{:.2f} formats to 2 decimal places.

4. Python Conditional Statements — 20 MCQs

1. Which keyword is used for decision making in Python?
A) if
B) when
C) switch
D) case
Answer: A) if
if is the primary conditional statement in Python.
2. What is the correct syntax for if-else in Python?
A) if (x > 5): else:
B) if x > 5: else:
C) if x > 5: else: ...
D) if x > 5: else:
Answer: C) if x > 5: else: ...
Correct syntax uses colons and proper indentation.
3. Which statement is used for multiple conditional checks?
A) elif
B) else if
C) elsif
D) switch
Answer: A) elif
elif (else if) checks multiple conditions.
4. What is the output of: print("A") if 5 > 3 else print("B")?
A) A
B) B
C) AB
D) Error
Answer: A) A
5 > 3 is True, so "A" is printed.
5. What is the output of: if 0: print("True") else: print("False")?
A) True
B) False
C) Error
D) None
Answer: B) False
0 is False, so the else block executes.
6. Which of the following is NOT a valid logical operator?
A) and
B) or
C) not
D) &&
Answer: D) &&
Python uses 'and', 'or', 'not' instead of symbols.
7. What is the output of: if (5 > 3 and 2 < 4): print("Yes")?
A) Yes
B) No
C) Error
D) None
Answer: A) Yes
Both conditions are True, so "Yes" is printed.
8. What is the output of: x = 10; if x: print("True") else: print("False")?
A) True
B) False
C) Error
D) None
Answer: A) True
Non-zero numbers are True in Python.
9. Which statement is used to handle multiple conditions?
A) if-elif-else
B) switch-case
C) if-elseif
D) select-case
Answer: A) if-elif-else
Python uses if-elif-else for multiple conditions.
10. What is the output of: print(3 > 2 > 1)?
A) True
B) False
C) Error
D) None
Answer: A) 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")?
A) A
B) B
C) AB
D) Error
Answer: B) B
Empty lists are False in Python.
12. Which of the following checks if a number is positive?
A) if num > 0
B) if num >= 0
C) if num < 0
D) if num == 0
Answer: A) if num > 0
num > 0 checks for positive numbers.
13. What is the output of: if (5 > 3) or (2 > 4): print("Yes") else: print("No")?
A) Yes
B) No
C) Error
D) None
Answer: A) Yes
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")?
A) A
B) B
C) C
D) AB
Answer: A) A
The first true condition executes, even if others would also be true.
15. What is the output of: if not False: print("A")?
A) A
B) B
C) Error
D) None
Answer: A) A
not False evaluates to True.
16. Which of the following is a ternary operator in Python?
A) if-else
B) ?:
C) if-else shorthand
D) elif
Answer: A) if-else
Python uses if-else as the ternary operator: x if condition else y.
17. What is the output of: (5 > 3) and print("A")?
A) A
B) False
C) Error
D) None
Answer: A) A
and evaluates both expressions. print() returns None.
18. What is the output of: if "": print("A") else: print("B")?
A) A
B) B
C) AB
D) Error
Answer: B) B
Empty strings are False in Python.
19. What is the output of: if 5: print("A") else: print("B")?
A) A
B) B
C) AB
D) Error
Answer: A) A
Non-zero numbers are True.
20. Which condition checks if x is between 5 and 10?
A) if 5 < x < 10
B) if x > 5 and x < 10
C) Both A and B
D) if x in range(5,10)
Answer: C) Both A and B
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?
A) for
B) while
C) do-while
D) repeat
Answer: B) while
while loop continues as long as the condition is true.
2. Which loop is used to iterate over a sequence in Python?
A) while
B) for
C) do-while
D) loop
Answer: B) for
for loop iterates over sequences like lists, tuples, strings.
3. Which statement is used to exit a loop prematurely?
A) exit
B) stop
C) break
D) continue
Answer: C) break
break immediately exits the loop.
4. What is the output of: for i in range(3): print(i, end=" ")?
A) 0 1 2
B) 1 2 3
C) 0 1 2 3
D) 1 2
Answer: A) 0 1 2
range(3) generates 0, 1, 2.
5. Which statement skips the rest of the loop iteration?
A) break
B) continue
C) pass
D) skip
Answer: B) continue
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=" ")?
A) 2 3 4
B) 1 2 3
C) 2 3 4 5
D) 1 2 3 4
Answer: A) 2 3 4
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=" ")?
A) 1 3 5 7 9
B) 1 2 3 4 5
C) 1 3 5 7 9 11
D) 0 2 4 6 8
Answer: A) 1 3 5 7 9
range(start, stop, step) with step=2 gives odd numbers.
8. Which loop does Python NOT support?
A) for
B) while
C) do-while
D) All are supported
Answer: C) do-while
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?
A) 0 1 2
B) 1 2 3
C) 0 1 2 3
D) 1 2
Answer: A) 0 1 2
while loop executes until i < 3 is false.
10. Which statement is used to do nothing in Python?
A) break
B) continue
C) pass
D) exit
Answer: C) pass
pass is a null operation that does nothing.
11. What is the output of: for i in [1, 2, 3]: print(i, end=" ")?
A) 1 2 3
B) 0 1 2
C) 1 2 3 4
D) 0 1 2 3
Answer: A) 1 2 3
for loop iterates over list elements.
12. What is the output of: for i in range(3): pass; print(i)?
A) 0 1 2
B) 2
C) 0 1 2 3
D) Error
Answer: A) 0 1 2
pass doesn't affect the loop; print(i) executes each iteration.
13. Which loop uses an iterator?
A) while
B) for
C) do-while
D) Both A and B
Answer: B) for
for loop automatically uses iterators.
14. What is the output of: for i in "ABC": print(i, end="")?
A) ABC
B) A B C
C) A\nB\nC
D) Error
Answer: A) ABC
for loop iterates over string characters.
15. What is the output of: while True: print("A"); break?
A) A
B) A A A ... (infinite)
C) Error
D) None
Answer: A) A
break exits the infinite loop after one iteration.
16. Which loop is more efficient for iterating over a sequence?
A) while
B) for
C) Both are equally efficient
D) Depends on the sequence
Answer: B) for
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)?
A) 0 1
B) 0 1 2
C) 2
D) 0 1 2 3
Answer: A) 0 1
break exits when i is 2.
18. What is the output of: for i in range(3): if i == 1: continue; print(i)?
A) 0 2
B) 0 1 2
C) 0 1
D) 1 2
Answer: A) 0 2
continue skips printing 1.
19. Which of the following is true about while loops?
A) They always execute at least once
B) They can create infinite loops
C) They are only for numbers
D) They don't support break
Answer: B) They can create infinite loops
while True: creates an infinite loop.
20. What is the output of: for i in range(3): print(i, end="") else: print("Done")?
A) 012Done
B) 012
C) Done
D) 0 1 2 Done
Answer: A) 012Done
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")?
A) 0
B) 0Done
C) 0 1 2 Done
D) 0 1
Answer: A) 0
break prevents else from executing.
22. Which method is used to iterate with both index and value?
A) enumerate()
B) zip()
C) range()
D) items()
Answer: A) enumerate()
enumerate() returns index and value pairs.
23. What is the output of: list(enumerate(['a','b','c']))?
A) [(0,'a'),(1,'b'),(2,'c')]
B) ['a','b','c']
C) [0,1,2]
D) [('a',0),('b',1),('c',2)]
Answer: A) [(0,'a'),(1,'b'),(2,'c')]
enumerate returns tuples of (index, value).
24. Which of the following creates an infinite loop?
A) while True:
B) for i in range(10):
C) while 1:
D) Both A and C
Answer: D) Both A and C
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=" ")?
A) 3 2 1
B) 1 2 3
C) 3 2 1 0
D) 0 1 2 3
Answer: A) 3 2 1
Negative step counts downward.

6. Python Lists — 20 MCQs

1. How do you create a list in Python?
A) []
B) ()
C) {}
D) <>
Answer: A) []
Square brackets are used to create lists.
2. What is the index of the first element in a list?
A) 0
B) 1
C) -1
D) first
Answer: A) 0
Python uses zero-based indexing.
3. Which method adds an element to the end of a list?
A) add()
B) append()
C) insert()
D) extend()
Answer: B) append()
append() adds a single element to the end of a list.
4. What is the output of: [1,2,3] + [4,5]?
A) [1,2,3,4,5]
B) [5,7]
C) Error
D) [1,2,3][4,5]
Answer: A) [1,2,3,4,5]
The + operator concatenates lists.
5. Which method removes the last element from a list?
A) pop()
B) remove()
C) delete()
D) discard()
Answer: A) pop()
pop() removes and returns the last element.
6. What is the output of: [1,2,3] * 2?
A) [1,2,3,1,2,3]
B) [2,4,6]
C) Error
D) [1,2,3,2]
Answer: A) [1,2,3,1,2,3]
* repeats the list.
7. How do you access the last element of a list?
A) list[-1]
B) list[last]
C) list[len(list)]
D) list[-0]
Answer: A) list[-1]
Negative index -1 accesses the last element.
8. Which method sorts a list?
A) sort()
B) sorted()
C) Both A and B
D) order()
Answer: C) Both A and B
sort() sorts in-place, sorted() returns a new sorted list.
9. What is the output of: len([1,2,3,4])?
A) 3
B) 4
C) 5
D) Error
Answer: B) 4
len() returns the number of elements.
10. Which method removes a specific element from a list?
A) remove()
B) pop()
C) delete()
D) discard()
Answer: A) remove()
remove() removes the first occurrence of a value.
11. What is the output of: [1,2,3].index(2)?
A) 0
B) 1
C) 2
D) 3
Answer: B) 1
index() returns the first index of the value.
12. What is the output of: [1,2,3,2,4].count(2)?
A) 1
B) 2
C) 3
D) 4
Answer: B) 2
count() returns the number of occurrences.
13. Which method reverses a list?
A) reverse()
B) reversed()
C) Both A and B
D) flip()
Answer: C) Both A and B
reverse() reverses in-place, reversed() returns an iterator.
14. What is the output of: [1,2][0:1]?
A) [1]
B) [2]
C) [1,2]
D) []
Answer: A) [1]
Slicing [0:1] gets element at index 0.
15. Which method inserts an element at a specific position?
A) insert()
B) append()
C) extend()
D) add()
Answer: A) insert()
insert(index, value) adds an element at the specified position.
16. What is the output of: [1,2,3].pop(1)?
A) 1
B) 2
C) 3
D) [1,3]
Answer: B) 2
pop(1) removes and returns the element at index 1.
17. Which method removes all elements from a list?
A) clear()
B) empty()
C) delete()
D) remove_all()
Answer: A) clear()
clear() removes all elements from the list.
18. What is the output of: [1,2,3] + [4,5] * 2?
A) [1,2,3,4,5,4,5]
B) [1,2,3,8,10]
C) Error
D) [1,2,3,4,5]
Answer: A) [1,2,3,4,5,4,5]
Multiplication happens before addition.
19. Which method extends a list with another list?
A) extend()
B) append()
C) add()
D) merge()
Answer: A) extend()
extend() adds all elements from another iterable.
20. What is the output of: [1,2,3][-2]?
A) 1
B) 2
C) 3
D) Error
Answer: B) 2
Negative index -2 accesses the second last element.

7. Python Tuples — 15 MCQs

1. How do you create a tuple in Python?
A) []
B) ()
C) {}
D) <>
Answer: B) ()
Parentheses are used to create tuples.
2. Which of the following is true about tuples?
A) Tuples are mutable
B) Tuples are immutable
C) Tuples can be changed after creation
D) Tuples are same as lists
Answer: B) Tuples are immutable
Tuples cannot be modified after creation.
3. What is the output of: len((1,2,3,4))?
A) 3
B) 4
C) 5
D) Error
Answer: B) 4
len() returns the number of elements in a tuple.
4. How do you create a tuple with a single element?
A) (1,)
B) (1)
C) [1]
D) {1}
Answer: A) (1,)
A trailing comma is needed for a single-element tuple.
5. Can you append to a tuple?
A) Yes
B) No
C) Sometimes
D) Using append()
Answer: B) No
Tuples are immutable, so they don't have append.
6. What is the output of: (1,2,3) + (4,5)?
A) (1,2,3,4,5)
B) (5,7)
C) Error
D) (1,2,3)(4,5)
Answer: A) (1,2,3,4,5)
+ concatenates tuples.
7. What is the output of: (1,2,3) * 2?
A) (1,2,3,1,2,3)
B) (2,4,6)
C) Error
D) (1,2,3,2)
Answer: A) (1,2,3,1,2,3)
* repeats the tuple.
8. Which method is available for tuples?
A) count()
B) index()
C) Both A and B
D) append()
Answer: C) Both A and B
Tuples have count() and index() methods.
9. What is the output of: (1,2,3).count(2)?
A) 0
B) 1
C) 2
D) 3
Answer: B) 1
count() returns the number of occurrences.
10. Can a tuple contain mutable elements?
A) Yes
B) No
C) Only if they are frozen
D) Not allowed
Answer: A) Yes
Tuples can contain lists, which are mutable.
11. What is the output of: (1,2,3)[1]?
A) 1
B) 2
C) 3
D) Error
Answer: B) 2
Index 1 accesses the second element.
12. What is tuple unpacking?
A) Assigning tuple elements to variables
B) Removing elements from tuple
C) Converting tuple to list
D) None of the above
Answer: A) Assigning tuple elements to variables
a, b = (1, 2) unpacks tuple into variables.
13. What is the output of: (1,2,3) == [1,2,3]?
A) True
B) False
C) Error
D) None
Answer: B) False
Tuples and lists are different types.
14. Which of the following converts a list to a tuple?
A) tuple(list)
B) list(tuple)
C) tuple(list)
D) tuple(list)
Answer: A) tuple(list)
tuple() constructor converts a list to a tuple.
15. What is the output of: type((1,2,3))?
A) <class 'list'>
B) <class 'tuple'>
C) <class 'set'>
D) <class 'dict'>
Answer: B) <class 'tuple'>
type() returns the correct data type.

8. Python Sets — 15 MCQs

1. How do you create a set in Python?
A) []
B) ()
C) {}
D) set()
Answer: D) set() or C) {}
Sets are created using {} or set() (empty set uses set()).
2. Which of the following is true about sets?
A) Sets can contain duplicate elements
B) Sets are ordered
C) Sets are unordered and unique
D) Sets are indexed
Answer: C) Sets are unordered and unique
Sets contain only unique elements and are unordered.
3. What is the output of: len({1,2,3,3,4})?
A) 3
B) 4
C) 5
D) 6
Answer: B) 4
Duplicate 3 is removed, so set has {1,2,3,4}.
4. Which method adds an element to a set?
A) add()
B) append()
C) insert()
D) extend()
Answer: A) add()
add() adds a single element to a set.
5. Which method removes an element from a set?
A) remove()
B) discard()
C) pop()
D) All of the above
Answer: D) All of the above
remove(), discard(), and pop() all remove elements.
6. What is the output of: {1,2,3} & {2,3,4} (intersection)?
A) {1,2,3}
B) {2,3}
C) {1,2,3,4}
D) {4}
Answer: B) {2,3}
& operator performs set intersection.
7. What is the output of: {1,2,3} | {3,4,5} (union)?
A) {1,2,3}
B) {1,2,3,4,5}
C) {3}
D) {1,2,3,4}
Answer: B) {1,2,3,4,5}
| operator performs set union.
8. What is the output of: {1,2,3} - {2,3} (difference)?
A) {1}
B) {1,2}
C) {2,3}
D) {1,2,3}
Answer: A) {1}
- operator removes elements present in the second set.
9. Which method removes all elements from a set?
A) clear()
B) empty()
C) delete()
D) remove_all()
Answer: A) clear()
clear() removes all elements from the set.
10. Can a set contain a list?
A) Yes
B) No
C) Only if immutable
D) Sometimes
Answer: B) No
Sets can only contain hashable (immutable) elements.
11. What is the output of: set([1,2,2,3,3,3])?
A) {1,2,3}
B) [1,2,3]
C) (1,2,3)
D) {1,2,2,3,3,3}
Answer: A) {1,2,3}
set() removes duplicates from the list.
12. What is the output of: {1,2,3} == {3,2,1}?
A) True
B) False
C) Error
D) None
Answer: A) True
Sets are equal regardless of order.
13. Which method returns a copy of a set?
A) copy()
B) clone()
C) duplicate()
D) copy_set()
Answer: A) copy()
copy() returns a shallow copy of the set.
14. What is the output of: {1,2,3}.issubset({1,2,3,4})?
A) True
B) False
C) Error
D) None
Answer: A) True
issubset() checks if set is a subset.
15. What is the output of: type({})?
A) <class 'set'>
B) <class 'dict'>
C) <class 'list'>
D) <class 'tuple'>
Answer: B) <class 'dict'>
{} creates a dictionary, not a set.

9. Python Dictionaries — 20 MCQs

1. How do you create a dictionary in Python?
A) []
B) ()
C) {} with key-value pairs
D) <>
Answer: C) {} with key-value pairs
Dictionaries use key:value pairs inside {}.
2. How do you access a value in a dictionary?
A) dict[index]
B) dict[key]
C) dict.get(index)
D) dict(value)
Answer: B) dict[key]
Dictionary values are accessed using keys.
3. Which method removes all items from a dictionary?
A) delete()
B) clear()
C) remove()
D) pop()
Answer: B) clear()
clear() removes all key-value pairs.
4. What is the output of: len({'a':1, 'b':2, 'c':3})?
A) 3
B) 4
C) 5
D) 6
Answer: A) 3
len() returns the number of key-value pairs.
5. Which method returns all keys of a dictionary?
A) keys()
B) values()
C) items()
D) get_keys()
Answer: A) keys()
keys() returns all keys as a view object.
6. What is the output of: {'a':1, 'b':2}.get('a', 0)?
A) 0
B) 1
C) 2
D) None
Answer: B) 1
get() returns the value for key 'a'.
7. Which method removes a specific key from a dictionary?
A) pop()
B) remove()
C) delete()
D) discard()
Answer: A) pop()
pop(key) removes and returns the value for key.
8. Can dictionary keys be any data type?
A) Yes
B) No, must be immutable
C) No, must be strings
D) Only numbers
Answer: B) No, must be immutable
Dictionary keys must be hashable/immutable.
9. What is the output of: {'a':1, 'b':2}.items()?
A) dict_items([('a',1), ('b',2)])
B) ['a','b']
C) [1,2]
D) {'a':1, 'b':2}
Answer: A) dict_items([('a',1), ('b',2)])
items() returns key-value pairs as tuples.
10. Which method updates a dictionary with another dictionary?
A) update()
B) merge()
C) extend()
D) add()
Answer: A) update()
update() merges another dictionary or iterable.
11. What is the output of: {'a':1, 'b':2} == {'b':2, 'a':1}?
A) True
B) False
C) Error
D) None
Answer: A) True
Dictionaries are equal if they have the same key-value pairs.
12. Which method creates a dictionary from keys and values?
A) dict.fromkeys()
B) dict.create()
C) dict.make()
D) dict.new()
Answer: A) dict.fromkeys()
fromkeys() creates a dictionary from a sequence of keys.
13. What is the output of: list({'a':1, 'b':2}.keys())?
A) ['a', 'b']
B) [1, 2]
C) [('a',1), ('b',2)]
D) ['a', 1, 'b', 2]
Answer: A) ['a', 'b']
keys() returns a view, list() converts it.
14. Can a dictionary have duplicate keys?
A) Yes
B) No
C) Only if values are different
D) Depends on version
Answer: B) No
Dictionary keys must be unique.
15. Which method returns the value for a key or a default if key doesn't exist?
A) get()
B) pop()
C) setdefault()
D) Both A and C
Answer: D) Both A and C
Both get() and setdefault() can return a default value.
16. What is the output of: {'a':1, 'b':2}.pop('a', 0)?
A) 1
B) 2
C) 0
D) None
Answer: A) 1
pop('a') removes and returns the value for key 'a'.
17. Which method returns all values of a dictionary?
A) values()
B) keys()
C) items()
D) get_values()
Answer: A) values()
values() returns all values as a view object.
18. What is the output of: dict(a=1, b=2)?
A) {'a':1, 'b':2}
B) {'a':1}
C) Error
D) {1:'a', 2:'b'}
Answer: A) {'a':1, 'b':2}
dict() can be called with keyword arguments.
19. Which of the following is a valid dictionary key?
A) list
B) tuple
C) dict
D) set
Answer: B) tuple
Tuples are hashable and can be dictionary keys.
20. What is the output of: {'a':1, 'b':2}.get('c', 'Not Found')?
A) 1
B) 2
C) Not Found
D) None
Answer: C) Not Found
get() returns the default when key doesn't exist.

10. Python Strings — 20 MCQs

1. Which method converts a string to uppercase?
A) upper()
B) toUpperCase()
C) capitalize()
D) casefold()
Answer: A) upper()
upper() converts all characters to uppercase.
2. What is the output of: "Hello".replace("e", "a")?
A) Hella
B) Hallo
C) Hello
D) Halo
Answer: B) Hallo
replace() replaces all occurrences.
3. Which method splits a string into a list?
A) split()
B) join()
C) divide()
D) separate()
Answer: A) split()
split() divides a string into a list of substrings.
4. What is the output of: "Python".find("t")?
A) 0
B) 1
C) 2
D) -1
Answer: C) 2
find() returns the index of the first occurrence.
5. Which method removes whitespace from the beginning and end?
A) strip()
B) lstrip()
C) rstrip()
D) trim()
Answer: A) strip()
strip() removes leading and trailing whitespace.
6. What is the output of: "Python"[::-1]?
A) Python
B) nohtyP
C) nohtyP
D) P
Answer: B) nohtyP
[::-1] reverses the string.
7. Which method joins list elements into a string?
A) join()
B) concat()
C) merge()
D) combine()
Answer: A) join()
join() concatenates list elements with a separator.
8. What is the output of: "Python".lower()?
A) PYTHON
B) python
C) Python
D) pYTHON
Answer: B) python
lower() converts all characters to lowercase.
9. Which method capitalizes the first letter of a string?
A) capitalize()
B) title()
C) upper()
D) lower()
Answer: A) capitalize()
capitalize() capitalizes only the first character.
10. What is the output of: "Hello World".startswith("Hello")?
A) True
B) False
C) Error
D) None
Answer: A) True
startswith() checks if the string starts with the prefix.
11. What is the output of: "Python".index("o")?
A) 2
B) 3
C) 4
D) 5
Answer: C) 4
"Python": P-0, y-1, t-2, h-3, o-4, n-5.
12. Which method counts occurrences of a substring?
A) count()
B) len()
C) find()
D) search()
Answer: A) count()
count() returns the number of non-overlapping occurrences.
13. What is the output of: " Python ".strip()?
A) " Python "
B) "Python"
C) " Python"
D) "Python "
Answer: B) "Python"
strip() removes leading and trailing spaces.
14. Which method checks if all characters are digits?
A) isdigit()
B) isnumeric()
C) isdecimal()
D) All of the above
Answer: D) All of the above
isdigit(), isnumeric(), and isdecimal() all check for digits.
15. What is the output of: "Hello" + "World"?
A) HelloWorld
B) Hello World
C) "Hello" "World"
D) Error
Answer: A) HelloWorld
+ concatenates strings without spaces.
16. Which method checks if all characters are letters?
A) isalpha()
B) isletter()
C) isalnum()
D) ischar()
Answer: A) isalpha()
isalpha() returns True if all characters are letters.
17. What is the output of: "Python".endswith("on")?
A) True
B) False
C) Error
D) None
Answer: A) True
endswith() checks if the string ends with the suffix.
18. Which method creates a string from a list with a separator?
A) join()
B) split()
C) concat()
D) merge()
Answer: A) join()
join() joins list elements with a string separator.
19. What is the output of: "Python".isupper()?
A) True
B) False
C) Error
D) None
Answer: B) False
isupper() checks if all characters are uppercase.
20. What is the output of: "Python".swapcase()?
A) pYTHON
B) PYTHON
C) python
D) pythON
Answer: A) pYTHON
swapcase() swaps uppercase to lowercase and vice versa.

11. Python Functions — 25 MCQs

1. Which keyword is used to define a function in Python?
A) function
B) def
C) define
D) fun
Answer: B) def
def is the keyword for function definition.
2. What is a function that calls itself called?
A) Iterative function
B) Recursive function
C) Lambda function
D) Nested function
Answer: B) Recursive function
Recursive functions call themselves.
3. What is a lambda function in Python?
A) A named function
B) An anonymous function
C) A recursive function
D) A built-in function
Answer: B) An anonymous function
Lambda functions are anonymous, one-line functions.
4. Which keyword returns a value from a function?
A) return
B) yield
C) output
D) result
Answer: A) return
return sends a value back to the caller.
5. What is the output of: def func(): return 5; print(func())?
A) 5
B) None
C) Error
D) 0
Answer: A) 5
func() returns 5, which is printed.
6. Which of the following is a built-in function?
A) print()
B) len()
C) type()
D) All of the above
Answer: D) All of the above
print(), len(), type() are all built-in functions.
7. What is the output of: def func(x=5): return x; func(10)?
A) 5
B) 10
C) 15
D) Error
Answer: B) 10
Default parameter is overridden by the argument.
8. Which of the following is true about function parameters?
A) They are optional
B) They can have default values
C) They can be keyword arguments
D) All of the above
Answer: D) All of the above
All statements are true about function parameters.
9. What is the output of: lambda x: x * 2 (3)?
A) 3
B) 6
C) 9
D) Error
Answer: B) 6
Lambda function multiplies x by 2.
10. Which keyword defines a generator function?
A) yield
B) return
C) generate
D) next
Answer: A) yield
yield makes a function a generator.
11. What is the output of: def func(): pass; print(func())?
A) None
B) Error
C) 0
D) pass
Answer: A) None
Functions without return statement return None.
12. Which of the following is a decorator syntax?
A) @decorator
B) decorator()
C) *decorator
D) &decorator
Answer: A) @decorator
@ symbol is used for decorators.
13. What is the output of: def func(a, b): return a + b; func(1,2,3)?
A) 3
B) 6
C) Error
D) None
Answer: C) Error
Too many arguments are passed.
14. Which of the following collects variable number of arguments?
A) *args
B) **kwargs
C) Both A and B
D) None
Answer: C) Both A and B
*args collects positional, **kwargs collects keyword arguments.
15. What is the output of: def func(*args): return sum(args); func(1,2,3)?
A) 3
B) 6
C) 1
D) Error
Answer: B) 6
*args collects 1,2,3 and sum returns 6.
16. Which keyword is used to import modules?
A) import
B) include
C) using
D) require
Answer: A) import
import is used to include modules.
17. What is the output of: def func(x): return x > 5; func(3)?
A) True
B) False
C) 3
D) Error
Answer: B) False
3 > 5 is False.
18. Which of the following creates a function with default argument?
A) def func(x=5): return x
B) def func(x=5) return x
C) def func(x=5):
D) def func(x=5) return x
Answer: A) def func(x=5): return x
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)?
A) 5
B) 10
C) Error
D) None
Answer: B) 10
func() changes x to 10 using global.
20. Which function returns the length of an object?
A) len()
B) length()
C) size()
D) count()
Answer: A) len()
len() is the built-in function for length.
21. What is the output of: def func(): yield 1; yield 2; list(func())?
A) [1, 2]
B) (1, 2)
C) {1, 2}
D) Error
Answer: A) [1, 2]
Generator yields values that are collected into a list.
22. Which of the following is NOT a built-in function?
A) max()
B) min()
C) average()
D) sum()
Answer: C) average()
average() is not a built-in function.
23. What is the output of: map(lambda x: x*2, [1,2,3])?
A) [2,4,6]
B) <map object>
C) (2,4,6)
D) Error
Answer: B) <map object>
map() returns an iterator, not a list.
24. Which of the following filters a list?
A) filter()
B) map()
C) reduce()
D) both A and C
Answer: A) filter()
filter() filters elements based on a condition.
25. What is the output of: sorted([3,1,2])?
A) [1,2,3]
B) [3,2,1]
C) [3,1,2]
D) Error
Answer: A) [1,2,3]
sorted() returns a new sorted list.

12. Python Modules — 15 MCQs

1. Which statement is used to import a module in Python?
A) include
B) import
C) using
D) require
Answer: B) import
import is used to bring in modules.
2. Which of the following is a built-in module in Python?
A) sys
B) os
C) math
D) All of the above
Answer: D) All of the above
sys, os, and math are all built-in modules.
3. What is the output of: import math; math.sqrt(16)?
A) 4.0
B) 4
C) 16
D) Error
Answer: A) 4.0
math.sqrt() returns the square root as a float.
4. Which keyword is used to import specific functions from a module?
A) from
B) import
C) from ... import
D) include
Answer: C) from ... import
from module import function imports specific items.
5. What is the output of: import random; random.randint(1,10)?
A) Always 1
B) Always 10
C) Random number between 1 and 10
D) Error
Answer: C) Random number between 1 and 10
randint() returns a random integer inclusive of both endpoints.
6. Which module provides time-related functions?
A) sys
B) time
C) os
D) datetime
Answer: B) time
time module provides time-related functions.
7. Which module provides operating system functionality?
A) os
B) sys
C) platform
D) All of the above
Answer: D) All of the above
os, sys, and platform all provide OS-related functions.
8. What is the output of: import sys; sys.version?
A) Error
B) Python version string
C) 3
D) None
Answer: B) Python version string
sys.version returns the Python version.
9. Which of the following is a way to install Python packages?
A) pip install
B) conda install
C) Both A and B
D) apt-get install
Answer: C) Both A and B
pip and conda are both package managers.
10. What is the output of: import datetime; datetime.datetime.now()?
A) Current date and time
B) Current date only
C) Current time only
D) Error
Answer: A) Current date and time
datetime.now() returns the current date and time.
11. Which module is used for working with JSON?
A) json
B) pickle
C) csv
D) xml
Answer: A) json
json module handles JSON data.
12. What is the output of: import math; math.pi?
A) 3.14
B) 3.141592653589793
C) 3
D) Error
Answer: B) 3.141592653589793
math.pi contains the value of π.
13. Which statement imports all functions from a module?
A) import *
B) from module import *
C) include all
D) import module all
Answer: B) from module import *
This imports all names from the module.
14. Which module is used for regular expressions?
A) re
B) regex
C) reg
D) expr
Answer: A) re
re module handles regular expressions.
15. What is the output of: import os; os.getcwd()?
A) Current working directory
B) Home directory
C) Error
D) None
Answer: A) 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?
A) open()
B) file()
C) read()
D) write()
Answer: A) open()
open() is used to open files.
2. Which mode is used to read a file in Python?
A) 'w'
B) 'r'
C) 'a'
D) 'x'
Answer: B) 'r'
'r' is the read mode.
3. Which method is used to read all lines of a file?
A) read()
B) readline()
C) readlines()
D) readall()
Answer: C) readlines()
readlines() returns all lines as a list.
4. Which mode is used to write to a file (overwrites)?
A) 'r'
B) 'a'
C) 'w'
D) 'x'
Answer: C) 'w'
'w' creates a new file or overwrites existing.
5. Which mode is used to append to a file?
A) 'r'
B) 'w'
C) 'a'
D) 'x'
Answer: C) 'a'
'a' appends to the end of the file.
6. Which method writes a string to a file?
A) write()
B) writeline()
C) writelines()
D) write_string()
Answer: A) write()
write() writes a string to the file.
7. What is the output of: with open('file.txt', 'r') as f: ...?
A) Error
B) File is automatically closed
C) File remains open
D) None
Answer: B) File is automatically closed
with statement automatically closes the file.
8. Which mode creates a file exclusively (fails if exists)?
A) 'w'
B) 'a'
C) 'x'
D) 'r'
Answer: C) 'x'
'x' creates a new file and raises error if exists.
9. Which method closes a file?
A) close()
B) end()
C) stop()
D) finish()
Answer: A) close()
close() closes the file.
10. Which module is used for working with CSV files?
A) csv
B) json
C) pickle
D) xml
Answer: A) csv
csv module handles CSV file operations.
11. What is the output of: file.read()?
A) Entire file content
B) First line
C) Last line
D) Error
Answer: A) Entire file content
read() reads the entire file.
12. Which mode opens a file for both reading and writing?
A) 'r+'
B) 'w+'
C) 'a+'
D) All of the above
Answer: D) All of the above
All these modes allow both read and write.
13. Which method checks if a file exists?
A) os.path.exists()
B) os.path.isfile()
C) Both A and B
D) file.exists()
Answer: C) Both A and B
Both check for file existence.
14. Which method is used to rename a file?
A) os.rename()
B) os.name()
C) file.rename()
D) rename.file()
Answer: A) os.rename()
os.rename() renames files.
15. What is the output of: os.remove('file.txt')?
A) Deletes the file
B) Renames the file
C) Error
D) None
Answer: A) Deletes the file
os.remove() deletes the file.
16. Which mode is used for binary files?
A) 'b'
B) 'bin'
C) 'binary'
D) 'B'
Answer: A) 'b'
'b' is used with other modes for binary files (e.g., 'rb').
17. Which module is used for file/directory path operations?
A) os.path
B) pathlib
C) Both A and B
D) path
Answer: C) Both A and B
Both os.path and pathlib handle paths.
18. What is the output of: file.tell()?
A) Current file position
B) File size
C) Error
D) None
Answer: A) Current file position
tell() returns the current file pointer position.
19. Which method moves the file pointer?
A) seek()
B) move()
C) position()
D) goto()
Answer: A) seek()
seek() moves the file pointer to a specific position.
20. Which module is used for serialization?
A) pickle
B) json
C) Both A and B
D) serialize
Answer: C) Both A and B
pickle and json both handle serialization.

14. Python Exception Handling — 20 MCQs

1. Which block is used to handle exceptions in Python?
A) try-except
B) try-catch
C) try-finally
D) catch-throw
Answer: A) try-except
Python uses try-except for exception handling.
2. Which block is always executed regardless of exception?
A) except
B) finally
C) catch
D) throw
Answer: B) finally
finally block executes regardless of exception.
3. Which keyword is used to raise an exception?
A) throw
B) raise
C) except
D) catch
Answer: B) raise
raise is used to throw exceptions.
4. What is the output of: try: 1/0 except ZeroDivisionError: print("Error")?
A) Error
B) 0
C) 1
D) None
Answer: A) Error
ZeroDivisionError is caught and "Error" is printed.
5. Which of the following is a built-in exception?
A) ValueError
B) TypeError
C) IndexError
D) All of the above
Answer: D) All of the above
All are built-in exceptions in Python.
6. Which block handles multiple exceptions?
A) except (Exception1, Exception2):
B) catch (Exception1, Exception2):
C) except Exception1, Exception2:
D) catch Exception1, Exception2:
Answer: A) except (Exception1, Exception2):
Multiple exceptions can be handled in one except block.
7. What is the output of: try: raise ValueError finally: print("Done")?
A) Done
B) Error
C) Done and Error
D) None
Answer: C) Done and Error
finally executes first, then the exception is raised.
8. Which exception is raised when a file is not found?
A) FileNotFoundError
B) IOError
C) Both A and B
D) OSError
Answer: C) Both A and B
FileNotFoundError and IOError both handle file errors.
9. Which exception is raised for invalid operations?
A) ValueError
B) TypeError
C) RuntimeError
D) All of the above
Answer: D) All of the above
All are exceptions for invalid operations.
10. What is the output of: try: print(1/0) except: print("Error") else: print("No Error")?
A) Error
B) No Error
C) Error No Error
D) None
Answer: A) Error
Exception occurs, so except block executes.
11. Which block is executed when no exception occurs?
A) except
B) else
C) finally
D) catch
Answer: B) else
else executes only if no exception occurs.
12. What is the output of: try: print(10/2) except ZeroDivisionError: print("Error")?
A) 5.0
B) 5
C) Error
D) None
Answer: A) 5.0
No exception occurs, so 5.0 is printed.
13. Which exception is raised when a list index is out of range?
A) IndexError
B) KeyError
C) TypeError
D) ValueError
Answer: A) IndexError
IndexError is raised for invalid list indices.
14. Which exception is raised for dictionary key errors?
A) KeyError
B) IndexError
C) TypeError
D) ValueError
Answer: A) KeyError
KeyError is raised for missing dictionary keys.
15. What is the output of: try: 10/2 except Exception: print("Error") else: print("Ok")?
A) Error
B) Ok
C) Error Ok
D) None
Answer: B) Ok
No exception, else block executes.
16. Which of the following is a valid exception handling structure?
A) try-except-finally
B) try-except-else-finally
C) try-finally
D) All of the above
Answer: D) All of the above
All combinations are valid in Python.
17. Which exception is raised when a variable is not defined?
A) NameError
B) TypeError
C) ValueError
D) SyntaxError
Answer: A) NameError
NameError is raised for undefined variables.
18. What is the output of: try: print("A") finally: print("B")?
A) A B
B) B A
C) A
D) B
Answer: A) A B
try executes first, then finally.
19. Which exception is raised for invalid type operations?
A) TypeError
B) ValueError
C) NameError
D) IndexError
Answer: A) TypeError
TypeError is raised for type mismatches.
20. How do you create a custom exception?
A) class MyError(Exception):
B) create MyError(Exception)
C) def MyError(Exception)
D) MyError = Exception()
Answer: A) class MyError(Exception):
Custom exceptions are created by subclassing Exception.

15. Python OOPs — 30 MCQs

1. What is the basic unit of Object-Oriented Programming?
A) Function
B) Class
C) Object
D) Module
Answer: B) Class
Classes are the fundamental building blocks of OOP.
2. Which concept hides the internal details of an object?
A) Inheritance
B) Polymorphism
C) Encapsulation
D) Abstraction
Answer: D) Abstraction
Abstraction hides implementation details.
3. Which keyword is used to create a class in Python?
A) class
B) object
C) struct
D) type
Answer: A) class
class is the keyword for class definition.
4. What is the constructor method in Python?
A) __init__
B) __new__
C) __str__
D) __repr__
Answer: A) __init__
__init__ is the constructor method.
5. What is inheritance in Python?
A) Creating a new class from an existing class
B) Creating multiple objects
C) Deleting a class
D) Modifying a class
Answer: A) Creating a new class from an existing class
Inheritance allows a class to inherit from another class.
6. Which of the following is NOT a pillar of OOP?
A) Inheritance
B) Polymorphism
C) Compilation
D) Encapsulation
Answer: C) Compilation
Compilation is not an OOP pillar.
7. What is polymorphism in Python?
A) Multiple forms of a function
B) Single form of a function
C) No function
D) All of the above
Answer: A) Multiple forms of a function
Polymorphism means many forms of the same function.
8. Which keyword is used to refer to the current object?
A) self
B) this
C) me
D) current
Answer: A) self
self refers to the current instance.
9. What is the output of: class A: pass; type(A())?
A) <class '__main__.A'>
B) <class 'object'>
C) Error
D) None
Answer: A) <class '__main__.A'>
type() returns the class of the object.
10. Which method is called when an object is deleted?
A) __del__
B) __delete__
C) __remove__
D) __destroy__
Answer: A) __del__
__del__ is the destructor method.
11. What is multiple inheritance?
A) Inheriting from one class
B) Inheriting from multiple classes
C) Inheriting from none
D) Inheriting from a single class
Answer: B) Inheriting from multiple classes
Multiple inheritance allows a class to inherit from multiple parents.
12. Which method returns a string representation of an object?
A) __str__
B) __repr__
C) Both A and B
D) __string__
Answer: C) Both A and B
Both __str__ and __repr__ return string representations.
13. What is encapsulation in OOP?
A) Hiding internal details
B) Exposing all details
C) No details
D) None of the above
Answer: A) Hiding internal details
Encapsulation wraps data and methods and hides internal details.
14. Which of the following is true about class variables?
A) Shared by all instances
B) Unique to each instance
C) Not accessible
D) Only in methods
Answer: A) Shared by 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)?
A) 5
B) Error
C) None
D) 0
Answer: A) 5
Instance variable x is set to 5.
16. Which of the following is a private attribute in Python?
A) __attr
B) _attr
C) attr
D) attr__
Answer: A) __attr
Double underscore indicates name mangling for privacy.
17. What is method overriding?
A) Redefining a method in child class
B) Deleting a method
C) Creating a new method
D) None of the above
Answer: A) Redefining a method in 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?
A) isinstance()
B) isInstance()
C) instanceof()
D) isClass()
Answer: A) isinstance()
isinstance() checks object class membership.
19. What is the output of: class A: x = 5; print(A.x)?
A) 5
B) Error
C) None
D) 0
Answer: A) 5
Class variable x is accessed using the class name.
20. Which of the following supports method overloading in Python?
A) Yes
B) No
C) Partial support
D) Depends on version
Answer: B) No
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)?
A) 5
B) 10
C) Error
D) None
Answer: B) 10
Instance variable x is changed to 10.
22. Which method is used to compare two objects?
A) __eq__
B) __cmp__
C) __compare__
D) __gt__
Answer: A) __eq__
__eq__ defines equality comparison.
23. What is the purpose of the super() function?
A) Call parent class methods
B) Delete parent class
C) Create parent class
D) None
Answer: A) Call parent class methods
super() calls methods from parent classes.
24. What is the output of: class A: pass; print(isinstance(A(), A))?
A) True
B) False
C) Error
D) None
Answer: A) True
isinstance() returns True for instance of the class.
25. Which of the following is a type of polymorphism?
A) Compile-time
B) Runtime
C) Both A and B
D) None
Answer: C) Both A and B
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)?
A) 5
B) Error
C) None
D) 0
Answer: B) Error
Private attribute __x cannot be accessed directly.
27. Which of the following creates an abstract class?
A) ABCMeta
B) abstract
C) virtual
D) interface
Answer: A) ABCMeta
ABCMeta is used to create abstract classes.
28. What is the purpose of the __call__ method?
A) Make object callable
B) Delete object
C) Create object
D) None
Answer: A) Make object callable
__call__ allows an object to be called like a function.
29. Which of the following is true about abstract methods?
A) Must be implemented in child class
B) Can be implemented in parent class
C) Are optional
D) None
Answer: A) Must be implemented in child class
Abstract methods must be implemented by subclasses.
30. What is the output of: class A: def __len__(self): return 5; print(len(A()))?
A) 5
B) Error
C) None
D) 0
Answer: A) 5
__len__ defines length, so len() returns 5.

16. Python Regular Expressions — 15 MCQs

1. Which module is used for regular expressions in Python?
A) regex
B) re
C) reg
D) pyregex
Answer: B) re
re module provides regex functionality.
2. Which method is used to find all matches of a pattern?
A) search()
B) match()
C) findall()
D) finditer()
Answer: C) findall()
findall() returns all matches as a list.
3. What is the output of: re.findall(r'\d+', 'a1b2c3')?
A) ['1', '2', '3']
B) ['a', 'b', 'c']
C) ['1b2c3']
D) Error
Answer: A) ['1', '2', '3']
\d+ matches one or more digits.
4. Which method searches for a pattern anywhere in the string?
A) match()
B) search()
C) findall()
D) fullmatch()
Answer: B) search()
search() finds pattern anywhere in the string.
5. What is the output of: re.sub(r'\d', 'X', 'a1b2c3')?
A) aXbXcX
B) a1b2c3
C) X X X
D) Error
Answer: A) aXbXcX
sub() replaces digits with 'X'.
6. Which pattern matches any whitespace character?
A) \s
B) \w
C) \d
D) \S
Answer: A) \s
\s matches whitespace characters.
7. What is the output of: re.match(r'\d+', '123abc')?
A) <re.Match object>
B) '123'
C) 'abc'
D) None
Answer: A) <re.Match object>
match() returns a match object if pattern matches.
8. Which pattern matches any character except newline?
A) .
B) \n
C) \t
D) \r
Answer: A) .
Dot matches any character except newline.
9. What is the output of: re.split(r'\s+', 'Hello World Python')?
A) ['Hello', 'World', 'Python']
B) ['Hello World Python']
C) ['H', 'e', 'l', 'l', 'o']
D) Error
Answer: A) ['Hello', 'World', 'Python']
split() splits on whitespace.
10. Which pattern matches any word character?
A) \w
B) \d
C) \s
D) \W
Answer: A) \w
\w matches letters, digits, and underscore.
11. What is the output of: re.findall(r'\w+', 'Hello World!')?
A) ['Hello', 'World']
B) ['Hello', 'World!']
C) ['Hello World']
D) Error
Answer: A) ['Hello', 'World']
\w+ matches word characters only.
12. Which method returns an iterator over matches?
A) finditer()
B) findall()
C) search()
D) match()
Answer: A) finditer()
finditer() returns an iterator of match objects.
13. What is the output of: re.compile(r'\d+').search('abc123def')?
A) <re.Match object>
B) '123'
C) 'abc'
D) None
Answer: A) <re.Match object>
search() returns match object for '123'.
14. Which pattern matches the start of a string?
A) ^
B) $
C) \A
D) \z
Answer: A) ^
^ matches the start of the string.
15. Which pattern matches the end of a string?
A) ^
B) $
C) \A
D) \Z
Answer: B) $
$ matches the end of the string.

17. Advanced Python — 25 MCQs

1. What is a generator in Python?
A) A function that returns a list
B) A function that yields values lazily
C) A class that creates objects
D) A module for data generation
Answer: B) A function that yields values lazily
Generators yield values one at a time.
2. What is a decorator in Python?
A) A function that modifies another function
B) A class that inherits from another
C) A module that adds features
D) A variable that holds data
Answer: A) A function that modifies another function
Decorators modify or enhance function behavior.
3. What is the output of: [x**2 for x in range(3)]?
A) [0, 1, 4]
B) [1, 4, 9]
C) [0, 1, 2]
D) [1, 2, 4]
Answer: A) [0, 1, 4]
List comprehension squares elements of range(3).
4. Which of the following is a context manager syntax?
A) with ... as
B) try ... finally
C) Both A and B
D) using ... as
Answer: C) Both A and B
with and try-finally both handle context management.
5. What is the output of: (lambda x: x**2)(3)?
A) 6
B) 9
C) 12
D) 3
Answer: B) 9
Lambda squares 3 to get 9.
6. Which of the following is true about async/await?
A) Used for asynchronous programming
B) Makes functions non-blocking
C) Both A and B
D) Only for threads
Answer: C) Both A and B
async/await enables asynchronous, non-blocking code.
7. What is the output of: sum(range(5))?
A) 10
B) 15
C) 20
D) 5
Answer: A) 10
sum of 0+1+2+3+4 = 10.
8. Which of the following is used for type hints?
A) typing
B) types
C) typehint
D) hint
Answer: A) typing
typing module provides type hint support.
9. What is the output of: dict([(1, 'a'), (2, 'b')])?
A) {1: 'a', 2: 'b'}
B) {1: 'a'}
C) Error
D) [1, 'a', 2, 'b']
Answer: A) {1: 'a', 2: 'b'}
dict() creates a dictionary from key-value pairs.
10. Which of the following is a mutable data type?
A) tuple
B) list
C) frozenset
D) str
Answer: B) list
Lists are mutable; tuples, frozensets, and strings are immutable.
11. What is the output of: zip([1,2], ['a','b'])?
A) [(1,'a'), (2,'b')]
B) [1,2,'a','b']
C) Error
D) zip object
Answer: D) zip object
zip() returns an iterator of tuples.
12. Which of the following is used for shallow copy?
A) copy.copy()
B) copy.deepcopy()
C) Both A and B
D) None
Answer: A) copy.copy()
copy() creates a shallow copy.
13. What is the output of: any([0, 1, 2])?
A) True
B) False
C) Error
D) None
Answer: A) True
any() returns True if any element is True.
14. Which of the following is used for deep copy?
A) copy.copy()
B) copy.deepcopy()
C) Both A and B
D) None
Answer: B) copy.deepcopy()
deepcopy() creates a recursive copy.
15. What is the output of: all([1, 2, 3])?
A) True
B) False
C) Error
D) None
Answer: A) True
all() returns True if all elements are True.
16. Which of the following is true about Python's GIL?
A) Prevents multiple threads from executing Python bytecode
B) Allows multiple threads to execute simultaneously
C) Only affects CPython
D) Both A and C
Answer: D) Both A and C
GIL limits thread execution in CPython.
17. What is the output of: sorted(['b','a','c'])?
A) ['a', 'b', 'c']
B) ['c', 'b', 'a']
C) ['b', 'a', 'c']
D) Error
Answer: A) ['a', 'b', 'c']
sorted() returns a sorted list.
18. Which of the following is used for parallel processing?
A) threading
B) multiprocessing
C) asyncio
D) All of the above
Answer: D) All of the above
All three provide concurrency mechanisms.
19. What is the output of: list(map(str, [1,2,3]))?
A) ['1', '2', '3']
B) [1, 2, 3]
C) ['1', '2', '3']
D) Error
Answer: A) ['1', '2', '3']
map() converts each number to string.
20. Which of the following is a frozen data type?
A) frozenset
B) tuple
C) str
D) All of the above
Answer: D) All of the above
frozenset, tuple, and str are all immutable.
21. What is the output of: reduce(lambda x, y: x+y, [1,2,3,4])?
A) 10
B) 24
C) 12
D) 6
Answer: A) 10
reduce() applies the function cumulatively.
22. Which of the following is true about Python's memory management?
A) Uses garbage collection
B) Uses reference counting
C) Both A and B
D) None
Answer: C) Both A and B
Python uses both reference counting and garbage collection.
23. What is the output of: list(enumerate(['a','b','c']))?
A) [(0,'a'),(1,'b'),(2,'c')]
B) ['a','b','c']
C) [0,1,2]
D) [('a',0),('b',1),('c',2)]
Answer: A) [(0,'a'),(1,'b'),(2,'c')]
enumerate() adds index to items.
24. Which of the following is a design pattern in Python?
A) Singleton
B) Factory
C) Observer
D) All of the above
Answer: D) All of the above
All are common design patterns.
25. What is the output of: list(filter(lambda x: x%2==0, [1,2,3,4,5]))?
A) [2,4]
B) [1,3,5]
C) [1,2,3,4,5]
D) Error
Answer: A) [2,4]
filter() keeps even numbers.

18. Python Standard Library — 20 MCQs

1. Which module provides time-related functions?
A) sys
B) time
C) os
D) datetime
Answer: B) time
time module provides time functions.
2. Which module provides random number generation?
A) sys
B) os
C) random
D) math
Answer: C) random
random module generates random numbers.
3. Which module is used for mathematical functions?
A) math
B) random
C) cmath
D) Both A and C
Answer: D) Both A and C
math and cmath handle mathematical functions.
4. Which module provides system-specific parameters?
A) os
B) sys
C) platform
D) All of the above
Answer: D) All of the above
All provide system-related information.
5. Which module is used for working with dates?
A) datetime
B) date
C) time
D) calendar
Answer: A) datetime
datetime module handles dates and times.
6. Which module is used for working with JSON?
A) json
B) pickle
C) csv
D) xml
Answer: A) json
json module handles JSON data.
7. Which module is used for file I/O operations?
A) os
B) io
C) Both A and B
D) file
Answer: C) Both A and B
os and io handle file I/O.
8. Which module is used for regular expressions?
A) re
B) regex
C) reg
D) expr
Answer: A) re
re module provides regex support.
9. Which module is used for data serialization?
A) pickle
B) json
C) Both A and B
D) serialize
Answer: C) Both A and B
Both pickle and json serialize data.
10. Which module is used for working with compressed files?
A) gzip
B) zipfile
C) tarfile
D) All of the above
Answer: D) All of the above
All handle compressed file formats.
11. Which module is used for working with paths?
A) os.path
B) pathlib
C) Both A and B
D) path
Answer: C) Both A and B
Both handle path operations.
12. Which module is used for working with collections?
A) collections
B) itertools
C) functools
D) All of the above
Answer: D) All of the above
All handle collections and functional operations.
13. Which module provides advanced iterators?
A) itertools
B) collections
C) functools
D) more_itertools
Answer: A) itertools
itertools provides iterator tools.
14. Which module is used for working with sockets?
A) socket
B) ssl
C) Both A and B
D) net
Answer: C) Both A and B
socket and ssl handle network communication.
15. Which module is used for working with email?
A) email
B) smtplib
C) Both A and B
D) mail
Answer: C) Both A and B
email and smtplib handle email operations.
16. Which module is used for working with XML?
A) xml
B) xml.etree
C) Both A and B
D) xmllib
Answer: C) Both A and B
xml and xml.etree handle XML.
17. Which module is used for working with HTML?
A) html
B) html.parser
C) Both A and B
D) htmllib
Answer: C) Both A and B
html and html.parser handle HTML.
18. Which module is used for working with CSV files?
A) csv
B) json
C) pickle
D) xml
Answer: A) csv
csv module handles CSV files.
19. Which module is used for working with temporary files?
A) tempfile
B) os
C) pathlib
D) io
Answer: A) tempfile
tempfile creates temporary files.
20. Which module is used for working with logging?
A) logging
B) log
C) syslog
D) logger
Answer: A) logging
logging module provides logging functionality.

19. Python Testing — 15 MCQs

1. Which module is used for unit testing in Python?
A) pytest
B) unittest
C) nose
D) All of the above
Answer: D) All of the above
unittest, pytest, and nose are testing frameworks.
2. Which class is used in the unittest module?
A) TestCase
B) Test
C) UnitTest
D) TestSuite
Answer: A) TestCase
unittest uses the TestCase class.
3. Which method is used to set up test fixtures?
A) setUp()
B) setup()
C) init()
D) prepare()
Answer: A) setUp()
setUp() runs before each test method.
4. Which method is used to tear down test fixtures?
A) tearDown()
B) teardown()
C) cleanup()
D) finish()
Answer: A) tearDown()
tearDown() runs after each test method.
5. Which assertion checks for equality?
A) assertEqual()
B) assertIs()
C) assertTrue()
D) assertFalse()
Answer: A) assertEqual()
assertEqual() checks if two values are equal.
6. Which assertion checks if a value is True?
A) assertTrue()
B) assertIs()
C) assertEqual()
D) assertIn()
Answer: A) assertTrue()
assertTrue() checks if value is True.
7. Which assertion checks if a value is False?
A) assertFalse()
B) assertTrue()
C) assertIs()
D) assertEqual()
Answer: A) assertFalse()
assertFalse() checks if value is False.
8. Which assertion checks if a value is in a collection?
A) assertIn()
B) assertContains()
C) assertIs()
D) assertEqual()
Answer: A) assertIn()
assertIn() checks membership.
9. Which tool is used for test coverage?
A) coverage
B) pytest-cov
C) Both A and B
D) testcov
Answer: C) Both A and B
coverage and pytest-cov measure test coverage.
10. Which assertion checks if two objects are the same?
A) assertIs()
B) assertEqual()
C) assertTrue()
D) assertFalse()
Answer: A) assertIs()
assertIs() checks identity.
11. Which method is used to run tests in unittest?
A) unittest.main()
B) unittest.run()
C) unittest.start()
D) unittest.execute()
Answer: A) unittest.main()
unittest.main() runs the test suite.
12. Which of the following is a testing framework?
A) pytest
B) unittest
C) doctest
D) All of the above
Answer: D) All of the above
All are Python testing frameworks.
13. Which assertion checks if an exception is raised?
A) assertRaises()
B) assertRaise()
C) assertException()
D) assertRaises()
Answer: A) assertRaises()
assertRaises() checks for expected exceptions.
14. Which tool is used for mocking in tests?
A) unittest.mock
B) mock
C) Both A and B
D) patch
Answer: C) Both A and B
unittest.mock and mock provide mocking.
15. Which decorator is used for test fixtures in pytest?
A) @pytest.fixture
B) @fixture
C) @test_fixture
D) @pytest.setup
Answer: A) @pytest.fixture
@pytest.fixture defines test fixtures.

20. Python Best Practices — 15 MCQs

1. Which style guide is recommended for Python?
A) PEP 8
B) PEP 20
C) PEP 257
D) PEP 484
Answer: A) PEP 8
PEP 8 is the Python style guide.
2. Which indentation is recommended in Python?
A) 2 spaces
B) 4 spaces
C) 8 spaces
D) 1 tab
Answer: B) 4 spaces
PEP 8 recommends 4 spaces for indentation.
3. Which naming convention is used for variables?
A) snake_case
B) camelCase
C) PascalCase
D) UPPERCASE
Answer: A) snake_case
Variables use snake_case in Python.
4. Which naming convention is used for classes?
A) snake_case
B) camelCase
C) PascalCase
D) UPPERCASE
Answer: C) PascalCase
Classes use PascalCase in Python.
5. What is the Python Zen?
A) PEP 20
B) PEP 8
C) PEP 257
D) PEP 484
Answer: A) PEP 20
PEP 20 is the Zen of Python.
6. Which of the following is a Python principle?
A) Simple is better than complex
B) Explicit is better than implicit
C) Both A and B
D) None
Answer: C) Both A and B
Both are principles from the Zen of Python.
7. Which tool is used for code linting?
A) flake8
B) pylint
C) Both A and B
D) black
Answer: C) Both A and B
flake8 and pylint are linters.
8. Which tool is used for code formatting?
A) black
B) autopep8
C) Both A and B
D) yapf
Answer: C) Both A and B
black, autopep8, and yapf are formatters.
9. Which of the following is a good practice?
A) Write comments
B) Use meaningful variable names
C) Keep functions small
D) All of the above
Answer: D) All of the above
All are good programming practices.
10. Which of the following is NOT a best practice?
A) Using meaningful names
B) Writing tests
C) Using global variables unnecessarily
D) Following PEP 8
Answer: C) Using global variables unnecessarily
Global variables should be avoided.
11. Which of the following is a docstring convention?
A) PEP 257
B) PEP 8
C) PEP 20
D) PEP 484
Answer: A) PEP 257
PEP 257 covers docstring conventions.
12. Which tool is used for type checking?
A) mypy
B) pytype
C) Both A and B
D) flake8
Answer: C) Both A and B
mypy and pytype are type checkers.
13. Which of the following is important for code readability?
A) Consistent indentation
B) Meaningful comments
C) Proper spacing
D) All of the above
Answer: D) All of the above
All contribute to code readability.
14. Which tool is used for dependency management?
A) pip
B) poetry
C) Both A and B
D) conda
Answer: C) Both A and B
pip, poetry, and conda manage dependencies.
15. Which of the following is a security best practice?
A) Validate input
B) Use parameterized queries
C) Keep dependencies updated
D) All of the above
Answer: D) All of the above
All are security best practices.

21. MySQL with Python — 25 MCQs

1. Which module is used to connect MySQL with Python?
A) mysql.connector
B) MySQLdb
C) PyMySQL
D) All of the above
Answer: D) All of the above
All are MySQL connectors for Python.
2. Which method is used to execute a SQL query?
A) query()
B) execute()
C) run()
D) select()
Answer: B) execute()
execute() runs SQL queries.
3. Which method fetches all rows from a query?
A) fetchall()
B) fetchone()
C) fetchmany()
D) fetch()
Answer: A) fetchall()
fetchall() returns all rows.
4. Which method commits changes to the database?
A) commit()
B) save()
C) flush()
D) update()
Answer: A) commit()
commit() saves changes to the database.
5. Which method rolls back changes?
A) rollback()
B) undo()
C) cancel()
D) revert()
Answer: A) rollback()
rollback() undoes uncommitted changes.
6. Which function creates a connection to MySQL?
A) connect()
B) mysql.connect()
C) mysql.connector.connect()
D) Both A and C
Answer: D) Both A and C
connect() is used in both modules.
7. Which method creates a cursor in MySQL?
A) cursor()
B) create_cursor()
C) get_cursor()
D) make_cursor()
Answer: A) cursor()
cursor() creates a cursor object.
8. Which SQL statement is used to insert data?
A) INSERT INTO
B) ADD INTO
C) PUT INTO
D) CREATE
Answer: A) INSERT INTO
INSERT INTO adds data to a table.
9. Which SQL statement is used to retrieve data?
A) GET
B) SELECT
C) RETRIEVE
D) FETCH
Answer: B) SELECT
SELECT retrieves data from a table.
10. Which SQL statement is used to update data?
A) CHANGE
B) MODIFY
C) UPDATE
D) ALTER
Answer: C) UPDATE
UPDATE modifies existing data.
11. Which SQL statement is used to delete data?
A) REMOVE
B) DROP
C) DELETE FROM
D) CLEAR
Answer: C) DELETE FROM
DELETE FROM removes data from a table.
12. Which SQL clause is used to filter results?
A) FILTER
B) WHERE
C) CONDITION
D) HAVING
Answer: B) WHERE
WHERE filters query results.
13. Which SQL clause is used to sort results?
A) SORT BY
B) ORDER BY
C) GROUP BY
D) ARRANGE BY
Answer: B) ORDER BY
ORDER BY sorts query results.
14. Which SQL keyword is used to prevent SQL injection?
A) Parameterized queries
B) Prepared statements
C) Both A and B
D) None
Answer: C) Both A and B
Parameterized queries/prepared statements prevent SQL injection.
15. Which exception is raised for MySQL errors?
A) mysql.connector.Error
B) MySQLdb.Error
C) Both A and B
D) DatabaseError
Answer: C) Both A and B
Both modules have their own Error classes.
16. Which method checks if a connection is open?
A) is_connected()
B) is_open()
C) connected()
D) open()
Answer: A) is_connected()
is_connected() checks connection status.
17. Which method closes a MySQL connection?
A) close()
B) disconnect()
C) Both A and B
D) end()
Answer: C) Both A and B
close() and disconnect() close connections.
18. Which method returns the last inserted ID?
A) lastrowid
B) insert_id()
C) Both A and B
D) last_id()
Answer: C) Both A and B
Both return the last inserted ID.
19. Which SQL statement creates a table?
A) MAKE TABLE
B) CREATE TABLE
C) NEW TABLE
D) ADD TABLE
Answer: B) CREATE TABLE
CREATE TABLE creates a new table.
20. Which SQL statement drops a table?
A) DROP TABLE
B) REMOVE TABLE
C) DELETE TABLE
D) CLEAR TABLE
Answer: A) DROP TABLE
DROP TABLE deletes a table.
21. Which SQL keyword is used for joining tables?
A) JOIN
B) UNION
C) Both A and B
D) COMBINE
Answer: C) Both A and B
JOIN and UNION combine tables.
22. Which function returns the number of rows affected?
A) rowcount
B) affected_rows()
C) Both A and B
D) rows_affected()
Answer: C) Both A and B
Both return the number of affected rows.
23. Which type of join returns all rows from both tables?
A) INNER JOIN
B) LEFT JOIN
C) FULL OUTER JOIN
D) RIGHT JOIN
Answer: C) FULL OUTER JOIN
FULL OUTER JOIN returns all rows from both tables.
24. Which SQL function is used for counting rows?
A) COUNT()
B) SUM()
C) AVG()
D) MAX()
Answer: A) COUNT()
COUNT() counts rows.
25. Which SQL function is used for calculating average?
A) AVG()
B) SUM()
C) COUNT()
D) MAX()
Answer: A) AVG()
AVG() calculates the average.

22. Python Threads — 20 MCQs

1. Which module is used for threading in Python?
A) thread
B) threading
C) multiprocessing
D) async
Answer: B) threading
threading module provides thread support.
2. Which method starts a thread in Python?
A) run()
B) start()
C) begin()
D) execute()
Answer: B) start()
start() begins thread execution.
3. Which method waits for a thread to finish?
A) wait()
B) join()
C) stop()
D) finish()
Answer: B) join()
join() waits for thread completion.
4. Which of the following is true about threads?
A) Threads share memory
B) Threads have their own memory
C) Threads are processes
D) None
Answer: A) Threads share memory
Threads within a process share memory.
5. What is a daemon thread?
A) A thread that runs in the background
B) A thread that runs in the foreground
C) A thread that stops immediately
D) A thread with high priority
Answer: A) A thread that runs in the background
Daemon threads run in the background.
6. Which method checks if a thread is alive?
A) is_alive()
B) is_running()
C) alive()
D) running()
Answer: A) is_alive()
is_alive() checks if thread is running.
7. Which function returns the current thread?
A) current_thread()
B) current()
C) get_current()
D) this_thread()
Answer: A) current_thread()
current_thread() returns the current thread.
8. Which function returns the number of active threads?
A) active_count()
B) count_active()
C) num_threads()
D) thread_count()
Answer: A) active_count()
active_count() returns the number of active threads.
9. Which lock prevents race conditions?
A) Lock
B) RLock
C) Semaphore
D) All of the above
Answer: D) All of the above
All are synchronization primitives.
10. What is the GIL in Python?
A) Global Interpreter Lock
B) General Instruction Lock
C) Global Instruction Lock
D) General Interpreter Lock
Answer: A) Global Interpreter Lock
GIL prevents multiple threads from executing Python bytecode.
11. Which of the following is NOT affected by GIL?
A) CPU-bound threads
B) I/O-bound threads
C) Both A and B
D) None
Answer: B) I/O-bound threads
I/O-bound threads release GIL during I/O operations.
12. Which method is used to acquire a lock?
A) acquire()
B) lock()
C) get()
D) take()
Answer: A) acquire()
acquire() locks the resource.
13. Which method is used to release a lock?
A) release()
B) unlock()
C) free()
D) put()
Answer: A) release()
release() unlocks the resource.
14. Which of the following is a thread-safe data structure?
A) queue.Queue
B) list
C) dict
D) set
Answer: A) queue.Queue
Queue is thread-safe by default.
15. What is a deadlock?
A) Two or more threads waiting for each other
B) A thread that stops
C) A thread that crashes
D) None
Answer: A) Two or more threads waiting for each other
Deadlock occurs when threads wait for each other.
16. Which function lists all active threads?
A) enumerate()
B) list_threads()
C) get_threads()
D) active_threads()
Answer: A) enumerate()
enumerate() returns a list of active threads.
17. Which of the following is a thread pool executor?
A) ThreadPoolExecutor
B) ProcessPoolExecutor
C) Both A and B
D) PoolExecutor
Answer: C) Both A and B
Both are pool executors from concurrent.futures.
18. Which module provides thread pools?
A) concurrent.futures
B) threading
C) multiprocessing
D) asyncio
Answer: A) concurrent.futures
concurrent.futures provides thread and process pools.
19. Which of the following is true about thread-local data?
A) Unique to each thread
B) Shared across threads
C) Global to all threads
D) None
Answer: A) Unique to each thread
Thread-local data is unique per thread.
20. Which class is used for thread-local data?
A) threading.local
B) thread.local
C) local
D) Both A and C
Answer: D) Both A and C
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)?
A) 6
B) 5
C) 7
D) 8
Answer: A) 6
2*3=6, 6//4=1, 1+5=6.
2. What is the output of: print("Python"[-1])?
A) P
B) n
C) o
D) h
Answer: B) n
Index -1 accesses the last character.
3. What is the output of: print(type([]))?
A) <class 'list'>
B) <class 'tuple'>
C) <class 'set'>
D) <class 'dict'>
Answer: A) <class 'list'>
[] creates a list.
4. What is the output of: [1,2,3][1:2]?
A) [1]
B) [2]
C) [2,3]
D) [1,2]
Answer: B) [2]
Slicing [1:2] gets the element at index 1.
5. What is the output of: bool([])?
A) True
B) False
C) Error
D) None
Answer: B) False
Empty lists are False.
6. What is the output of: set([1,2,2,3,3,3])?
A) {1,2,3}
B) [1,2,3]
C) (1,2,3)
D) {1,2,2,3,3,3}
Answer: A) {1,2,3}
set() removes duplicates.
7. What is the output of: print(3 > 2 > 1)?
A) True
B) False
C) Error
D) None
Answer: A) True
Chained comparison: 3>2 AND 2>1.
8. What is the output of: print(5 // 2)?
A) 2.5
B) 2
C) 3
D) 2.0
Answer: B) 2
Floor division returns the integer part.
9. What is the output of: print(2 ** 3 ** 2)?
A) 512
B) 64
C) 256
D) 128
Answer: A) 512
Right associativity: 3**2=9, 2**9=512.
10. What is the output of: print("Hello" + "World")?
A) HelloWorld
B) Hello World
C) "Hello" "World"
D) Error
Answer: A) HelloWorld
+ concatenates strings without spaces.
11. What is the output of: print(list(range(3)))?
A) [0,1,2]
B) [1,2,3]
C) [0,1,2,3]
D) [1,2]
Answer: A) [0,1,2]
range(3) generates 0,1,2.
12. What is the output of: print("Python".upper())?
A) PYTHON
B) python
C) Python
D) pYTHON
Answer: A) PYTHON
upper() converts to uppercase.
13. What is the output of: print(10 % 3)?
A) 3
B) 1
C) 2
D) 0
Answer: B) 1
10 divided by 3 gives remainder 1.
14. What is the output of: print(5 & 3)?
A) 1
B) 2
C) 3
D) 4
Answer: A) 1
5(101) & 3(011) = 1(001).
15. What is the output of: print(2 << 3)?
A) 8
B) 16
C) 4
D) 12
Answer: B) 16
2 << 3 = 2 * 8 = 16.
16. What is the output of: print(15 >> 2)?
A) 3
B) 60
C) 7
D) 15
Answer: A) 3
15 >> 2 = 15 // 4 = 3.
17. What is the output of: print(not 5 > 3)?
A) True
B) False
C) Error
D) None
Answer: B) False
5 > 3 is True, not True is False.
18. What is the output of: print(len("Python"))?
A) 5
B) 6
C) 7
D) 4
Answer: B) 6
"Python" has 6 characters.
19. What is the output of: print("Hello"[1:3])?
A) el
B) Hel
C) lo
D) ell
Answer: A) el
Index 1 to 3 (exclusive): e, l.
20. What is the output of: print("A" * 3)?
A) AAA
B) A A A
C) A
D) Error
Answer: A) AAA
* repeats strings.
21. What is the output of: print(1, 2, 3, sep="-")?
A) 1-2-3
B) 1 2 3
C) 1,2,3
D) 123
Answer: A) 1-2-3
sep defines the separator.
22. What is the output of: print(3 + 4 * 2)?
A) 14
B) 11
C) 10
D) 12
Answer: B) 11
4*2=8, 3+8=11.
23. What is the output of: print((3 + 4) * 2)?
A) 14
B) 11
C) 10
D) 12
Answer: A) 14
3+4=7, 7*2=14.
24. What is the output of: print("Python".replace("t", "p"))?
A) Pypython
B) Pypon
C) Python
D) Pypthon
Answer: A) Pypython
replaces 't' with 'p'.
25. What is the output of: print(5 ^ 2)?
A) 7
B) 3
C) 8
D) 10
Answer: A) 7
5(101) ^ 2(010) = 7(111).
26. What is the output of: print(~5)?
A) -6
B) -5
C) 4
D) 6
Answer: A) -6
~x = -x - 1.
27. What is the output of: print(5 ^ 2 ^ 3)?
A) 4
B) 6
C) 8
D) 10
Answer: A) 4
5^2=7, 7^3=4.
28. What is the output of: print("Python".count("t"))?
A) 1
B) 2
C) 3
D) 0
Answer: B) 2
"Python" has 2 't's.
29. What is the output of: print("Python".find("o"))?
A) 2
B) 3
C) 4
D) 5
Answer: C) 4
Index of 'o' is 4.
30. What is the output of: print("Python".index("n"))?
A) 4
B) 5
C) 6
D) 3
Answer: B) 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 →
Previous: Python Case Studies Next: Practice Problems →