1
import msvcrt
x: int = 0
while not msvcrt.getch() == ' ':
    if x <= 10000:
        print(x)
        x += x
    else:
        print("space")

Loop is not stopping when the "space" is pressed.

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

2

msvcrt.getch() returns a bytestring rather than a string so when you press space it will return b' ', not ' '.

Therefore change:

while not msvcrt.getch() == ' ':

To:

while not msvcrt.getch() == b' ':
Loocid
  • 6,112
  • 1
  • 24
  • 42
  • didn`t change it just flies through 0 not even counting or caring about space key. – Ramazan KARADEMİR Dec 07 '18 at 01:31
  • Change `x: int = 0` to `x = 0` and `x+=x` to `x+=1`. – Loocid Dec 07 '18 at 01:33
  • yes it should have been x += 1 my bad but space is not working still. maybe it not being able to catch it up idk – Ramazan KARADEMİR Dec 07 '18 at 01:34
  • After the changes your script works fine for me. It increments x on any button press except space, where it stops. – Loocid Dec 07 '18 at 01:37
  • import msvcrt x = 0 while not msvcrt.getch() == b' ': if x <= 10000: print(x) x += 1 else: print("space") – Ramazan KARADEMİR Dec 07 '18 at 01:40
  • Yep, works fine as your described. I press space and it prints `space` and exits. – Loocid Dec 07 '18 at 01:43
  • i am using idle and it doesn`t stop careless of space . – Ramazan KARADEMİR Dec 07 '18 at 01:45
  • The Windows console is Unicode (at least for the basic multilingual plane), so it's actually more efficient to use `msvcrt.getwch() == ' '` instead. The performance difference is trivial, but using Unicode supports more characters and is more idiomatic in Python 3. The 'w' in the name indicates it's the [w]ide-character version. – Eryk Sun Dec 07 '18 at 06:11
  • @RamazanKARADEMİR, `getch` and `getwch` are console functions. They don't work in IDLE unless you manually allocate a console via `AllocConsole`, and even then it requires the console window to have focus. – Eryk Sun Dec 07 '18 at 06:12
0
import msvcrt
x = 0
while not msvcrt.getch() == b' ':
    if x <= 10000:
        print(x)
        x += 1
    else:
        print("space")

thanks for your interests