A program that can’t make decisions is like a robot that can only walk straight. Boring!
A program with conditionals is a smart assistant that analyzes a situation and acts differently depending on it. Cool!
Today we’ll teach your programs to think.
๐ฏ What Are Conditionals?
A conditional is about making a choice: “if… then…”
Real-world examples:
IF it is raining:
take an umbrella
IF temperature > 30:
turn on the air conditioner
IF password is correct:
grant access
In Python it looks almost the same!
๐ฅ The if Statement โ Basic Check
Syntax:
if condition:
code that runs when condition is True
Key elements:
1. if โ the keyword
2. condition โ what we’re checking
3. : โ colon is required!
4. 4-space indent โ everything inside the if block
Simplest example:
age = 18
if age >= 18:
print("You are an adult! ๐")
What happens:
1. Python checks: age >= 18 โ 18 >= 18 โ True
2. Condition is True โ the code inside runs
3. We see: “You are an adult! ๐”
Change age = 15 and run again โ nothing is printed!
Try it yourself:
password = input("Enter password: ")
if password == "secret123":
print("โ
Access granted!")
Important: == is equality check, while = is assignment!
x = 5 # Assignment: x is now 5
x == 5 # Check: is x equal to 5? โ True
โ if-else: Two Branches
Often you need to handle both cases: when True and when False.
Syntax:
if condition:
code if True
else:
code if False
Example:
age = int(input("How old are you? "))
if age >= 18:
print("๐ You are an adult")
else:
print("๐ถ You are still a child")
What happens:
- If age >= 18 โ first block
- Otherwise (age < 18) โ second block
- Only ONE of the blocks runs!
Guess the Number game:
secret = 7
guess = int(input("Guess a number from 1 to 10: "))
if guess == secret:
print("๐ Correct!")
else:
print(f"๐ข Wrong. It was: {secret}")
๐ฏ elif: Multiple Choices
What if you have more than two cases?
Syntax:
if condition1:
code1
elif condition2:
code2
elif condition3:
code3
else:
code4
elif = else if = “otherwise if”
Example โ grading system:
score = int(input("Your score (0-100): "))
if score >= 90:
print("๐ Grade: A (Excellent!)")
elif score >= 80:
print("๐ Grade: B (Good)")
elif score >= 70:
print("๐ Grade: C (Satisfactory)")
elif score >= 60:
print("๐ Grade: D (Passing)")
else:
print("โ Grade: F (Fail)")
How it works:
1. Checks >= 90 โ if True, runs and stops, the rest are skipped
2. If False โ checks >= 80
3. And so on, top to bottom
4. If all are False โ runs else
Order matters!
# โ WRONG โ first condition catches everything!
if score >= 60:
print("D")
elif score >= 80: # Never runs!
print("B")
# โ
CORRECT โ from largest to smallest
if score >= 80:
print("B")
elif score >= 60:
print("D")
๐ Comparison Operators
What can you check?
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
equal to | 5 == 5 |
True |
!= |
not equal to | 5 != 3 |
True |
> |
greater than | 5 > 3 |
True |
< |
less than | 5 < 10 |
True |
>= |
greater than or equal | 5 >= 5 |
True |
<= |
less than or equal | 3 <= 5 |
True |
Examples:
x = 10
if x > 5:
print("x is greater than 5") # Runs
if x != 20:
print("x is not 20") # Runs
if x == 10:
print("x equals 10") # Runs
if x <= 10:
print("x is less than or equal to 10") # Runs
Checking strings:
name = input("Your name: ")
if name == "Anna":
print("Hello, Anna!")
city = "New York"
if city != "London":
print("This is not London")
Important: Case matters!
if "anna" == "Anna": # False!
print("Equal")
# To ignore case:
name = input("Name: ").lower() # Convert to lowercase
if name == "anna":
print("That's Anna!")
๐ก Useful Examples
Checking parity:
number = int(input("Enter a number: "))
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
% is the modulo operator. Even numbers divide by 2 with no remainder!
Checking a range:
age = int(input("Age: "))
if age < 0:
print("โ Invalid age")
elif age < 13:
print("๐ถ Child")
elif age < 20:
print("๐ Teenager")
elif age < 60:
print("๐ผ Adult")
else:
print("๐ด Senior")
Traffic light:
color = input("Traffic light color: ").lower()
if color == "green":
print("๐ข Go!")
elif color == "yellow":
print("๐ก Get ready!")
elif color == "red":
print("๐ด Stop!")
else:
print("๐ค That's not a valid traffic light color")
โ ๏ธ Common Mistakes
1. Forgot the colon:
# โ Error!
if age >= 18
print("OK")
# โ
Correct:
if age >= 18:
print("OK")
2. Forgot the indentation:
# โ Error!
if age >= 18:
print("OK")
# โ
Correct (4 spaces or Tab):
if age >= 18:
print("OK")
3. Used = instead of ==:
# โ Assignment instead of comparison!
if age = 18:
print("OK")
# โ
Equality check:
if age == 18:
print("OK")
4. Condition in else:
# โ else doesn't take a condition!
if x > 10:
print("High")
else x < 5:
print("Low")
# โ
Use elif:
if x > 10:
print("High")
elif x < 5:
print("Low")
else:
print("Medium")
๐ฎ Practice Tasks
Easy level:
1. Password check
Ask for a password. If it’s “python123”, print “Access granted”, otherwise “Access denied”.
2. Age check
Ask for an age. Determine the category: child (<13), teenager (13โ17), adult (18+).
3. Discount calculator
Ask for a purchase amount. If >= 1000 โ 10% discount; if >= 5000 โ 20% discount.
Medium level:
4. Time of day
Ask for the hour (0โ23). Print: night, morning, afternoon, or evening.
5. Grade converter
Ask for a score (0โ100). Print the grade: A (90+), B (80+), C (70+), D (60+), F (<60).
6. Leap year check
Ask for a year. Determine if it’s a leap year (divisible by 4 but not by 100, or divisible by 400).
๐ Summary
You learned:
โ
Use if for a single condition
โ
Use if-else for two branches
โ
Use if-elif-else for multiple choices
โ
Apply comparison operators
โ
Avoid common mistakes
Next step: Learn logical operators (and, or, not) to combine conditions!
Practice in CodeHS โ write several programs with conditionals. Programming is like a sport: the more you practice, the better you get! ๐ช
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!