- Home
- /
- Python if Statement
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python if Statement
if Statement
In programming, we often make decisions based on certain conditions. The if
statement helps us do exactly that.
It allows the program to run a block of code only if a condition is True. If the condition is False, that block is skipped completely, and the program moves on.
Basic Structure of if
if condition:
# code runs only if condition is True
Example:
Let’s say you’re checking if a customer has enough money to buy apples.
apple_price = 180
user_budget = 200
if apple_price <= user_budget:
print("Add 1kg apples to the shopping cart.")
Output:
Add 1kg apples to the shopping cart.
In this case, since 180 <= 200
is True, the print statement is executed.
What Happens If the Condition is False?
What Happens If the Condition is False?
apple_price = 220
user_budget = 200
if apple_price <= user_budget:
print("Add 1kg apples to the shopping cart.")
Output:
(Nothing will be printed)
The condition is False (220 <= 200
is not True), so Python skips the code inside the if
block.
Use Case Summary
Use an if
statement when:
You want to perform an action only under certain conditions
You want your code to respond differently depending on a value or state