Python Programming · Practice by type
Python Programming MCQ Questions and Answers
Multiple-choice questions on Python Programming concepts and common errors, topic by topic, each with the answer and a clear explanation.
- 615 questions
- 25 topics
- Answers checked on a real compiler
Python Basics and Syntax 25 questions
- How does CPython run a .py file? Easy
- How does Python mark a block of code? Easy
- Writing a comment in Python Easy
- Which name is a valid identifier? Easy
- Which word is a Python keyword? Easy
- Default values of sep and end in print() Easy
- What type does input() return? Easy
- Indentation recommended by PEP 8 Easy
- Purpose of if __name__ == "__main__" Medium
- What is a docstring? Medium
- Continuing a statement on the next line Medium
- What does pass do? Easy
- Which statement about Python is false? Medium
- Several statements on one line Easy
- When are syntax errors reported? Hard
- Error: expected an indented block Easy
- Error: unexpected indent Easy
- Error: missing colon after if Easy
- Error: a keyword used as a variable name Easy
- Error: Python 2 style print Easy
- Error: apostrophe inside a single-quoted string Medium
- Error: Print with a capital P Easy
- Error: joining a string and a number Easy
- Error: arithmetic on input() Medium
- Bug: the sum of two inputs is wrong Medium
Variables and Data Types 25 questions
- What is a variable in Python? Easy
- Dynamic and strong typing Medium
- Which type is immutable? Easy
- Largest value of an int Easy
- Which value is truthy? Medium
- is versus == Medium
- The relationship between bool and int Medium
- What is None? Easy
- Converting "12.5" with int() Medium
- How round() treats .5 Hard
- Does b = a copy a list? Medium
- Writing a complex number Easy
- Why prefer isinstance()? Hard
- Changing a character of a string Medium
- Why is 0.1 + 0.2 not exactly 0.3? Medium
- Error: using a variable before assigning it Easy
- Error: int() on a decimal string Easy
- Error: len() of a number Easy
- Error: a space in a variable name Easy
- Error: changing one character of a string Medium
- Error: a variable named str Medium
- Error: a number with a leading zero Medium
- Bug: comparing floats with == Medium
- Bug: bool("False") is True Hard
- Bug: the backup changes too Medium
Operators and Expressions 25 questions
- The result type of / Easy
- Floor division with a negative number Medium
- The sign of the remainder Medium
- Associativity of ** Medium
- Unary minus and ** Medium
- What a chained comparison means Easy
- What or returns Medium
- Short-circuit evaluation Medium
- What does ^ do? Easy
- The value of ~x Medium
- in with a dictionary Medium
- Incrementing a variable Easy
- The walrus operator Medium
- Precedence of not, and, or Hard
- x *= 2 + 3 Hard
- Error: average of an empty list Easy
- Error: = instead of == in a condition Easy
- Error: using ++ Easy
- Error: multiplying two strings Medium
- Error: an incomplete range check Easy
- Bug: grade == "A" or "B" Medium
- Bug: average loses its decimals Easy
- Bug: wrong temperature conversion Medium
- Bug: ^ used as a power operator Medium
- Error: comparing a string with a number Medium
Conditional Statements 25 questions
- The keyword for "else if" Easy
- How many branches of an if-elif chain run? Easy
- Which if does an else belong to? Medium
- An empty list as a condition Easy
- Python's ternary syntax Easy
- any() and all() on an empty list Hard
- Which version added match-case? Easy
- Fall-through in match-case Medium
- The default case in match Easy
- A bare name in a case Hard
- What is a guard? Medium
- Variables created inside an if Medium
- Testing one value against several Medium
- The right way to test for None Medium
- Why use guard clauses? Medium
- Error: else if instead of elif Easy
- Error: elif after else Easy
- Error: an if block with only a comment Medium
- Error: else indented differently from its if Medium
- Error: a constant name in a case Hard
- Error: a variable assigned in only one branch Medium
- Bug: the topper is graded as a pass Medium
- Bug: two labels printed for one temperature Easy
- Bug: menu choice 1 is "invalid" Medium
- Bug: an 18-year-old cannot vote Easy
Loops 25 questions
- Is the stop value of range included? Easy
- Counting down with range Easy
- When does a loop's else run? Medium
- What does continue do? Easy
- break in nested loops Medium
- do-while in Python Easy
- The loop variable after the loop Medium
- What does enumerate() give? Easy
- zip() with lists of different lengths Medium
- for n in 5 Easy
- Looping over a dictionary Easy
- Removing items while looping Hard
- A float step in range Medium
- When is a while condition checked? Easy
- How many times does the inner body run? Medium
- Error: looping over an int Easy
- Error: an index one past the end Easy
- Error: a for loop without a colon Easy
- Error: break outside a loop Medium
- Bug: the sum of 1 to 10 is 45 Easy
- Bug: not every even number is removed Medium
- Error: deleting dict keys during iteration Hard
- Bug: the total is only the last mark Easy
- Bug: "not found" printed several times Medium
- Error: a decimal step in range Medium
Strings 25 questions
- Are strings mutable? Easy
- What does s[-1] mean? Easy
- A slice beyond the end Medium
- Reversing a string Easy
- find() versus index() Medium
- split() with no argument Medium
- join() with numbers Medium
- isdigit() on "-5" Medium
- How strings are compared Medium
- Why does s.upper() "not work"? Easy
- What is a raw string? Medium
- count() and overlapping matches Hard
- ord() and chr() Easy
- Triple-quoted strings Easy
- An f-string format spec Medium
- Error: index equal to the length Easy
- Error: joining numbers Easy
- Error: index() of a missing substring Medium
- Error: double quotes inside a double-quoted string Easy
- Bug: the name is not converted to capitals Easy
- Bug: "python" not found at the start Hard
- Bug: word count includes empty strings Medium
- Bug: "Madam" is not a palindrome Medium
- Error: append() on a string Easy
- Error: repeating a string a float number of times Medium
Lists 25 questions
- append() versus extend() Easy
- What does list.sort() return? Easy
- remove() versus pop() Easy
- Properties of a list Easy
- The [[0] * 3] * 3 trap Hard
- What can sorted() take? Medium
- What is a stable sort? Hard
- Shallow copy of a nested list Medium
- insert() at an index past the end Medium
- A float as a list index Medium
- The cost of pop(0) Hard
- a += [x] versus a = a + [x] Hard
- remove() with duplicates Easy
- Sorting a list of mixed types Medium
- What does a[:] create? Easy
- Error: pop() from an empty list Easy
- Error: remove() of an absent item Easy
- Error: sorting numbers and strings together Medium
- Error: marks = marks.sort() Medium
- Bug: append() where extend() was meant Easy
- Bug: one seat booked, a whole column booked Hard
- Bug: "last three" gives two items Medium
- Error: a missing comma in a list literal Easy
- Error: the middle element with / Medium
- Error: push() on a list Easy
Tuples 25 questions
- Creating a one-item tuple Easy
- What immutability means for tuples Easy
- How many methods does a tuple have? Medium
- What creates a tuple? Medium
- A list inside a tuple Medium
- Unpacking the wrong number of values Easy
- Returning several values Easy
- Tuples as dictionary keys Medium
- How tuples are compared Medium
- sorted() on a tuple Medium
- The type of a starred target Medium
- Why use namedtuple? Medium
- Adding an item to a tuple Easy
- t[0] += [x] where t[0] is a list Hard
- When to prefer a tuple Easy
- Error: assigning to a tuple item Easy
- Error: append() on a tuple Easy
- Error: too many values to unpack Easy
- Error: not enough values to unpack Medium
- Bug: looping over ("red") prints letters Medium
- Error: a list inside a tuple key Medium
- Error: adding an int to a tuple Easy
- Error: index() of an absent value Easy
- Bug: sorted tuple never equals the expected one Medium
- Error: += on a list stored in a tuple Hard
Sets 25 questions
- Creating an empty set Easy
- Properties of a set Easy
- Indexing a set Easy
- remove() versus discard() Easy
- The intersection operator Easy
- Symmetric difference Medium
- Is set difference commutative? Medium
- Which item can be added to a set? Medium
- 1, True and 1.0 in a set Hard
- Why frozenset? Medium
- Why test membership in a set? Medium
- Proper subset Medium
- union() versus update() Medium
- Order of elements in a set Medium
- A set comprehension Easy
- Error: remove() of a missing element Easy
- Error: indexing a set Easy
- Error: a list inside a set Medium
- Error: {} used as an empty set Medium
- Error: adding two sets with + Easy
- Bug: unique visits come out in the wrong order Medium
- Bug: "Python" and "python" counted twice Easy
- Error: removing elements while looping over a set Hard
- Bug: union() does not add the new members Medium
- Error: pop() from an empty set Medium
Dictionaries 25 questions
- What can be a dictionary key? Easy
- d[key] versus d.get(key) Easy
- What does in test for a dict? Easy
- Are dictionaries ordered? Medium
- A key written twice Medium
- What does popitem() remove? Medium
- Are keys() views copies? Hard
- What does setdefault() do? Medium
- What is defaultdict for? Medium
- Which value wins in a merge? Medium
- dict.fromkeys() with a list Hard
- Counter.most_common() Medium
- The key with the largest value Medium
- 1 and True as keys Hard
- The cost of a dictionary lookup Easy
- Error: reading a missing key with [] Easy
- Error: a list as a dictionary key Easy
- Error: append() on a dictionary Easy
- Error: dict() from items of the wrong length Hard
- Error: sum() over a dictionary Medium
- Bug: searching a value with in Easy
- Bug: one student's mark appears for everyone Hard
- Bug: every word is counted once Medium
- Error: a missing colon in a dict literal Easy
- Bug: changing a copy changes the original Medium
Functions 25 questions
- A function without return Easy
- The type of *args Easy
- The type of **kwargs Easy
- When are default values evaluated? Medium
- Order of default parameters Easy
- Parameters after * Medium
- Parameters before / Hard
- The LEGB rule Medium
- Why the global keyword? Medium
- What does nonlocal do? Medium
- How arguments are passed Medium
- Cause of UnboundLocalError Hard
- Unpacking in a call Medium
- Functions as objects Easy
- print versus return Easy
- Error: a required argument is missing Easy
- Error: a default parameter before a required one Easy
- Error: incrementing a global without global Medium
- Bug: the square is None Easy
- Bug: each order contains the previous orders Hard
- Error: an argument given twice Medium
- Error: a positional argument after a keyword argument Easy
- Error: too many positional arguments Easy
- Error: using the result of a function that prints Medium
- Error: calling a function before defining it Easy
Recursion 25 questions
- The purpose of a base case Easy
- Recursion without a base case Easy
- Python's recursion limit Easy
- Tail-call optimisation Medium
- Cost of naive recursive Fibonacci Medium
- What does @lru_cache do? Medium
- Code after the recursive call Medium
- Local variables in recursive calls Medium
- Moves for Tower of Hanoi Medium
- Recursive binary search Medium
- Space used by linear recursion Hard
- Mutual recursion Medium
- lru_cache and list arguments Hard
- Where recursion fits best Easy
- The base case of factorial Easy
- Error: no base case Easy
- Error: a base case that is skipped Medium
- Bug: every factorial is 0 Easy
- Error: the recursive result is not returned Medium
- Bug: the "reversed" string is unchanged Medium
- Bug: "abca" is called a palindrome Medium
- Error: correct recursion that is too deep Hard
- Error: lru_cache with a list argument Hard
- Error: a def line without a colon Easy
- Error: a base case that does not cover the empty list Hard
Lambda Functions 25 questions
- What can a lambda body contain? Easy
- return inside a lambda Easy
- The name of a lambda Medium
- lambda versus def Easy
- What does map() return? Medium
- What filter() keeps Easy
- Where is reduce()? Easy
- The late-binding trap Hard
- if-else in a lambda Medium
- Sorting by two keys Medium
- Passing a function to map Medium
- operator.itemgetter Medium
- What does functools.partial do? Medium
- reduce() on an empty list Hard
- Assigning a lambda to a name Medium
- Error: return inside a lambda Easy
- Error: an assignment in a lambda Medium
- Error: calling a lambda with too few arguments Easy
- Bug: every handler reports the last item Hard
- Bug: the total of the prices is 0 Medium
- Error: a key that returns None for some items Hard
- Bug: zeros dropped and negatives kept Medium
- Error: reduce() of an empty list Medium
- Bug: numeric strings sort in the wrong order Easy
- Error: passing a call result instead of a function Medium
List Comprehensions 25 questions
- What does a list comprehension produce? Easy
- Where does a filter go? Easy
- Where does if-else go? Medium
- Order of several for clauses Medium
- Flattening a matrix Medium
- Round brackets around a comprehension Easy
- Iterating a generator twice Medium
- Does the loop variable leak? Medium
- A dict comprehension Easy
- Why use a generator in sum()? Medium
- Two if clauses in a row Hard
- Comprehensions for side effects Medium
- len() of a generator Medium
- A safe 2-D grid Medium
- A set comprehension Easy
- Error: else in the filter position Medium
- Error: a conditional expression without else Medium
- Error: using the loop variable after the comprehension Medium
- Error: for clauses in the wrong order Hard
- Bug: the second count is 0 Medium
- Error: len() of a generator expression Medium
- Bug: a comprehension used only to print Medium
- Bug: negatives removed instead of replaced Easy
- Error: converting bad data inside a comprehension Easy
- Bug: words of equal length overwrite each other Medium
Modules and Packages 25 questions
- What is a module? Easy
- import x versus from x import y Easy
- Importing a module twice Medium
- What is sys.path? Medium
- The value of __name__ Easy
- The role of __init__.py Medium
- Where relative imports work Hard
- What does __all__ control? Medium
- Why avoid import *? Medium
- A file named random.py Medium
- Re-running a module Medium
- Why use a virtual environment? Easy
- ModuleNotFoundError versus ImportError Hard
- Using an import alias Easy
- What is requirements.txt for? Easy
- Error: a misspelt module name Easy
- Error: importing a name the module does not have Easy
- Error: calling a function without the module prefix Easy
- Error: a function the module does not have Easy
- Error: a variable that replaces a module Medium
- Error: from os import * replaces open() Hard
- Error: import math.sqrt Medium
- Error: a relative import in a script Hard
- Bug: test output appears when the module is imported Medium
- Bug: the edited setting is not picked up Hard
Exception Handling 25 questions
- When does the else of a try run? Easy
- When does finally run? Easy
- Which except clause runs? Medium
- Catching several types in one clause Easy
- The exception raised by int("abc") Easy
- Why avoid a bare except? Medium
- Base class for custom exceptions Easy
- raise with no arguments Medium
- What does raise … from do? Hard
- Is KeyboardInterrupt an Exception? Hard
- Catching a syntax error Medium
- When to use assert Medium
- What is EAFP? Medium
- The name bound by except … as e Hard
- raise with a string Easy
- Error: catching the wrong exception type Easy
- Error: a try with neither except nor finally Easy
- Error: else placed before except Medium
- Bug: a valid number is reported as invalid Medium
- Bug: the specific message never appears Medium
- Error: raising a string Easy
- Error: a misspelt exception name in except Hard
- Bug: money disappears on a failed transfer Hard
- Error: using a value that was never assigned Medium
- Error: re-raising when nothing is being handled Hard
File Handling 25 questions
- Opening an existing file with "w" Easy
- The append mode Easy
- The "x" mode Medium
- Why use with? Easy
- What readline() returns Medium
- What readlines() returns Easy
- Does write() add a newline? Easy
- The return value of write() Medium
- Reading a huge file Medium
- Reading a file a second time Medium
- What binary mode returns Medium
- Opening a missing file for reading Easy
- Characters versus bytes Hard
- Types read from a CSV file Medium
- "r+" versus "w+" Hard
- Error: reading a file that does not exist Easy
- Error: writing to a file opened for reading Easy
- Error: reading after the with block Medium
- Error: writing a number to a text file Easy
- Error: writing text to a binary file Medium
- Bug: the log keeps only the last entry Easy
- Bug: all names end up on one line Easy
- Bug: the second count is 0 Medium
- Error: "x" mode on an existing file Medium
- Bug: a valid user is denied Medium
OOP in Python 25 questions
- What is self? Easy
- The role of __init__ Easy
- Class attributes Easy
- Assigning a class attribute through an instance Medium
- __str__ versus __repr__ Medium
- == without __eq__ Medium
- Double underscore attributes Hard
- A single leading underscore Easy
- What does @property give you? Medium
- The first argument of a classmethod Medium
- What is a staticmethod? Medium
- A list as a class attribute Hard
- What @dataclass generates Medium
- A method defined without self Easy
- The pillars of OOP Easy
- Error: a method without self Easy
- Error: creating an object without a required argument Easy
- Error: an attribute name typo Easy
- Error: an attribute used without self. Medium
- Bug: every cart shows the same items Medium
- Error: assigning to a read-only property Medium
- Error: _init_ instead of __init__ Hard
- Error: a class header without a colon Easy
- Error: __str__ that prints instead of returning Medium
- Bug: two identical points are "different" Medium
Inheritance and Polymorphism 25 questions
- Inheriting from a class Easy
- What does super() do? Easy
- Method overriding Easy
- A parent method calling an overridden method Medium
- What is the MRO? Medium
- The MRO of a diamond Hard
- Instantiating an abstract class Medium
- Duck typing Medium
- isinstance with subclasses Easy
- Method overloading in Python Medium
- Overloading + Easy
- Why __radd__? Hard
- Returning NotImplemented Hard
- Forgetting super().__init__() Medium
- Inheritance or composition? Medium
- Error: creating an object of an abstract class Easy
- Error: parent attributes never initialised Medium
- Error: super().__init__() without the required argument Medium
- Error: an impossible method resolution order Hard
- Bug: the parent method runs instead of the override Easy
- Bug: every manager is labelled an employee Medium
- Error: + on objects without __add__ Easy
- Error: sum() of objects with only __add__ Hard
- Bug: the shared base is initialised twice Hard
- Error: an override that calls itself Medium
Iterators and Generators 25 questions
- Iterable versus iterator Easy
- What signals the end of iteration? Easy
- next() with a default Easy
- What makes a generator function? Easy
- Calling a generator function Medium
- yield versus return Easy
- Why generators save memory Medium
- Reusing a generator Medium
- Methods of an iterator class Medium
- What does yield from do? Medium
- A return value in a generator Hard
- send() on a fresh generator Hard
- StopIteration inside a generator Hard
- Taking items from an infinite generator Medium
- Is range an iterator? Medium
- Error: next() after the last item Easy
- Error: next() on a list Easy
- Error: __iter__ that returns a list Hard
- Bug: the second report is empty Medium
- Bug: only the first square is produced Easy
- Error: indexing a generator Medium
- Bug: the custom range works only once Hard
- Error: StopIteration leaking out of a generator Hard
- Error: sending a value to a generator that has not started Hard
- Bug: prices use the new rate instead of the old one Hard
Decorators 25 questions
- What does @deco mean? Easy
- What is a decorator? Easy
- Why *args and **kwargs in a wrapper? Medium
- functools.wraps Medium
- When does the decorator itself run? Medium
- A decorator that takes arguments Hard
- The order of stacked decorators Medium
- A decorator that forgets return wrapper Medium
- Closures and decorators Medium
- Class-based decorators Medium
- Built-in decorators Easy
- A wrapper that does not return Easy
- Reaching the original function Hard
- Updating a counter in a wrapper Hard
- Typical uses of decorators Easy
- Error: the decorator does not return the wrapper Easy
- Error: a wrapper that accepts no arguments Easy
- Bug: the decorated function returns None Easy
- Error: @repeat used without its argument Hard
- Error: a plain decorator used with brackets Medium
- Bug: help text and name are lost Medium
- Bug: price formatted before the discount is applied Hard
- Error: a decorator not followed by a def Medium
- Error: updating a closure counter without nonlocal Hard
- Bug: a cache that ignores the second argument Hard
Regular Expressions 25 questions
- match() versus search() Easy
- When to use fullmatch() Medium
- Why raw strings for patterns? Medium
- The result of a failed search Easy
- What findall returns Easy
- What \w matches Easy
- Greedy versus lazy Medium
- ^ and $ Easy
- The word boundary \b Medium
- findall and groups Hard
- Backreferences in re.sub Medium
- Matching a literal dot Easy
- What is a lookahead? Hard
- Case-insensitive matching Easy
- A non-capturing group Hard
- Error: calling group() when nothing matched Easy
- Error: an unbalanced parenthesis in the pattern Medium
- Bug: \b without a raw string Hard
- Bug: no amount found in the sentence Easy
- Bug: one quoted word captures too much Medium
- Bug: a fake domain passes the check Medium
- Bug: only the domain endings are returned Hard
- Bug: a 7-digit PIN is accepted Medium
- Error: a number as the replacement Medium
- Error: searching inside a number Easy
Python Built-in Functions 25 questions
- round(2.5) Medium
- What sorted() returns Easy
- max() with a key Easy
- max() of an empty list Medium
- The start value of sum() Medium
- any() and all() on empty input Medium
- zip() and different lengths Easy
- What reversed() returns Medium
- divmod() with a negative number Hard
- pow() with three arguments Medium
- isinstance with several types Easy
- getattr() with a default Medium
- enumerate() with start Easy
- Why is eval() dangerous? Medium
- Naming a variable sum Medium
- Error: max() of an empty list Easy
- Error: sum() of strings Easy
- Error: a variable named list Medium
- Bug: 2.675 rounds to 2.67 Hard
- Error: zip(strict=True) with unequal lengths Medium
- Bug: ₹99.99 becomes ₹99 Easy
- Error: len() of a number Easy
- Bug: the "largest" score is 9 Medium
- Error: chr() with an invalid code point Medium
- Error: getattr() without a default Medium
Tricky Python Output Questions 20 questions
- Does assignment copy a list? Easy
- When are default arguments evaluated? Medium
- Late binding in closures Hard
- Rounding .5 values Medium
- // versus int() Medium
- What and/or return Medium
- The value of nums.sort() Easy
- 1, 1.0 and True as keys Hard
- Truthiness versus equality Medium
- Iterating a generator twice Medium
- Error: reading a variable before a local assignment Medium
- Error: a list as a dictionary key Easy
- Error: adding keys while iterating Medium
- Bug: every student gets the previous student's subjects Medium
- Bug: one negative number survives Medium
- Error: changing a tuple item Easy
- Error: using the result of sort() Medium
- Bug: editing a copy changes the original board Hard
- Error: __str__ that formats self Hard
- Error: calling a method through the class Medium
Python Coding Interview Questions 20 questions
- Average cost of a dict lookup Easy
- Removing from the front of a list Medium
- What kind of heap is heapq? Easy
- Complexity of sorted() Easy
- Requirement for binary search Easy
- Recognising a sliding window problem Medium
- Shortest path in an unweighted grid Medium
- Optimal two sum Medium
- Recognising dynamic programming Medium
- Space used by recursion Hard
- Error: hi starts one past the end Medium
- Bug: maximum subarray of negatives is 0 Medium
- Bug: one element used twice Medium
- Error: popping from an empty stack Easy
- Bug: "top 3 scores" are the lowest Medium
- Bug: "most frequent" sorted alphabetically Easy
- Error: counting with d[k] += 1 Easy
- Bug: reversing a linked list loses nodes Hard
- Error: heap entries that cannot be compared Hard
- Bug: intervals merged without sorting Medium
Ready to test your Programming?
Timed online tests with instant scores and explanations.