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?

后端 未结 6 734
悲哀的现实
悲哀的现实 2021-01-18 17:36

I have the following code using a for loop:

    total = 0
    for num in range(101):
       total = total + num
       print(total)

Now the

6条回答
  •  孤城傲影
    2021-01-18 18:01

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

提交回复
热议问题