Python Programming · Practice by type
Python Programming Output Questions with Answers
Predict-the-output questions for every Python Programming topic. Each program was run on Python 3, so the answer is its real output, with a step-by-step explanation.
- 385 questions
- 25 topics
- Answers checked on a real compiler
Python Basics and Syntax 15 questions
- print() with sep and end Easy
- Separators and adjacent string literals Medium
- type() of basic values Easy
- Comments and a stray string Easy
- Backslash and bracket continuation Easy
- Several statements on one line Easy
- Adding two inputs Easy
- Unpacking a string into print() Medium
- f-string with a format spec Medium
- Multiplying a string and a number Easy
- Names that differ only in case Easy
- Chaining print() with end Medium
- The value of __name__ in a script Medium
- Reading a function's docstring Medium
- Which lines belong to the if-blocks? Easy
Variables and Data Types 15 questions
- Chained assignment and rebinding Easy
- Simultaneous assignment Medium
- int() versus round() Medium
- Arithmetic with True and False Easy
- Truth values of common objects Medium
- A very large integer Easy
- Comparing a float sum Medium
- Types produced by / and // Easy
- Two names, one list Medium
- += on a string Medium
- Converting between number bases Medium
- Parts of a complex number Medium
- Checking None Easy
- isinstance() and type() with True Hard
- A chain of augmented assignments Medium
Operators and Expressions 15 questions
- // and % with negative numbers Medium
- Precedence and associativity of ** Medium
- Chained comparisons Medium
- Values returned by and / or Hard
- Bitwise operators Medium
- Mixed arithmetic precedence Easy
- in with strings, lists and dicts Medium
- Which function calls run? Hard
- The walrus operator in an if Medium
- Conditional expression and the and/or idiom Medium
- Augmented assignment evaluates the whole right side Medium
- is versus == for lists Easy
- divmod() and three-argument pow() Medium
- == across numeric types and strings Medium
- not with comparisons Hard
Conditional Statements 15 questions
- The order of elif branches Easy
- Nested if with else Easy
- Three separate if statements Easy
- Truthiness of different values Medium
- A chained conditional expression Medium
- match-case with sequence patterns Hard
- match-case with literals and a guard Medium
- A variable created inside an if Medium
- and protecting against None Medium
- Which if does this else belong to? Medium
- Comparing strings with different case Easy
- all() and any() in an if-elif chain Medium
- in with a string of vowels Hard
- match-case with mapping patterns Hard
- Chained comparison and not in conditions Easy
Loops 15 questions
- Three forms of range() Easy
- for-else with and without break Medium
- Skipping multiples of 3 with continue Easy
- The value after a while loop Easy
- The loop variable after the loop Medium
- break inside a nested loop Medium
- enumerate() with start Easy
- zip() stops at the shortest Easy
- Changing the loop variable inside the loop Medium
- Removing items while iterating a list Hard
- while with an else clause Medium
- Summing with a step Easy
- A descending number triangle Medium
- Looping over a dictionary Medium
- An empty range and reversed() Medium
Strings 15 questions
- Indexing and slicing a word Easy
- Slices with steps Medium
- Slices past the end of a string Medium
- split() and join() Medium
- strip() with characters Medium
- find(), rfind() and count() Medium
- replace() with a count Easy
- Calling a method without assigning it Easy
- title() and swapcase() Hard
- Comparing strings Medium
- ord() and chr() Easy
- isdigit(), isalnum() and isspace() Medium
- Number formatting in f-strings Medium
- Repetition and membership Medium
- Escape sequences and raw strings Hard
Lists 15 questions
- append() and extend() Easy
- pop() with and without an index Easy
- Assigning the result of sort() Easy
- sorted() with different keys Medium
- A grid built with * Hard
- Slice assignment Medium
- remove(), index() and count() Easy
- insert() with a large and a negative index Medium
- += and + on an aliased list Hard
- list() of a string and del with a slice Easy
- Negative slices of a list Medium
- max() and sorted() with key=abs Medium
- Starred unpacking of a list Medium
- Comparing lists Medium
- A shallow copy of a nested list Hard
Tuples 15 questions
- (5) versus (5,) Easy
- Packing and unpacking Easy
- Changing a list stored in a tuple Medium
- +, * and slicing on tuples Easy
- count(), index() and sorted() Medium
- Comparing tuples Medium
- A function that returns three values Easy
- Nested unpacking Medium
- Starred unpacking of a short tuple Medium
- Tuples as dictionary keys Medium
- A namedtuple and _replace() Medium
- Converting iterables with tuple() Medium
- Sorting a list of tuples Hard
- += on a tuple Medium
- zip() produces tuples Easy
Sets 15 questions
- Duplicates in a set literal Easy
- The type of {}, set() and {1} Easy
- Union, intersection, difference and symmetric difference Easy
- Subset, proper subset and disjoint Medium
- add() an existing item and discard() a missing one Easy
- The unique letters of a word Easy
- 1, True and 1.0 in one set Hard
- update() versus add() with a tuple Medium
- Set comprehensions Medium
- A frozenset as a dictionary key Medium
- Removing duplicates with and without order Medium
- Set methods with other iterables Medium
- a - b versus b - a Easy
- In-place set operators Medium
- Equality of sets and lists Easy
Dictionaries 15 questions
- Adding and replacing values Easy
- get() and in Easy
- A key written twice in a literal Medium
- 1, True and 1.0 as keys Hard
- pop() and popitem() Medium
- keys() is a live view Medium
- setdefault() inside print() Hard
- Counting letters with get() Easy
- Merging dictionaries Medium
- Dict comprehensions Medium
- fromkeys() with a list default Hard
- Sorting a dictionary by value Medium
- update() with keywords and looping over items() Easy
- Updating a nested dictionary Medium
- Counter and dictionary equality Medium
Functions 15 questions
- Capturing the result of a print-only function Easy
- Default and keyword arguments Easy
- A list as a default argument Hard
- *args with no and several arguments Easy
- **kwargs collects a dict Medium
- A local variable with a global's name Easy
- Updating a global variable Easy
- nonlocal in a nested function Medium
- A default taken from a variable Medium
- Unpacking a list and a dict into a call Medium
- Early returns and a bare return Medium
- Using a function as an object Easy
- A keyword-only parameter Medium
- Passing a list and an int Medium
- Every kind of parameter at once Hard
Recursion 15 questions
- Sum of 1 to n recursively Easy
- A recursive countdown Easy
- Printing after the recursive call Medium
- Printing before and after the call Hard
- How many calls does fib(5) make? Hard
- A recursive power function Easy
- Reversing a string recursively Medium
- Sum of digits recursively Easy
- Euclid's GCD recursively Easy
- Fibonacci with lru_cache Medium
- Two functions calling each other Medium
- Summing a nested list Medium
- Binary representation recursively Medium
- Counting Tower of Hanoi moves Medium
- Catching RecursionError Hard
Lambda Functions 15 questions
- Calling lambdas with defaults Easy
- Sorting by length, then alphabetically Medium
- map() with one and two iterables Medium
- filter() with a lambda and with None Medium
- reduce() with and without an initial value Medium
- Lambdas created in a loop Hard
- Capturing the loop value with a default Hard
- A conditional lambda Easy
- max() and min() with lambda keys on a dict Medium
- Lambdas returned from a function Medium
- The name and result of a lambda Medium
- Sorting a list of dictionaries Easy
- functools.partial Medium
- A lambda reads a variable at call time Medium
- A lambda that returns a lambda Hard
List Comprehensions 15 questions
- Squares and a filter Easy
- if-else inside a comprehension Easy
- Two for clauses Medium
- A nested comprehension Medium
- Flattening a list of lists Easy
- Transposing with a nested comprehension Medium
- Dict comprehensions Easy
- A set comprehension of remainders Easy
- Summing a generator twice Medium
- The comprehension variable does not leak Medium
- Two if clauses Hard
- A comprehension over a string Easy
- The walrus operator in a comprehension Hard
- Grids built with * and with a comprehension Medium
- enumerate() and zip() in comprehensions Medium
Modules and Packages 15 questions
- math.floor, ceil and sqrt Easy
- from … import with an alias Easy
- A module imported under an alias Easy
- Importing the same module twice Medium
- __name__ of an imported module and of the script Easy
- Exploring a module with dir() Medium
- collections.deque with maxlen Medium
- permutations, combinations and product Medium
- Date arithmetic with datetime Medium
- json.dumps and json.loads Medium
- Building paths with pathlib Medium
- import * with __all__ Hard
- Module code runs once; reload runs it again Hard
- The __main__ guard in an imported module Medium
- mean, median and mode from statistics Easy
Exception Handling 15 questions
- except and finally Easy
- The else clause Easy
- A general handler before a specific one Medium
- finally when the try block returns Medium
- Inspecting an exception object Medium
- An exception passing through an inner try Medium
- Raising and catching a custom exception Easy
- Logging and re-raising Medium
- The message of a KeyError Hard
- Skipping bad values in a loop Easy
- try, except, else and finally together Medium
- Chaining with raise … from Hard
- Catching an AssertionError Easy
- The exception hierarchy Medium
- The except variable after the block Hard
File Handling 15 questions
- Writing then reading a file Easy
- write() return value and writelines() Medium
- Overwriting and appending Easy
- readline() followed by readlines() Medium
- Iterating over a file with strip() Easy
- tell() and seek() Medium
- Exclusive creation with "x" Medium
- Catching FileNotFoundError Easy
- Is the file closed after with? Easy
- Writing and reading bytes Medium
- Reading a CSV file with DictReader Medium
- Saving and loading JSON Medium
- write_text, read_text and exists Easy
- Characters and bytes on disk Hard
- Overwriting with "r+" Medium
OOP in Python 15 questions
- A simple class with a method Easy
- Shadowing a class attribute Medium
- A mutable class attribute Hard
- __str__ and __repr__ Medium
- Counting instances with a class attribute Easy
- == with and without __eq__ Medium
- A property with a setter Medium
- Name mangling Hard
- A classmethod alternative constructor Medium
- Calling a staticmethod Easy
- Bound methods Medium
- An object's __dict__ Medium
- A dataclass Medium
- __len__ and __contains__ Medium
- Methods that return self Medium
Inheritance and Polymorphism 15 questions
- Overriding and calling super() Easy
- isinstance and issubclass Easy
- Method lookup in a diamond Hard
- The order of cooperative __init__ calls Hard
- Polymorphism over a list of shapes Easy
- Duck typing with unrelated classes Medium
- Operator overloading Medium
- A child __init__ without super() Medium
- Abstract classes and incomplete subclasses Medium
- Inherited and overridden class attributes Medium
- A parent method using child hooks Medium
- __str__ inherited by a subclass Easy
- super() through three levels Medium
- sum() of custom objects with __radd__ Hard
- Two parents with the same method Medium
Iterators and Generators 15 questions
- iter(), next() and a default Easy
- When does a generator's code run? Hard
- Collecting a generator into a list Easy
- Using a generator twice Medium
- A custom iterator class Medium
- An iterable class whose __iter__ yields Medium
- yield from several iterables Medium
- islice() over count() Medium
- A generator's return value Hard
- zip() is a one-shot iterator Medium
- iter() of an iterator and of a list Medium
- An infinite Fibonacci generator with break Medium
- Sending values into a generator Hard
- in on an iterator Hard
- takewhile() and groupby() Hard
Decorators 15 questions
- A wrapper that prints before and after Easy
- __name__ with and without wraps Medium
- Decorator code at definition time Hard
- A decorator that changes the result Easy
- A decorator with an argument Medium
- The order of stacked decorators Medium
- Which wrapper runs first? Hard
- Counting calls with a wrapper attribute Medium
- A memoising decorator Hard
- A class used as a decorator Medium
- Decorating a method Medium
- A registration decorator Medium
- lru_cache hits and misses Medium
- Decorators created in a loop Hard
- @property is a decorator Medium
Regular Expressions 15 questions
- search() and findall() Easy
- match() versus search() Easy
- Validating with fullmatch() Easy
- Capturing groups Medium
- Named groups Medium
- Greedy and lazy quantifiers Medium
- Collapsing whitespace with sub() Easy
- Reordering a date with backreferences Medium
- Splitting on several delimiters Medium
- findall with two groups Medium
- ^ with and without MULTILINE Medium
- Capitalised words with \b Easy
- An escaped and an unescaped dot Medium
- A function as the replacement Medium
- Password rules with lookaheads Hard
Python Built-in Functions 15 questions
- abs, round and pow Medium
- min and max with key and default Easy
- sum() with a start value Medium
- sorted() and reversed() Easy
- enumerate() and zip() Easy
- any() and all() edge cases Medium
- divmod and number bases Medium
- Shifting letters with chr and ord Easy
- type() and isinstance() Medium
- getattr, setattr and hasattr Medium
- map() over two lists and filter(None) Medium
- What is callable? Easy
- range() as a sequence Medium
- format(), repr() and str() Medium
- Converting strings Medium
Tricky Python Output Questions 30 questions
- The type of print()'s result Easy
- + and += on an aliased list Medium
- Repetition and join Easy
- /, // and % with negatives Medium
- Chained comparisons Medium
- An empty list compared with False Medium
- Strings that look like numbers Easy
- Slices that go out of range Medium
- Slicing a string several ways Medium
- Equal keys in a dictionary Hard
- Adding rounded halves Medium
- When a function reads a global Medium
- Chaining methods that return None Medium
- set() and split() on the same word Medium
- Starred unpacking of a string Medium
- A growing default list Medium
- Multipliers built in a loop Hard
- in on a generator, then list() Hard
- Mutating vs rebinding a class attribute Hard
- += on a list inside a tuple Hard
- The order of try, return and finally Medium
- A local and a global with the same name Medium
- super() along the MRO Hard
- __eq__ without __hash__ Hard
- Four ways to turn -3.5 into an int Medium
- Two independent closures Medium
- Renaming keys while looping over a snapshot Hard
- Chained assignment with a list and an int Medium
- A stable sort by length Medium
- try / except / else / finally in a loop Hard
Python Coding Interview Questions 10 questions
- The order of heap pops Medium
- deque operations Medium
- bisect_left and bisect_right Medium
- Counter.most_common with ties Medium
- Sorting by frequency, then value Medium
- Rotating a matrix with zip Hard
- Range sums with prefix sums Medium
- Reversing words and characters Easy
- any() stops early Hard
- Grouping anagrams with a dict Medium
Ready to test your Programming?
Timed online tests with instant scores and explanations.