Validating an Input
Question:
I am a beginner python programmer and was hoping to get some help. I was trying to create a procedure where it would check if a user’s input is either empty or a single alphabetic character. I am having trouble as every time I run it, and I type 2, it doesn’t print anything. However, if I do multiples letters such as "ad", it says to enter only one character…
What I did:
# Create Validate function
def validate_input(LETTER):
if len(LETTER) == 0 or len(LETTER) == 1:
pass
elif len(LETTER) >= 2 or not LETTER.islapha():
print('Sorry, please enter a single letter')
else:
print('Sorry, please enter a letter')
#Ask for inputs
# Create function to validate input that returns true or false. If false then ask for input again.
first_char = input('Enter first character(lower cases) or press Enter: ')
validate_input(first_char)
What I got:
Enter first character(lower cases) or press Enter: 2
Enter second character(lower cases) or press Enter: ad
Sorry, please enter a single letter
Thanks in advance for your help…
Answers:
You need to change the order of your checks. At the moment, the check for the length happens before the check for the type of character, and a success on the first check will skip the later ones.
def validate_input(LETTER):
if len(LETTER) == 0:
pass
elif len(LETTER) >= 2 or not LETTER.isalpha():
print('Sorry, please enter a single letter')
elif len(LETTER) == 1:
pass
else:
print('Sorry, please enter a letter')
I am a beginner python programmer and was hoping to get some help. I was trying to create a procedure where it would check if a user’s input is either empty or a single alphabetic character. I am having trouble as every time I run it, and I type 2, it doesn’t print anything. However, if I do multiples letters such as "ad", it says to enter only one character…
What I did:
# Create Validate function
def validate_input(LETTER):
if len(LETTER) == 0 or len(LETTER) == 1:
pass
elif len(LETTER) >= 2 or not LETTER.islapha():
print('Sorry, please enter a single letter')
else:
print('Sorry, please enter a letter')
#Ask for inputs
# Create function to validate input that returns true or false. If false then ask for input again.
first_char = input('Enter first character(lower cases) or press Enter: ')
validate_input(first_char)
What I got:
Enter first character(lower cases) or press Enter: 2
Enter second character(lower cases) or press Enter: ad
Sorry, please enter a single letter
Thanks in advance for your help…
You need to change the order of your checks. At the moment, the check for the length happens before the check for the type of character, and a success on the first check will skip the later ones.
def validate_input(LETTER):
if len(LETTER) == 0:
pass
elif len(LETTER) >= 2 or not LETTER.isalpha():
print('Sorry, please enter a single letter')
elif len(LETTER) == 1:
pass
else:
print('Sorry, please enter a letter')