Just a quick question because I really can’t find a simple solution to my problem.
Is there a way to get a user input that is meant to be a integer, but when a string is entered
the program will not break and instead displays “Error”
I’ve been trying to work around it by converting strings to integers and vice-versa, but I constantly get “invalid literal for int() with base 10” error, or when it displays “Error” it does so in an infinite loop.
Here’s my code just to help clear the question
choice = input("Enter your choice: ")
while choice != 3:
if choice == 1:
get_songs()
print
main()
elif choice == 2:
read_songs()
print
main()
else:
print "Invalid choice"
So essentially I want the else operation to work for strings as well as for an integer that is greater than 3 or less than 1.
You get an exception, specifically a
ValueError. You can catch the exception using anexceptblock. For more info, refer to whatever language tutorial you’ve been using thus far, or try Google forexcept block Python.When you detect that the input isn’t correct, you need to get new input before you try the loop again. Put the input-getting stuff inside your loop. Do not use recursion (calling
main()from withinmain) in addition to the loop; you’re only going to confuse yourself this way. Because you don’t get a value forchoiceuntil you’re inside the loop, it’s easier to explicitlybreakout of the loop when you find the appropriatechoicevalue, instead of trying to control the loop with it (i.e. testing for it in thewhilecondition).We can also use
continueto simplify the loop structure: instead of doing all the work in thetryblock, we limit that to the part where we extract a number. We usecontinuein theexceptblock to skip the rest of the loop when we don’t have an actual number, and only do the rest of the loop when we do. (After all, maybe the code we call forchoice == 1orchoice == 2couldraise ValueErrorfor some totally different reason, and we’d want to do something different about that.)