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!')
juliomalegria
25k14 gold badges77 silver badges89 bronze badges
asked May 10, 2012 at 5:18
ScorpDt
431 gold badge1 silver badge3 bronze badges
1 Answer 1
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!')
Katriel
124k19 gold badges141 silver badges172 bronze badges
answered May 10, 2012 at 5:35
Ashwini Chaudhary
252k60 gold badges479 silver badges520 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
jamylak
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) <= 10Ashwini Chaudhary
@jamylak Thanks, I really didn't knew that
If uses left to right checking.jamylak
+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.
Ashwini Chaudhary
@jamylak no that isn't sarcasm, it was helpful.
Karl Knechtel
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.lang-py
print()but could you please confirm that?SyntaxErroris not an exception that normally happens at runtime.ValueErrorinstead ofSyntaxError. Also you can't compareintswithstringsso you should change your line toif a == 'y' or 1 <= int(a) <= 10