0

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@user1716168: This is a lot more simple than your code, and it's the correct way to handle this problem.
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()

3 Comments

I cannot utilize "import", "any", and "char" commands. I am limited to lists, and string manipulators, and the other most basic stuff. The other guy's way works... At least for operator input but not for numeric input...
any is a built-in function. Why can't you use it? Also, char is just a variable name, not a command.
@user1716168, as Tim pointed out, any is a builtin function. I don't understand why you can't use that (unless you are modifying its value for some weird reason). Anyway, I simplified the code a bit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.