Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.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
Python 即使条件为false,while循环仍会再次循环一次_Python_Loops_While Loop - Fatal编程技术网

Python 即使条件为false,while循环仍会再次循环一次

Python 即使条件为false,while循环仍会再次循环一次,python,loops,while-loop,Python,Loops,While Loop,我的代码似乎永远卡在这个while循环中: array = [] b = 1 while b != 0: b = int(input("please enter whole numbers ")) array += [b] print (array) 代码的意思是将用户输入放入数组,并在用户输入0时停止。我不知道为什么即使条件为false,循环仍能继续代码。我认为只要条件为false,python就会停止 我不想让0成为数组中的一个元素。我想你可以使用自己的退出条件,

我的代码似乎永远卡在这个while循环中:

array = []
b = 1
while b != 0:
    b = int(input("please enter whole numbers "))
    array += [b]
print (array)     
代码的意思是将用户输入放入数组,并在用户输入0时停止。我不知道为什么即使条件为false,循环仍能继续代码。我认为只要条件为false,python就会停止


我不想让
0
成为数组中的一个元素。我想你可以使用自己的退出条件,而不依赖
语句本身来停止:

array = []

while True:   # never exit here
    b = int(input("please enter whole numbers "))
    if b == 0:
        break    # exit the loop here
    array += [b]
print (array)   
“休息”可以帮助你做到这一点

array=[1]
而数组[-1]!=0:
b=int(输入(“请输入整数”))
数组+=[b]
如果数组[-1]==0:
打印(数组[1:-1])
打破

希望这有帮助:)

为了不使用break,我对magamongo的答案做了一些修改,但您也可以像quamrana的答案一样使用break:

array = []
b = 1
while b != 0:
    b = int(input("please enter whole numbers "))
    array += [b]
array = array[:-1]
print(array)

而循环仅在程序返回到循环顶部检查您设置的条件时停止(您使用了
b!=0
)。在返回顶部之前,它必须将所有语句通读到底部,在您的例子中包括
array+=[b]
。这意味着上次
b
将为
0
。您似乎在数组的开头添加了
1
,在数组的结尾添加了
0
。OP当然不希望在结尾处出现
0
。好的,然后用“打印(数组[1:-1])代替“打印(数组)”“非常感谢你这么快回复我,你帮了我很大的忙谢谢,是的,我想过使用break,但我的老师还没有教过,像你在这里做的那样使用基本工具更有意义。我从来没想过。再谢谢你一次,不客气。当循环结束前有很多操作时,中断可能很有用。但如果您使用相同的计算,我认为防止break语句更好,因为它们会中断执行流。