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()
You were very close in your 2nd code. You would need to do some changes, and your code should be like this: –
for loopand continue the
whileloop.else blockof yourfor-loopandbreak out of the while loop.
expressionoutside your while loop, you would need to declare it outside the while loop.