Python Practice Test: Control Flow, If Statements and Loops
- If Statements and Loops
- 10 questions
- 13 minutes
Ten questions that ask you to trace short pieces of code. Tip: write down the value of each variable after every loop pass.
Tap an option to mark your answer. You can change your mind, or tap the same option again to leave the question blank. The correct answers and explanations appear when you finish the test.Tap an option to answer; tap it again to leave the question blank.
Your result
- 0 correct
- 0 wrong
- 0 blank
-
Question 1
total = 0
for i in range(1, 5):
total += i
print(total)What does the code print?
Correct answer: B
range(1, 5) produces 1, 2, 3 and 4, which add up to 10. The end value 5 is excluded.
-
Question 2
n = 0
while True:
n += 1
if n == 3:
break
print(n)What does the code print?
Correct answer: D
The loop increases n until it equals 3 and then break leaves the loop.
-
Question 3
for i in range(5):
if i % 2 == 0:
continue
print(i)What is the output?
Correct answer: A
continue skips the rest of the loop body for even numbers, so only 1 and 3 are printed.
-
Question 4
x = 15
if x > 10:
print("A")
elif x > 5:
print("B")
else:
print("C")What does the code print?
Correct answer: C
Only the first branch whose condition is true runs. Since 15 > 10, the elif is never checked.
-
Question 5
print(list(range(2, 10, 3)))
What does the code print?
Correct answer: B
The sequence starts at 2 and steps by 3 until it reaches a value of 10 or more.
-
Question 6
for n in [1, 2, 3]:
if n == 5:
break
else:
print("no break")What does the code print?
Correct answer: A
A for loop's else block runs when the loop finishes without hitting break. 5 is never in the list, so break never happens.
-
Question 7
print(not (3 > 2 and 1 > 2))
What does the code print?
Correct answer: D
3 > 2 is True and 1 > 2 is False, so the and expression is False and not turns it into True.
-
Question 8
count = 0
for i in range(3):
for j in range(2):
count += 1
print(count)What does the code print?
Correct answer: B
The inner loop runs 2 times for each of the 3 outer passes, giving 3 x 2 = 6 increments.
-
Question 9
if 4 > 3:
print("yes")What happens when this code runs?
Correct answer: C
The body of an if statement must be indented. Without it Python stops before running any line.
-
Question 10
x = 7
print("even" if x % 2 == 0 else "odd")What does the code print?
Correct answer: A
The conditional expression picks the text after if when the test is true; 7 % 2 is 1, so the else value is used.
Questions you leave blank are not counted as wrong.