SeesSound
SeesSound

Reputation: 505

Python updating a loop

my program takes a mathematical input and checks it for errors before proceeding, here is the part of the code I need help with:

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()

Now I have set up an error loop but the problem I am having is that I don't know what to update the loop with in this scenario. Anyone?

I need something simple such as the "while True" code in the answers below. The rest are too advanced. I need something close to the code that is posted in this OP.

Upvotes: 0

Views: 137

Answers (2)

Tyler Crompton
Tyler Crompton

Reputation: 12672

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()

Upvotes: 1

Alok Singhal
Alok Singhal

Reputation: 96171

I would do it something like this:

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

You only want to call introduction() once per bad expression. The way you do it now, you are calling introduction() for every invalid character in expression.

Upvotes: 3

Related Questions