0
0
Pythonprogramming~5 mins

For loop execution model in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a for loop used for in Python?
A for loop is used to repeat a block of code multiple times, once for each item in a sequence like a list or string.
Click to reveal answer
beginner
How does Python decide how many times to run the code inside a for loop?
Python runs the code once for each item in the sequence you give it. It stops when it reaches the end of the sequence.
Click to reveal answer
beginner
What happens to the loop variable in each iteration of a for loop?
The loop variable takes the value of the next item in the sequence each time the loop runs.
Click to reveal answer
beginner
Explain the flow of a for loop with an example:
for x in [1, 2, 3]: print(x)
The loop runs 3 times. First, x = 1 and prints 1. Then x = 2 and prints 2. Finally, x = 3 and prints 3. Then it stops.
Click to reveal answer
beginner
Can a for loop run zero times? When?
Yes, if the sequence is empty (like an empty list), the for loop does not run at all.
Click to reveal answer
What does the loop variable represent in a for loop?
AThe total number of items in the sequence
BEach item in the sequence, one at a time
CThe index of the last item only
DA fixed value throughout the loop
How many times will this loop run?
for i in []: print(i)
A0 times
B1 time
CDepends on i
DInfinite times
What happens after the for loop finishes all items?
AThe loop variable resets to zero
BThe program stops
CThe loop restarts automatically
DThe program continues with the next line after the loop
Which of these is a valid sequence to use in a for loop?
AA boolean like True
BA number like 5
CA list like [1, 2, 3]
DA single character like 'a'
What is printed by this code?
for c in 'Hi': print(c)
AH then i on separate lines
BHi on one line
CNothing
DError
Describe how a for loop works in Python, including what the loop variable does.
Think about how the loop variable changes each time.
You got /4 concepts.
    Explain what happens if the sequence in a for loop is empty.
    What does the loop do when there is nothing to loop over?
    You got /3 concepts.