Conditional Statements
Introduction to Conditional Statements
Conditional statements are the primary mechanism for implementing branching logic in Python. They allow programs to execute different code blocks based on specific conditions.
Basic Conditional Structures
Simple if
Statement
The simplest form of conditional statement checks a single condition:
x = 10
if x > 5:
print("x is greater than 5")
if-else
Statement
Provides an alternative path when the condition is not met:
age = 20
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
if-elif-else
Statement
Handles multiple condition checks:
score = 75
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'D'
print(f"Your grade is: {grade}")
Conditional Statement Flow
graph TD
A[Start] --> B{Condition 1}
B -->|True| C[Execute Block 1]
B -->|False| D{Condition 2}
D -->|True| E[Execute Block 2]
D -->|False| F[Execute Default Block]
Advanced Conditional Techniques
Nested Conditions
Conditions can be nested within each other:
x = 10
y = 5
if x > 0:
if y > 0:
print("Both x and y are positive")
Conditional Expressions (Ternary Operator)
## Syntax: value_if_true if condition else value_if_false
result = "Even" if x % 2 == 0 else "Odd"
Comparison Operators
Operator |
Description |
Example |
== |
Equal to |
x == y |
!= |
Not equal to |
x != y |
> |
Greater than |
x > y |
< |
Less than |
x < y |
>= |
Greater than or equal to |
x >= y |
<= |
Less than or equal to |
x <= y |
Best Practices
- Keep conditions simple and readable
- Use meaningful variable names
- Avoid deeply nested conditions
- Utilize logical operators for complex conditions
At LabEx, we recommend practicing these conditional statement patterns to improve your Python programming skills.