Conditional Statements in Python: Making Decisions with If-Else
One of the most important features in programming is **decision-making**—choosing different actions based on conditions. Python provides `if`, `else`, and `elif` statements to control program flow based on conditions.
Why Use Conditional Statements?
- Dynamic Behavior: Helps a program react differently to different inputs.
- Game Logic: Determines whether a player wins or loses.
- Data Filtering: Extracts relevant information based on conditions.
- User Interaction: Adapts program responses based on user choices.
The `if` Statement
The `if` statement **executes a block of code only if a condition is met**.
# Basic if statement
temperature = 30
if temperature > 25:
print("It's a hot day!")
The `else` Statement
If the condition in `if` **is not met**, the `else` block runs.
# Using if-else
temperature = 18
if temperature > 25:
print("It's a hot day!")
else:
print("It's a cool day.")
The `elif` Statement
If you need **multiple conditions**, use `elif` (short for "else if").
# Using if-elif-else
temperature = 20
if temperature > 30:
print("It's very hot!")
elif temperature > 25:
print("It's warm.")
elif temperature > 15:
print("It's mild.")
else:
print("It's cold.")
Using Comparison Operators in Conditions
Python allows the use of **comparison operators** (`==`, `!=`, `>`, `<`, `>=`, `<=`) inside conditions.
# Checking for equality
password = "secure123"
if password == "secure123":
print("Access granted!")
else:
print("Access denied!")
Using Logical Operators (`and`, `or`, `not`)
You can combine conditions using logical operators.
and
- Both conditions must be true.or
- At least one condition must be true.not
- Negates a condition.
# Checking multiple conditions
age = 20
has_ID = True
if age >= 18 and has_ID:
print("You can enter.")
else:
print("Entry denied.")
Using Nested `if` Statements
`if` statements can be **nested** within each other for more complex decisions.
# Nested if conditions
score = 85
if score >= 50:
print("Passed!")
if score >= 80:
print("Excellent performance!")
Conclusion
Conditional statements allow you to write programs that **make decisions dynamically**. Understanding `if`, `else`, and `elif` will help you create interactive and intelligent programs.
What kind of decision-making logic do you want to implement in your projects?