Reputation: 108
I would like to know how I can get my code to not crash if a user types anything other than a number for input. I thought that my else statement would cover it but I get an error.
Traceback (most recent call last): File "C:/Python33/Skechers.py", line 22, in run_prog = input() File "", line 1, in NameError: name 's' is not defined
In this instance I typed the letter "s".
Below is the portion of the code that gives me the issue. The program runs flawlessly other than if you give it letters or symbols.
I want it to print "Invalid input" instead of crashing if possible.
Is there a trick that I have to do with another elif statement and isalpha function?
while times_run == 0:
print("Would you like to run the calculation?")
print("Press 1 for YES.")
print("Press 2 for NO.")
run_prog = input()
if run_prog == 1:
total()
times_run = 1
elif run_prog == 2:
exit()
else:
print ("Invalid input")
print(" ")
I tried a few variations of this with no success.
elif str(run_prog):
print ("Invalid: input")
print(" ")
I appreciate any feedback even if it is for me to reference a specific part of the python manual.
Thanks!
Upvotes: 2
Views: 431
Reputation: 75
You can do this:
while times_run == 0:
print("Would you like to run the calculation?")
print("Press 1 for YES.")
print("Press 2 for NO.")
run_prog = input()
if run_prog == 1:
total()
times_run = 1
elif run_prog == 2:
exit()
elif run_prog not in [1,2]:
print('Please enter a number between 1 and 2.')
If the user writes s
the text Please enter a number between 1 and 2
will appear
Upvotes: 1
Reputation: 798626
Contrary to what you think, your script is not being run in Python 3.x. Somewhere on your system you have Python 2.x installed and the script is running in that, causing it to use 2.x's insecure/inappropriate input()
instead.
Upvotes: 3
Reputation: 140569
The error message you showed indicates that input()
tried to evaluate the string typed as a Python expression. This in turn means you're not actually using Python 3; input
only does that in 2.x. Anyhow, I strongly recommend you do it this way instead, as it makes explicit the kind of input you want.
while times_run == 0:
sys.stdout.write("Would you like to run the calculation?\n"
"Press 1 for YES.\n"
"Press 2 for NO.\n")
try:
run_prog = int(sys.stdin.readline())
except ValueError:
run_prog = 0
if not (1 <= run_prog <= 2):
sys.stdout.write("Invalid input.\n")
continue
# ... what you have ...
Upvotes: 1