SeesSound
SeesSound

Reputation: 505

Python looping error checks

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. I need something close to the code that is posted in this OP. Something like:

expression= introduction()#just asks user to input a math expression    
operators= set("*/+-")
numbers= set("0123456789")
while True:
    for i in expression:
        if i not in numbers and i not in operators:
            print("Please enter valid inputs, please try again.")
            expression= introduction()
    else:
        break

Note that this code doesn't work either. It loops for every single mistake that the user inputs for "expression".

Things such as what is below are too advanced and I cannot use them:

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

import string

expression = introduction()    
operators = {'*', '/', '+', '-'}
numbers = set(string.digits)
while any(char not in numbers and char not in operators for char in expression):
    print("Please enter valid inputs, please try again.")
    expression = introduction()

Upvotes: 0

Views: 2582

Answers (2)

Nicolas
Nicolas

Reputation: 5668

If you can't use all() or any(), you could test the length of the list which contains the errors:

if [c for c in expression if c not in operators|numbers]:
    # error

Without the | operator:

if [c for c in expression if c not in operators and c not in numbers]:
    # error

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213193

You were very close in your 2nd code. You would need to do some changes, and your code should be like this: -

expression = ""
operators= set("*/+-")
numbers= set("0123456789")
while True:
    expression= introduction()  # You should read the next expression here
    for i in expression:
        if i not in numbers and i not in operators:
            print("Please enter valid inputs, please try again.")
            break # You should have a break here
    else:
        break

print expression  # Print if valid
  • If the expression is not valid, it will only break out of for loop and continue the while loop.
  • And, if the expression is valid, it will execute the else block of your for-loop and break out of the while loop.
  • To use your expression outside your while loop, you would need to declare it outside the while loop.

Upvotes: 1

Related Questions