且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-08-09 03:48:23

我想从稍微不同的角度来解决这个问题.

I'd like to approach this question from a slightly different perspective.

如果我们查看官方Python语法规范,我们可以看到(大约),while语句使用test,而for语句使用exprlisttestlist.

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.

从概念上讲,我们可以理解while语句需要做一件事:它可以重复计算的表达式.

Conceptually, then, we can understand that a while statement needs one thing: an expression that it can repeatedly evaluate.

另一方面,for语句需要 two :要评估的表达式的集合,以及将这些评估的结果绑定到其中的多个名称.

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.

考虑到这一点,有意义的是while语句不会自动创建一个临时变量,因为它也可以接受文字.相反,for语句必须绑定到某些名称.

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.

(严格来说,就Python语法而言,在for语句中将文字放在期望的位置是有效的,但是在上下文上这没有意义,因此该语言禁止使用.)

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