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
0 day streakBest –
Python
word = "python"print(word[1:4])

1 / 10

What does this program print?

0 correct

Your score and streak are saved in this browser. No account needed.

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 types
1Slicingprint(word[1:4])

What does this program print?

word = "python"print(word[1:4])
  1. Apyt
  2. Bytho
  3. Cyth
  4. 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 Python
2Divisionprint(7 // 2, 7 / 2, -7 // 2)

What does this program print?

print(7 // 2, 7 / 2, -7 // 2)
  1. A3 3.5 -4
  2. B3 3.5 -3
  3. C3.5 3.5 -3.5
  4. 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 Python
3f-stringsprint(f"{name} is {age + 1}")

What does this program print?

name = "Ana"age = 31print(f"{name} is {age + 1}")
  1. AAna is 31
  2. BIt raises TypeError
  3. C{name} is {age + 1}
  4. 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 explained
4Strings are immutableprint(name)

What does this program print?

name = "rune"name.upper()print(name)
  1. ARUNE
  2. Brune
  3. CRune
  4. 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 Python
5Type conversionprint("3" + "4", int("3") + int("4"))

What does this program print?

print("3" + "4", int("3") + int("4"))
  1. A34 7
  2. B7 7
  3. C34 34
  4. 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 Python
6TruthinessWhich of these values counts as True in an if statement?

Which of these values counts as True in an if statement?

  1. A[] (an empty list)
  2. B0
  3. C"0" (a string holding zero)
  4. 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 Python
7Negative indexesprint(nums[-1], nums[:-1])

What does this program print?

nums = [10, 20, 30, 40]print(nums[-1], nums[:-1])
  1. A10 [20, 30, 40]
  2. B40 [10, 20, 30]
  3. C40 [10, 20, 30, 40]
  4. 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)
  1. A2
  2. B8
  3. C4
  4. 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 functions
9Dictionariesprint(ages.get("ben"), ages.get("ben", 0))

What does this program print?

ages = {"ana": 31}print(ages.get("ben"), ages.get("ben", 0))
  1. AIt raises KeyError
  2. B0 0
  3. CNone 0
  4. 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 Python
10Tuplespoint[0] = 5

What happens when this program runs?

point = (1, 2)point[0] = 5
  1. AIt raises TypeError
  2. Bpoint becomes (5, 2)
  3. Cpoint becomes [5, 2]
  4. 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 Python

Core

Collections, scope and errors
11Lists and referencesprint(a)

What does this program print?

a = [1, 2, 3]b = ab.append(4)print(a)
  1. A[1, 2, 3]
  2. BIt raises an error
  3. C[4, 1, 2, 3]
  4. 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 copy
12Equality and identityprint(a == b, a is b)

What does this program print?

a = [1, 2]b = [1, 2]print(a == b, a is b)
  1. ATrue True
  2. BTrue False
  3. CFalse False
  4. 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 Python
13List 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])
  1. A[0, 1, 4, 9, 16]
  2. B[0, 2, 4]
  3. C[1, 9]
  4. 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 Python
14Dictionary 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})
  1. A{'cake': 10}
  2. B{'tea': 4, 'cake': 10}
  3. C{'cake': 5}
  4. 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 Python
15Setsprint(len(set(nums)), sorted(set(nums)))

What does this program print?

nums = [3, 1, 3, 2, 1]print(len(set(nums)), sorted(set(nums)))
  1. A5 [1, 1, 2, 3, 3]
  2. B3 [3, 1, 2]
  3. C3 [1, 2, 3]
  4. 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 sets
16sort() and sorted()print(result, nums)

What does this program print?

nums = [3, 1, 2]result = nums.sort()print(result, nums)
  1. A[1, 2, 3] [3, 1, 2]
  2. BNone [1, 2, 3]
  3. C[1, 2, 3] [1, 2, 3]
  4. 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)
  1. A30
  2. B(20, 30)
  3. C[20, 30]
  4. 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 Python
18Scopeprint(count)

What does this program print?

count = 0​def increase():    count = 5​increase()print(count)
  1. A0
  2. B5
  3. CNone
  4. 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 Python
19Loops 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")
  1. Aeven found
  2. BIt raises SyntaxError
  3. CNothing
  4. 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 make
20Exceptions print("done")

What does this program print?

try:    print(int("12a"))except ValueError:    print("bad number")finally:    print("done")
  1. Abad number, then done
  2. B12
  3. Cbad number
  4. 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 exceptions

Tricky

The ones interviews love
21Mutable default argumentsprint(add_item("b"))

What does this program print?

def add_item(item, items=[]):    items.append(item)    return items​add_item("a")print(add_item("b"))
  1. A['b']
  2. B['a', 'b']
  3. C['a']
  4. 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 Python
22Nested listsprint(grid)

What does this program print?

grid = [[0] * 2] * 2grid[0][0] = 1print(grid)
  1. A[[1, 0], [0, 0]]
  2. BIt raises IndexError
  3. C[[1, 1], [1, 1]]
  4. 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 Python
23Closures 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])
  1. A[0, 1, 2]
  2. B[3, 3, 3]
  3. C[2, 2, 2]
  4. 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 Python
24and / 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)
  1. ATrue True False
  2. Bdefault b 0
  3. Cdefault a None
  4. 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 Python
25Chained comparisonsprint(3 > 2 > 1, (3 > 2) > 1)

What does this program print?

print(3 > 2 > 1, (3 > 2) > 1)
  1. ATrue False
  2. BTrue True
  3. CFalse False
  4. 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 Python
26Generatorsprint(sum(squares), sum(squares))

What does this program print?

squares = (n * n for n in range(3))print(sum(squares), sum(squares))
  1. A5 5
  2. B0 5
  3. C5 0
  4. 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 explained
27Class attributesprint(b.items)

What does this program print?

class Cart:    items = []​a = Cart()b = Cart()a.items.append("tea")print(b.items)
  1. A[]
  2. BIt raises AttributeError
  3. CNone
  4. 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 explained
28return and finallyprint(check())

In what order are the two words printed?

def check():    try:        return "try"    finally:        print("cleanup")​print(check())
  1. Atry, then cleanup
  2. Bcleanup, then try
  3. COnly try
  4. 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 exceptions
29Float 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)
  1. AFalse True
  2. BTrue True
  3. CFalse False
  4. 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 Python
30*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)
  1. A4 []
  2. BIt raises TypeError
  3. C2 [3, 4]
  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 Python

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.