I have the following code using a for loop:
total = 0
for num in range(101):
total = total + num
print(total)
Now the same result using a while loop:
num = 0
total = 0
while num <= 99:
num = num + 1
total = total + num
print(total)
Why is it that I do not have to define num in the first case, but I do have to define it in the second? Are they both not variables?
Well, for
is a special statement that automatically defines the variable for you. It would be redundant to require you to declare the variable in advance.
while
is a general purpose loop construct. The condition for a while
statement doesn't even have to include a variable; for example
while True:
or
while my_function() > 0:
I'd like to approach this question from a slightly different perspective.
If we look at the official Python grammar specification, we can see that (approximately speaking), a while
statement takes a test
, while a for
statement takes an exprlist
and testlist
.
Conceptually, then, we can understand that a while
statement needs one thing: an expression that it can repeatedly evaluate.
On the other hand, a for
statement needs two: a collection of expressions to be evaluated, as well as a number of names to bind the results of those evaluations to.
With this in mind, it makes sense that a while
statement would not automatically create a temporary variable, since it can accept literals too. Conversely, a for
statement must bind to some names.
(Strictly speaking, it is valid, in terms of Python grammar, to put a literal where you would expect a name in a for
statement, but contextually that wouldn't make sense, so the language prohibits it.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With