← Back to Python Course | Chapter 3: Control Flow | Lesson 1 of 10

Python if Statement

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

python
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

python
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

python
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

python
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

python
logged_in = True
is_admin = True
if logged_in:
    if is_admin:
        print("Welcome, admin")

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.