Making Decisions: The Robot’s Crossroads
Teach your Python robot how to make decisions using if, elif, and else statements, comparison operators, and visual flowcharts.
Welcome back, programmer! 🚀
Our Python robot now has a memory (variables), but it is still just following our orders blindly. Today, we are going to teach the robot how to think and make decisions!
In video games, if your player touches a lava block, they lose. If they reach the golden cup, they win. How does the computer know what to do? It uses If/Else Crossroads!
The Signpost in the Woods#
Imagine your robot is walking through a magical forest and comes to a fork in the road. There is a signpost that asks a question: “Do you have at least 10 gold coins?”
graph TD
Start([Robot walks in]) --> Decision{Coins >= 10?}
Decision -->|Yes - True| PathA["Buy Magic Sword! ⚔️"]
Decision -->|No - False| PathB["Keep exploring... 🗺️"]
In Python, we write this crossroad using if and else:
coins = 12
if coins >= 10:
print("You buy a Magic Sword! ⚔️")
else:
print("Keep exploring the forest... 🗺️")pythonHow to Write Decisions in Python#
There are three golden rules to remember when telling the robot to make a decision:
- The Question: We ask the question using a comparison symbol (like
>=for greater than or equal to). - The Colon
:: Always put a colon at the end of your question line. It is like telling the robot, “Here starts the path!” - The Indentation (4 Spaces): Indent the lines of code inside each path by pressing the Spacebar 4 times (or the Tab key). This shows Python which commands belong to which path!
Comparison Symbols (Robot Questions)#
When asking questions, the robot uses these comparison symbols:
>(Greater than)<(Less than)==(Is equal to? Note: We use TWO equals signs to ask a question, and ONE equals sign to put things in a box!)!=(Is NOT equal to?)>=(Greater than or equal to)<=(Less than or equal to)
What if there are More than Two Paths? (elif)#
What if we have a third choice? For example:
- If we have 10 coins, we buy a sword.
- If we have 5 coins, we buy a shield.
- Otherwise, we keep exploring.
We use elif (short for “else if”) to add more signposts:
coins = 6
if coins >= 10:
print("Buy Magic Sword! ⚔️")
elif coins >= 5:
print("Buy Wooden Shield! 🛡️")
else:
print("Keep exploring... 🗺️")pythonSince coins is 6, the robot checks the first path (False), checks the second path (True), and says: "Buy Wooden Shield! 🛡️".
Try It Yourself! 🎮#
Can you write a code block that checks your game score?
- Make a variable
scoreand set it to120. - If the score is greater than
100, print"New High Score! 🏆". - Otherwise, print
"Good job! Play again! 🎮".
Try changing the score to 80 and see what the robot says!
Next time, we will learn how to make our robot perform tasks over and over again without getting tired. See you there!