Depending on the situation, you may want to use a series of if statements or an if/elif/else statement.
A series of if statements is best if you want the possibility of multiple code sections to run. An if/elif/else statement is best when you only want one of the sections to run.
Here are some different examples to show you different ways to structure these statements.
Categorize A Person By Age (Only One Possibility) - Working Examples
Example 1:
iif age <= 2:
age_category = "baby"
elif age <= 12:
age_category = "child"
elif age <= 19:
age_category = "teenager"
elif age <= 54:
age_category = "adult"
else:
age_category = "elderly"
Example 2:
if age <= 2:
age_category = "baby"
elif age <= 12:
age_category = "child"
elif age <= 19:
age_category = "teenager"
elif age <= 54:
age_category = "adult"
elif age > 54:
age_category = "elderly"
Example 3:
if age <= 2:
age_category = "baby"
if 2 < age <= 12:
age_category = "child"
if 12 < age <= 19:
age_category = "teenager"
if 19 < age <= 54:
age_category = "adult"
if age > 55:
age_category = "elderly"
Categorize A Person By Age (Only One Possibility) - Non-Working Examples
In all of these examples, all people age 55 and younger will be categorized as an adult
(including babies, children, and teenagers who will be miscategorized)
and all over 55 will be correctly categorized as elderly.
Bad Example 1:
if age <= 2:
age_category = "baby"
if age <= 12:
age_category = "child"
if age <= 19:
age_category = "teenager"
if age <= 55:
age_category = "adult"
if age > 55:
age_category = "elderly"
Bad Example 2:
if age <= 2:
age_category = "baby"
if age <= 12:
age_category = "child"
if age <= 19:
age_category = "teenager"
if age <= 55:
age_category = "adult"
else:
age_category = "elderly"
Bad Example 3:
if age >= 54:
age_category = "elderly"
elif age < 54:
age_category = "adult"
elif age <= 19:
age_category = "teenager"
elif age <= 12:
age_category = "child"
else:
age_category = "baby"
Print all of the following properties [even, positive, perfect square] of the number that is applicable (more than one possibility):
Working Example
if number % 2 == 0:
print("even")
if number > 0:
print("positive")
if math.sqrt(num) == int(math.sqrt(num)):
print("perfect square")
Print all of the following properties [even, positive, perfect square] of the number that is applicable (more than one possibility):
Non-Working Examples
if number % 2 == 0:
print("even")
elif number > 0:
print("positive")
elif math.sqrt(num) == int(math.sqrt(num)):
print("perfect square")
All even numbers will only be labeled as even.
Perfect squares (which are all positive) will be labeled at even if they're even, or positive otherwise.
if number % 2 == 0:
print("even")
elif number > 0:
print("positive")
else:
print("perfect square")
All even numbers will only be labeled as even.
Perfect squares (which are all positive) will be labeled at even if they're even, or positive otherwise.
All numbers that aren't even or positive will be labeled as perfect squares.