Python If-Else Statements
The if-else
statement in Python allows you to execute certain blocks of code based on specific conditions. This control structure is fundamental for decision-making in Python programs.
Syntax of If-Else Statements
if condition:
# Block of code to execute if condition is True
else:
# Block of code to execute if condition is False
How the If-Else Statement Works
- Condition Evaluation:
- The
if
statement evaluates a condition (a Boolean expression that results in eitherTrue
orFalse
).
- The
- True Condition:
- If the condition evaluates to
True
, the block of code immediately under theif
statement is executed.
- If the condition evaluates to
- False Condition:
- If the condition evaluates to
False
, the block of code under theelse
statement (if provided) is executed.
- If the condition evaluates to
Example of If-Else Statement
Here’s a simple example that checks whether a number is positive or negative:
number = int(input("Enter a number: "))
if number >= 0:
print("The number is positive or zero.")
else:
print("The number is negative.")
Flow of Execution
- Input: The user inputs a number.
- Condition Check: The program checks if the number is greater than or equal to zero.
- If
True
, it prints “The number is positive or zero.” - If
False
, it prints “The number is negative.”
- If
Multiple Conditions with Elif
You can extend the if-else
structure using elif
(short for “else if”) to check multiple conditions.
Syntax of If-Elif-Else
if condition1:
# Block of code to execute if condition1 is True
elif condition2:
# Block of code to execute if condition2 is True
else:
# Block of code to execute if both condition1 and condition2 are False
Example of If-Elif-Elsenumber = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
elif number == 0:
print("The number is zero.")
else:
print("The number is negative.")
Key Points
- The
if-else
structure is crucial for controlling the flow of a Python program. - You can have multiple
elif
branches between anif
and anelse
. - The blocks of code inside
if
,elif
, andelse
statements must be indented.
Using if-else
statements allows for more dynamic and responsive Python programs that can handle various input scenarios and make decisions based on conditions.