我正在尝试将用户输入插入列表,直到用户输入“0”。现在,一旦我输入0
,它就不会退出while循环。
这是我的代码:
num_array = []
inputnum = raw_input('Please enter a number: ')
num_array.append(inputnum)
while inputnum != 0:
inputnum = raw_input('Please enter a number: ')
num_array.append(inputnum)
for i in range(len(num_array) - 1):
print(num_array[i] + ' + ')
print(num_array[total - 1] + ' = ' + sum(num_array))
答案 0 :(得分:1)
尝试检查:
num_array = []
# raw_input return value as string,int convert it to string.
inputnum = int(raw_input('Please enter a number: '))
num_array.append(inputnum)
# earlier check for string '0' to interger 0 so the condition returned true but now int() converted inputnum to integer.
while inputnum != 0:
inputnum = int(raw_input('Please enter a number: '))
num_array.append(inputnum)
for i in range(len(num_array) - 1):
print("%d +" % num_array[i])
# sum() gave exception because earlier num_array had string type but int() converted all the value to integer.
print("%d = %d" % (num_array[len(num_array) - 1],sum(num_array)))
答案 1 :(得分:0)
尝试使用
while inputnum != '0':
因为raw_input函数返回一个字符串,而不是整数。但是,如果您的input_num需要是一个整数,那么请遵循上述解决方案。