Python 3 KeyboardInterrupt error
Asked Answered
B

2

15

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.

Boozer answered 17/6, 2016 at 17:58 Comment(4)
That's the whole point of Ctrl + C. It's a hotkey to exit out of whatever program you're running.Expressway
really? Never knew that that was a thing in pythonBoozer
Not just Python, anything you run in the command line. It's been that way since early UNIX systems.Expressway
Oh im new to coding im only 14 don't even know what UNIX systems are but I guess that makes senseBoozer
H
22

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.

Heathheathberry answered 17/6, 2016 at 20:14 Comment(2)
Gratz to 10k :-)Spiel
As a side note, if you have a Mac copy is command-c and KeyboardInterupt is control-c so I never get this issue when copying stuff. ;PHeathheathberry
G
0

Also, in your program, if someone inputs "Hello", it would not reply hello back as the first letter is capital, so you can use:

if test.isupper == True:
  print("Hello!")
Geld answered 27/8, 2021 at 12:12 Comment(1)
Please provide additional details in your answer. As it's currently written, it's hard to understand your solution.Pretend

© 2022 - 2024 — McMap. All rights reserved.