Logo
Python Introduction
Python Installation and Project Setup
Running Python Programs
Python Syntax and Indentation Rules
Python Variables
Python Comments
Python Data Types
Python Type Conversion and Type Checking
Python Input and Output Functions
Python Operators
Python Arithmetic Operators
Python Assignment Operators
Python Logical Operators
Python Comparison Operators
Python Bitwise Operators
Python Membership Operators
Python Identity Operators
Python Walrus Operator
Python Operator Precedence
Python Conditional Statements
Python if Statement
Python if else
Python if elif else
Python match case Statement
Python Loops
Python for Loop
Python for else Loop
Python while Loop
Python break statement
Python continue statement
Python pass statement
Python Strings
Python String Slicing
Python String Concatenation
Python String Formatting
Python Escape Characters
Python Lists
Python Access List Items
Python Add List Items
Python Change List Items
Python Remove List Items
Python Sort Lists
Python Copy Lists
Python Join Lists
Python List Methods
Python Tuples
Python Access Tuple Items
Python Update Tuples
Python Unpack Tuples
Python Loop Tuples
Python Join Tuples
Python Tuple Methods
Python NamedTuple
Python Sets
Python Access Set Items
Python Add Set Items
Python Remove Set Items
Python Join Sets
Python Copy Sets
Python Dictionaries
Python Functions
Python Lambda Functions
Python Higher Order Functions
Python Classes and Objects
Python OOP Principles
Python Magic Methods
Python Context Managers
Python Error Handling and Debugging
Python File Handling
Python Modules and Packages
Python Iterators and Generators

Python if else

When you want a Python program to make a decision and take one of two possible paths, the python if else statement is the tool you reach for. Every beginner learning Python eventually needs to compare two values, check user input, or branch program logic based on a condition, and the if else statement in python is exactly built for that job. In this blog you will learn the exact syntax of the if else statement, how indentation defines the if block and the else block, how to write a boolean expression with a comparison operator, how logical operators support decision making inside an if else statement, how truthy and falsy values drive conditional logic, how to write a python if else statement in one line using a conditional expression, and how the if else statement in python adapts its control flow to strings, numbers, and lists inside a real program.

Understanding the Python If Else Statement Syntax

A python if else statement, as described in the official Python documentation, always starts with the if keyword, followed by a condition, followed by a colon. Right after that colon comes an indented block of code that runs only when the condition evaluates to True. The else keyword then introduces a second block, also followed by a colon, and that else block runs only when the same condition evaluates to False. This two-branch shape is the entire idea behind the if else statement in python: one path executes when the condition holds, and the other path executes when it does not. Python programmers rely on this exact syntax constantly, since almost every conditional statement in a real program eventually needs both an if branch and an else branch to control its control flow.

Here is the simplest possible python if else example you can run in any online compiler:

python
age = 20

if age >= 18:
    print("You are eligible to vote")
else:
    print("You are not eligible to vote")

Python reads the condition age >= 18 first. Since age is 20, the comparison is True, so Python runs the code under the if line and skips the else block entirely. If age had been 15 instead, the condition would be False and Python would jump straight to the else block, skipping the if block. This is the core behavior every if else statement in python follows: exactly one of the two blocks runs, never both, and never neither, which makes the statement a reliable building block for decision making in any Python program.

Output:
You are eligible to vote

How Indentation Shapes a Python If Else Block

Python does not use curly braces to group statements the way many other languages do. Instead, the if else statement in python relies entirely on indentation to know which lines belong to the if block and which lines belong to the else block. The standard convention is four spaces per indentation level, and every statement inside a block must line up at the same indentation depth. If the indentation is inconsistent, Python raises an IndentationError instead of running your python if else statement, so getting the whitespace right is not optional when you write Python.

python
score = 42

if score > 50:
    print("Checking pass conditions")
    print("Score is above fifty")
else:
    print("Checking fail conditions")
    print("Score is fifty or below")

Notice that both print statements under the if line share the same indentation, and both print statements under the else line share a separate matching indentation. Python groups each set of lines into a single block based purely on that whitespace, which is a core part of the if else syntax that beginners must get comfortable with early. Because score is 42, the condition score > 50 is False, so the else block runs both of its lines in order, while the if block above it is skipped completely in this python if else example.

Output:
Checking fail conditions
Score is fifty or below

Writing a Boolean Expression for a Python If Else Statement

Every python if else statement depends on a boolean expression that Python can evaluate to either True or False, and a comparison operator is the most common way to build that expression. Python supports equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=) as comparison operators. Whichever comparison operator you choose, the resulting boolean expression feeds directly into the if else statement, deciding which branch actually executes as part of the program's conditional logic and overall control flow.

python
temperature = 15

if temperature == 0:
    print("Water is freezing")
else:
    print("Water is not freezing")

In this python if else example, the boolean expression temperature == 0 checks for exact equality using a comparison operator. Since temperature holds 15, that expression evaluates to False, so control passes to the else block. Swapping in a different comparison operator, such as temperature < 5 or temperature >= 30, changes which values trigger the if block versus the else block, but the overall shape of the python if else statement stays identical no matter which boolean expression drives its conditional logic.

Output:
Water is not freezing

Combining Conditions with Logical Operators

A single comparison operator is not always enough for real decision making, so Python lets you combine multiple boolean expressions inside one python if else statement using the logical operators and, or, and not. The and operator requires both conditions to be True before the if block runs, the or operator only needs one of the conditions to be True, and the not operator flips a True value to False or a False value to True. These logical operators let the if else statement in python express far richer conditional logic than a single comparison operator ever could, which matters once decision making in a program depends on more than one factor at once.

