The if statement
The programs you've written so far follow one straight path: Python runs every line, top to bottom, whatever the user types. Real programs choose: they warn when it's hot, congratulate the winner, ask a new user to pick a password. A conditional statement runs a group of lines only when a condition is true.
temperature = int(input("Temperature: "))
if temperature > 25:
print("It's hot today.")
print("Remember to drink water.")
print("Have a nice day!")
30Temperature: 30
It's hot today.
Remember to drink water.
Have a nice day!If the user types 18 instead, the condition temperature > 25 is false. Python skips the two indented lines, and the whole run is just this:
Temperature: 18
Have a nice day!
The parts of an if statement
- The keyword
ifstarts the statement. temperature > 25is the condition.>means "greater than"; the next step shows the other ways to compare.- The line ends with a colon
:. - The lines below it that are indented, moved to the right by four spaces, form a block. They run only when the condition is true.
- The first line back at the left edge,
print("Have a nice day!"), is no longer part of the block. It runs every time, whatever the condition was.
The input decides which lines run, so the same program can behave differently each time. That's why the checks on this site run your program with several inputs: each one should take the right path.
Don't forget the colon
Without the colon at the end of the if line, Python can't read the program:
temperature = 30
if temperature > 25
print("It's hot today.")
File "main.py", line 2
if temperature > 25
^
SyntaxError: expected ':'The ^ points to the end of line 2, where Python expected the colon. As with every syntax error, nothing runs at all.