我尝试了以下操作,但没有得到预期的输出。
def main():
while True:
numbers = list(map(int(input("Enter a number: ").split())))
answer2 = input("Continue? (yes/no) ")
if answer2 == "no":
break
numbers.append(answer)
print(multiply(numbers.append(answer)))
def multiply(numbers):
total = 1
for x in numbers:
total = total * x
return total
main()
答案 0 :(得分:0)
此代码中有很多错误。首先,answer
变量没有设置在任何地方,但这可能是剩余的。其次,从字符串到整数到映射到列表的转换肯定是没有任何意义的。还要记住,numbers
变量在每次循环迭代中都会重新分配,因此即使继续操作,也会丢失先前输入的数据。固定代码:
def main():
numbers = []
while True:
answer = int(input("Enter a number: "))
numbers.append(answer)
answer2 = input("Continue? (yes/no) ")
if answer2 == "no":
break
print(multiply(numbers))
def multiply(numbers):
total = 1
for x in numbers:
total = total * x
return total
main()
输出:
Enter a number: 1
Continue? (yes/no) yes
Enter a number: 5
Continue? (yes/no) yes
Enter a number: 3
Continue? (yes/no) no
15