
Every useful program needs to make decisions. Whether you are checking if a user typed the right password, deciding which discount to apply at checkout, or figuring out whether a file exists before opening it, your code needs a way to choose between different paths. That is exactly what Python if else statements do — they let your program evaluate a condition and run different blocks of code depending on whether that condition is True or False.
Python if else is one of the first and most important concepts in the language. Once you understand how it works, a huge range of everyday programming problems become straightforward to solve. This guide walks you through every part of the syntax with clear examples, from the simplest single condition check to nested blocks, logical operators, and real-world use cases.
The simplest form of conditional logic is the plain if statement. You give Python a condition to evaluate, and if that condition is True, the indented code block beneath it runs. If it is False, Python skips that block entirely and moves on to whatever comes after.
The syntax looks like this:
if condition:
# code to run when condition is True
The colon at the end of the if line is required, and the indented block below it is what Python considers the body of the if statement. Python uses indentation instead of curly braces to define code blocks, so the indentation is mandatory, not optional.
Here is a concrete python if else example using a temperature check:
temperature = 35
if temperature > 30:
print("It is hot outside.")
print("Check complete.")
It is hot outside.
Check complete.
Because temperature is 35 and the expression 35 > 30 evaluates to True, the first print runs. The second print runs regardless because it sits outside the if block — it is not indented under the condition.
Now set temperature to 25 and the output changes:
temperature = 25
if temperature > 30:
print("It is hot outside.")
print("Check complete.")
Check complete.
The condition 25 > 30 is False, so Python skips the indented block and jumps straight to the unindented line below.
An if statement on its own only acts when the condition is True. But most real programs need to do something different when the condition is False as well. That is what the else clause is for. The else block runs whenever the if condition evaluates to False.
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not old enough to vote yet.")
You are not old enough to vote yet.
The python if else statement here covers both possibilities — either the person is old enough or they are not. Exactly one of the two blocks will always run. You will never reach a situation where both blocks execute or neither one does.
The else clause does not take a condition of its own. It is simply the fallback that catches everything the if condition did not. Think of it as the default path your program takes when the main check fails.
number = 7
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
7 is odd.
The modulo operator returns the remainder after division. 7 divided by 2 leaves a remainder of 1, not 0, so the condition is False and the else block runs.
Python if else statements rely on conditions that produce True or False. The most common way to build those conditions is with Python's comparison operators:
| Operator | Meaning |
|---|---|
| == | equal to |
| != | not equal to |
| > | greater than |
| < | less than |
| >= | greater than or equal to |
| <= | less than or equal to |
Each of these returns either True or False, which is exactly what an if statement needs to decide which path to take.
x = 10
y = 20
if x == y:
print("x and y are equal.")
else:
print("x and y are not equal.")
x and y are not equal.
price = 49.99
budget = 50.00
if price <= budget:
print("You can afford this item.")
else:
print("This item is over your budget.")
You can afford this item.
You can also chain multiple independent python if else statements one after another. Each one is a completely separate check and does not share state with the others:
stock = 0
is_available = False
if stock > 0:
print("In stock.")
else:
print("Out of stock.")
if is_available:
print("Available for order.")
else:
print("Not available for order.")
Out of stock.
Not available for order.
Each if else block runs independently. Both conditions happen to be False here, so both else branches run.
You will often need to check more than one thing inside a single if else statement. Python lets you combine conditions using the logical operators and, or, and not.
The and operator requires both conditions to be True for the overall expression to be True. If either side is False, the whole thing is False.
username = "admin"
password = "secret123"
if username == "admin" and password == "secret123":
print("Login successful.")
else:
print("Invalid credentials.")
Login successful.
Change the password to something wrong and the else block runs instead, because the second condition becomes False and and requires both to be True.
The or operator requires at least one condition to be True. If either side is True, the overall expression is True.
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It is the weekend!")
else:
print("It is a weekday.")
It is the weekend!
The not operator flips a boolean value. True becomes False and False becomes True. This is useful when you want to run code when something is absent or inactive.
is_raining = False
if not is_raining:
print("Great day for a walk.")
else:
print("Better stay inside.")
Great day for a walk.
not False evaluates to True, so the if block runs. You can also combine all three logical operators in more complex conditions by grouping with parentheses:
age = 25
has_license = True
has_insurance = False
if age >= 18 and has_license and not has_insurance:
print("You need insurance before you can drive.")
else:
print("All requirements checked.")
You need insurance before you can drive.
Sometimes a decision depends on a previous decision. In those cases you can place an if else block inside another if else block. This is called nesting, and Python handles it through indentation levels.
account_active = True
balance = 150
if account_active:
if balance >= 100:
print("Transaction approved.")
else:
print("Insufficient funds.")
else:
print("Your account is not active.")
Transaction approved.
The outer if checks whether the account is active. Only when that condition is True does Python enter the inner if else block to check the balance. If account_active were False, Python would skip the entire nested structure and jump straight to the outer else.
Here is another nested python if else example for an age and membership check:
age = 22
is_member = True
if age >= 18:
if is_member:
print("Welcome back, member! Enjoy your discount.")
else:
print("Welcome! Consider becoming a member for discounts.")
else:
print("You must be 18 or older to enter.")
Welcome back, member! Enjoy your discount.
Nested if else python logic is powerful, but it can become hard to follow if you stack too many levels. When you find yourself three or four levels deep, it is usually a sign that you can simplify using and/or logic to combine conditions, which keeps the code flatter and easier to read.
Python's if else does not strictly require the boolean literals True or False. It works with any value, because every Python object has a boolean interpretation. Values that behave like True inside a condition are called truthy, and values that behave like False are called falsy.
Common falsy values:
Everything else is truthy. This lets you write cleaner python conditional statements without explicit comparisons:
items = []
if items:
print(f"You have {len(items)} item(s) in your cart.")
else:
print("Your cart is empty.")
Your cart is empty.
Instead of writing if len(items) > 0, you can write if items directly. An empty list is falsy, so the else branch runs. This is idiomatic Python and you will see it throughout real codebases.
name = ""
if name:
print(f"Hello, {name}!")
else:
print("No name was provided.")
No name was provided.
An empty string is falsy, so the else branch runs. Populate name with any non-empty string and the if branch runs instead.
A very common pattern in Python is placing a python if else statement inside a function so the function returns different values based on a condition. This makes your logic reusable and easy to test.
def check_speed(speed):
if speed > 120:
return "Over the speed limit."
else:
return "Within the speed limit."
print(check_speed(90))
print(check_speed(135))
Within the speed limit.
Over the speed limit.
The function evaluates the condition on the argument passed in and returns the appropriate string. The if else structure makes it clear that exactly one return statement will execute per call.
You can also use if else to guard against invalid input before doing any real work:
def divide(a, b):
if b == 0:
return "Cannot divide by zero."
else:
return a / b
print(divide(10, 2))
print(divide(10, 0))
5.0
Cannot divide by zero.
The if else here acts as a safety gate. When b is zero the function returns an error message immediately. Otherwise it proceeds with the division. This is one of the most practical uses of python if else in real applications.
Python if else statements work naturally inside loops. You can inspect each item as you iterate and take a different action depending on the condition.
numbers = [4, 7, 2, 9, 6, 3]
for num in numbers:
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")
4 is even.
7 is odd.
2 is even.
9 is odd.
6 is even.
3 is odd.
For every number in the list the if else block runs fresh, evaluating the condition against that specific value. This is a core pattern for filtering, categorizing, and processing data with python decision making.
You can also accumulate results into separate lists:
scores = [88, 45, 72, 30, 95, 60]
passed = []
failed = []
for score in scores:
if score >= 50:
passed.append(score)
else:
failed.append(score)
print("Passed:", passed)
print("Failed:", failed)
Passed: [88, 72, 95, 60]
Failed: [45, 30]
Using = instead of ==: The single equals sign is the assignment operator. The double equals sign is the comparison operator. Writing if x = 5: causes a SyntaxError. Always use == when comparing values inside a condition.
Forgetting the colon: Every if and else line must end with a colon. Leaving it out causes a SyntaxError immediately.
Wrong indentation: Python determines which code belongs to the if or else block purely by indentation. If a line that should be inside the else block is accidentally placed at the outer indent level, it will run unconditionally and produce the wrong result.
balance = 30
if balance >= 50:
print("Purchase approved.")
else:
print("Insufficient balance.")
print("This always runs regardless of the condition.")
Insufficient balance.
This always runs regardless of the condition.
The third print is not indented under the else, so Python treats it as outside the entire if else block and runs it every time.
Using is instead of ==: The is operator checks whether two variables point to the same object in memory, not whether they have the same value. For comparing numbers, strings, or other values, always use == rather than is.
Writing else with a condition: The else clause never takes a condition. It is simply the fallback for when the if condition is False. Trying to write else x > 5: will cause a SyntaxError. If you need to test a second specific condition, you need a separate if statement.
This final example uses only python if else statements — no other conditional forms — to build a small order processing system that checks stock, validates payment, and applies a loyalty discount.
def process_order(item, price, stock, payment, is_loyal_customer):
print(f"--- Processing order for: {item} ---")
if stock <= 0:
print("Result: Item is out of stock. Order cancelled.")
return
if payment < price:
print(f"Result: Payment of ${payment} is insufficient. Price is ${price}.")
return
final_price = price
if is_loyal_customer:
final_price = price * 0.90
print(f"Loyalty discount applied. New price: ${final_price:.2f}")
else:
print("No discount applied.")
if payment >= final_price:
change = payment - final_price
print(f"Result: Order confirmed. Change returned: ${change:.2f}")
else:
print(f"Result: Payment of ${payment} is still insufficient after discount.")
process_order("Laptop Bag", 45.00, 10, 50.00, True)
print()
process_order("Notebook", 12.00, 0, 15.00, False)
print()
process_order("USB Cable", 8.00, 5, 5.00, False)
print()
process_order("Mouse Pad", 10.00, 3, 10.00, False)
--- Processing order for: Laptop Bag ---
Loyalty discount applied. New price: $40.50
Result: Order confirmed. Change returned: $9.50
--- Processing order for: Notebook ---
Result: Item is out of stock. Order cancelled.
--- Processing order for: USB Cable ---
Result: Payment of $5 is insufficient. Price is $8.0.
--- Processing order for: Mouse Pad ---
No discount applied.
Result: Order confirmed. Change returned: $0.00
Every decision in this program is handled with a plain if or if else block. Stock is checked first, then payment sufficiency, then the loyalty discount, then final confirmation. Each block has a clear True path and a clear False path, which is exactly how Python if else statements are designed to work.
For more on Python's control flow tools, see the official Python tutorial on control flow.