Python if Statement
In this page:
Basic If Statement
An if statement runs its indented block only when its condition evaluates to True; if the condition is False, Python skips straight past the whole block without executing any of it, and moves on to whatever comes next.
Example: Basic If Statement
age = 20
if age >= 18:
print("You can vote")
The Importance of Indentation
Python identifies which lines belong to the if block purely by indentation — conventionally 4 spaces — rather than braces. A line indented less than the if itself is understood to be outside the block, even without any closing keyword.
Example: The Importance of Indentation
age = 20
if age >= 18:
print("Inside the if block")
print("Outside the if block")
Relational Operators in Conditions
Comparison operators like == (equal to) and != (not equal to) are the building blocks of most conditions, each producing a True or False value that the if statement then acts on.
Example: Relational Operators in Conditions
status = "active"
if status == "active":
print("Account is active")
Checking Truthiness
Python treats non-empty containers and non-zero numbers as truthy and empty ones ("", [], 0) as falsy, so you can write if my_list: directly instead of the more verbose if len(my_list) > 0: to check whether a list has anything in it.
Example: Checking Truthiness
my_list = [1, 2]
if my_list:
print("List has items")
Nested If Blocks
Placing one if inside another lets you check a second condition only once the first has already passed — for example, checking a user is logged in before checking whether they're an admin — narrowing the logic step by step.
Example: Nested If Blocks
logged_in = True
is_admin = True
if logged_in:
if is_admin:
print("Welcome, admin")
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: