Else
Do one thing when true, another when false.
1is_raining = False
2if is_raining:
3 print("Take an umbrella!")
4else:
5 print("Enjoy the sunshine!")
$ python3 main.py
Enjoy the sunshine!
Every line, explained
is_raining = 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 is_raining:- 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.) The condition here is just the variable is_raining, which is False, so the indented line below is skipped.
print("Take an umbrella!")- 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: the condition above is False.
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. Notice else: is NOT indented; it lines up with the if it belongs to.
print("Enjoy the sunshine!")- 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.