What if you want your program to do different things based on different conditions? That’s where decision-making comes in, and the most fundamental tool for this in Python is the if
statement. It allows a part of your code to run only if a certain condition is true.
Table of Contents
❓ How Does an If Statement Work?
An if
statement includes a condition followed by an indented block of code (its body). When the program reaches the if
statement, it evaluates the condition. If the condition is True, the code inside the body is executed. If the condition is False, the body is skipped entirely, and the program continues with the next line after the indented block.
⚖️ Writing Conditions with Relational Operators
The condition in an if
statement is typically a Boolean expression—something that evaluates to either True or False. You often create these using relational operators to compare values. The most common ones are: ==
(equal to), !=
(not equal to), <
(less than), >
(greater than), <=
(less than or equal to), and >=
(greater than or equal to). For example, if age >= 18:
checks if the value in the `age` variable is 18 or more.
📝 Structuring Your Code Correctly
The structure is crucial. The condition must be followed by a colon (:
). The code that should run if the condition is true *must* be indented underneath the if
line. This indentation tells Python which lines belong to the if
block. For example: num = float(input("Enter a number: "))
if num == 0:
print("The number was zero.")
Using if
statements is the first step toward creating programs that can react and adapt, making your code much more intelligent and powerful.
---
Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.
- Python Coding Essentials: Reliability by Abstraction
- Python Coding Essentials: Different Types of Data
- Python Coding Essentials: Embrace Storage and Persistence
- Python Coding Essentials: Neater Code with Modules
- Python Coding Essentials: Lock Down with Data Encryption
- Python Coding Essentials: Files and Modules Done Quickly
- Python’s Itertools Module – How to Loop More Efficiently