我有一个用python 3编写的真正的基本计算器程序。第一次是这样,在给出答案后,可以提示用户做另一个问题。后续循环用于验证用户输入。
出于某种原因,内部循环工作正常,如果我选择关闭程序,主循环将工作,但是,如果我选择做另一个问题,它循环要求数字而不是开始询问什么问题。< / p>
while True:
# User inputs type of problem & input is validated
while True:
problem = input()
if problem not in ('1', '2', '3', '4'):
print('You did not make a valid selection, please try again.')
else:
break
# User inputs numbers for problems & input is validated
while True:
num1 = input('Please input the first number in the problem')
num2 = input('Please input the second number in the problem')
isnum1 = is_number(num1)
isnum2 = is_number(num2)
if isnum1 is False or isnum2 is False:
print('You did not enter a number')
else:
num1 = float(num1)
num2 = float(num2)
break
# Perform appropriate math
ans = 0
if problem == '1':
ans = num1 + num2
print(num1, '+', num2, '=', ans)
elif problem == '2':
ans = num1 - num2
print(num1, '-', num2, '=', ans)
elif problem == '3':
ans = num1 * num2
print(num1, '*', num2, '=', ans)
elif problem == '4':
ans = num1 / num2
print(num1, '/', num2, '=', ans)
# Ask if user would like to perform another problem or exit
nxt = input('Would you like to do another problem?\n 1 - Yes\n 2 - No')
if nxt not in ('1', '2'):
print('You did not make a valid selection.')
elif nxt == '2':
break
exit(0)
答案 0 :(得分:1)
你的问题是problem
没有留下范围,所以仍然定义了你,并且你突破了第一个循环。
这是你的第一个循环:
while True:
problem = input()
if problem not in ('1', '2', '3', '4'):
print('You did not make a valid selection, please try again.')
else:
break
在此之前未定义 problem
。但是在此之后 定义了。因此,当外部while
循环循环时,问题将保持定义。因此,您的第二个if
子句(else
)将执行,中断。
要证明这一点,请执行以下操作:
while True:
problem = input()
if problem not in ('1', '2', '3', '4'):
print('You did not make a valid selection, please try again.')
else:
print('You have made a valid selection: {}".format(problem)) # This will display, showing that the loop is executed.
break
要解决此问题,请执行以下操作:
problem = None
while True:
problem = input()
if problem not in ('1', '2', '3', '4'):
print('You did not make a valid selection, please try again.')
else:
print('You have made a valid selection: {}".format(problem))
break
答案 1 :(得分:1)
纳撒尼尔说,我离开了problem
。但是,如果我只是在循环之前设置problem = None
,则没有提示用户选择问题的说明。
所以我改变了这段代码:
if nxt not in ('1', '2'):
print('You did not make a valid selection.')
elif nxt == '2':
break
对此:
if nxt not in ('1', '2'):
print('You did not make a valid selection.')
elif nxt =='1':
print('Please select the type of problem you would like to complete.\n 1 - Addition\n 2 - Subtraction\n 3 - Multiplication\n 4 - Division\n')
problem = 0
elif nxt == '2':
break
现在一切都很好。感谢Nathaniel正确方向的观点。