-1

I am trying to make it so that the while loop stops when you press c without stopping it using input.

The code I have at the moment is this:

    while True:
        print("Test")
        if msvcrt.kbhit():
            if (msvcrt.getch() == "c"):
                os._exit(0)
                break
            elif (msvcrt.getch() != "c"):
                continue

FYI I am on windows. Any ideas on how to do it besides the attempt I have already done?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • 1
    did you see this? http://stackoverflow.com/questions/13180941/how-to-kill-a-while-loop-with-a-keystroke – somesingsomsing Mar 31 '17 at 20:56
  • I assume you're on Python 3 since you're using `print` as a function. In this case `msvcrt.getch()` returns `bytes`, and `b"c" != "c"`. You want `msvcrt.getwch()` to get a Unicode character that Python 3 returns as `str`. – Eryk Sun Apr 05 '17 at 23:14

1 Answers1

0

The problem is in the line if (msvcrt.getch() == "c"):.

You don't use getch() == "c" but getch() == 99 or but getch() == ord("c").

Why? Because it's what ord() returns. It returns an integer representing the Unicode code point of the only character in the string, in this case c.


By the way, Python already has KeyboardInterrupt that allows using Ctrl+C for interrupting code. You can also try-except it.


Note: You may also want to use 67 for if Caps Lock is on.

Juan T
  • 1,219
  • 1
  • 10
  • 21