LearnFrenzy
Sign in Take a free test

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

  1. print() with sep and end Easy
  2. Separators and adjacent string literals Medium
  3. type() of basic values Easy
  4. Comments and a stray string Easy
  5. Backslash and bracket continuation Easy
  6. Several statements on one line Easy
  7. Adding two inputs Easy
  8. Unpacking a string into print() Medium
  9. f-string with a format spec Medium
  10. Multiplying a string and a number Easy
  11. Names that differ only in case Easy
  12. Chaining print() with end Medium
  13. The value of __name__ in a script Medium
  14. Reading a function's docstring Medium
  15. Which lines belong to the if-blocks? Easy

Variables and Data Types 15 questions

  1. Chained assignment and rebinding Easy
  2. Simultaneous assignment Medium
  3. int() versus round() Medium
  4. Arithmetic with True and False Easy
  5. Truth values of common objects Medium
  6. A very large integer Easy
  7. Comparing a float sum Medium
  8. Types produced by / and // Easy
  9. Two names, one list Medium
  10. += on a string Medium
  11. Converting between number bases Medium
  12. Parts of a complex number Medium
  13. Checking None Easy
  14. isinstance() and type() with True Hard
  15. A chain of augmented assignments Medium

Operators and Expressions 15 questions

  1. // and % with negative numbers Medium
  2. Precedence and associativity of ** Medium
  3. Chained comparisons Medium
  4. Values returned by and / or Hard
  5. Bitwise operators Medium
  6. Mixed arithmetic precedence Easy
  7. in with strings, lists and dicts Medium
  8. Which function calls run? Hard
  9. The walrus operator in an if Medium
  10. Conditional expression and the and/or idiom Medium
  11. Augmented assignment evaluates the whole right side Medium
  12. is versus == for lists Easy
  13. divmod() and three-argument pow() Medium
  14. == across numeric types and strings Medium
  15. not with comparisons Hard

Conditional Statements 15 questions

  1. The order of elif branches Easy
  2. Nested if with else Easy
  3. Three separate if statements Easy
  4. Truthiness of different values Medium
  5. A chained conditional expression Medium
  6. match-case with sequence patterns Hard
  7. match-case with literals and a guard Medium
  8. A variable created inside an if Medium
  9. and protecting against None Medium
  10. Which if does this else belong to? Medium
  11. Comparing strings with different case Easy
  12. all() and any() in an if-elif chain Medium
  13. in with a string of vowels Hard
  14. match-case with mapping patterns Hard
  15. Chained comparison and not in conditions Easy

Loops 15 questions

  1. Three forms of range() Easy
  2. for-else with and without break Medium
  3. Skipping multiples of 3 with continue Easy
  4. The value after a while loop Easy
  5. The loop variable after the loop Medium
  6. break inside a nested loop Medium
  7. enumerate() with start Easy
  8. zip() stops at the shortest Easy
  9. Changing the loop variable inside the loop Medium
  10. Removing items while iterating a list Hard
  11. while with an else clause Medium
  12. Summing with a step Easy
  13. A descending number triangle Medium
  14. Looping over a dictionary Medium
  15. An empty range and reversed() Medium

Strings 15 questions

  1. Indexing and slicing a word Easy
  2. Slices with steps Medium
  3. Slices past the end of a string Medium
  4. split() and join() Medium
  5. strip() with characters Medium
  6. find(), rfind() and count() Medium
  7. replace() with a count Easy
  8. Calling a method without assigning it Easy
  9. title() and swapcase() Hard
  10. Comparing strings Medium
  11. ord() and chr() Easy
  12. isdigit(), isalnum() and isspace() Medium
  13. Number formatting in f-strings Medium
  14. Repetition and membership Medium
  15. Escape sequences and raw strings Hard

Lists 15 questions

  1. append() and extend() Easy
  2. pop() with and without an index Easy
  3. Assigning the result of sort() Easy
  4. sorted() with different keys Medium
  5. A grid built with * Hard
  6. Slice assignment Medium
  7. remove(), index() and count() Easy
  8. insert() with a large and a negative index Medium
  9. += and + on an aliased list Hard
  10. list() of a string and del with a slice Easy
  11. Negative slices of a list Medium
  12. max() and sorted() with key=abs Medium
  13. Starred unpacking of a list Medium
  14. Comparing lists Medium
  15. A shallow copy of a nested list Hard

