Decisions: Making Choices with 'If'
Programs can choose between paths by checking whether something is true.
So far our programs run straight through, top to bottom. But real programs need to make decisions "" to do one thing in some situations and something different in others. That's where the word if comes in.
You make 'if' decisions all day
You already think in if statements constantly:
- If it's raining, take an umbrella.
- If the light is red, stop.
- If I'm hungry, make a snack; otherwise, keep working.
Programs do exactly this. An if statement checks whether something is true, and only runs certain instructions when it is.
The shape of an 'if'
Here's the idea in pseudo-code:
if temperature > 30:
show "It's hot! Drink water."Read it as: "If the value in temperature is greater than 30, then show the message." If the temperature is 31, the message appears. If it's 18, the program simply skips that line and moves on. The > symbol means "greater than."
Adding an 'otherwise' with else
Often you want to do one thing or another. The word else means "otherwise":
if temperature > 30:
show "It's hot! Drink water."
else:
show "The weather is fine."Now exactly one of the two messages will appear. The computer checks the condition, picks a path, and runs only that path. It's a fork in the road.
Conditions are true-or-false questions
The part after if is called a condition. It's always a question that's either true or false (remember booleans from earlier?). Some common comparisons:
a > b"" is a greater than b?a < b"" is a less than b?a == b"" is a equal to b? (Note: two equals signs to ask a question, because one equals sign already means "put into"!)
Tip: That double equals == for "is equal to" versus single = for "put into" catches almost everyone at first. A single = stores a value; a double == asks a yes/no question. You'll get used to it fast.
Why decisions matter
Decisions are what make programs feel smart and responsive. A login that says "wrong password," a game that knows when you win, an app that shows a warning only when your battery is low "" all of it is built from humble if statements.
Quick check
Q1 What does an 'if' statement do in a program?
Q2 Why do many languages use == (double equals) to check if two things are equal?
Want to save your progress? It's free.
Create a free account