Python conditions with parenthesis in a while not loop

Question:

So I’m learning programming with Karel and I’m a little confused about conditionals with parenthesis and specifically what would happen in a loop.

def build_line():
    while not (front_is_blocked() or beeper_is_present()):
        face_east()
        put_beeper()
        move()
def build_line():
    while not front_is_blocked() or not beeper_is_present():
        face_east()
        put_beeper()
        move()

In the line while not (front_is_blocked() or beeper_is_present()) and while not front_is_blocked() or not beeper_is_present() do they mean the same thing? That the loop will only start if the front is clear OR there are no beepers present?

Asked By: hsuehtt98

||

Answers:

No. The expression not (front_is_blocked() or beeper_is_present()) is equivalent to not front_is_blocked() and not beeper_is_present() per DeMorgan’s Laws. Notice the and vs or in your 2nd code sample.

Answered By: Allan Wind

They aren’t the same. Here’s a truth table where each column represents a different combination of front_blocked and beeper_present values:

T T F F  front_blocked
T F T F  beeper_present
-----------------------
T T T F  front_blocked or beeper_present
F F F T  not (front_blocked or beeper_present)
F T T T  not front_blocked or not beeper_present

Note that front_blocked or beeper_present is a simple or, which means it’s true as long as there’s at least one T value (i.e. in all scenarios except F F), and the following line not (front_blocked or beeper_present) is the inverse of that, making it true only for F F (this is a logical NOR).

not front_blocked or not beeper_present inverts the individual values before taking the or, so it’s true as long as there’s at least one F value, making it true in all scenarios except T T (this is a logical NAND — you could also write it as not (front_blocked and beeper_present)).

Answered By: Samwise

Both the functions are not same. In first function , while loop will only execute when both other functions (ie front_is_blocked and beeper_is_present) returning False, while in later function even if either of function is returning True, while statement will execute.

Answered By: codeman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.