为什么我不必使用range()在for循环中定义变量,但是在Python中必须在while循环中定义变量? [英] 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?

查看:224
本文介绍了为什么我不必使用range()在for循环中定义变量,但是在Python中必须在while循环中定义变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用for循环使用以下代码:

I have the following code using a for loop:

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

现在使用while循环获得相同的结果:

Now the same result using a while loop:

    num = 0
    total = 0
    while num <= 99:
         num = num + 1
         total = total + num
         print(total)

为什么在第一种情况下不必定义num,但是在第二种情况下必须定义num?他们都不都是变量吗?

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.

如果我们查看官方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.)

这篇关于为什么我不必使用range()在for循环中定义变量,但是在Python中必须在while循环中定义变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