【发布时间】: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