Why do I not have to define the variable in a for

2019-06-23 17:33发布

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?

6条回答
The star\"
2楼-- · 2019-06-23 17:57

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

查看更多
欢心
3楼-- · 2019-06-23 17:59

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:

x = 12     # this is an assignment, and because we're outside functions x
           # is deduced to be a global

def foo():
    print(x)     # we only "read" x, thus we're talking of the global

def bar():
    x = 3        # this is an assignment inside a function, so x is local
    print(x)     # will print 3, not touching the global

def baz():
    x += 3       # this will generate an error: we're writing so it's a
                 # local, but no value has been ever assigned to it so it
                 # has "no value" and we cannot "increment" it

def baz2():
    global x     # this is a declaration, even if we write in the code
                 # x refers to the global
    x += 3       # Now fine... will increment the global

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 a global or nonlocal 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).

查看更多
男人必须洒脱
4楼-- · 2019-06-23 18:04

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.

查看更多
一夜七次
5楼-- · 2019-06-23 18:08

Python for loops assign the variable and let you use it. We can transform a for loop into a while loop to understand how Python actually does it (hint: it uses iterables!):

iterator = iter(iterable)  # fresh new iterator object
done = False
while not done:
    try:
        item = next(iterator)
        # inside code of a for loop, we can use `item` here
    except StopIteration:
        done = True
查看更多
Fickle 薄情
6楼-- · 2019-06-23 18:09

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:
查看更多
The star\"
7楼-- · 2019-06-23 18:17

If you are coming from other programming languages like C, C++ or Java then do not confuse with for 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.

查看更多
登录 后发表回答