An if statement helps your program decide what to do based on a condition. It lets your code choose different paths like making a decision in real life.
0
0
If statement execution flow in Python
Introduction
When you want to check if a number is positive or negative and act differently.
When you want to check if a user entered the correct password before allowing access.
When you want to do something only if it is raining outside.
When you want to give a discount only if the customer buys more than 5 items.
Syntax
Python
if condition: # code to run if condition is True elif another_condition: # code to run if another_condition is True else: # code to run if none of the above conditions are True
The if line checks a condition that is either True or False.
The elif and else parts are optional and help check more conditions or run code if none match.
Examples
This checks if the temperature is above 30 and prints a message if true.
Python
if temperature > 30: print("It's hot outside!")
This checks multiple conditions to print different grades.
Python
if score >= 90: print("You got an A") elif score >= 80: print("You got a B") else: print("Keep trying!")
This chooses between two actions based on whether it is raining.
Python
if is_raining: print("Take an umbrella") else: print("No umbrella needed")
Sample Program
This program checks the temperature and prints a message based on its value.
Python
temperature = 25 if temperature > 30: print("It's hot outside!") elif temperature > 20: print("The weather is nice.") else: print("It's a bit cold.")
OutputSuccess
Important Notes
Indentation (spaces before code) is very important in Python to show which code belongs to the if or else.
Only one block of code runs in an if-elif-else chain, the first condition that is True.
If no condition is True and there is no else, nothing happens.
Summary
If statements let your program make choices based on conditions.
Use if, elif, and else to check multiple conditions.
Indent your code properly to show which parts belong to each condition.