gpt4 book ai didi

python - 在 'while' 循环之外定义变量

转载 作者:行者123 更新时间:2023-12-01 04:37:09 25 4
gpt4 key购买 nike

[背景信息:我目前正在 MIT edx 网站完成 Python 编程类(class),并且正在研究有关 while 循环的部分。]

我一直在努力解决的问题如下:“编写一个 while 循环,将 1 到 end 的值相加,包括 1 和 end。end 是我们为您定义的变量。”

当我尝试回答这个问题时,我输入:

while end != 0:
total = 0 + end
end = end-1
print total

我为“end”输入的任何值的返回结果都是 1,这显然是不正确的。

但是,当我再次尝试时,我在循环外部定义了“total”,并输入:

total = 0
while end != 0:
total = total + end
end = end-1
print total

这有效!

我的问题是:为什么我输入的第一个代码不起作用?在循环之外定义“total”有什么意义?

最佳答案

在第一个代码块中,每次运行 total = 0 + end 时,都会重置 total

total = 0 + 10
total = 0 + 9
total = 0 + 8
...
total = 0 + 1

最后,运行的最后一行是 total = 0 + 1 等于 1

在第二个循环中,您将利用 total 的先前值:

total = 0
total = 0 + 10
total = 10 + 9
total = 19 + 8
...
total = 54 + 1

每次通过循环,total 都会增加并被利用。在第一个中,您在每个循环中重写了总数。

关于python - 在 'while' 循环之外定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31523650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com