0

I'm a total beginner so please excuse my ignorance.
What i want to do is basically get an input from the user, which is either a number from 1 to 9 or a space. I've come up with some code from looking around this website that I believe should work but doesn't. When I try to run it, it just does nothing, no error message or anything.

import msvcrt
numInput = 0
while numInput == 0 :
    if msvcrt.kbhit():
        if msvcrt.getch() == "1":
            numInput = "1"
        elif (msvcrt.getch() == "2"):
            numInput = "2"
        elif (msvcrt.getch() == "3"):
            numInput = "3"
        elif (msvcrt.getch() == "4"):
            numInput = "4"
        elif (msvcrt.getch() == "5"):
            numInput = "5"
        elif (msvcrt.getch() == "6"):
            numInput = "6"
        elif (msvcrt.getch() == "7"):
            numInput = "7"
        elif (msvcrt.getch() == "8"):
            numInput = "8"
        elif (msvcrt.getch() == "9"):
            numInput = "9"
        elif (msvcrt.getch() == " "):
            numInput = " "
Phoenixx
  • 23
  • 3
  • As talked about in [this] (https://stackoverflow.com/questions/16076853/using-msvcrt-getch-in-eclipse-pydev) discussion. You have to run this program from the console. – Professor_Joykill Jul 06 '17 at 20:07
  • Are you running this on Windows and from the Command Prompt? – zwer Jul 06 '17 at 20:07

1 Answers1

1

msvcrt.getch() READS key. Also there's nothing you do with numInput value.

You've got:

if msvcrt.getch() == "1":
    numInput = "1"
elif (msvcrt.getch() == "2"):
    numInput = "2"
....

First msvcrt.getch() reads the key you've detected with msvcrt.kbhit(). If its '1' then it'll exit the loop. If not, it'll go to second if and BLOCKS until you press key again. After you press the key python will check it against '2'. And so on. Thus if you press 1, your code will exit loop just fine. If you want to exit with 2, then you've to press 2 twice (because first you check for 1)... you get the drill. Try this one:

while numInput == 0 :
    if msvcrt.kbhit():
        v = msvcrt.getch()
        if v == "1":
            numInput = "1"
        ...
print(numInput)

Note: this loop will also monopolize one core of your procesor, but that's another story.

Radosław Cybulski
  • 2,952
  • 10
  • 21
  • I would also suggest, even though it's outside the scope of the question, that the OP could use something like: `if (v in "0123456789") and (len(v) == 1): numInput = v` that way they don't have a chain of the same kind of code over and over. – Davy M Jul 06 '17 at 20:28
  • Yea. I didnt even get that far, as OP seems to be learning to code. I dont want to give too many changes in one step. :) – Radosław Cybulski Jul 07 '17 at 06:04