If Statements, Elif, and Else in Python
Here's where programming gets genuinely interesting. So far, our programs have been straight lines — they do things in order and that's it. But real programs need to make decisions: "if the user entered a valid number, proceed; if not, show an error message."
This is conditional logic, and it's one of the most fundamental concepts in all of programming.
The if Statement
temperature = 35
if temperature > 30:
print("It's hot outside!")
print("Maybe stay inside with the air conditioning.")
The structure is:
- The word
if - A condition (something that evaluates to
TrueorFalse) - A colon
: - An indented block of code that runs only if the condition is True
That indentation is crucial. Python uses indentation — spaces at the beginning of lines — to know which code belongs to which block. [[[The standard is 4 spaces (or one Tab press in most editors)](https://www.python.org/dev/peps/pep-0008/)](https://www.python.org/dev/peps/pep-0008/)](https://peps.python.org/pep-0008/).
If the condition is False, Python just skips that indented block entirely and continues with whatever comes after.
The else Clause
What if you want to do something different when the condition is False?
temperature = 15
if temperature > 30:
print("It's hot!")
else:
print("It's not that hot.")
print("Maybe bring a jacket.")
The else block runs when the if condition is False. Only one of the two blocks ever runs — never both.
The elif Clause: Multiple Conditions
[[[elif is short for "else if"](https://docs.python.org/3/tutorial/controlflow.html)](https://docs.python.org/3/tutorial/controlflow.html)](https://docs.python.org/3/tutorial/controlflow.html) — it lets you chain multiple conditions together:
temperature = 22
if temperature > 35:
print("Dangerously hot. Stay inside.")
elif temperature > 25:
print("Warm and sunny. Nice day!")
elif temperature > 15:
print("Comfortable. Perfect weather.")
elif temperature > 5:
print("Chilly. Bring a jacket.")
else:
print("Cold. Wrap up warmly.")
Python evaluates these from top to bottom and runs the first block whose condition is True, then skips all the rest. So if temperature is 40, it prints "Dangerously hot" and ignores all the elif and else blocks entirely.
You can have as many elif clauses as you want. Only one else at the end, and that's optional.
Indentation: Python's Most Distinctive Feature
Python's indentation requirement is either elegant or infuriating depending on your mood — sometimes both on the same day. Many major programming languages use curly braces {} to group code (such as Java, C, C++, JavaScript, Go, and Rust), [while others like Ruby, Haskell, and Lisp do not](https://en.wikibooks.org/wiki/Haskell/Indentation). Python uses indentation, and that's just the deal.
# Python style (indentation-based):
if x > 0:
print("Positive")
print("Still in the if block")
print("Back to the main program")
# What the equivalent looks like in other languages (conceptually):
# if (x > 0) {
# print("Positive");
# print("Still in the if block");
# }
# print("Back to the main program");
The great thing about Python's approach: it forces readable code. Code that's properly indented is visually clear about what belongs where. According to PEP 8, Python disallows mixing tabs and spaces for indentation, raising an error rather than causing subtle bugs. Stick to spaces (4 per level) and you'll be fine.
Nested Conditions
You can put conditions inside conditions. This is called nesting.
age = 20
has_id = True
if age >= 18:
if has_id:
print("Welcome! Come on in.")
else:
print("We need to see some ID.")
else:
print("Sorry, you're not old enough.")
You can also use and to combine conditions and avoid nesting altogether:
if age >= 18 and has_id:
print("Welcome! Come on in.")
elif age >= 18 and not has_id:
print("We need to see some ID.")
else:
print("Sorry, you're not old enough.")
Both work. The nested version sometimes reads more naturally; the and version is more compact. Pick whichever one makes the logic clearer to a future reader — which, a month from now, will be you, staring at this code with absolutely no memory of writing it.
Putting It Together: A Real Decision-Making Program
# Grade calculator
print("=== Grade Calculator ===")
score = int(input("Enter your score (0-100): "))
if score >= 90:
grade = "A"
message = "Excellent work!"
elif score >= 80:
grade = "B"
message = "Good job!"
elif score >= 70:
grade = "C"
message = "Passing, but you could do better."
elif score >= 60:
grade = "D"
message = "Barely made it."
else:
grade = "F"
message = "Time to study more."
print(f"\nScore: {score}")
print(f"Grade: {grade}")
print(f"Comment: {message}")
[That \n inside the f-string is a newline character — it tells Python to start a new line at that point](https://docs.python.org/3/tutorial/introduction.html). So print(f"\nScore: {score}") prints a blank line first, then "Score: 90" (or whatever the score is).
Only visible to you
Sign in to take notes.