6.3. if, elif, else
Table of Contents
The Basic `if` Statement
In this chapter, you’ll focus on how to use if, elif, and else to control which parts of your code run.
A basic if statement checks a condition and runs a block of code only if that condition is True.
age = 20
if age >= 18:
print("You are an adult.")How it works:
age >= 18is a condition (a comparison that results inTrueorFalse).- The line under
ifis indented (by 4 spaces here).
Indentation tells Python which lines belong to theifblock. - If the condition is
False, the indented code is skipped.
You can have any number of lines inside the if block:
age = 20
if age >= 18:
print("You are an adult.")
print("You can enter the website.")
print("Enjoy your stay!")
All three print lines run only if age >= 18 is True.
Adding an `else` Block
else is used when you want to run alternative code if the if condition is False.
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")How it works:
- Python checks
if age >= 18. - If it’s
True, only theifblock runs. - If it’s
False, theelseblock runs instead. - Exactly one of the two blocks (
iforelse) will run.
More realistic example:
temperature = 30
if temperature > 25:
print("It's warm outside.")
else:
print("It's not very warm today.")Multiple Choices with `elif`
Sometimes there are more than two possibilities.
That’s what elif is for: “else if”.
Basic pattern:
if condition1:
# code if condition1 is True
elif condition2:
# code if condition2 is True and condition1 was False
elif condition3:
# code if condition3 is True and all above were False
else:
# code if none of the conditions were TrueExample: grading system
score = 72
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")Important details:
- Python checks the conditions top to bottom.
- As soon as it finds a
Truecondition, it runs that block and skips the rest. - Only one block among
if/elif/elseruns.
In the example above:
- If
scoreis 95 →score >= 90isTrue→ prints"Grade: A"→ done. - If
scoreis 85 →score >= 90isFalse,score >= 80isTrue→ prints"Grade: B"→ done. - If
scoreis 40 → allif/elifconditions areFalse→elseruns.
When to Use `if`, `elif`, and `else`
Some common patterns:
`if` only
Use if alone when you only care about one situation and don’t need an “otherwise”.
age = 19
if age >= 18:
print("You can vote.")
If the condition is False, nothing happens.
`if` + `else`
Use if + else when there are two exclusive options.
number = 3
if number % 2 == 0:
print("Even")
else:
print("Odd")This guarantees one of the two messages is printed.
`if` + `elif` (+ `else`)
Use if + elif when you have several possible categories.
hour = 14
if hour < 12:
print("Good morning")
elif hour < 18:
print("Good afternoon")
else:
print("Good evening")Here:
- If
hour < 12: morning - Else if
hour < 18: afternoon - Else: evening
Execution Order and “First Match” Rule
With if–elif–else chains, remember:
- Conditions are checked in order, from top to bottom.
- The first condition that is
Trueis chosen. - After that block runs, the rest of the chain is ignored.
Example:
x = 10
if x > 0:
print("Positive")
elif x > 5:
print("Greater than 5")
Even though x > 5 is True, you will only see:
PositiveBecause:
x > 0is checked first and isTrue, so"Positive"is printed.- The
elif x > 5is never checked.
To make the second condition work as intended, you’d have to reorder them:
x = 10
if x > 5:
print("Greater than 5")
elif x > 0:
print("Positive")Now the output is:
Greater than 5Attaching `else` to the Right `if`
An else (and elif) always belongs to the nearest previous if that doesn’t already have an else.
Correct example:
age = 17
if age >= 18:
print("Adult")
else:
print("Minor")Incorrect structure (common confusion):
# This is valid Python, but maybe not what you intended:
age = 17
if age >= 18:
if age >= 21:
print("You can drink alcohol (in some countries).")
else:
print("You are under 18.")
Here, the else is paired with the inner if age >= 21, not the outer one.
So "You are under 18." only runs if age >= 18 is True and age >= 21 is False.
In other words:
- If
age = 17→ outerifisFalse→ nothing runs. - If
age = 19→ outerifisTrue, innerifisFalse→"You are under 18."prints (which is wrong logically).
You usually want this instead:
age = 17
if age >= 18:
if age >= 21:
print("You can drink alcohol (in some countries).")
else:
print("You are an adult, but cannot drink alcohol yet.")
else:
print("You are under 18.")
Notice how indentation makes it clear which else belongs to which if.
Writing Clear Conditions
You can often simplify and clarify your if / elif / else blocks.
Avoid overlapping conditions
Example with overlapping:
score = 85
if score >= 70:
print("Pass")
elif score >= 80:
print("Good")
Here, "Good" will never print, because if score >= 80, then score >= 70 is also True, and the first condition already matches.
Better:
score = 85
if score >= 80:
print("Good")
elif score >= 70:
print("Pass")Use `elif` instead of multiple separate `if`s (when appropriate)
Sometimes beginners write:
temperature = 10
if temperature < 0:
print("Freezing")
if temperature < 15:
print("Cold")
if temperature < 25:
print("Mild")
If temperature = 10, all three messages except "Freezing" will print, which might not be what you want.
To choose exactly one category, use elif and else:
temperature = 10
if temperature < 0:
print("Freezing")
elif temperature < 15:
print("Cold")
elif temperature < 25:
print("Mild")
else:
print("Warm")Now only one message is printed.
Common Pitfalls with `if` / `elif` / `else`
1. Forgetting the colon `:`
Every if, elif, and else line must end with :.
if age >= 18:
print("Adult")
elif age >= 13:
print("Teen")
else:
print("Child")
If you miss a colon, you’ll get a SyntaxError.
2. Mixing up `==` and `=`
=is for assignment (storing a value in a variable).==is for comparison (checking equality in conditions).
Incorrect:
if x = 10: # Error!
print("x is 10")Correct:
x = 10
if x == 10:
print("x is 10")3. Indentation mistakes
Blocks under if, elif, and else must be consistently indented.
Incorrect:
age = 20
if age >= 18:
print("Adult") # Not indented → errorCorrect:
age = 20
if age >= 18:
print("Adult")Or with multiple lines:
age = 20
if age >= 18:
print("Adult")
print("Welcome!")All lines in the block must be indented the same amount.
Small Practice Ideas
Here are a few small programs you can try to write using if, elif, and else:
- Day of the week greeting
- Ask the user to enter a number from 1 to 7.
- If 1 → print
"Monday", if 2 →"Tuesday", …, if 7 →"Sunday". - Use
if/elif/elseto handle it. - Ticket price based on age
- If age < 3 →
"Free". - If age is 3–12 →
"Child ticket". - If age is 13–64 →
"Adult ticket". - If age is 65 or older →
"Senior ticket". - Simple login check
- Store a correct password in a variable.
- Ask the user to input a password.
- If it matches →
"Access granted", else →"Access denied".
As you practice, pay attention to:
- Using
ifwhen you only need a single check. - Adding
elsewhen you need an “otherwise”. - Adding
elifwhen you have several categories. - The order of your conditions and how it affects which block runs.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Chapter 1: What Is Programming?
- ☰ 1.1. What is a computer program?
- ☰ 1.2. What is Python?
- ☰ 1.3. Where is Python used?
- ☰ 1.4. How programming helps solve problems
- ☰ 1.5. Your first Python program
-
- ☰ 2. Chapter 2: Setting Up Python
- ☰ 2.1. Installing Python (Windows / macOS / Linux)
- ☰ 2.2. Using Python in the terminal
- ☰ 2.3. Using an IDE (IDLE / VS Code)
- ☰ 2.4. Running Python scripts
- ☰ 2.5. Python interactive mode
-
- ☰ 3. Chapter 3: Variables and Data Types
- ☰ 3.1. What is a variable?
- ☰ 3.2. Creating variables
- ☰ 3.3. Numbers
- ☰ 3.4. Test
- ☰ 3.5. Boolean values
- ☰ 3.6. Type checking
-
- ☰ 4. Chapter 4: Basic Operations
- ☰ 4.1. Arithmetic operations
- ☰ 4.2. Working with numbers
- ☰ 4.3. String operations
- ☰ 4.4. Combining text and variables
- ☰ 4.5. Comments in Python
-
- ☰ 5. Chapter 5: User Input and Output
- ☰ 5.1. Getting input from the user
- ☰ 5.2. Converting input to numbers
- ☰ 5.3. Formatting output
- ☰ 5.4. Writing interactive programs
-
- ☰ 6. Chapter 6: Conditions
- ☰ 6.1. Comparison operators
- ☰ 6.2. Logical operators
- ☰ 6.3. if, elif, else
- ☰ 6.4. Nested conditions
- ☰ 6.5. Common beginner mistakes
-
- ☰ 7. Chapter 7: Loops
- ☰ 7.1. Why loops are useful
- ☰ 7.2. for loops
- ☰ 7.3. while loops
- ☰ 7.4. Loop counters
- ☰ 7.5. break and continue
- ☰ 7.6. Loop exercises
-
- ☰ 8. Chapter 8: Data Collections
- ☰ 8.1. Lists
- ☰ 8.2. Tuples
- ☰ 8.3. Dictionaries
- ☰ 8.4. Sets (basics)
- ☰ 8.5. Choosing the right data structure
-
- ☰ 9. Chapter 9: Functions
- ☰ 9.1. Why functions matter
- ☰ 9.2. Defining functions
- ☰ 9.3. Parameters and arguments
- ☰ 9.4. Return values
- ☰ 9.5. Scope (local vs global)
- ☰ 9.6. Reusing code
-
- ☰ 10. Chapter 10: Working with Files
- ☰ 10.1. What is a file?
- ☰ 10.2. Reading text files
- ☰ 10.3. Writing and appending files
- ☰ 10.4. File paths
- ☰ 10.5. Simple file-based programs
-
- ☰ 11. Chapter 11: Errors and Debugging
- ☰ 11.1. Types of errors
- ☰ 11.2. Reading error messages
- ☰ 11.3. Common beginner errors
- ☰ 11.4. try and except
- ☰ 11.5. Debugging strategies
-
- ☰ 12. Chapter 12: Using Python Libraries
- ☰ 12.1. What is a library?
- ☰ 12.2. Importing modules
- ☰ 12.3. Standard libraries
- ☰ 12.3.1. math
- ☰ 12.3.2. random
- ☰ 12.3.3. datetime
-
- ☰ 12.4. Installing external libraries with pip
-
- ☰ 13. Chapter 13: Object-Oriented Programming
- ☰ 13.1. What is object-oriented programming?
- ☰ 13.2. Classes and objects
- ☰ 13.3. The `__init__` method
- ☰ 13.4. Attributes and methods
- ☰ 13.5. Encapsulation
- ☰ 13.6. Inheritance (basics)
- ☰ 13.7. Simple OOP examples
-
- ☰ 14. Chapter 14: Automation with Python
- ☰ 14.1. What is automation?
- ☰ 14.2. Automating simple tasks
- ☰ 14.3. Working with files and folders
- ☰ 14.4. Automating text processing
- ☰ 14.5. Scheduling scripts
- ☰ 14.6. Practical automation examples
-
- ☰ 15. Chapter 15: Web Development with Python
- ☰ 15.1. How the web works (basic overview)
- ☰ 15.2. Introduction to Flask
- ☰ 15.3. Creating a simple web server
- ☰ 15.4. Routing and templates
- ☰ 15.5. Handling user input (forms)
- ☰ 15.6. Very basic APIs
-
- ☰ 16. Chapter 16: Data Science with Python
- ☰ 16.1. What is data science?
- ☰ 16.2. Working with data
- ☰ 16.3. Introduction to NumPy
- ☰ 16.4. Introduction to pandas
- ☰ 16.5. Data visualization with matplotlib
- ☰ 16.6. Simple data analysis examples
-
- ☰ 17. Chapter 17: Mini Projects
- ☰ 17.1. Number guessing game
- ☰ 17.2. Simple calculator
- ☰ 17.3. To-do list
- ☰ 17.4. Password generator
- ☰ 17.5. Quiz application
- ☰ 17.6. Small web or data project
-
- ☰ 18. Chapter 18: Next Steps
- ☰ 18.1. How to practice Python
- ☰ 18.2. Writing clean and readable code
- ☰ 18.3. Choosing a specialization
- ☰ 18.3.1. Web development
- ☰ 18.3.2. Data science
- ☰ 18.3.3. Automation
- ☰ 18.3.4. Software development
-
- ☰ 18.4. Learning resources and communities
-
- ☰ 19. Appendix
- ☰ 19.1. Python syntax cheat sheet
- ☰ 19.2. Common errors and solutions
- ☰ 19.3. Glossary of terms
-
Comments
Please login to add a comment.
Don't have an account? Register now!