python
username = "admin"
password_correct = True

if username == "admin" and password_correct:
    print("Access granted")
else:
    print("Access denied")

Here the python if else statement only grants access when both conditions are satisfied together: the username must equal admin, and password_correct must also be True. Because and demands both sides to hold, changing either condition to False would immediately redirect the control flow into the else block instead, which is exactly the kind of layered decision making a real login screen relies on when its if else statement checks more than one piece of information at once.

Output:
Access granted

Checking Truthy and Falsy Values in a Python If Else Statement

A python if else statement does not require an explicit comparison operator at all. Python can evaluate almost any value directly for its truthiness, meaning the if else statement treats the value itself as a boolean expression based on a set of built-in rules. Empty strings, the number zero, empty lists, and the special value None are all falsy, so they trigger the else block, while non-empty strings, non-zero numbers, and non-empty collections are truthy and trigger the if block of the statement.

python
cart_items = []

if cart_items:
    print("Your cart has items")
else:
    print("Your cart is empty")

Since cart_items is an empty list, Python treats it as falsy, so this if else statement in python runs the else branch even though there is no comparison operator anywhere in the condition. Add even a single element to that list and the same boolean expression instantly becomes truthy, flipping the conditional logic of the python if else statement into the if block on the very next run, which shifts the entire control flow of the program.

Output:
Your cart is empty

Writing a Python If Else Statement in One Line

Python also offers a compact, single-line form of the if else statement known as a conditional expression, sometimes called the ternary form. Instead of spreading the if block and the else block across separate indented lines, you write value_if_true first, then the if keyword and the condition, then the else keyword and value_if_false, all on one line. This one-line syntax is handy when you only need to assign one of two values rather than run a whole block of statements, and it still follows the exact same conditional logic as a multi-line python if else statement.

python
temperature = 28
weather = "hot" if temperature > 25 else "cool"
print(weather)

This single line does the same job as a full multi-line if else statement in python: it checks the boolean expression temperature > 25, and because 28 satisfies that condition, weather is assigned the string hot. If the condition had been False, weather would have been assigned cool instead. This one-line python if else example works well for short assignments, though longer or more involved decision making usually reads more clearly as a standard multi-line if else statement.

Output:
hot

Using Python If Else with Strings, Numbers, and Lists

A python if else statement is not limited to numeric comparisons; the same syntax works regardless of the data type inside the boolean expression. With strings, you can compare exact text values or check membership using the in keyword. With numbers, a comparison operator such as greater than or equal to works exactly as expected. With lists, the truthiness rules from earlier still apply, and the in keyword can also check whether a specific item exists before the if else statement in python decides which branch to run, which is a common pattern in real conditional logic and control flow.

python
fruit = "mango"
basket = ["apple", "banana", "mango"]
price = 3.5

if fruit in basket and price < 5:
    print("Affordable fruit is available")
else:
    print("Fruit is missing or too expensive")

if fruit == "mango":
    print("Mango was selected")
else:
    print("A different fruit was selected")

The first python if else statement mixes a string membership check with a numeric boolean expression, while the second statement compares two strings directly for equality using a comparison operator. Both examples show how the same if else syntax adapts naturally to whatever data type sits inside the condition, without needing any special rules for strings, numbers, or lists.

Output:
Affordable fruit is available
Mango was selected

Practical Use Case: A Python If Else Discount Calculator

A common real-world scenario for a python if else statement is calculating a discount based on how much a customer spends, which is a great example of decision making in an actual Python program. Picture a small online store where any purchase above a set threshold qualifies for a discount, and every other purchase pays full price. This scenario maps directly onto the if block and the else block of a single if else statement in python, with a boolean expression built from a comparison operator deciding which branch applies and shaping the resulting control flow.

python
order_total = 120.0

if order_total >= 100:
    discount = order_total * 0.10
    final_price = order_total - discount
    print("Discount applied:", discount)
    print("Final price:", final_price)
else:
    discount = 0
    final_price = order_total
    print("No discount applied")
    print("Final price:", final_price)

Because the spending amount is 120.0, the boolean expression checking against the threshold evaluates to True, so the if block of this python if else statement computes a ten percent discount and subtracts it from that amount. Had the customer spent less, the else block would have kept the discount at zero instead. This is exactly the kind of decision making an if else statement in python handles cleanly, turning one comparison operator into two clearly separated outcomes for the shopper.

Output:
Discount applied: 12.0
Final price: 108.0

Complete Working Example of a Python If Else Statement

The full python if else example below pulls together everything covered so far into one runnable program: a multi-line if else statement, a comparison operator, logical operators, truthy checks, and a one-line conditional expression, all wired into a single self-contained script that shows the complete syntax of the if else statement in python in action.

python
username = "admin"
login_attempts = 2
cart_items = ["headphones", "charger"]
order_total = 85.0

if username == "admin" and login_attempts < 3:
    print("Login successful")
else:
    print("Login failed")

if cart_items:
    print("Cart contains", len(cart_items), "item(s)")
else:
    print("Cart is empty")

shipping_label = "free shipping" if order_total >= 50 else "standard shipping"
print("Shipping option:", shipping_label)

if order_total >= 100:
    print("Order qualifies for a discount")
else:
    print("Order does not qualify for a discount")

Each python if else statement in this script checks a different boolean expression, from login credentials to cart contents to order value, yet every single one follows the same two-branch conditional logic and control flow explained throughout this if else statement guide.

Output:
Login successful
Cart contains 2 item(s)
Shipping option: free shipping
Order does not qualify for a discount