Definition
In Python, the if-else statement is used for conditional execution of code. It allows you to run certain blocks of code only if a specified condition is true, and optionally run another block if the condition is false.
The general syntax is:
``python
if condition:
code block if condition is True
else:
code block if condition is False
`
You can also use elif (short for "else if") to check multiple conditions:
`python
if condition1:
code block if condition1 is True
elif condition2:
code block if condition2 is True
else:
code block if all conditions are False
`
Worked Example
Problem:
Write a Python program that checks if a number $x$ is positive, negative, or zero.
Step 1: Assign a value to $x$.
`python`
x = -5
Step 2: Use if-elif-else to check the value.
`python`
if x > 0:
print("x is positive")
elif x 0$ is False
- $x < 0$ is True
So, the output will be:
`
x is negative
Takeaways
- Use if
,elif, andelseto control the flow of your Python programs based on conditions. - Conditions are expressions that evaluate to either True
orFalse. - Indentation is crucial in Python: code blocks under if
,elif, andelse` must be indented.