【问题标题】:Equivalent while loop block for a for loop blockfor 循环块的等效 while 循环块
【发布时间】:2019-06-03 14:50:08
【问题描述】:

我是一个新手,试图从 Al Sweigart 的 Automate The Boring Stuff with Python 中学习 Python,我偶然发现了他的代码块来回答一个数学问题:“所有的总和是多少?从 0 到 100 的数字?”显然,这是高斯老师想让他忙起来时提出的问题。

Sweigart 使用了for 循环和range() 函数来得到答案:

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

在后面的一页中,他说“实际上可以使用 while 循环来做与 for 循环相同的事情;for 循环更简洁。”

如何在 while 循环中呈现此语句?

我尝试将for 替换为while,但出现错误:“未定义名称'num'。”我还尝试使用另一个论坛的另一个代码块来建立一个求和数学方程,但完全迷路了。

print('Gauss was presented with a math problem: add up all the numbers from 0 to 100. What was the total?')
a=[1,2,3,4,5,...,100]
i=0
while i< len(a)-1:
    result=(a[i]+a[i+1])/2
    print(result)
    i +=1

然后,我尝试在一个等式中设置i,该等式会循环直到添加每个数字,但卡住了。

print('Gauss was presented with a math problem: add up all the numbers from 0 to 100. What was the total?')
i=0
while i<101:
    i=i+1
    a=i

while 语句会不会太复杂而无法保证付出努力?

【问题讨论】:

  • 在您声称“未定义名称'num'”的代码中,没有“num”,因此您必须引用一些不同的代码。

标签: python-3.x for-loop while-loop


【解决方案1】:

你的最后一个例子很接近。

这种形式的for循环:

for x in range(N):
    # ...

可以用while 循环替换,如下所示:

x = 0
while x < N:
    # ...
    x += 1  # equivalent to x = x + 1

只要确保其余代码保持不变!

【讨论】:

    【解决方案2】:

    for 循环更简洁。注意我们需要一个“计数器”变量,在本例中为 i 和 while 循环。这并不是说我们在 for 循环中不需要它们,但是它们很好地集成到语法中以使代码更简洁。

    i = 0
    total = 0
    while i < 101:
        total += i
        i += 1
    print(total)
    

    Python 的 for 循环语法也是 foreach 的等价物:

    for eachItem in list:
    # Do something
    

    【讨论】:

    • 谢谢!这正是我正在寻找的代码分解类型。我一直在寻找如何让方程式相互补充的问题上磕磕绊绊。现在我看到你需要第二个变量来避免 i 变成 0。
    猜你喜欢
    • 2015-04-17
    • 2022-01-12
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 2016-04-15
    • 2020-02-22
    • 2019-11-10
    • 1970-01-01
    相关资源
    最近更新 更多