python 循环定义变量,为什么我不必使用range()在for循环中定义变量,但是在Python中必须在while循环中定义变量?...

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值