Python Basics : If / Elif / Else
A simple guide to making decisions in Python using conditional statements.
What Are Conditional Statements?
Conditional statements allow Python to make decisions and run different code depending on whether a condition is True or False.
Python uses:
ifelifelse
Basic Structure
if condition:
# code runs if condition is True
elif another_condition:
# code runs if the previous conditions are False AND this is True
else:
# code runs if all conditions are False
Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
| == | equal to | 5 == 5 |
| != | not equal | 5 != 3 |
| > | greater than | 10 > 3 |
| < | less than | 2 < 9 |
| >= | greater or equal | 5 >= 5 |
| <= | less or equal | 3 <= 7 |
Using input() With Numbers
input() returns a string, so we must convert it:
num = int(input("Enter a number: "))
Examples
1. Even or Odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
2. Check Age Group
age = int(input("Enter age: "))
if age < 13:
print("Child")
elif age < 20:
print("Teen")
elif age < 60:
print("Adult")
else:
print("Senior")
3. Positive, Negative, or Zero
num = int(input("Enter number: "))
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
Tips for Beginners
- Indentation (spaces) matters in Python.
- Every
if,elif, andelseends with a:. - Conditions must evaluate to True or False.
- Use
int()when expecting a number.
What’s Next?
- loops (
for,while)