Tuples 15 questions

  1. (5) versus (5,) Easy
  2. Packing and unpacking Easy
  3. Changing a list stored in a tuple Medium
  4. +, * and slicing on tuples Easy
  5. count(), index() and sorted() Medium
  6. Comparing tuples Medium
  7. A function that returns three values Easy
  8. Nested unpacking Medium
  9. Starred unpacking of a short tuple Medium
  10. Tuples as dictionary keys Medium
  11. A namedtuple and _replace() Medium
  12. Converting iterables with tuple() Medium
  13. Sorting a list of tuples Hard
  14. += on a tuple Medium
  15. zip() produces tuples Easy

Sets 15 questions

  1. Duplicates in a set literal Easy
  2. The type of {}, set() and {1} Easy
  3. Union, intersection, difference and symmetric difference Easy
  4. Subset, proper subset and disjoint Medium
  5. add() an existing item and discard() a missing one Easy
  6. The unique letters of a word Easy
  7. 1, True and 1.0 in one set Hard
  8. update() versus add() with a tuple Medium
  9. Set comprehensions Medium
  10. A frozenset as a dictionary key Medium
  11. Removing duplicates with and without order Medium
  12. Set methods with other iterables Medium
  13. a - b versus b - a Easy
  14. In-place set operators Medium
  15. Equality of sets and lists Easy

Dictionaries 15 questions

  1. Adding and replacing values Easy
  2. get() and in Easy
  3. A key written twice in a literal Medium
  4. 1, True and 1.0 as keys Hard
  5. pop() and popitem() Medium
  6. keys() is a live view Medium
  7. setdefault() inside print() Hard
  8. Counting letters with get() Easy
  9. Merging dictionaries Medium
  10. Dict comprehensions Medium
  11. fromkeys() with a list default Hard
  12. Sorting a dictionary by value Medium
  13. update() with keywords and looping over items() Easy
  14. Updating a nested dictionary Medium
  15. Counter and dictionary equality Medium

Functions 15 questions

  1. Capturing the result of a print-only function Easy
  2. Default and keyword arguments Easy
  3. A list as a default argument Hard
  4. *args with no and several arguments Easy
  5. **kwargs collects a dict Medium
  6. A local variable with a global's name Easy
  7. Updating a global variable Easy
  8. nonlocal in a nested function Medium
  9. A default taken from a variable Medium
  10. Unpacking a list and a dict into a call Medium
  11. Early returns and a bare return Medium
  12. Using a function as an object Easy
  13. A keyword-only parameter Medium
  14. Passing a list and an int Medium
  15. Every kind of parameter at once Hard

Recursion 15 questions

  1. Sum of 1 to n recursively Easy
  2. A recursive countdown Easy
  3. Printing after the recursive call Medium
  4. Printing before and after the call Hard
  5. How many calls does fib(5) make? Hard
  6. A recursive power function Easy
  7. Reversing a string recursively Medium
  8. Sum of digits recursively Easy
  9. Euclid's GCD recursively Easy
  10. Fibonacci with lru_cache Medium
  11. Two functions calling each other Medium
  12. Summing a nested list Medium
  13. Binary representation recursively Medium
  14. Counting Tower of Hanoi moves Medium
  15. Catching RecursionError Hard

Lambda Functions 15 questions

  1. Calling lambdas with defaults Easy
  2. Sorting by length, then alphabetically Medium
  3. map() with one and two iterables Medium
  4. filter() with a lambda and with None Medium
  5. reduce() with and without an initial value Medium
  6. Lambdas created in a loop Hard
  7. Capturing the loop value with a default Hard
  8. A conditional lambda Easy
  9. max() and min() with lambda keys on a dict Medium
  10. Lambdas returned from a function Medium
  11. The name and result of a lambda Medium
  12. Sorting a list of dictionaries Easy
  13. functools.partial Medium
  14. A lambda reads a variable at call time Medium
  15. A lambda that returns a lambda Hard

