Computers Needs Rules
Life is full of choices. If it is raining, take an umbrella. If I am hungry, eat a cookie.
Computers can make these choices too, but we have to give them the rules. We use the magic word if.
The if Statement
age = 10
if age > 7:
print("You are old enough to play!")
The Anatomy of a Decision
if: The keyword.age > 7: The check (The Question). Is age bigger than 7?:: The colon (Essential! Don’t forget it).- Indentation: The next line is pushed in (indented).
Rule: The indented code only runs if the answer is YES (True).
If age was 5, the computer would say nothing.
The else Statement (Or Else!)
What if we want to say something when the answer is NO?
password = input("What use the secret password? ")
if password == "python":
print("Access Granted. Welcome, Master.")
else:
print("Access Denied! Run away!")
Note: We use == (two equals signs) to ask “Are these the same?”. One = is for assigning values.
Common Checks
a > b: Is a bigger than b?a < b: Is a smaller than b?a == b: Are they equal?a != b: Are they NOT equal?
Try It Yourself: The Bouncer
Write a program that asks for the user’s age.
- If they are over 18, say “You can drive a car.”
- Else, say “You keep riding your bike.”
age = input("How old are you? ")
# Trick: Convert text to number using int()
age_number = int(age)
if age_number > 18:
print("Vroom vroom!")
else:
print("Pedal pedal!")
This post is part of the Python Basics for Kids series, based on “Python for Kids from 8 to 88”.