
The Python if statement is the fundamental building block of decision-making in any Python program. When you need your code to do something only under a specific condition — like checking whether a number is positive, whether a username exists, or whether a file has content — the Python if statement is the tool that makes it happen. It evaluates a condition and executes an indented block of code only when that condition turns out to be True. If the condition is False, the block is skipped entirely and execution continues after it.
This guide covers everything you need to know about the Python if statement: how to write one correctly, how Python evaluates conditions, how to combine conditions using logical operators, what truthy and falsy values mean inside an if condition, how nesting works, and how to use if statements with membership tests and function calls.
Writing a Python if statement follows a fixed pattern. You start with the keyword if, write the condition you want to check, add a colon, and then indent the code you want to run when that condition is True.
temperature = 30
if temperature > 25:
print("It is hot today")
Output
It is hot today
The condition temperature > 25 evaluates to True because 30 is greater than 25, so Python runs the indented print statement. The colon after the condition is required — Python will raise a SyntaxError without it.
Indentation defines which lines belong to the if block. The standard in Python is four spaces per level. Every line that should run when the condition is True must be indented consistently to the same level.
balance = 500
if balance >= 100:
print("Your balance is sufficient")
print("You can proceed with the transaction")
Output
Your balance is sufficient
You can proceed with the transaction
Both print statements are indented under the if statement, so both run when the condition is True. Any line that returns to the original indentation level sits outside the if block and runs regardless of the condition.
When the condition in an if statement evaluates to False, Python skips the entire indented block and moves to whatever comes next in the program. Nothing inside the if block runs.
speed = 60
limit = 80
if speed > limit:
print("You are speeding")
print("Speed check complete")
Output
Speed check complete
Here speed (60) is not greater than limit (80), so the condition is False and the print inside the if block is skipped. The final print statement is not indented under the if, so it always runs.
This behavior is intentional — the Python if statement is designed to run code conditionally, not unconditionally. You can place as many statements as you need inside the if block, and all of them will be skipped when the condition is False.
stock = 0
if stock > 0:
print("Item is in stock")
print("Ready to ship")
print("Inventory check done")
Output
Inventory check done
Both lines inside the if block are skipped because stock is 0, which is not greater than 0. Only the unindented line at the end runs.
You can write multiple if statements one after another. Unlike chained conditions, each if statement is evaluated independently. Python checks every single one, and any whose condition is True will have its block executed.
score = 85
if score >= 50:
print("You passed the exam")
if score >= 75:
print("You earned a merit award")
if score >= 90:
print("You earned a distinction")
Output
You passed the exam
You earned a merit award
All three if conditions are checked. The first two are True (85 >= 50 and 85 >= 75), so both of their blocks run. The third is False (85 is not >= 90), so it is skipped. This is different from chaining — every if gets its own independent evaluation.
Multiple independent if statements are useful when several conditions can all be True at the same time and you want to act on each one separately.
text = "Python programming is fun and practical"
if "Python" in text:
print("Mentions Python")
if "fun" in text:
print("Mentions fun")
if "difficult" in text:
print("Mentions difficult")
Output
Mentions Python
Mentions fun
Each if statement checks for a different word. "Python" and "fun" are present, so their blocks run. "difficult" is not in the string, so that block is skipped entirely.
The condition inside an if statement is most commonly a comparison — checking how one value relates to another. Python provides six comparison operators for this purpose, and each one returns either True or False.
| Operator | Meaning | Example |
|---|---|---|
| == | Equal to | x == 10 |
| != | Not equal to | x != 0 |
| > | Greater than | x > 5 |
| < | Less than | x < 100 |
| >= | Greater than or equal to | x >= 18 |
| <= | Less than or equal to | x <= 99 |
price = 49.99
budget = 50.00
if price <= budget:
print("You can afford this item")
Output
You can afford this item
The condition price <= budget evaluates to True because 49.99 is less than or equal to 50.00, so the block runs.
Python also allows chained comparisons, which let you check whether a value falls within a range in a single condition:
age = 25
if 18 <= age <= 65:
print("Eligible for working-age benefits")
Output
Eligible for working-age benefits
The chained comparison 18 <= age <= 65 checks both conditions at once. Python evaluates this as (18 <= age) and (age <= 65) internally. This is a clean and readable way to test range conditions in a Python if statement.
String comparisons also work with these operators. Python compares strings alphabetically (lexicographically) based on the Unicode value of each character.
name = "Maria"
if name > "Alex":
print(name, "comes after Alex alphabetically")
Output
Maria comes after Alex alphabetically
For a full reference on comparison behavior, see the Python comparison operators documentation.
Logical operators let you combine multiple conditions inside a single Python if statement. Python has three: and, or, and not. These give you precise control over when your if block should run.
The and operator requires both conditions to be True. If either one is False, the whole expression is False and the block is skipped.
age = 22
has_ticket = True
if age >= 18 and has_ticket:
print("Access granted to the event")
Output
Access granted to the event
Both age >= 18 and has_ticket must be True for the if block to run. Since both are True here, the message prints.
The or operator requires at least one condition to be True. Even if the other is False, the block still runs.
is_weekend = False
is_holiday = True
if is_weekend or is_holiday:
print("Office is closed today")
Output
Office is closed today
is_weekend is False, but is_holiday is True. Because at least one is True, the or expression evaluates to True and the block runs.
The not operator inverts a boolean value. A True becomes False and a False becomes True. This lets you write conditions that check for the absence of something.
is_authenticated = False
if not is_authenticated:
print("Please log in to continue")
Output
Please log in to continue
Since is_authenticated is False, not is_authenticated becomes True, which triggers the if block. You can also combine all three logical operators in a single condition, using parentheses to control the evaluation order.
user_role = "admin"
is_active = True
is_banned = False
if (user_role == "admin" or user_role == "moderator") and is_active and not is_banned:
print("Full dashboard access granted")
Output
Full dashboard access granted
Python evaluates and before or by default, but the parentheses here make the intent explicit and easy to read. See Python boolean operations for the full evaluation rules.
The condition inside a Python if statement does not have to be a direct comparison. Python treats many values as either truthy (evaluated as True in a condition) or falsy (evaluated as False). This lets you write cleaner, more natural-sounding conditions without explicit comparisons.
The following values are always falsy in Python:
Every other value is truthy.
username = "alice"
if username:
print("Welcome,", username)
Output
Welcome, alice
A non-empty string is truthy, so the if block runs. You do not need to write username != "" — checking the value directly is cleaner and more idiomatic.
When you want to act on a falsy value, combine the not operator with the value:
cart_items = []
if not cart_items:
print("Your cart is empty")
Output
Your cart is empty
An empty list is falsy, so not cart_items becomes True and the block runs.
count = 0
if not count:
print("No records found")
Output
No records found
Zero is falsy. not 0 is True, so the message prints. You can read more about this behavior in the Python truth value testing documentation.
A nested if statement is a Python if statement written inside the body of another if statement. You use this when a second condition only makes sense to check after a first condition has already been confirmed True.
is_logged_in = True
account_verified = True
if is_logged_in:
if account_verified:
print("Access to dashboard granted")
Output
Access to dashboard granted
Python checks is_logged_in first. Since it is True, it enters that block and checks account_verified. Since that is also True, the inner block runs. If either condition were False, the corresponding block would be skipped.
Each additional level of nesting requires another level of indentation. The inner if block is indented four spaces under the outer if block, and any code it contains is indented eight spaces total.
file_exists = True
file_readable = True
file_size = 2048
if file_exists:
if file_readable:
if file_size > 0:
print("File is ready to process")
print("Size:", file_size, "bytes")
Output
File is ready to process
Size: 2048 bytes
All three conditions are True, so all three if blocks are entered and the two print statements inside the innermost block run. If file_exists were False, neither of the inner if statements would even be evaluated — Python exits the outer block immediately.
Nesting gives you precise layered control. Keep nesting to two or three levels whenever possible — deeper nesting tends to become harder to read.
Python's in operator works naturally inside an if statement to check whether a value exists within a list, string, tuple, set, or dictionary. The result is True if the value is found and the if block runs; if not found, the block is skipped.
approved_countries = ["Canada", "Germany", "Australia", "Japan"]
user_country = "Germany"
if user_country in approved_countries:
print(user_country, "is an approved region")
Output
Germany is an approved region
Python scans the list for "Germany", finds it, and the condition evaluates to True.
The not in operator checks for absence — the if block runs only when the value is not found:
blocked_domains = ["spam.net", "phishing.org", "malware.io"]
sender_domain = "gmail.com"
if sender_domain not in blocked_domains:
print("Email from", sender_domain, "is allowed")
Output
Email from gmail.com is allowed
"gmail.com" is not in the blocked list, so not in evaluates to True and the message prints.
Membership testing also works with strings. When you use in with a string, Python checks whether the left-hand value is a substring of the right-hand string:
log_line = "ERROR: database connection failed at 14:32"
if "ERROR" in log_line:
print("Critical log detected:", log_line)
Output
Critical log detected: ERROR: database connection failed at 14:32
Any expression that returns True or False — including a function call — can serve as the condition in a Python if statement. This lets you write clean, readable checks without storing the result in a separate variable first.
def is_prime(n):
if n < 2:
return False
i = 2
if i * i <= n:
if n % i == 0:
return False
i = i + 1
return True
number = 17
if is_prime(number):
print(number, "is a prime number")
Output
17 is a prime number
The function is_prime returns True or False. Passing it directly as the condition in the if statement is concise and expressive. Python calls the function, receives True, and runs the block.
Built-in functions work the same way:
values = [4, 7, 2, 9, 1]
if any(v > 8 for v in values):
print("At least one value exceeds 8")
Output
At least one value exceeds 8
The built-in any function returns True if at least one element in the iterable satisfies the condition. The generator expression v > 8 for v in values checks each item, and any wraps the result — which feeds directly into the if statement.
This program uses only Python if statements to validate a product order. It checks stock availability, payment confirmation, delivery region eligibility, and order size — each as a separate condition — and prints a status message for each check that passes.
def process_order(product, quantity, payment_confirmed, delivery_region):
stock = {
"laptop": 10,
"mouse": 50,
"keyboard": 0,
"monitor": 5
}
approved_regions = ["North America", "Europe", "Australia"]
if product not in stock:
print("Product not found:", product)
return
if not payment_confirmed:
print("Order rejected: payment not confirmed")
return
available = stock[product]
if available == 0:
print("Order rejected:", product, "is out of stock")
return
if quantity > available:
print("Order rejected: only", available, "units available for", product)
return
if delivery_region not in approved_regions:
print("Order rejected: delivery to", delivery_region, "is not supported")
return
if quantity >= 10:
print("Bulk order discount applied for", quantity, "units of", product)
if quantity >= 1:
print("Order confirmed:", quantity, "x", product, "to", delivery_region)
process_order("laptop", 3, True, "Europe")
process_order("keyboard", 2, True, "North America")
process_order("mouse", 15, True, "Asia")
process_order("monitor", 10, False, "Australia")
process_order("mouse", 20, True, "Europe")
Output
Order confirmed: 3 x laptop to Europe
Order rejected: keyboard is out of stock
Order rejected: delivery to Asia is not supported
Order rejected: payment not confirmed
Bulk order discount applied for 20 units of mouse
Order confirmed: 20 x mouse to Europe
Each check in process_order is its own Python if statement. The function works through each condition independently: product existence, payment status, stock level, quantity availability, and region eligibility. When a critical check fails, the function returns early. When the bulk threshold is met, an extra message prints before the confirmation. Every decision in this program is made using only the Python if statement.