List Comprehensions 15 questions

  1. Squares and a filter Easy
  2. if-else inside a comprehension Easy
  3. Two for clauses Medium
  4. A nested comprehension Medium
  5. Flattening a list of lists Easy
  6. Transposing with a nested comprehension Medium
  7. Dict comprehensions Easy
  8. A set comprehension of remainders Easy
  9. Summing a generator twice Medium
  10. The comprehension variable does not leak Medium
  11. Two if clauses Hard
  12. A comprehension over a string Easy
  13. The walrus operator in a comprehension Hard
  14. Grids built with * and with a comprehension Medium
  15. enumerate() and zip() in comprehensions Medium

Modules and Packages 15 questions

  1. math.floor, ceil and sqrt Easy
  2. from … import with an alias Easy
  3. A module imported under an alias Easy
  4. Importing the same module twice Medium
  5. __name__ of an imported module and of the script Easy
  6. Exploring a module with dir() Medium
  7. collections.deque with maxlen Medium
  8. permutations, combinations and product Medium
  9. Date arithmetic with datetime Medium
  10. json.dumps and json.loads Medium
  11. Building paths with pathlib Medium
  12. import * with __all__ Hard
  13. Module code runs once; reload runs it again Hard
  14. The __main__ guard in an imported module Medium
  15. mean, median and mode from statistics Easy

Exception Handling 15 questions

  1. except and finally Easy
  2. The else clause Easy
  3. A general handler before a specific one Medium
  4. finally when the try block returns Medium
  5. Inspecting an exception object Medium
  6. An exception passing through an inner try Medium
  7. Raising and catching a custom exception Easy
  8. Logging and re-raising Medium
  9. The message of a KeyError Hard
  10. Skipping bad values in a loop Easy
  11. try, except, else and finally together Medium
  12. Chaining with raise … from Hard
  13. Catching an AssertionError Easy
  14. The exception hierarchy Medium
  15. The except variable after the block Hard

File Handling 15 questions

  1. Writing then reading a file Easy
  2. write() return value and writelines() Medium
  3. Overwriting and appending Easy
  4. readline() followed by readlines() Medium
  5. Iterating over a file with strip() Easy
  6. tell() and seek() Medium
  7. Exclusive creation with "x" Medium
  8. Catching FileNotFoundError Easy
  9. Is the file closed after with? Easy
  10. Writing and reading bytes Medium
  11. Reading a CSV file with DictReader Medium
  12. Saving and loading JSON Medium
  13. write_text, read_text and exists Easy
  14. Characters and bytes on disk Hard
  15. Overwriting with "r+" Medium

OOP in Python 15 questions

  1. A simple class with a method Easy
  2. Shadowing a class attribute Medium
  3. A mutable class attribute Hard
  4. __str__ and __repr__ Medium
  5. Counting instances with a class attribute Easy
  6. == with and without __eq__ Medium
  7. A property with a setter Medium
  8. Name mangling Hard
  9. A classmethod alternative constructor Medium
  10. Calling a staticmethod Easy
  11. Bound methods Medium
  12. An object's __dict__ Medium
  13. A dataclass Medium
  14. __len__ and __contains__ Medium
  15. Methods that return self Medium

Inheritance and Polymorphism 15 questions

  1. Overriding and calling super() Easy
  2. isinstance and issubclass Easy
  3. Method lookup in a diamond Hard
  4. The order of cooperative __init__ calls Hard
  5. Polymorphism over a list of shapes Easy
  6. Duck typing with unrelated classes Medium
  7. Operator overloading Medium
  8. A child __init__ without super() Medium
  9. Abstract classes and incomplete subclasses Medium
  10. Inherited and overridden class attributes Medium
  11. A parent method using child hooks Medium
  12. __str__ inherited by a subclass Easy
  13. super() through three levels Medium
  14. sum() of custom objects with __radd__ Hard
  15. Two parents with the same method Medium

