Basic Syntax issues, trouble using "or"

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Jameth
Posts: 3
Joined: Sat Dec 04, 2021 9:08 pm

Basic Syntax issues, trouble using "or"

Post by Jameth » Sat Dec 04, 2021 9:34 pm

Hello Everyone!

Im enjoying my first crack at MicroPython, feels somehow more robust than C, which I'm almost dangerous with, but after an afternoon goolging today I'm finding it really hard to do a simple thing, I'm sure I'm just not seeing something here, but id be grateful for some help :) I want my loop below to input move_amnt if i type in either "cw" or "ccw" for direction

My code below works in the wider program, except for the line if direction != ('cw' or 'cww'):

Code: Select all

while True:
    direction = input('Move Clockwise, or couter-Clockwise? ')
    if direction != ('cw' or 'ccw'):
        print ('unrecognised direction')
        continue
    else:
        move_amnt = int(input ('how far? (180° ≈ 1500)? '))
    if direction == ('cw'):
        move_cw()
    elif direction == ('ccw'):
        move_ccw()
In this case, entering "ccw" will print "unrecognised direction", hit the continue and ill be prompted to input direction again, while cw works fine, and def move_cw() runs. This also happens the other way round if i swap round cw and ccw.

The "first" option always works fine, but the other option is not considered, and i don't know why, there dosen't seem to be anything that complicated about the syntax for or in MicroPython

I'm sure its obvious to someone, but I'm stumped :P

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Basic Syntax issues, trouble using "or"

Post by Roberthh » Sun Dec 05, 2021 7:44 am

The statement if direction != ('cw' or 'ccw'): is proper Python syntax, but does not express, what you want. A proper statement's would be:

if direction != "cw" and direction != "ccw":

or as more Python specific code:

if not direction in ("cw", "ccw"):

The logic behind that is independent from Python or Micropython, just the Syntac is Python-Specific.
In your statement, ('cw' or 'ccw') evaluates to True, since the logic value of both 'cw' and 'ccw' is True, and so the whole expression turns into direction != True. If direction is not empty, that would turn into True != True, and that is always False.

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Basic Syntax issues, trouble using "or"

Post by pythoncoder » Sun Dec 05, 2021 10:52 am

To add to that, in Python most things evaluate as True in a logical context. Exceptions are False (obviously!), 0, None, b"", and "". Also empty tuples, lists, sets and dicts.
Peter Hinch
Index to my micropython libraries.

Post Reply