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?
- echo("Hi")
- print("Hi")
- console.log("Hi")
- printf("Hi")
Show answer
Correct: print("Hi")
print() is the standard function for output.
What type is 3.14?
- int
- float
- str
- decimal
Show answer
Correct: float
Decimal numbers are float.
What does 7 // 2 evaluate to?
- 3.5
- 3
- 4
- 2
Show answer
Correct: 3
// is integer division and rounds down: 3.
What does 7 % 2 evaluate to?
- 3
- 1
- 0
- 3.5
Show answer
Correct: 1
% returns the remainder of the division: 7 = 3·2 + 1.
How does a comment begin in Python?
- //
- /*
- #
- --
Show answer
Correct: #
Single-line comments begin with #.
What does this code print?
x = 5
x += 3
print(x)- 5
- 3
- 8
- 53
Show answer
Correct: 8
x += 3 is equivalent to x = x + 3, so 8.
Which loop counts 0, 1, 2?
- for i in range(3):
- for i in range(1, 3):
- for i in 3:
- 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?
- l[last]
- l[-1]
- l[len(l)]
- 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]))- <class 'tuple'>
- <class 'list'>
- <class 'array'>
- <class 'set'>
Show answer
Correct: <class 'list'>
Square brackets create a list.
Which data type is immutable?
- list
- dict
- tuple
- set
Show answer
Correct: tuple
Tuples cannot be changed after they are created.
What does "a,b,c".split(",") do?
- Returns
["a","b","c"] - Returns "abc"
- Returns 3
- 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?
- True
- False
- None
- Error
Show answer
Correct: False
Empty collections count as false (False).
How do you define a function f?
- function f():
- def f():
- fun f():
- func f():
Show answer
Correct: def f():
Functions begin with def.
What does a function without return give back?
- 0
- ""
- None
- Error
Show answer
Correct: None
Without return, the return value is None.
What does this code print?
s = "Python"
print(s[1:4])- Pyt
- yth
- ytho
- Pyth
Show answer
Correct: yth
Slicing [1:4] takes indices 1, 2, 3: "yth".
How do you convert the string "42" to a number?
- int("42")
- toInt("42")
- Number("42")
- 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])- [0, 2, 4, 6]
- [0, 4]
- [2, 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] and [2]
- [1] and [1, 2]
- [1, 2] and [1, 2]
- 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?
- Opens the file faster
- Closes the file automatically
- Encrypts the file
- 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?
- Error
- A set with 1, 2, 3
- A dictionary
- 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, 2]
- [1, 2, 3]
- [3]
- 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?
- True
- False
- None
- 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?
- It is a keyword for private attributes
- It refers to the current object
- It calls the base class
- 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?
KeyErrorerror- Returns 0
- Returns None
- 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")- A
- B
- A and B
- Error
Show answer
Correct: A and B
The exception is caught ("A"), finally always runs ("B").
What is *args in a function definition?
- A pointer
- Collects any number of positional arguments into a tuple
- Collects named arguments
- 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?
- dict(zip(["a","b"], [1,2]))
- dict(["a","b"], [1,2])
- {["a","b"]: [1,2]}
- 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?
- Sorts
lin place by length - Returns a new list sorted by length
- Sorts in descending order
- 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 ==?
- No difference
ischecks identity,==checks equality of valuesischecks values,==checks identityisapplies 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?
- Ends a program
- Turns the function into a generator and delivers values lazily
- Starts a thread
- 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?
- Memory leaks
- Multiple threads executing Python bytecode at the same time
- Import cycles
- 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])- [0, 1, 2]
- [2, 2, 2]
- [3, 3, 3]
- 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?
- For threads
- Caching function results (memoization)
- For sorting
- 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?
- The whole thread blocks
- The coroutine hands control back to the event loop until the result is ready
- A new process starts
- 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__?
- A kind of thread pool
- A class option that replaces the attribute dictionary with fixed fields and saves memory
- An import mechanism
- 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?
- They are allowed only for classes
@dabovedef fis equivalent tof = d(f)- They run only at program end
- 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.