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?
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 atest
, while afor
statement takes anexprlist
andtestlist
.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, afor
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.)In python there is no need, in most cases, to define/declare variables.
The rule is that if you write (assign) a variable then the variable is a local variable of the function; if you only read it instead then it's a global.
Variables assigned at top-level (outside any function) are global... so for example:
The
for
statement is simply a loop that writes to a variable: if no declaration is present then the variable will be assumed to be a local; if there is aglobal
ornonlocal
declaration then the variable used will have the corresponding scope (nonlocal
is used to write to local variable of the enclosing function from code in a nested function: it's not used very frequently in Python).For Loop iterates each element from the list until the given range. So no need of any variable to check condition.
While Loop iterates until the given condition is true. Here we need some variable or value to check the condition, So the variable num is used before the loop.
Python
for
loops assign the variable and let you use it. We can transform afor
loop into awhile
loop to understand how Python actually does it (hint: it uses iterables!):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 awhile
statement doesn't even have to include a variable; for exampleor
If you are coming from other programming languages like
C
,C++
orJava
then do not confuse withfor in
loop of python.In python,
for in
loop pick one item from list of items and does something with help of the picked item.