Line At A Time
Lesson 13: The and Keyword
The and Keyword Combine conditions with and.
1hungry = True
2have_snacks = False
3if hungry and have_snacks:
4 print("Snack time!")
5else:
6 print("No snacks right now")
Terminal
$ python3 main.py
No snacks right now
Every line, explained
hungry = True
A boolean is a value that can only be True or False, and in Python both words must start with a CAPITAL letter. Writing true or false is an error.
have_snacks = False
A boolean is a value that can only be True or False, and in Python both words must start with a CAPITAL letter. Writing true or false is an error.
if hungry and have_snacks:
if checks the condition after it. Two things to notice: the line ends with a colon :, and the lines that belong to the if are indented 4 spaces underneath. Python uses indentation to know exactly which code is "inside" the if. If the condition is True the indented code runs; otherwise Python skips it. (The editor indents for you here; in a real editor you would type the 4 spaces.) and means the condition is only True if BOTH sides are True. True and False is False, so this branch is skipped.
print("Snack time!")
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. Skipped: we have no snacks.
else:
else: is the "otherwise" branch. When the if condition is False, the indented code under else: runs instead. Exactly one of the two branches runs, never both.
print("No snacks right now")
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. This is the line that runs.