I have noticed that on any python 3 program no matter how basic it is if you press CTRL c it will crash the program for example:
test=input("Say hello")
if test=="hello":
print("Hello!")
else:
print("I don't know what to reply I am a basic program without meaning :(")
If you press CTRL c the error will be KeyboardInterrupt is there anyway of stopping this from crashing the program?
The reason I want to do this is because I like to make my programs error proof, and whenever I want to paste something into the input and I accidentally press CTRL c I have to go through my program again..Which is just very annoying.
Control-C
will raise a KeyboardInterrupt
no matter how much you don't want it to. However, you can pretty easily handle the error, for example, if you wanted to require the user to hit control-c twice in order to quit while getting input you could do something like:
def user_input(prompt):
try:
return input(prompt)
except KeyboardInterrupt:
print("press control-c again to quit")
return input(prompt) #let it raise if it happens again
Or to force the user to enter something no matter how many times they use Control-C
you could do something like:
def upset_users_while_getting_input(prompt):
while True: # broken by return
try:
return input(prompt)
except KeyboardInterrupt:
print("you are not allowed to quit right now")
Although I would not recommend the second since someone who uses the shortcut would quickly get annoyed at your program.