Skip to content

Module 5 · Conditional Statements — topic 2 of 10

if

The if statement runs a block of code only when its condition is true. Learn its exact syntax, how the block is defined, guard clauses, and using several independent if statements.

Beginner 10 min read·Lesson 61 of 306 in Python Programming

Learning objectives

  • Write an if statement with a correctly indented block
  • Use if for optional actions and guard clauses
  • Know when several separate ifs are appropriate

Definition

The if statement runs a block of code only when its condition is true. Learn its exact syntax, how the block is defined, guard clauses, and using several independent if statements.

Introduction

The if statement is the simplest decision: “if this is true, do that”. When the condition is false, Python skips the block entirely and carries on with the rest of the program.

Why it matters

Many actions are optional: show a warning only when something is wrong, add a bonus only when it is earned, print debugging details only when a setting is on. A lone if expresses exactly this kind of “extra step when needed”.

Detailed explanation

The header line is if, a condition and a colon. The block underneath must be indented, usually by four spaces, and may contain any number of statements, including other ifs and loops.

Python evaluates the condition once each time execution reaches the if. If the result is truthy the block runs from top to bottom; if falsy the whole block is skipped.

Several consecutive if statements are independent: each condition is checked, and any number of blocks may run. That is different from if-elif, where at most one block runs.

A guard clause is an if at the start of a function that handles a special case and returns early, such as if not items: return 0. It keeps the main logic unindented and easy to read.

An if block must contain at least one statement. If you need a block that deliberately does nothing yet, write pass.

Syntax

Python
if condition:
statement_1
statement_2
  • condition can be any expression.
  • The colon is required.
  • All statements of the block share the same indentation.

Code examples

An optional message

Python
balance = 350
if balance < 500:
print("Low balance: please top up")
print("Balance:", balance)
Output
Low balance: please top up
Balance: 350

Independent checks

Python
password = "sunshine"
if len(password) < 10:
print("Use at least 10 characters")
if password.isalpha():
print("Add a number or symbol")
if password.islower():
print("Add a capital letter")
Output
Use at least 10 characters
Add a number or symbol
Add a capital letter

More examples

A guard clause

Python
def average_marks(marks):
if not marks:
return None
total = sum(marks)
return round(total / len(marks), 1)
print(average_marks([62, 75, 88]))
print(average_marks([]))
Output
75.0
None

Step-by-step explanation

  • if not marks: is true for an empty list, so the function returns None straight away.
  • Without the guard, dividing by len([]) would raise ZeroDivisionError.
  • For a non-empty list the guard is skipped and the average is calculated normally.
  • round(..., 1) keeps one decimal place: (62 + 75 + 88) / 3 = 75.0.

Expected output

Running “A guard clause” prints exactly:

TextOutput
75.0
None

Practical applications

  • Password strength meters run several independent checks and show every problem at once.
  • Web views use guard clauses to return early when a user isn’t logged in.
  • Logging code prints details only if a debug flag is enabled.

Best practices

  • Use a lone if for optional actions.
  • Handle special cases early with guard clauses.
  • Use separate ifs only when the checks are truly independent.

Common mistakes

Using separate ifs when only one action should happen

Avoid

if marks >= 75: grade = "A"
if marks >= 40: grade = "B"

Prefer

if marks >= 75: grade = "A"
elif marks >= 40: grade = "B"

With two separate ifs, a mark of 90 sets grade to A and then overwrites it with B.

An empty block

Avoid

if ready:
# do this later

Prefer

if ready:
pass # do this later

A block needs at least one statement; a comment alone causes an IndentationError.

Key takeaways

  • if runs its block only when the condition is true.
  • Consecutive ifs are independent; several may run.
  • pass fills a block that intentionally does nothing.

Try it yourself

  1. 1
    Write a function that returns 0 for a negative number using a guard clause, and otherwise returns the number doubled.
  2. 2
    Check a username for three independent problems: shorter than 4 characters, contains a space, starts with a digit. Print a message for each problem found.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerIn an if / elif / elif / else chain, how many branches run?
Practise this topic