Home > Back-end >  How do I solve issue of execution of code inside an if condition (not running even when if condition
How do I solve issue of execution of code inside an if condition (not running even when if condition

Time:05-16

Okay so apparently my if condition should be true, and the lines of code in the if should be executed. But unfortunately the statements in if conditions are not working.

    def drive(self, msg):
       self.move = 0
       self.move = msvcrt.getch()
       self.speed()

   def speed(self):
       print(self.move.lower())      #print 'w'
       if self.move.lower() == 'w':   
           print("I'm in W!!!")      #but this doesn't get executed
           self.control.setBrake(0)
           accel  = 0.05
           if accel > 1:
               accel = 1.0

Please help

CodePudding user response:

msvcrt.getch() returns a byte string, as stated by the docs (emphasis mine):

https://docs.python.org/3/library/msvcrt.html#msvcrt.getch

Read a keypress and return the resulting character as a byte string. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return '\000' or '\xe0'; the next call will return the keycode. The Control-C keypress cannot be read with this function.

So if you press w you should actually get b'w' (and not 'w') as a result.

Changing the check to

if self.move.lower() == b'w': # notice the prefix

should fix your problem.

Alternatively, you could decode your byte string to a string, but you'd have to account for decoding errors:

self.move = msvcrt.getch().decode()

CodePudding user response:

does this work?

def speed(self):
       print(self.move.decode('ASCII').lower())      #print 'w'
       if self.move.decode('ASCII').lower() == 'w':   
           print("I'm in W!!!")      #but this doesn't get executed
           self.control.setBrake(0)
           accel  = 0.05
           if accel > 1:
               accel = 1.0
  • Related