Teaching Python to choose
Learn how if and else let your program make decisions โ do this if something is true, otherwise do that.
The if statement is how Python makes decisions. You tell Python: "IF this is true, do this. ELSE, do that." It is like a fork in the road โ the program picks one path based on a condition.
๐ก Think of it like this:
Imagine you are walking home and see a sign: "IF it is raining, take the bus. ELSE, walk through the park." You check the weather and choose your path. Python does the same thing with if/else!
Without if/else, every program would do the exact same thing every time. Decisions make programs smart โ they can react differently depending on the situation.
Where you see this in real life:
Python uses indentation (spaces at the start of a line) to know which code belongs to the if statement. Most other languages use curly braces { } instead!
The ifstatement lets Python make decisions. It checks if something is true, and if it is, it runs some code. If not, it can run different code withelse.
Notice the indentation (spaces at the start of the line). Python uses indentation to know which code belongs to the if statement!
Change the age value and run again!๐ก Try changing age to 8 and run again. What happens?
What if there are more than two options? Useelif(short for "else if") to check multiple conditions!
Click โถ Run to see the output!In Python, indentation is not just for looks โ it is part of the syntax! Code inside an if statement MUST be indented (usually 4 spaces).
โ Correct
if True: print("Hi!") print("Bye!")โ Error!
if True: print("Hi!") print("Bye!")Why does Python use indentation (spaces at the start of lines)?