Making Decisions
Without decisions, a program is just a boring list of commands that always does the exact same thing. By teaching Python to make choices using if and else, your code becomes smart. It can react to different situations!
Comparing Things
Before Python can make a decision, it needs to ask a question. In Python, questions are called conditionsA condition is a statement that is either True or False. Python uses them to decide what to do.. A condition is always either True or False.
Here are the tools Python uses to compare things:
Is equal to
Notice the double equals! Single = is for variables, == is for comparing.
5 == 5 # True 5 == 6 # False
Is NOT equal to
The exclamation mark means "not".
5 != 6 # True "hi" != "hi" # False
Less than / Greater than
Standard math symbols.
10 > 5 # True 2 < 1 # False
Less/Greater or Equal
Includes the number itself.
5 >= 5 # True 10 <= 9 # False
Taking Action
Now that we can ask questions, let's use the if and else statements to actually do something.
age = 20 if age >= 18: print("You can buy a car!") else: print("Sorry, you need to walk.")
In many languages, you use curly brackets
{} to group code.
Python uses spaces (indentation) instead. If you forget to indent the code inside an if,
Python will throw an IndentationError. Python is very neat and expects you to be neat too!
Multiple Choices
What if there are more than two options? Like grades: A, B, C, or F?
We use elif (which stands for "else if"). You can have as many elif blocks as you want.
score = 85 if score >= 90: print("Grade: A. Sarpanch is proud.") elif score >= 80: print("Grade: B. Not bad!") elif score >= 70: print("Grade: C. Need to study more.") else: print("Grade: F. Oh dear.")
Note: Python checks conditions from top to bottom. As soon as it finds one that is True, it runs that code and skips all the rest.
Think of if/elif/else like standing at a crossroads with signposts.
if: Is this the right path? If yes, go down it.
elif: If not, what about this other path? If yes, take it.
else: If none of the paths were right, take the default path (usually the one home).
The Pizza Flowchart
if statement checks a condition. If it's True, it takes one path. If False, it takes the else path.The Food Order
if hungry:
order_food()hungry = False... what happens now?""Oh no... I forgot the
else. Now I'm starving!"Making Decisions
Change the temperature variable and see how Python's decision changes.
- Change the temperature to 15. What prints?
- Change it to 35. What prints?
- Add a new
elifcondition for when it's exactly 25.
Decisions — Done! 🚦
- Conditions are questions that evaluate to
TrueorFalse. - Use == to check if things are equal, and != for not equal.
- if statements execute code only if the condition is True.
- elif lets you check another condition if the first one was False.
- else provides a catch-all if absolutely none of the conditions were True.
- Indentation (spaces) tells Python which code belongs inside the if/else block!