The if Statement
So far, your programs have run every line, one after another, from top to bottom. But a program often has to decide what to do: show a warning only if a password is too short, or give a discount only if the customer is a student. We make decisions like that all the time: if it rains, I'll take an umbrella.
In Python, you write a decision with the if statement:
temperature = 30
if temperature > 25:
print("It's hot, take a cap")
print("Have a nice day")This prints:
It's hot, take a cap
Have a nice dayThe if statement has four parts:
- the keyword
if. A keyword is a word with a special meaning in Python; - a condition:
temperature > 25. A condition is a question that can only be answered yes (true) or no (false): is the temperature greater than 25? - a colon
:at the end of the line; - a block of code: the indented lines below the line with
if. The block runs only if the condition is true.
The lines of the block are indented: they start with 4 spaces. In Python, indentation isn't just for looks: it's how Python knows which lines belong to the block. You don't have to count the spaces. When you type the colon and press Enter, the editor indents the next line by itself, and the Tab key adds 4 spaces, too. When the block is done, delete the indentation of the next line with Backspace.
After the block, the program goes on as usual, so Have a nice day is printed either way. If temperature were 10, the condition would be false: the program would skip the block and print only Have a nice day.
A block can't be empty. If you forget to indent the line under the if, the program prints nothing and ends with an error:
temperature = 30
if temperature > 25:
print("It's hot, take a cap")Traceback (most recent call last):
File "<exec>", line 3
print("It's hot, take a cap")
^^^^^
IndentationError: expected an indented block after 'if' statement on line 2Read it from the last line: Python expected an indented block after the if statement on line 2, but line 3 isn't indented. The other typical mistake is a missing colon: if temperature > 25 without it ends with SyntaxError: expected ':'.
Instructions
- 1
Below the variable, write an
ifstatement with the conditionmonitor_price < 4000. In its block, printI will buy the monitor. - 2
Below the block, without indentation, write a second
ifstatement with the conditionmonitor_price > 4000that printsIt's too expensive. Run the program: it still prints onlyI will buy the monitor, because 3000 isn't greater than 4000, so the second block is skipped.