输入特定输入时中断

values = []
while True:
   values.append(int(input('Enter a value:')))
   if values.append(int(input('Enter a value:'))) == 0:
      break

输入0时,我试图退出代码。我究竟做错了什么?

评论
Oswal
Oswal

Each time you call input a new input is being entered, and list.append will add the input to the list and return None, which is not equal to 0.

You can use a variable val to store the input, and use it to test, if you want to store the value 0 in the list, append it before checking:

values = []
while True:
   val = int(input('Enter a value:'))
   values.append(val)  #  this will add `0` to the list when it's entered
   if val == 0:
      break

如果您不想存储它,请在if之后附加:

values = []
while True:
   val = int(input('Enter a value:'))
   if val == 0:
      break
   values.append(val)  #  this won't add `0` to the list when it's entered
点赞
评论
心太冷
心太冷

values.append(...)的返回为None。它仅更新变量。 这意味着您的代码始终在检查“ None == 0”,并且永远不会退出。

a = values.append(int(input('Enter a value:')))
>> Enter a value:0
print(a) 
>> None 
print(values) 
>> [0]

对您的代码的修复是:

while True:
    result = int(input('Enter a value:'))
    if result == 0:
        break
点赞
评论