if-elif-else
Instruction
The if-elif-else
statement is used for conditional execution of code blocks based on the evaluation of boolean expressions. Here’s how each part works:
if
Statement: Evaluates a boolean expression. If the expression isTrue
, it executes the corresponding block of code.elif
Statement: Short for “else if”. If the precedingif
orelif
condition wasFalse
, it evaluates the current boolean expression. IfTrue
, it executes the corresponding block of code.else
Statement: If all preceding conditions wereFalse
, it executes the corresponding block of code.
Syntax
if condition1:
# Code block executed when condition1 is True
elif condition2:
# Code block executed when condition2 is True
else:
# Code block executed when all preceding conditions are False
PythonExample
age = 25
if age < 18:
print("You are a minor.")
elif age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")
PythonOutput:
You are an adult.
PythonTruth Check
In Python, any object can be tested for a truth value. The following values are considered False
in a boolean context:
None
False
- Zero of any numeric type:
0
,0.0
,0j
, etc. - Any empty sequence:
''
,()
,[]
- Any empty mapping:
{}
All other values are considered True
.
Example
value = ""
if value:
print("The value is true.")
else:
print("The value is false.")
PythonOutput:
The value is false.
PythonTernary (Three-Place) If/Else Expression
Python supports a concise way to write if-else
statements using a ternary conditional operator. It’s a single-line expression that returns one of two values based on the evaluation of a condition.
Syntax
value_if_true if condition else value_if_false
PythonExample
age = 20
status = "minor" if age < 18 else "adult"
print(status) # Output: adult
PythonDetailed Examples
Complex if-elif-else
Let’s consider a more complex example involving multiple conditions:
temperature = 30
if temperature < 0:
print("Freezing weather")
elif 0 <= temperature < 10:
print("Very Cold weather")
elif 10 <= temperature < 20:
print("Cold weather")
elif 20 <= temperature < 30:
print("Normal in Temp")
elif 30 <= temperature < 40:
print("It's Hot")
else:
print("It's Very Hot")
PythonOutput:
Normal in Temp
PythonTruthy and Falsy Values
Here’s how different values are evaluated in conditions:
values = [None, False, 0, 0.0, '', [], {}, "hello", [1, 2, 3], {1: "one"}]
for value in values:
if value:
print(f"{value} is True")
else:
print(f"{value} is False")
PythonOutput:
None is False
False is False
0 is False
0.0 is False
is False
[] is False
{} is False
hello is True
[1, 2, 3] is True
{1: 'one'} is True
PythonUsing Ternary Operator
Here’s an example using the ternary operator for a quick decision-making process:
num = 5
result = "Even" if num % 2 == 0 else "Odd"
print(result) # Output: Odd
PythonCombining if-elif-else
with Functions
You can also use conditional statements within functions to determine outputs based on inputs:
def evaluate_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
print(evaluate_grade(85)) # Output: B
PythonThese examples cover the basic and some advanced uses of conditional statements in Python. Understanding these concepts is crucial for writing effective and efficient Python code.