The basics of syntax

INPUT · Slides

Combining conditions

01 / 06

Meeting two conditions at once

Sometimes you need two conditions together — "18 or over and under 65". For that, join them with and.

and is True only when both hold. If either one fails, it is False.

age = 30if age >= 18 and age < 65:    print("standard")

Result

standard

02 / 06

Meeting either one

When either will do — "Saturday or Sunday" — use or.

or is True if at least one of them holds. Both holding is fine too.

day = "sat"if day == "sat" or day == "sun":    print("day off")

Result

day off

03 / 06

Words, not symbols

Most other languages use the symbols && and ||. Python uses the words and and or.

Read if age >= 18 and age < 65: out loud and it is very nearly an English sentence. Python caring about readability shows up here as well.

print(True and False)print(True or False)

Result

False
True

04 / 06

Flip it round with not

not turns a condition inside out. True becomes False and False becomes True.

Useful, but overusing it makes things hard to read. x != 5 is tidier than not x == 5, is it not? If the opposite condition is easy to write, write that instead.

print(not True)stock = 0if not stock > 0:    print("sold out")

Result

False
sold out

05 / 06

The shape people get wrong

For "when x is 1 or 2" you will be tempted to write if x == 1 or 2:. That does not do what you think.

Python reads it as (x == 1) or (2), which holds no matter what x is. Each side of an or needs a complete condition of its own.

x = 5if x == 1 or x == 2:    print("1 or 2")else:    print("neither")

Result

neither

06 / 06

Something only Python lets you write

"At least 10 and at most 20" can actually be written 10 <= x <= 20, exactly the way you would in maths.

Very few languages allow that. 10 <= x and x <= 20 works too, but the first one is the Python way.

x = 15if 10 <= x <= 20:    print("in range")

Result

in range