In addition to the basic if, elif, and else structures in Python, there are several other conditional structures and techniques you can use:
1. Nested if Statements:
You can place an if statement inside another if statement to check multiple conditions.
age = 25
if age >= 18:
if age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")
else:
print("You are a minor.")
2. Switch Case (Using Dictionaries):
Python does not have a built-in switch statement, but you can mimic it using dictionaries.
def switch_case(age):
return {
'child': "You are a child.",
'teenager': "You are a teenager.",
'adult': "You are an adult.",
'senior': "You are a senior citizen."
}.get(age, "Invalid age group")
age_group = 'adult'
print(switch_case(age_group))
3. Ternary Operator:
This is a shorthand way to write simple if statements.
age = 15
status = "You are a minor." if age < 18 else "You are an adult."
print(status)
4. Logical Operators:
You can combine conditions using logical operators like and, or, and not.
age = 30
if age >= 18 and age < 65:
print("You are an adult.")
5. List Comprehensions with Conditionals:
You can use conditionals within list comprehensions for filtering.
ages = [10, 15, 20, 65]
status = ["minor" if age < 18 else "adult" for age in ages]
print(status)
Further Learning:
To explore these structures in more depth, consider practicing with related labs on LabEx or looking for resources that cover control flow in Python. If you have specific questions about any of these structures, feel free to ask!
