我的程序在继续之前需要数学输入并检查错误,这是我需要帮助的代码的一部分:
expression= introduction()#just asks user to input a math expression
operators= set("*/+-")
numbers= set("0123456789")
for i in expression:
while i not in numbers and i not in operators:
print("Please enter valid inputs, please try again.")
expression= introduction()
现在我已经设置了一个错误循环,但我遇到的问题是我不知道在这种情况下如何更新循环。任何人吗?
我需要一些简单的东西,例如下面答案中的“while True”代码。其余的太先进了。我需要一些贴近本OP中发布的代码的东西。
答案 0 :(得分:3)
我会这样做:
valid = operators | numbers
while True:
expression = introduction()
if set(expression) - valid:
print 'not a valid expression, try again'
else:
break
您只想在每个错误introduction()
致电expression
一次。您现在就这样做了,为introduction()
中的每个无效字符致电expression
。
答案 1 :(得分:1)
expression = introduction()
operators = {'*', '/', '+', '-'}
while any(not char.isnumeric() and char not in operators for char in expression):
print("Please enter valid inputs, please try again.")
expression = introduction()