Conditionals · 15 min

Combine conditions and test boundaries

Use Boolean operators, chained comparisons, and modulo.

Jump to the automation lab

and requires both conditions to succeed, or needs at least one, and not reverses a Boolean value. Python short-circuits, so capacity > 0 and used / capacity > 0.8 avoids dividing by zero.

The chained comparison 1 <= day <= 5 includes both endpoints. Modulo % returns the remainder. The expression number % 2 == 0 checks whether a whole number is even.

Test the value immediately before a cutoff, the cutoff itself, and the value after it. This catches bugs where > should have been >=.

Follow the example

Wednesday falls inside the weekday range.

Worked examples

Check parity

Dividing an even integer by two leaves a remainder of zero. The function returns the Boolean from that comparison.

parity.py
def is_even(number):
    return number % 2 == 0

print(is_even(12))  # True
print(is_even(7))   # False

Run the example and practice

Also allow Saturday (day 6) from 10:00 up to, but excluding, 13:00. Keep the weekday hours and sample calls.

Target output

True
False
True
Show a hint

Assign the weekday and Saturday conditions to separate names and join them with or.

Output

Ready

Run your code to see the output here.

Check output also tests your code with additional cases.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
def is_open(day, hour):
    weekday = 1 <= day <= 5 and 9 <= hour < 17
    saturday = day == 6 and 10 <= hour < 13
    return weekday or saturday

print(is_open(3, 16))
print(is_open(3, 17))
print(is_open(6, 10))

Automation lab

Flag an item for reorder

Reorder a product when stock is low and there is no delivery on the way. Keep discontinued items out of the reorder list.

Output

Ready

Run the example to see the output here.

Set on_hand to 5. Then try a lower value with on_order set to True.

Further reading in Automate the Boring Stuff with Python by Al Sweigart