3.1.2.13 Python loops | else
The for loop and the else branch
for loops behave a bit differently - take a look at the snippet in the editor and run it.
The output may be a bit surprising.
The
i variable retains its last value.
Modify the code a bit to carry out one more experiment.
i = 111
for i in range(2, 1):
print(i)
else:
print("else:", i)
Can you guess the output?
The loop's body won't be executed here at all. Note: we've assigned the
ivariable before the loop.
Run the program and check its output.
When the loop's body isn't executed, the control variable retains the value it had before the loop.
Note: if the control variable doesn't exist before the loop starts, it won't exist when the execution reaches the
else branch.
How do you feel about this variant of
else?
Now we're going to tell you about some other kinds of variables. Our current variables can only store one value at a time, but there are variables that can do much more - they can store as many values as you want.
0
1
2
3
4
else: 4
Comments
Post a Comment