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.
❓ 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.
More Topics
- How to Pass Command Line Arguments to Your Python Script
- Solving the Classic FizzBuzz Problem in Python: A Step-by-Step Tutorial
- How to Solve the Pythagorean Theorem with a Python Script
- What’s the Difference Between Syntax, Runtime, and Logic Errors in Python?
- What Are Dictionaries in Python and How Do You Use Them?
- Thinking Recursively: A Beginner’s Introduction to Recursion in Python
- How to Read and Write Files in Python