Conditional Statements
Imagine you're at a traffic light. If it's green, you go; if it's red, you stop. In programming, conditional statements let your code make decisions based on conditions. Python's primary conditional statements are `if`, `elif`, and `else`.
The if statement
Use `if` to execute a block of code only if a condition is true.
age = 18
if age >= 18:
print("You are an adult.")
if-else
Use `else` to run a block when the condition is false.
temperature = 25
if temperature > 30:
print("It's hot outside.")
else:
print("It's pleasant.")
if-elif-else (multiple conditions)
Use `elif` (short for "else if") to check additional conditions.
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'F'
print(f"Grade: {grade}")
Nested if statements
You can put if statements inside other if statements.
x = 10
if x > 5:
print("x is greater than 5")
if x > 8:
print("x is also greater than 8")
Two Minute Drill
- `if` executes a block if condition is True.
- `elif` checks additional conditions; `else` runs if none match.
- Indentation determines block boundaries.
- Comparison operators: ==, !=, <, >, <=, >=.
- Logical operators: and, or, not.
Need more clarification?
Drop us an email at career@quipoinfotech.com
