Combining conditions

Part of the free LogicWiz Python course, Module 2: Decisions and loops. The examples and practice run in the app.

Is 2100 a leap year? year % 4 == 0 says yes. The calendar says no. One condition is not enough; you need to combine them.

You'll learn to

  • Join conditions with and, or, not
  • Check membership with in
  • Know which values count as True or False (truthiness)
  • Turn a flowchart into code: largest of three, leap year

Learn

and, or, not

age = 19
has_id = True
print(age >= 18 and has_id)
print(age < 12 or age > 60)
print(not has_id)

and is True only if both sides are True. or is True if at least one is. not flips True and False.

and vs or

andor
True only when both sides are TrueTrue when at least one side is True
Stops at the first False sideStops at the first True side
age = 60 and hascardday == "Sat" or day == "Sun"

in: is it inside?

print("a" in "chai")
print("z" in "chai")
ch = "e"
print(ch in "aeiou")
print("dosa" in "idli dosa vada")

in checks whether something appears inside a string. ch in "aeiou" is the neat way to test for a vowel.

Truthiness

if does not need a real True or False. Python treats some values as falsy:

  • 0 and 0.0
  • "" (an empty string)
  • None

Everything else is truthy, even "0", "False" and -1.

So if name: means "if name is not empty". Also: and / or give back one of their operands, not always True or False. name or "Guest" gives name if it is truthy, otherwise "Guest".

Truthiness in action

print(bool(0), bool(""), bool("0"), bool(-1))
name = ""
print(name or "Guest")
print(0 or 5)
print(3 and 0)
if name:
    print("Hello", name)
else:
    print("Please type your name")

Flowchart to code: largest of three

a, b, c = 12, 45, 30
if a >= b and a >= c:
    big = a
elif b >= c:
    big = b
else:
    big = c
print("Largest:", big)

Each diamond in the flowchart becomes a condition. If a beats both, it is the answer. If not, the answer is whichever of b and c is bigger.

The leap year rule

year = int(input())
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print(year, "is a leap year")
else:
    print(year, "is not a leap year")

Divisible by 4 and not by 100, or divisible by 400. So 2024 and 2000 are leap years; 2100 and 1900 are not. Try them.

if ch == "a" or "e": is always True. Python reads it as (ch == "a") or ("e"), and "e" is a non-empty string, so it is truthy. Write ch == "a" or ch == "e", or better, ch in "ae".

CBSE asks: leap year, largest of three numbers, vowel or consonant, and the order of logical operators: not first, then and, then or. So True or False and False is True or (False and False) = True.

In one line

and needs both, or needs one, not flips; 0, "" and None are falsy; write ch == "a" or ch == "e", never ch == "a" or "e".