This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 2: Logical operators

Logical operations in conditions

face Josiah Wang

Now, imagine you are given the code below. Try to understand what it does.

x = 8
y = 3
z = 5

if x < 2:
    print("Good x")

if x > 7:
    print("Good x")

if 2 <= x <= 7:
    print("Bad x")

if y > 3:
    if z > 4:
        print("Good yz")
    else:
        print("Bad yz")
else:
    print("Bad yz")
1

Question 1

Can you rewrite the code to make it more compact, but still keep the same behaviour and output? You can use the logical operators and, or and not to help you achieve this. You can copy and paste the code from above and modify it in this text box.

Sample solution:

Here is my solution. Is yours similar?

x = 8
y = 3
z = 5

if x < 2 or x > 7:
    print("Good x")
else:
    print("Bad x")

if y > 3 and z > 4:
    print("Good yz")
else:
    print("Bad yz")