The if
statement in Python is used to execute a block of code only when a specified condition is True. It is the foundation for decision-making in Python programs, allowing the program to respond dynamically based on conditions.
Example
temperature = 30
if temperature > 25:
print("It's a hot day!")
Output:
It's a hot day!
Syntax
if condition:
# Code to execute if the condition is True
condition
: A statement that evaluates to True or False.
Why Use if?
- Dynamic Decisions: Enables programs to behave differently based on specific conditions.
- User Interaction: Processes user inputs and makes decisions accordingly.
- Core Logic: Forms the basis for building complex program logic.
Common Examples
1. Checking Even or Odd
number = 7
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
Output:
Odd number
2. Age Check
age = 16
if age >= 18:
print("You can vote.")
else:
print("You are not eligible to vote.")
Output:
You are not eligible to vote.
3. Grading System
marks = 82
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
else:
print("Grade: C")
Output:
Grade: B
4. Nested if Example
num = 12
if num > 0:
if num % 3 == 0:
print("Positive and divisible by 3")
Output:
Positive and divisible by 3
Key Notes
- Conditions can involve comparison (
>
,<
,==
, etc.) and logical operators (and
, or,not
). - Always use proper indentation to define the code block.
- Combine if, elif, and else to handle multiple conditions effectively.
This structure ensures you have a definition, an example immediately following, the syntax, why use it, and other common examples for clarity.