Python if Statement: Make Decisions in Code
What Is an if Statement?
So far, Python ran every line of your program, top to bottom. With an if statement, a program can decide: run some lines only when a condition is True.
age = 20
if age >= 18:
print("You can vote.")
print("Thank you!")You can vote. Thank you!
Change age to 15 and run it again. Now You can vote. disappears, but Thank you! still prints.
Remember the diamond in a flowchart from chapter 3? An if is that diamond, written in Python:
- Start: Start
- Decision: Is age 18 or more?yesShow: You can vote.noSkip it
- Input or output: Show: Thank you!
- End: End
The condition
The part after if is the condition. It's a question with a True or False answer, like the comparisons from chapter 5: age >= 18, name == "Sunny", price > 100.
- If it's
True, Python runs the lines under theif. - If it's
False, Python skips them and carries on below.
Think of a door with a guard: the guard asks one question. Answer yes, and you go through the door. Answer no, and you walk on past it.
An if runs its lines only when its condition is True.