Rocket wants the fuel check to do something, not just print True or False. "If the fuel is high enough, say ready," he says. "Otherwise, say refuel. Just like a real launch."
He types the lines quickly, presses F5, and IDLE shows a box that says IndentationError.
Raven looks at the code. "What do you notice?" she asks. "Your print line sits right under the if, against the left edge. In your notebook you always indent the steps that belong to a rule."
Nova draws a bright bracket around the lines under the if. "Would you like a hint?" she asks. "In Python, the spaces at the start of a line show which lines belong to the if."
Rocket adds four spaces and tries again.
An if statement runs a block of lines only when its condition is True. The line with if ends with a colon. The lines that belong to it are indented by four spaces.
else gives a second block that runs when the condition is False. Exactly one of the two blocks runs, never both. A line that is not indented runs either way.
IDLE helps: after you type a line ending with a colon and press Enter, it indents the next line for you. Press Backspace to come back out.
# launch_check.py
fuel = int(input("Fuel percent: "))
if fuel >= 80:
print("Fuel OK. Ready for launch.")
else:
print("Not enough fuel. Refuel first.")
print("Check complete.") Two runs, one with 85 and one with 60:
Fuel percent: 85 Fuel OK. Ready for launch. Check complete.
Fuel percent: 60 Not enough fuel. Refuel first. Check complete.
fuel = 85
if fuel >= 80:
print("Fuel OK") This program has no spaces before print. IDLE shows an IndentationError box: expected an indented block after the if statement. Add four spaces before print to fix it.
The % sign gives the remainder. A number is even when it divides by 2 with nothing left over. So number % 2 == 0 is True for even numbers.
# even_odd.py
number = int(input("Pick a whole number: "))
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
print("Thanks for testing!") | Statement | True or false? |
|---|---|
| The line after if must end with a colon. | ? |
| The if line itself must end with a colon. | ? |
| Both the if block and the else block can run in one go. | ? |
| A line that is not indented runs whether the condition is True or False. | ? |
Your programs can now choose between two paths. Tomorrow you will give them more than two choices.