4

I'm new in programming and I have an issue when doing the input validation. My program requires to input number from 1 to 10 or the letter y but it seems that I cannot do an error handler for this.

def checkingInput():
    while True:
        try:
            a = input()
            if 10 >= a >= 1 or a == 'y':
                return value
            else:
                print('Invalid input!')
        except NameError:
            print('Name error!Please try again!')
        except SyntaxError:
            print('Syntax Error!Please try again!')
4
  • I presume you are using python 3 due to the print() but could you please confirm that? Commented May 10, 2012 at 5:19
  • 2
    SyntaxError is not an exception that normally happens at runtime. Commented May 10, 2012 at 5:31
  • I think you want ValueError instead of SyntaxError. Also you can't compare ints with strings so you should change your line to if a == 'y' or 1 <= int(a) <= 10 Commented May 10, 2012 at 5:32
  • Also, if this is python 3 you do not need to catch NameError either Commented May 10, 2012 at 5:34

1 Answer 1

4

as jamylak suggested change the if condition to :

if a == 'y' or 1 <= int(a) <= 10:

program:

def checkingInput():
    while True:
        try:
            a = input('enter')
            if a == 'y' or 1 <= int(a) <= 10:
                return a
            else:
                print('Invalid input!')
        except ValueError:
            print('Value error! Please try again!')
Sign up to request clarification or add additional context in comments.

5 Comments

doesn't work if a is 'y' since if statement checks conditions from left to right and won't be able to convert 'y' to int. Do this instead: if a == 'y' or 1 <= int(a) <= 10
@jamylak Thanks, I really didn't knew that If uses left to right checking.
+1 Also i can't tell if that is sarcasm or not... If it is I'm sorry but I just thought it was worth explaining for other people reading this.
@jamylak no that isn't sarcasm, it was helpful.
As an aside: proper style dictates a name of check_input - the punctuation (all lowercase with an underscore in between) is the preference of the Python community, but all programmers would prefer the name check over checking: since the function does something, give it a name that's imperative, rather than descriptive.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.