The if Statement
- Used to test a condition.
- If the condition is True, the indented block of code executes.
- If the condition is False, the block is skipped.
Syntax:
if condition:
# Code executes if condition is True
Example:
age = 20
if age >= 18:
print("You are an adult.")
Important Note:
- Indentation is crucial in Python.
- Statements with the same indentation belong to the same block.
- Different indentation levels define separate blocks.
The if-else Statement
- Adds an alternative block when the condition is False.
Syntax:
if condition:
# Code executes if condition is True
else:
# Code executes if condition is False
Example:
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
The elif Statement
- Used when there are multiple conditions.
- Executes the first True condition and skips the rest.
Syntax:
if condition1:
# Code executes if condition1 is True
elif condition2:
# Code executes if condition1 is False and condition2 is True
else:
# Code executes if all conditions are False
Example:
age = 14
if age < 13:
print("Child")
elif age < 18:
print("Teenager")
else:
print("Adult")
Boolean Expressions and Conditional Execution
Boolean Expressions:
- A Boolean expression evaluates to True or False.
- Used in
if, if-else, and elif statements.
Relational Operators:
OperatorMeaning>Greater than<Less than>=Greater than or equal to<=Less than or equal to==Equal to!=Not equal to
Logical Operators:
OperatorMeaningandBoth conditions must be TrueorAt least one condition must be TruenotNegates a condition
Example with Boolean Expressions:
x = 10
y = 5
if x > y and y > 0:
print("Both conditions are True")