Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么这个WHILE循环没有结束?[Python]_Python_While Loop - Fatal编程技术网

为什么这个WHILE循环没有结束?[Python]

为什么这个WHILE循环没有结束?[Python],python,while-loop,Python,While Loop,我正试图在Python中创建一个多值计算器,使用While,For/in带有列表的句子 numbers = [] out = 0 while out == 0: numbers.append(int(input('Add a number: '))) out2 = input('''[0]To keep adding numbers [1]To add and leave: ''') if out2 == 1: out == 1 #In theory

我正试图在Python中创建一个多值计算器,使用While,For/in带有列表的句子

numbers = []
out = 0

while out == 0:
    numbers.append(int(input('Add a number: ')))
    out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
    if out2 == 1:
        out == 1

#In theory if out == 1 the while loop should end and go to:

for add in numbers:
    add = numbers
print(add)


我试着用而不是句子,但我犯了一个明显的错误。我想这是一个相当愚蠢的理解错误,但我真的不知道我做错了什么。如果你能帮助我,我将非常高兴。

首先,变量赋值应该用
=
而不是
=
完成。您的问题是,在第二个
input()
(让用户选择他/她是留下还是离开)中,您需要首先将输入从字符串转换为int,或者通过数字的字符串表示进行检查(故障保护):

但是,中断循环的最佳方法是使用
break

while out == 0:
    numbers.append(int(input('Add a number: ')))
    out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
    if out2 == '1':
        break

除了在其他2个答案中指出的错误外,您从用户处获得的输入是
str
,而不是将其转换为
int

因此,它永远不会达到
if
条件,因此您的程序不会结束

请试试这个

numbers = []
out = 0

while out == 0:
    numbers.append(int(input('Add a number: ')))
    out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
    print(type(out2))
    if int(out2) == 1: # Convert the out2 to an int here
        print(f" Inside if condition")
        out = 1 # Use an assignment operator here

您的答案是正确的,虽然您所写的内容已包含在其他答案中,但可能其他两个答案也不完整,这就是为什么我们不需要重复两次相同的答案,而且使用
'1'
检查比
int(out2)
更好,因为如果输入为非int,则会抛出错误,不过,你必须是自动防故障的,如果你想使用它,还是把它放在
试一下吧..除了
块,你仍然不值得投反对票,因为时间问题可能是时间问题。我只是在发布后才得到你的答案。否则我就不会:)哈哈,这就是解决办法,我从没想过会是那个小东西。非常感谢您的帮助。另外,正如@WasifHasan所建议的,如果输入不是int,请确保进行失败检查。如果是练习程序,则可以。否则,请进行typecheck或“1”检查:(谢谢,这也是我出错的原因之一。
numbers = []
out = 0

while out == 0:
    numbers.append(int(input('Add a number: ')))
    out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
    print(type(out2))
    if int(out2) == 1: # Convert the out2 to an int here
        print(f" Inside if condition")
        out = 1 # Use an assignment operator here