Python If and Else
The lines under if run only when the answer is True. cups = 2 stores 2. Then if cups > 1: asks the question from the comparison page. 2 is larger than 1, so the answer is True, and print("tea") runs. The lines under else do not run. You do not see water.
cups = 2
if cups > 1:
print("tea")
else:
print("water")
The screen shows tea. water is not written.
else runs when the answer is False
cups = 1 stores 1. cups > 1 is now False, so the tea line is skipped. The lines under else run, and print("water") writes water. else is the other path. It is not a second question, and it does not store a new value.
cups = 1
if cups > 1:
print("tea")
else:
print("water")
The screen shows water. tea is not written.
Only one of those two prints runs. In the first program you see tea. In the second you see water. You never see both on the same run. The previous page joined two answers with and, or, and not. This page takes one True or False answer and picks a path.
if and else each end with a colon. That colon says the indented lines belong to that path. Leave the colon out and the program stops. if and else are lowercase. If with a capital letter stops.
else lines up with if. The print lines sit four spaces further in, the same indent as the indentation page. Push else itself in, under if, and the program stops. else is the partner of if, not a line inside the tea path.
The next page names several cases
This page has two paths. It does not repeat lines, and it does not store a function. The next page names several cases with match.
Say these yourself
- cups = 2 writes tea. The water line does not run.
- cups = 1 writes water. The tea line does not run.
- Only one of the two prints runs.
- else lines up with if. A missing colon stops the program.
- The next page names several cases with match.
Easy to misread
- Expecting both tea and water on one run
- Pushing else in, under if
- Leaving out the colon after if or else
- Writing If or Else with a capital letter
- Writing if cups = 2. One equals sign stores. It does not ask. The question here is cups > 1
Keep
The lines under if run only when the answer is True.
The lines under else run only when that answer is False.
cups = 2 writes tea. cups = 1 writes water.
Only one of those prints runs.
else lines up with if, and each of them ends with a colon.
The next page names several cases with match.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top