尝试使用带有列表的For / In 句子在 Python 中创建多值计算器
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)
我尝试使用 While Not 语句,但出现一个明显的错误。我想这是我的理解力很愚蠢的错误,但是我真的无法理解我在做什么错。如果您能帮助我,我会很高兴。
答案 0 :(得分:1)
首先,变量分配应使用=
而非==
完成。您的问题是在第二个input()
中(您让用户选择要停留还是退出),您需要先将输入从字符串转换为int,或者通过数字的字符串表示进行检查(失败-安全):
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
但是,打破循环的最佳方法是使用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
答案 1 :(得分:0)
除了其他两个答案中指出的错误之外,您还以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