Iterators and Generators 15 questions

  1. iter(), next() and a default Easy
  2. When does a generator's code run? Hard
  3. Collecting a generator into a list Easy
  4. Using a generator twice Medium
  5. A custom iterator class Medium
  6. An iterable class whose __iter__ yields Medium
  7. yield from several iterables Medium
  8. islice() over count() Medium
  9. A generator's return value Hard
  10. zip() is a one-shot iterator Medium
  11. iter() of an iterator and of a list Medium
  12. An infinite Fibonacci generator with break Medium
  13. Sending values into a generator Hard
  14. in on an iterator Hard
  15. takewhile() and groupby() Hard

Decorators 15 questions

  1. A wrapper that prints before and after Easy
  2. __name__ with and without wraps Medium
  3. Decorator code at definition time Hard
  4. A decorator that changes the result Easy
  5. A decorator with an argument Medium
  6. The order of stacked decorators Medium
  7. Which wrapper runs first? Hard
  8. Counting calls with a wrapper attribute Medium
  9. A memoising decorator Hard
  10. A class used as a decorator Medium
  11. Decorating a method Medium
  12. A registration decorator Medium
  13. lru_cache hits and misses Medium
  14. Decorators created in a loop Hard
  15. @property is a decorator Medium

Regular Expressions 15 questions

  1. search() and findall() Easy
  2. match() versus search() Easy
  3. Validating with fullmatch() Easy
  4. Capturing groups Medium
  5. Named groups Medium
  6. Greedy and lazy quantifiers Medium
  7. Collapsing whitespace with sub() Easy
  8. Reordering a date with backreferences Medium
  9. Splitting on several delimiters Medium
  10. findall with two groups Medium
  11. ^ with and without MULTILINE Medium
  12. Capitalised words with \b Easy
  13. An escaped and an unescaped dot Medium
  14. A function as the replacement Medium
  15. Password rules with lookaheads Hard

Python Built-in Functions 15 questions

  1. abs, round and pow Medium
  2. min and max with key and default Easy
  3. sum() with a start value Medium
  4. sorted() and reversed() Easy
  5. enumerate() and zip() Easy
  6. any() and all() edge cases Medium
  7. divmod and number bases Medium
  8. Shifting letters with chr and ord Easy
  9. type() and isinstance() Medium
  10. getattr, setattr and hasattr Medium
  11. map() over two lists and filter(None) Medium
  12. What is callable? Easy
  13. range() as a sequence Medium
  14. format(), repr() and str() Medium
  15. Converting strings Medium

Tricky Python Output Questions 30 questions

  1. The type of print()'s result Easy
  2. + and += on an aliased list Medium
  3. Repetition and join Easy
  4. /, // and % with negatives Medium
  5. Chained comparisons Medium
  6. An empty list compared with False Medium
  7. Strings that look like numbers Easy
  8. Slices that go out of range Medium
  9. Slicing a string several ways Medium
  10. Equal keys in a dictionary Hard
  11. Adding rounded halves Medium
  12. When a function reads a global Medium
  13. Chaining methods that return None Medium
  14. set() and split() on the same word Medium
  15. Starred unpacking of a string Medium
  16. A growing default list Medium
  17. Multipliers built in a loop Hard
  18. in on a generator, then list() Hard
  19. Mutating vs rebinding a class attribute Hard
  20. += on a list inside a tuple Hard
  21. The order of try, return and finally Medium
  22. A local and a global with the same name Medium
  23. super() along the MRO Hard
  24. __eq__ without __hash__ Hard
  25. Four ways to turn -3.5 into an int Medium
  26. Two independent closures Medium
  27. Renaming keys while looping over a snapshot Hard
  28. Chained assignment with a list and an int Medium
  29. A stable sort by length Medium
  30. try / except / else / finally in a loop Hard

Python Coding Interview Questions 10 questions

  1. The order of heap pops Medium
  2. deque operations Medium
  3. bisect_left and bisect_right Medium
  4. Counter.most_common with ties Medium
  5. Sorting by frequency, then value Medium
  6. Rotating a matrix with zip Hard
  7. Range sums with prefix sums Medium
  8. Reversing words and characters Easy
  9. any() stops early Hard
  10. Grouping anagrams with a dict Medium

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links