
Python if-else Statements
One of the first and most essential concepts you'll encounter in Python—and programming in general—is the if-else
statement. It allows your code to make decisions, executing different blocks of code depending on whether a condition is true or false. Think of it like a fork in the road: depending on certain conditions, your program takes one path or another.
Let's start with the simplest form: the if
statement. It checks a condition, and if that condition evaluates to True
, it runs the indented block of code underneath it.
age = 20
if age >= 18:
print("You are an adult.")
In this example, since age
is 20 (which is indeed greater than or equal to 18), the message "You are an adult." will be printed. If age
were less than 18, nothing would happen—the if
block would simply be skipped.
But what if you want to do something else when the condition is false? That's where else
comes in.
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Here, because age
is 16, the condition age >= 18
is false, so the else
block runs instead, printing "You are a minor."
Sometimes, you need to check multiple conditions. You can do this with elif
, which is short for "else if." It allows you to chain conditions together.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
In this case, since score
is 85, it doesn’t meet the first condition (>=90), but it does meet the second (>=80), so "Grade: B" is printed. The rest of the conditions are skipped.
It's important to understand that conditions are evaluated in order. As soon as one condition is true, its block is executed, and the rest are ignored. This is why the order of your elif
statements matters.
You can also nest if
statements inside other if
or else
blocks. This is useful for more complex decision-making.
num = 10
if num > 0:
print("Positive number")
if num % 2 == 0:
print("and it's even")
else:
print("and it's odd")
else:
print("Non-positive number")
Here, we first check if num
is positive. If it is, we then check whether it's even or odd. This nested structure helps handle multi-layered conditions.
You're not limited to simple comparisons. You can use logical operators like and
, or
, and not
to combine conditions.
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive.")
else:
print("You cannot drive.")
Both conditions must be true for the if
block to run. If either is false, the else
block executes.
Similarly, you can use or
if at least one condition needs to be true.
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
print("No work today!")
else:
print("Time to work.")
Since is_weekend
is true, the message "No work today!" is printed, even though is_holiday
is false.
You can also use the not
operator to invert a condition.
is_raining = False
if not is_raining:
print("Let's go outside!")
else:
print("Better stay indoors.")
Because is_raining
is false, not is_raining
becomes true, so we go outside.
In Python, you can write one-line if-else statements, known as ternary expressions. They are concise but best used for simple conditions.
age = 22
status = "adult" if age >= 18 else "minor"
print(status)
This assigns "adult" to status
if the condition is true, otherwise "minor".
Be cautious: although ternary expressions are compact, they can reduce readability if overused or too complex.
You can also have an if
statement without an else
. Sometimes, you only care about the true case.
temperature = 30
if temperature > 25:
print("It's a hot day.")
If temperature
is 20, nothing is printed.
It's worth noting that in Python, indentation is crucial. The code inside an if
, elif
, or else
block must be indented (usually by 4 spaces). Incorrect indentation will lead to errors or unexpected behavior.
Let’s look at a practical example: checking user input.
user_input = input("Enter a number: ")
if user_input.isdigit():
num = int(user_input)
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")
else:
print("That's not a valid number.")
Here, we first check if the input is a digit. If it is, we convert it to an integer and check if it's even or odd. If not, we print an error message.
Another common use case is validating data.
email = "user@example.com"
if "@" in email and "." in email:
print("Valid email format.")
else:
print("Invalid email.")
This checks if the email contains both "@" and ".", though note that real email validation is more complex.
You can use if-else
statements in loops to perform actions conditionally on each iteration.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
This loops through the list and prints whether each number is even or odd.
Remember, you can have multiple elif
blocks, but only one else
block, and it must come last.
day = "Wednesday"
if day == "Monday":
print("Start of the work week.")
elif day == "Friday":
print("Almost weekend!")
elif day == "Saturday" or day == "Sunday":
print("Weekend!")
else:
print("Midweek day.")
Depending on the value of day
, the appropriate message is printed.
In some cases, you might want to check if a value is in a list or other collection.
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Yes, banana is in the list.")
This is a clean and readable way to check membership.
You can also use if-else
with dictionaries to handle different cases.
def handle_response(code):
responses = {
200: "OK",
404: "Not Found",
500: "Internal Server Error"
}
if code in responses:
return responses[code]
else:
return "Unknown status code"
print(handle_response(404)) # Output: Not Found
This function returns the appropriate message for known status codes and a default for others.
Another useful technique is using if
statements to assign variables conditionally.
x = 10
y = 20
max_value = x if x > y else y
print(max_value) # Output: 20
Here, max_value
is assigned the larger of x
or y
.
You can also use comparison chaining in conditions.
x = 15
if 10 <= x <= 20:
print("x is between 10 and 20")
This checks if x
is greater than or equal to 10 and less than or equal to 20.
Be mindful of common pitfalls, such as using =
(assignment) instead of ==
(equality) in conditions.
# Wrong
if x = 10:
print("x is 10")
# Correct
if x == 10:
print("x is 10")
The first example will cause a syntax error because assignment isn’t allowed in conditions.
Another pitfall is forgetting the colon at the end of the if
, elif
, or else
line.
# Wrong
if x > 5
print("x is greater than 5")
# Correct
if x > 5:
print("x is greater than 5")
Missing the colon will result in a syntax error.
Also, ensure that you're comparing values of the same type when necessary.
num = 10
if num == "10": # This is False because 10 != "10"
print("Equal")
else:
print("Not equal")
Here, num
is an integer, and we're comparing it to a string, so they are not equal.
You can use if
statements with None
to check if a variable has been assigned a value.
value = None
if value is None:
print("Value is not set")
Using is
is preferred for comparing with None
because it checks for identity, not just equality.
In Python, empty sequences and collections are considered false in a boolean context. This can simplify your conditions.
my_list = []
if not my_list:
print("The list is empty")
This is more Pythonic than checking if len(my_list) == 0
.
Similarly, non-empty sequences are considered true.
my_list = [1, 2, 3]
if my_list:
print("The list has items")
This prints the message because my_list
is not empty.
You can use this behavior to write concise conditions.
name = input("Enter your name: ")
if name:
print(f"Hello, {name}!")
else:
print("You didn't enter a name.")
If the user enters nothing, name
will be an empty string, which is false, so the else
block runs.
For numbers, zero is considered false, and non-zero numbers are true.
count = 0
if count:
print("There are items")
else:
print("No items")
This will print "No items" because count
is zero.
You can also use if-else
statements in list comprehensions for conditional inclusion of elements.
numbers = [1, 2, 3, 4, 5]
squares_of_evens = [x**2 for x in numbers if x % 2 == 0]
print(squares_of_evens) # Output: [4, 16]
This creates a list of squares for even numbers only.
Similarly, you can use conditional expressions in comprehensions.
numbers = [1, 2, 3, 4, 5]
labeled = ["even" if x % 2 == 0 else "odd" for x in numbers]
print(labeled) # Output: ['odd', 'even', 'odd', 'even', 'odd']
This labels each number as "even" or "odd" in a new list.
When working with if-else
, readability is key. Avoid writing overly complex conditions that are hard to understand. Instead, break them down or use variables.
# Hard to read
if (x > 0 and y < 0) or (x < 0 and y > 0):
print("x and y have opposite signs")
# Better
x_positive = x > 0
y_positive = y > 0
have_opposite_signs = x_positive != y_positive
if have_opposite_signs:
print("x and y have opposite signs")
The second version is clearer and easier to maintain.
You can also use parentheses to group conditions and clarify order of evaluation.
if (x > 0 and y > 0) or (z > 0):
print("At least one pair is positive")
This makes it clear that x > 0 and y > 0
is one group, and z > 0
is another.
In some cases, you might want to use pass
as a placeholder in an if
block.
x = 10
if x > 5:
pass # TODO: handle this case later
else:
print("x is small")
pass
does nothing and is useful when you're sketching out code.
You can have multiple conditions in a single if
statement using logical operators.
age = 25
income = 50000
if age >= 18 and income > 30000:
print("Eligible for loan")
Both conditions must be true for eligibility.
Alternatively, using or
:
is_student = True
is_senior = False
if is_student or is_senior:
print("Eligible for discount")
If either condition is true, the discount applies.
You can mix and
and or
, but use parentheses to avoid ambiguity.
if (age >= 65 or is_disabled) and has_insurance:
print("Eligible for benefit")
This ensures that either age >= 65
or is_disabled
is true, and has_insurance
is also true.
Remember that and
has higher precedence than or
, so without parentheses, age >= 65 or is_disabled and has_insurance
would be interpreted as age >= 65 or (is_disabled and has_insurance)
, which might not be what you want.
In Python, you can use if-else
statements to handle exceptions or edge cases gracefully.
def divide(a, b):
if b == 0:
return "Cannot divide by zero"
else:
return a / b
print(divide(10, 2)) # Output: 5.0
print(divide(10, 0)) # Output: Cannot divide by zero
This prevents a division by zero error.
You can also use if-else
in return statements for concise function definitions.
def is_adult(age):
return True if age >= 18 else False
print(is_adult(20)) # Output: True
Although in this case, you could simply return age >= 18
directly.
Another common pattern is using if-else
with isinstance()
to check variable types.
def double_value(x):
if isinstance(x, (int, float)):
return x * 2
else:
return "Unsupported type"
print(double_value(5)) # Output: 10
print(double_value("a")) # Output: Unsupported type
This ensures the function only doubles numeric types.
You can use if-else
statements to implement simple state machines or decision trees.
def traffic_light(color):
if color == "red":
return "Stop"
elif color == "yellow":
return "Caution"
elif color == "green":
return "Go"
else:
return "Invalid color"
print(traffic_light("red")) # Output: Stop
This returns the appropriate action for each traffic light color.
In loops, if-else
can be used with break
or continue
to control flow.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
continue # Skip the rest of the loop for this iteration
print(num)
# Output: 1, 2, 4, 5
Here, when num
is 3, continue
skips the print
statement.
Similarly, you can use break
to exit the loop early.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break # Exit the loop entirely
print(num)
# Output: 1, 2
Once num
becomes 3, the loop terminates.
You can also use if-else
with while
loops.
count = 0
while count < 5:
if count % 2 == 0:
print(f"{count} is even")
else:
print(f"{count} is odd")
count += 1
This prints whether each number from 0 to 4 is even or odd.
In some cases, you might want to use an if
statement without a condition to check for truthiness.
value = "Hello"
if value:
print("Value is truthy")
Since value
is a non-empty string, it's truthy, so the message is printed.
Conversely, you can check for falsiness.
value = ""
if not value:
print("Value is falsy")
An empty string is falsy, so this prints the message.
You can use if-else
statements to validate function arguments.
def greet(name):
if not name:
raise ValueError("Name cannot be empty")
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
greet("") # Raises ValueError
This ensures that name
is not empty before greeting.
Another useful application is handling different input formats.
def process_input(data):
if isinstance(data, str):
return data.upper()
elif isinstance(data, list):
return [item.upper() for item in data]
else:
return "Unsupported input type"
print(process_input("hello")) # Output: HELLO
print(process_input(["a", "b"])) # Output: ['A', 'B']
print(process_input(123)) # Output: Unsupported input type
This function handles both strings and lists of strings.
You can use if-else
in lambda functions for simple conditional expressions.
is_even = lambda x: True if x % 2 == 0 else False
print(is_even(4)) # Output: True
Although again, lambda x: x % 2 == 0
would suffice.
In data processing, if-else
can be used to categorize values.
scores = [85, 92, 78, 60, 45]
grades = []
for score in scores:
if score >= 90:
grades.append("A")
elif score >= 80:
grades.append("B")
elif score >= 70:
grades.append("C")
elif score >= 60:
grades.append("D")
else:
grades.append("F")
print(grades) # Output: ['B', 'A', 'C', 'D', 'F']
This categorizes each score into a grade.
You can also use if-else
with dictionary.get() to provide default values.
data = {"name": "Alice", "age": 30}
country = data.get("country", "Unknown")
print(country) # Output: Unknown
Since "country" key doesn't exist, the default "Unknown" is returned.
Similarly, you can use if-else
to handle missing keys.
data = {"name": "Alice", "age": 30}
if "country" in data:
country = data["country"]
else:
country = "Unknown"
print(country) # Output: Unknown
Although .get()
is more concise for this purpose.
In summary, Python's if-else statements are versatile and fundamental to writing dynamic code. They allow your programs to respond to different conditions, making them more intelligent and flexible. Practice using them in various scenarios to become comfortable with decision-making in your code.
Condition Type | Example | Outcome |
---|---|---|
Simple if | if x > 0: print("Positive") |
Prints if x is positive |
if-else | if x > 0: print("Positive") else: print("Non-positive") |
Prints based on condition |
if-elif-else | if x > 0: print("Positive") elif x < 0: print("Negative") else: print("Zero") |
Handles multiple cases |
- Simple if: Executes code only if the condition is true.
- if-else: Executes one block if true, another if false.
- if-elif-else: Handles multiple conditions in sequence.
Remember to use indentation correctly, as it defines the blocks of code. Also, be mindful of the order of conditions in elif
chains, as the first true condition wins.