Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

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!')
share|improve this question
    
I presume you are using python 3 due to the print() but could you please confirm that? – jamylak May 10 '12 at 5:19
    
Yes i use python 3.1 – ScorpDt May 10 '12 at 5:25
2  
SyntaxError is not an exception that normally happens at runtime. – Ignacio Vazquez-Abrams May 10 '12 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 – jamylak May 10 '12 at 5:32
1  
Thank you guys! – ScorpDt May 10 '12 at 5:55

1 Answer 1

up vote 4 down vote accepted

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!')
share|improve this answer
    
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 May 10 '12 at 5:37
    
@jamylak Thanks, I really didn't knew that If uses left to right checking. – Ashwini Chaudhary May 10 '12 at 5:47
    
+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 May 10 '12 at 5:50
    
@jamylak no that isn't sarcasm, it was helpful. – Ashwini Chaudhary May 10 '12 at 6:00
    
Oh alright thanks then :D – jamylak May 10 '12 at 6:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.