概述
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 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.)
最后
以上就是玩命苗条为你收集整理的python 循环定义变量,为什么我不必使用range()在for循环中定义变量,但是在Python中必须在while循环中定义变量?...的全部内容,希望文章能够帮你解决python 循环定义变量,为什么我不必使用range()在for循环中定义变量,但是在Python中必须在while循环中定义变量?...所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复