PyPython

Python quiz – 36 questions with answers

Try it interactively

With scoring, random questions, and saved progress – or go straight to the timed exam with certificate.

Beginner (16 questions)

How do you print text to the console in Python?

  1. echo("Hi")
  2. print("Hi")
  3. console.log("Hi")
  4. printf("Hi")
Show answer

Correct: print("Hi")

print() is the standard function for output.

What type is 3.14?

  1. int
  2. float
  3. str
  4. decimal
Show answer

Correct: float

Decimal numbers are float.

What does 7 // 2 evaluate to?

  1. 3.5
  2. 3
  3. 4
  4. 2
Show answer

Correct: 3

// is integer division and rounds down: 3.

What does 7 % 2 evaluate to?

  1. 3
  2. 1
  3. 0
  4. 3.5
Show answer

Correct: 1

% returns the remainder of the division: 7 = 3·2 + 1.

How does a comment begin in Python?

  1. //
  2. /*
  3. #
  4. --
Show answer

Correct: #

Single-line comments begin with #.

What does this code print?

x = 5
x += 3
print(x)
  1. 5
  2. 3
  3. 8
  4. 53
Show answer

Correct: 8

x += 3 is equivalent to x = x + 3, so 8.

Which loop counts 0, 1, 2?

  1. for i in range(3):
  2. for i in range(1, 3):
  3. for i in 3:
  4. while i < 3
Show answer

Correct: for i in range(3):

range(3) produces 0, 1, 2.

How do you access the last element of a list l?

  1. l[last]
  2. l[-1]
  3. l[len(l)]
  4. l.end()
Show answer

Correct: l[-1]

Negative indices count from the end: -1 is the last element.

What is the output?

print(type([1, 2]))
  1. <class 'tuple'>
  2. <class 'list'>
  3. <class 'array'>
  4. <class 'set'>
Show answer

Correct: <class 'list'>

Square brackets create a list.

Which data type is immutable?

  1. list
  2. dict
  3. tuple
  4. set
Show answer

Correct: tuple

Tuples cannot be changed after they are created.

What does "a,b,c".split(",") do?

  1. Returns ["a","b","c"]
  2. Returns "abc"
  3. Returns 3
  4. Raises an error
Show answer

Correct: Returns ["a","b","c"]

split splits the string at the separator and returns a list.

What does print(bool([])) print?

  1. True
  2. False
  3. None
  4. Error
Show answer

Correct: False

Empty collections count as false (False).

How do you define a function f?

  1. function f():
  2. def f():
  3. fun f():
  4. func f():
Show answer

Correct: def f():

Functions begin with def.

What does a function without return give back?

  1. 0
  2. ""
  3. None
  4. Error
Show answer

Correct: None

Without return, the return value is None.

What does this code print?

s = "Python"
print(s[1:4])
  1. Pyt
  2. yth
  3. ytho
  4. Pyth
Show answer

Correct: yth

Slicing [1:4] takes indices 1, 2, 3: "yth".

How do you convert the string "42" to a number?

  1. int("42")
  2. toInt("42")
  3. Number("42")
  4. parse("42")
Show answer

Correct: int("42")

int() converts strings to integers.

Intermediate (12 questions)

What does this code print?

print([x * 2 for x in range(4) if x % 2 == 0])
  1. [0, 2, 4, 6]
  2. [0, 4]
  3. [2, 4]
  4. [0, 2]
Show answer

Correct: [0, 4]

Only even x (0 and 2) are doubled: [0, 4].

What output is produced?

def f(x, l=[]):
    l.append(x)
    return l
print(f(1))
print(f(2))
  1. [1] and [2]
  2. [1] and [1, 2]
  3. [1, 2] and [1, 2]
  4. Error
Show answer

Correct: [1] and [1, 2]

Mutable default values are created only once and shared between calls – a classic pitfall.

What is with open(...) as f: used for?

  1. Opens the file faster
  2. Closes the file automatically
  3. Encrypts the file
  4. Allows read-only access
Show answer

Correct: Closes the file automatically

The context manager closes the file even on errors.

What does {1, 2, 2, 3} evaluate to?

  1. Error
  2. A set with 1, 2, 3
  3. A dictionary
  4. A tuple
Show answer

Correct: A set with 1, 2, 3

Sets store only unique values.

What output does the code produce?

a = [1, 2]
b = a
b.append(3)
print(a)
  1. [1, 2]
  2. [1, 2, 3]
  3. [3]
  4. Error
Show answer

Correct: [1, 2, 3]

b = a copies only the reference – both names point to the same list.

What does print(0.1 + 0.2 == 0.3) print?

  1. True
  2. False
  3. None
  4. Error
Show answer

Correct: False

Floating-point numbers are stored in binary; 0.1 + 0.2 gives 0.30000000000000004.

What does self do in a method?

  1. It is a keyword for private attributes
  2. It refers to the current object
  3. It calls the base class
  4. It is the class itself
Show answer

Correct: It refers to the current object

self is the reference to the instance the method was called on.

What does d.get("x", 0) do when the key is missing?

  1. KeyError error
  2. Returns 0
  3. Returns None
  4. Creates the key
Show answer

Correct: Returns 0

get returns the default value without modifying the dictionary.

What does this code print?

try:
    print(1 / 0)
except ZeroDivisionError:
    print("A")
finally:
    print("B")
  1. A
  2. B
  3. A and B
  4. Error
Show answer

Correct: A and B

The exception is caught ("A"), finally always runs ("B").

What is *args in a function definition?

  1. A pointer
  2. Collects any number of positional arguments into a tuple
  3. Collects named arguments
  4. A multiplication
Show answer

Correct: Collects any number of positional arguments into a tuple

*args bundles additional positional arguments into a tuple, **kwargs bundles named ones into a dictionary.

Which expression creates {"a": 1, "b": 2} from two lists?

  1. dict(zip(["a","b"], [1,2]))
  2. dict(["a","b"], [1,2])
  3. {["a","b"]: [1,2]}
  4. zip(["a","b"], [1,2])
Show answer

Correct: dict(zip(["a","b"], [1,2]))

zip forms pairs, dict turns them into a dictionary.

What does sorted(l, key=len) do?

  1. Sorts l in place by length
  2. Returns a new list sorted by length
  3. Sorts in descending order
  4. Returns the lengths
Show answer

Correct: Returns a new list sorted by length

sorted creates a new list; key determines the sort criterion.

Advanced (8 questions)

What is the difference between is and ==?

  1. No difference
  2. is checks identity, == checks equality of values
  3. is checks values, == checks identity
  4. is applies only to numbers
Show answer

Correct: is checks identity, == checks equality of values

== compares contents, is checks whether it is the same object in memory.

What does the keyword yield do?

  1. Ends a program
  2. Turns the function into a generator and delivers values lazily
  3. Starts a thread
  4. Declares a constant
Show answer

Correct: Turns the function into a generator and delivers values lazily

Functions with yield are generators: they deliver values on demand and keep their state.

What does the GIL (Global Interpreter Lock) prevent in CPython?

  1. Memory leaks
  2. Multiple threads executing Python bytecode at the same time
  3. Import cycles
  4. Recursion
Show answer

Correct: Multiple threads executing Python bytecode at the same time

Because of the GIL, threads give no parallelism for CPU-bound code – use multiprocessing for that.

What does this code print?

funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
  1. [0, 1, 2]
  2. [2, 2, 2]
  3. [3, 3, 3]
  4. Error
Show answer

Correct: [2, 2, 2]

The lambdas bind the variable i, not its value – after the loop i == 2. Fix: lambda i=i: i.

What is functools.lru_cache for?

  1. For threads
  2. Caching function results (memoization)
  3. For sorting
  4. For compressing
Show answer

Correct: Caching function results (memoization)

The decorator remembers results for arguments that have already been computed.

What happens at await inside an async def function?

  1. The whole thread blocks
  2. The coroutine hands control back to the event loop until the result is ready
  3. A new process starts
  4. The code continues immediately without waiting
Show answer

Correct: The coroutine hands control back to the event loop until the result is ready

await pauses only the current coroutine; the event loop can run other tasks.

What are __slots__?

  1. A kind of thread pool
  2. A class option that replaces the attribute dictionary with fixed fields and saves memory
  3. An import mechanism
  4. A type hint
Show answer

Correct: A class option that replaces the attribute dictionary with fixed fields and saves memory

With __slots__, instances have no __dict__, which saves memory and prevents typos in attribute names.

Which statement about decorators is true?

  1. They are allowed only for classes
  2. @d above def f is equivalent to f = d(f)
  3. They run only at program end
  4. They always change the return value
Show answer

Correct: @d above def f is equivalent to f = d(f)

The @ syntax is shorthand for replacing the function with the result of the decorator.