Conditionals
What are conditionals?
Conditionals allow a program to make decisions by executing different blocks of code depending on whether a condition is true or false. This allows the program flow to adapt to different situations.
| Structure | Description |
|---|---|
if | Evaluates a condition. If true, the code block is executed. |
elif | (else if) Evaluates another condition if the previous one was false. |
else | Executes if no previous condition was true. |
match | Evaluates a variable against multiple cases (case) and executes the block corresponding to the first matching pattern. |
-
Comparison with if
if temperature > 30:
print("It's hot")
if age >= 18 and country == "Colombia":
print("You can vote")
if "admin" in roles:
print("You have full access") -
Example applying roles
user = "John"
role = "editor"
active = True
if active:
if role == "admin":
print(f"Welcome {user}, you have full access.")
elif role == "editor":
print(f"Hello {user}, you can edit content.")
else:
print(f"Hello {user}, limited access.")
else:
print("Inactive account.") -
match application example
status = "active"
match status:
case "active":
print("The user is active.")
case "inactive":
print("The user is inactive.")
case _:
print("Unknown status.")