Free Python quiz
Python Practice Questions.
Thirty Python questions in three levels. Pick an answer and see at once whether you were right, and why.
- 30 questions
- 3 levels
- No sign-in
- Checked on Python 3.14
word = "python"print(word[1:4])Slicing
1 / 10
What does this program print?
0 correct · Keys 1 to 4 to answer
Your score and streak are saved in this browser. No account needed.
Question bank
All 30 Python questions and answers
Prefer to read? Open any question to see the code, the answer and the reason behind it.
Basics
Syntax and everyday types1Slicingprint(word[1:4])
What does this program print?
word = "python"print(word[1:4])- Apyt
- Bytho
- Cyth
- Dpyth
Answer: C. A slice starts at the first index and stops before the second. Index 1 is "y" and index 4 is "o", so you get the characters at 1, 2 and 3.
Slice strings in Python2Divisionprint(7 // 2, 7 / 2, -7 // 2)
What does this program print?
print(7 // 2, 7 / 2, -7 // 2)- A3 3.5 -4
- B3 3.5 -3
- C3.5 3.5 -3.5
- D3 3 -4
Answer: A. / always gives a float. // is floor division: it rounds down towards negative infinity, not towards zero, so -7 // 2 is -4.
Arithmetic operators in Python3f-stringsprint(f"{name} is {age + 1}")
What does this program print?
name = "Ana"age = 31print(f"{name} is {age + 1}")- AAna is 31
- BIt raises TypeError
- C{name} is {age + 1}
- DAna is 32
Answer: D. Anything inside the braces of an f-string is run as Python code and the result is placed in the text. age + 1 is worked out first, giving 32.
Python f-strings explained4Strings are immutableprint(name)
What does this program print?
name = "rune"name.upper()print(name)- ARUNE
- Brune
- CRune
- DIt raises an error
Answer: B. upper() returns a new string and leaves the original alone. Nothing stores the result here, so it is thrown away. Write name = name.upper() to keep it.
String immutability in Python5Type conversionprint("3" + "4", int("3") + int("4"))
What does this program print?
print("3" + "4", int("3") + int("4"))- A34 7
- B7 7
- C34 34
- DIt raises TypeError
Answer: A. + between two strings joins them, so "3" + "4" is "34". After int() turns each one into a number, + adds them.
Type conversion in Python6TruthinessWhich of these values counts as True in an if statement?
Which of these values counts as True in an if statement?
- A[] (an empty list)
- B0
- C"0" (a string holding zero)
- DNone
Answer: C. Empty containers, 0 and None are all falsy. A string is falsy only when it is empty. "0" has one character in it, so it is truthy.
The None data type in Python7Negative indexesprint(nums[-1], nums[:-1])
What does this program print?
nums = [10, 20, 30, 40]print(nums[-1], nums[:-1])- A10 [20, 30, 40]
- B40 [10, 20, 30]
- C40 [10, 20, 30, 40]
- DIt raises IndexError
Answer: B. A negative index counts from the end, so nums[-1] is the last item. nums[:-1] is everything up to, but not including, the last item.
8range() print(n)
How many numbers does this loop print?
for n in range(2, 10, 3): print(n)- A2
- B8
- C4
- D3
Answer: D. range(2, 10, 3) starts at 2, adds 3 each time, and stops before 10. That gives 2, 5 and 8: three numbers.
Python built-in iteration functions9Dictionariesprint(ages.get("ben"), ages.get("ben", 0))
What does this program print?
ages = {"ana": 31}print(ages.get("ben"), ages.get("ben", 0))- AIt raises KeyError
- B0 0
- CNone 0
- DNone None
Answer: C. get() never raises for a missing key. It returns None, or the second argument when you give one. ages["ben"] is the form that raises KeyError.
Nested dictionaries in Python10Tuplespoint[0] = 5
What happens when this program runs?
point = (1, 2)point[0] = 5- AIt raises TypeError
- Bpoint becomes (5, 2)
- Cpoint becomes [5, 2]
- DNothing changes and no error
Answer: A. Tuples cannot be changed after they are created. Python raises TypeError: 'tuple' object does not support item assignment. Build a new tuple, or use a list.
Pack and unpack tuples in PythonCore
Collections, scope and errors11Lists and referencesprint(a)
What does this program print?
a = [1, 2, 3]b = ab.append(4)print(a)- A[1, 2, 3]
- BIt raises an error
- C[4, 1, 2, 3]
- D[1, 2, 3, 4]
Answer: D. b = a does not copy the list. Both names point to the same list, so appending through b changes what a sees. Use a.copy() when you want a separate list.
Copy Python lists: shallow vs deep copy12Equality and identityprint(a == b, a is b)
What does this program print?
a = [1, 2]b = [1, 2]print(a == b, a is b)- ATrue True
- BTrue False
- CFalse False
- DFalse True
Answer: B. == compares values, and the two lists hold the same values. is asks whether both names point to the very same object, and these are two separate lists.
Object comparison in Python13List comprehensionsprint([n * n for n in range(5) if n % 2 == 0])
What does this program print?
print([n * n for n in range(5) if n % 2 == 0])- A[0, 1, 4, 9, 16]
- B[0, 2, 4]
- C[1, 9]
- D[0, 4, 16]
Answer: D. The if keeps only the even numbers from 0 to 4, which are 0, 2 and 4. Each one is then squared.
List comprehensions in Python14Dictionary comprehensionsprint({k: v * 2 for k, v in prices.items() if v > 2})
What does this program print?
prices = {"tea": 2, "cake": 5}print({k: v * 2 for k, v in prices.items() if v > 2})- A{'cake': 10}
- B{'tea': 4, 'cake': 10}
- C{'cake': 5}
- D['cake', 10]
Answer: A. The if drops "tea" because 2 is not greater than 2. Only "cake" is kept, with its value doubled.
Dictionary comprehensions in Python15Setsprint(len(set(nums)), sorted(set(nums)))
What does this program print?
nums = [3, 1, 3, 2, 1]print(len(set(nums)), sorted(set(nums)))- A5 [1, 1, 2, 3, 3]
- B3 [3, 1, 2]
- C3 [1, 2, 3]
- D2 [1, 3]
Answer: C. A set keeps one copy of each value, so the five items become three. sorted() then returns them as an ordered list.
Working with Python sets16sort() and sorted()print(result, nums)
What does this program print?
nums = [3, 1, 2]result = nums.sort()print(result, nums)- A[1, 2, 3] [3, 1, 2]
- BNone [1, 2, 3]
- C[1, 2, 3] [1, 2, 3]
- DNone [3, 1, 2]
Answer: B. list.sort() sorts the list in place and returns None. sorted(nums) is the one that returns a new sorted list and leaves the original alone.
17Unpackingprint(rest)
What does this program print?
first, *rest = [10, 20, 30]print(rest)- A30
- B(20, 30)
- C[20, 30]
- D[10, 20]
Answer: C. The starred name collects everything left over, and always as a list. first takes 10, so rest is [20, 30].
Pack and unpack tuples in Python18Scopeprint(count)
What does this program print?
count = 0def increase(): count = 5increase()print(count)- A0
- B5
- CNone
- DIt raises UnboundLocalError
Answer: A. Assigning to count inside the function creates a new local variable. The global count is untouched. Return the new value instead of reaching for the global statement.
Common variable mistakes in Python19Loops with else print("no even number")
What does this program print?
for n in [1, 3, 5]: if n % 2 == 0: print("even found") breakelse: print("no even number")- Aeven found
- BIt raises SyntaxError
- CNothing
- Dno even number
Answer: D. A loop else block runs when the loop finishes without hitting break. None of the numbers is even, so break never runs and the else block does.
Common Python mistakes beginners make20Exceptions print("done")
What does this program print?
try: print(int("12a"))except ValueError: print("bad number")finally: print("done")- Abad number, then done
- B12
- Cbad number
- Ddone
Answer: A. int("12a") raises ValueError, so the except block prints "bad number". finally runs whether or not there was an error, so "done" follows.
Handle Python errors with exceptionsTricky
The ones interviews love21Mutable default argumentsprint(add_item("b"))
What does this program print?
def add_item(item, items=[]): items.append(item) return itemsadd_item("a")print(add_item("b"))- A['b']
- B['a', 'b']
- C['a']
- DIt raises an error
Answer: B. A default value is created once, when the function is defined, not on every call. Both calls share the same list. Use items=None and create the list inside the function.
Default parameter values in Python22Nested listsprint(grid)
What does this program print?
grid = [[0] * 2] * 2grid[0][0] = 1print(grid)- A[[1, 0], [0, 0]]
- BIt raises IndexError
- C[[1, 1], [1, 1]]
- D[[1, 0], [1, 0]]
Answer: D. The outer * 2 repeats a reference to the same inner list, so both rows are one list. Build rows separately: [[0] * 2 for _ in range(2)].
Nested lists in Python23Closures in loopsprint([f() for f in fns])
What does this program print?
fns = [lambda: i for i in range(3)]print([f() for f in fns])- A[0, 1, 2]
- B[3, 3, 3]
- C[2, 2, 2]
- D[0, 0, 0]
Answer: C. Each lambda looks up i when it is called, not when it is made. By then the loop has finished and i is 2. Write lambda i=i: i to capture each value.
Nested functions in Python24and / or return valuesprint(0 or "default", "a" and "b", None or 0)
What does this program print?
print(0 or "default", "a" and "b", None or 0)- ATrue True False
- Bdefault b 0
- Cdefault a None
- D0 a None
Answer: B. or returns the first truthy value, or the last value when none is truthy. and returns the first falsy value, or the last value when all are truthy. Neither one converts to True or False.
Short-circuit evaluation in Python25Chained comparisonsprint(3 > 2 > 1, (3 > 2) > 1)
What does this program print?
print(3 > 2 > 1, (3 > 2) > 1)- ATrue False
- BTrue True
- CFalse False
- DFalse True
Answer: A. 3 > 2 > 1 means 3 > 2 and 2 > 1, which is True. With the brackets, 3 > 2 is worked out first and gives True, and True > 1 is False because True equals 1.
Comparison operators in Python26Generatorsprint(sum(squares), sum(squares))
What does this program print?
squares = (n * n for n in range(3))print(sum(squares), sum(squares))- A5 5
- B0 5
- C5 0
- DIt raises StopIteration
Answer: C. A generator can be read only once. The first sum() uses up every value (0 + 1 + 4). The second finds nothing left and returns 0. Use a list when you need the values twice.
The Python iter() function explained27Class attributesprint(b.items)
What does this program print?
class Cart: items = []a = Cart()b = Cart()a.items.append("tea")print(b.items)- A[]
- BIt raises AttributeError
- CNone
- D['tea']
Answer: D. items is defined on the class, so every instance shares the one list. Create it in __init__ with self.items = [] to give each cart its own.
Python class attributes explained28return and finallyprint(check())
In what order are the two words printed?
def check(): try: return "try" finally: print("cleanup")print(check())- Atry, then cleanup
- Bcleanup, then try
- COnly try
- DOnly cleanup
Answer: B. finally runs before the function actually hands back its value. So "cleanup" is printed inside the function, and then the caller prints the returned "try".
Handle Python errors with exceptions29Float precisionprint(0.1 + 0.2 == 0.3, round(0.1 + 0.2, 2) == 0.3)
What does this program print?
print(0.1 + 0.2 == 0.3, round(0.1 + 0.2, 2) == 0.3)- AFalse True
- BTrue True
- CFalse False
- DTrue False
Answer: A. Floats are stored in binary and cannot hold 0.1 or 0.2 exactly, so the sum is 0.30000000000000004. Rounding first, or math.isclose(), gives the comparison you meant.
Numeric precision in Python30*args and **kwargsshow(1, 2, a=3, b=4)
What does this program print?
def show(*args, **kwargs): print(len(args), sorted(kwargs))show(1, 2, a=3, b=4)- A4 []
- BIt raises TypeError
- C2 [3, 4]
- D2 ['a', 'b']
Answer: D. Positional arguments land in the tuple args, and named ones in the dictionary kwargs. sorted() on a dictionary gives its keys.
Positional and keyword arguments in PythonKeep going
What to do after this quiz
FAQ
Questions people ask
Are these Python practice questions good for beginners?
Yes. Start with the Basics level: it needs only variables, strings, lists and dictionaries. Core adds comprehensions, scope and exceptions, and Tricky covers the behaviour that catches experienced people out.
Which Python version do the answers apply to?
Every snippet was run on Python 3.14 and the marked answer matches what it printed. Nothing here depends on a recent feature, so the answers hold on any Python 3 version.
Is my score saved?
Yes, in your browser on this device. Your best score for each level, your day streak and the question you stopped at are all there when you come back. Nothing is sent to a server and you do not need an account.
How do I get more Python questions?
Open the AI Quiz Generator on Rune Learn, type a topic such as "Python dictionaries" or "decorators", and it writes a fresh quiz with explanations.