Python Control Statements
Python If else
Learn Python If else with clear explanations, Python examples, and practical programming guidance.
What are conditional statements in Python?
Conditional statements let a program choose which code to run based on a condition. Python evaluates the condition as a Boolean value. When it is true, the associated indented block runs; otherwise, Python checks another branch or skips the block.
| Statement | Use it when... |
|---|---|
if | You need to run code only when a condition is true. |
if ... else | There are exactly two possible paths. |
if ... elif ... else | Several mutually exclusive conditions must be checked. |
Nested if | A second condition depends on the first condition being true. |
The if statement
An if statement runs its indented block only when the condition is true. The colon begins the block, and indentation defines its boundaries:
age = 18
if age >= 18:
print("You can vote.")If the condition is false, Python skips the block and continues with the next statement.
The if ... else statement
Use else when one of two actions must run:
age = 16
if age >= 18:
print("You can vote.")
else:
print("You cannot vote yet.")Exactly one branch runs. The else block does not have its own condition; it handles every case not matched by the if.
The if ... elif ... else statement
Use elif to test multiple conditions in order. Python stops at the first condition that is true:
temperature = 22
if temperature >= 30:
print("Hot")
elif temperature >= 20:
print("Warm")
elif temperature >= 10:
print("Cool")
else:
print("Cold")Order matters. Put more specific or higher thresholds before broader conditions so the intended branch can be reached.
Nested conditional statements
A nested conditional is an if statement inside another conditional block. It is useful when the second check should happen only after the first requirement succeeds:
marks = 82
if marks >= 40:
if marks >= 75:
print("Passed with distinction")
else:
print("Passed")
else:
print("Failed")Deep nesting can make code difficult to read. When possible, combine conditions or move the decision into a well-named function.
Comparison operators in conditions
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | status == "active" |
!= | Not equal to | role != "guest" |
<, <= | Less than or less than or equal to | score < 50 |
>, >= | Greater than or greater than or equal to | age >= 18 |
is | Same object identity | value is None |
in | Member exists in a container | "admin" in roles |
Combining conditions
Use and when all conditions must be true, or when at least one condition can be true, and not to reverse a result:
age = 25
has_id = True
is_member = False
if age >= 18 and has_id:
print("Access approved")
if is_member or has_id:
print("A verification option is available")
if not is_member:
print("Membership is not active")A verification option is available
Membership is not active
Use parentheses when a condition mixes and and or. They make the intended grouping clear and prevent precedence mistakes.
Truthy and falsy values
Python allows any object in a condition. Empty strings and collections, zero, None, and False are falsy; most non-empty or non-zero values are truthy:
items = ["Python"]
if items:
print("The list has items")
name = ""
if not name:
print("A name is required")A name is required
Independent if statements versus elif
Use separate if statements when more than one message may be correct. Use elif when only one branch should run:
age = 65
# Both conditions can produce a message
if age >= 18:
print("Adult")
if age >= 60:
print("Senior benefits may apply")
# Only the first matching branch runs
if age >= 60:
print("Senior")
elif age >= 18:
print("Adult")Validating user input
Conditions are commonly used to validate values before processing them. Convert input safely and check the valid range:
try:
marks = int(input("Enter marks from 0 to 100: "))
if 0 <= marks <= 100:
print("Valid marks")
else:
print("Marks must be between 0 and 100")
except ValueError:
print("Please enter a whole number")Chained comparisons such as 0 <= marks <= 100 are equivalent to checking both limits with and.
Conditional expressions
A conditional expression chooses one of two values in a single line. Use it only when the logic remains easy to read:
score = 72
result = "Pass" if score >= 40 else "Fail"
print(result)Common mistakes
- Use a colon after
if,elif, andelse. - Indent every statement that belongs to a conditional block consistently.
- Use
==for value comparison; a single=assigns a value. - Use
is Nonefor checkingNone, not== None. - Check conditions in the correct order because
elifstops after the first match. - Validate and convert external input before comparing it with numbers.
Best practices
- Keep conditions short and give complex rules descriptive function names.
- Prefer guard clauses to deeply nested blocks when returning early is clear.
- Use parentheses for complex Boolean expressions.
- Choose
eliffor mutually exclusive outcomes and separateifstatements for independent checks.
Further Reading
Continue learning with these related Python tutorials:
Continue learning
