If Else
If Else
Sometimes a condition is true, and sometimes it is false.
What if you want your program to do one thing when the answer is true, and another thing when the answer is false?
That is where if else is useful.
What Is If Else?
Use if when something should happen only when a condition is true.
Use else when you want a different action when the condition is false.
age = 16
if age >= 18:
print("You can vote")
else:
print("You are too young to vote")
How It Works
Let’s break it down:
- Python checks if
age >= 18 - If true, it prints the first message
- If false, it prints the message under
else
Only one block will run.
Why Else Is Helpful
Without else, nothing happens when the condition is false.
With else, your program always gives a result.
Another Example
number = 7
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
The Colon and Indentation
Both if and else need a colon :.
The code under each block must be indented.
if condition:
print("True")
else:
print("False")
Code Along
password = "python123"
if password == "python123":
print("Access granted")
else:
print("Wrong password")
Mini Challenge
Build a pass or fail checker.
Steps:
- Ask the user to enter a test score
- If the score is 50 or more, print:
You passed - Otherwise, print:
You failed
Real World Use Case
Apps use if else to check login details, payment success, subscription status, and many other decisions.
Quiz
- When does the
elseblock run? - Can both
ifandelserun at the same time? - Why is indentation important?
- What will happen if the condition is false?
Assignment
Create a program that stores a number. If the number is positive, print Positive. Otherwise, print Not positive.
Summary
You learned how to use if else to make programs choose between two different actions.