Search code examples
pythonpython-3.xmsvcrt

Problem in code while using Python msvcrt


Only getting a blank screen, what is wrong?

import msvcrt
while(1):
  choice = msvcrt.getch()
  if(choice =='a'):
      print('a')
  elif(choice =='s'):
      print('s')

Solution

  • Your problem is that getch() returns a byte not a string. If you press a the value of choice is the bytestring b'a' which is not the same as the string 'a'. Consider this:

    >>> choice = b'a'
    >>> choice == 'a'
    False
    >>> choice.decode() == 'a'
    True
    

    And your screen is remaining blank because neither if-condition can ever be true, and you have no catch-all else: clause. You could have discovered this for yourself simply by printing out the value of choice.

    Change your test from

    if choice =='a':
    

    to

    if choice.decode() == 'a':
    

    (and do drop those unnecessary parens from your if tests).

    In Python 2, your original code would have worked the way you expect.