What are Conditional Statements?
A conditional statement allows your program to make decisions and execute different code depending on whether a condition is true or false.
It’s like giving your program a choice:
- If this happens, do this.
- Otherwise, do something else.
In Python, conditional statements use the keywords:if
elif
(else if)else
The if
Statement
The most basic conditional structure.
It runs a block of code only if the condition is true.
if condition:
# code block
Example
age = 18
if age >= 18:
print("You are an adult")
The if-elif-else
Statement
For more than two choices, use elif
(short for else if).
Syntax:
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block if none above are true
Example
score = 75
if score >= 90:
print("Grade: A")
elif score >= 75:
print("Grade: B")
else:
print("Grade: C or below")
Relational Operators
These operators compare two values and return True
or False
.
Operator | Meaning | Example |
---|---|---|
== |
equal to | x == y |
!= |
not equal to | x != y |
> |
greater than | x > y |
< |
less than | x < y |
>= |
greater or equal | x >= y |
<= |
less or equal | x <= y |
Logical Operators
Sometimes you need to check multiple conditions.
Operator | Meaning | Example |
---|---|---|
and |
Both conditions are true | (x > 0 and x < 10) |
or |
At least one is true | (x == 0 or y == 0) |
not |
Inverts the condition | not(x > 10) |
Indentation Matters!
In Python, the code block after if
, elif
, and else
must be indented (by 4 spaces or a tab).
✅ Correct:
if age >= 18:
print("Adult")
else:
print("Not adult")
🚫 Incorrect: