Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I not have to define the variable in a for loop using range(), but I do have to in a while loop in Python?

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?

like image 775
codingbryan Avatar asked May 28 '19 05:05

codingbryan


2 Answers

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:
like image 196
Selcuk Avatar answered Sep 20 '22 11:09

Selcuk


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.)

like image 43
gmds Avatar answered Sep 21 '22 11:09

gmds