0

私のプログラムは数学的な入力を受け取り、先に進む前にエラーがないかチェックします。これは私が助けが必要なコードの部分です:

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に掲載されているコードに近いものが必要です。

4

2 に答える 2

3

私はそれを次のようにします:

valid = operators | numbers
while True:
    expression = introduction()
    if set(expression) - valid:
        print 'not a valid expression, try again'
    else: 
        break

introduction()bad ごとに 1 回だけ呼び出しますexpression。今のやり方では、introduction()のすべての無効な文字を呼び出していますexpression

于 2012-11-07T23:32:36.647 に答える
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()
于 2012-11-07T23:33:38.563 に答える