Input Validation | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Input Validation

I'm hoping to learn how to validate a user's input. I'd like the code to ask for an input; the user enter an input, in this case Y/N or just enter. If the user enter's a valid value then the code will continue to run, however, if the user does not enter a valid input, the code will return an error message and then offer additional chances to enter a valid input. I considered a 'while loop,' but I was hoping to write something more efficient. Here is what I am trying, it doesn't work because once the AssertionError is triggered, the code stops entirely. def section_addition(): #asks user if they are ready to begin the addition lesson ready_addition = input("Are you ready (Y/N)? ").lower() or "-" assert(ready_addition[0] == "y" or ready_addition == "-" or ready_addition[0] == "n"), "Enter Y or N."

31st Jan 2019, 7:15 PM
EconPilot
EconPilot - avatar
1 Answer
+ 8
While loop is probably the most efficient solution but you can use recursion if you don't want a loop def section_addition(): #asks user if they are ready to begin the addition lesson ready_addition = input("Are you ready (Y/N)? ").lower() or "-" if ready_addition[0] in 'yn-': return True print('Enter Y or N') section_addition()
31st Jan 2019, 9:24 PM
Mert Yazıcı
Mert Yazıcı - avatar