+ 1
Need help With a loop
I have an input where the user selects one of three options (1,2,3) How do i create an error loop to make sure they dont type in something wrong? And if they do, how can i make it ask for the same input again? Also at the end of code, how do you start the code over again if they want to use the program again? Should it be part of a larger loop? Thanks for the help!
3 Answers
0
if not usr_input.isalpha(): break
0
Don't know what is the 'count' for...
If I got it right with the question, you should also check wether the number is between 1 and 3.
and to simplify the code, you can use the lower() function on usr_input.
while True:
usr_input = raw_input('Enter a number 1, 2 or 3: ') #for python 3.x use - input()
if usr_input.lower() == 'done':
break
try :
value = int(usr_input) #if you need decimal point replace int() with float()
if value>0 and value<4:
print ("Invalid input. Please insert a number 1, 2, 3 or type done to finish")
continue
except:
print ("Invalid input. Please insert a number 1, 2, 3 or type done to finish")
continue
print (value)
0
Hey I did not pay good attention on the problem, here is how should be done to work so only user entry of 1, 2 or 3 will be accepted and the rest will return prompt for correct entry, the version Benjamin posted does not work correctly with all numbers,
# Created by Krasimir Vatchinsky - KGV Consulting Corp
# info@kgvconsultingcorp.com
#This is for python 2.7.x version, for python 3.x.x version replace raw_input() with input()
while True:
usr_input = raw_input('Enter numbers 1, 2 or 3: ')# you can change int() with float() if you want numbers with decimal point
if usr_input == 'done' or usr_input == 'Done' or usr_input == 'DONE':
quit()
try:
numerical_input = int(usr_input)
if numerical_input > 0 and numerical_input < 4 :
print ("Great you enter : ", usr_input)
continue
else:
print ("Invalid input. Please insert a number 1, 2, 3 or type done to finish")
except:
print ("Invalid input. Please insert a number 1, 2, 3 or type done to finish")
continue
print (numerical_input)
#here is the result:
python numberentry.py
Enter numbers 1, 2 or 3: 1
('Great you enter : ', '1')
Enter numbers 1, 2 or 3: 2
('Great you enter : ', '2')
Enter numbers 1, 2 or 3: 3
('Great you enter : ', '3')
Enter numbers 1, 2 or 3: 4
Invalid input. Please insert a number 1, 2, 3 or type done to finish
Enter numbers 1, 2 or 3: 5
Invalid input. Please insert a number 1, 2, 3 or type done to finish
Enter numbers 1, 2 or 3: done
~/Development/Python