Conditional statements allow you to make decisions in your Python programs based on certain conditions. The most common conditional statements in Python are if
, else
, and elif
(short for "else if").
# Using if statement
age = 18
if age >= 18:
print("You are an adult.")
# Using if-else statement
score = 85
if score >= 60:
print("Congratulations! You passed.")
else:
print("Unfortunately, you didn't pass.")
# Using if-elif-else statement
num = 7
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
In Python, the blocks of code within the conditional statements are defined by indentation, not curly braces as in some other programming languages. Additionally, the colon (:
) at the end of the if
, else
, and elif
lines indicate the beginning of a new block of code.
You can also nest conditional statements inside each other to create more complex decision-making logic.
# Nested if-else statement
age = 22
if age >= 18:
print("You are an adult.")
if age >= 21:
print("You can legally drink.")
else:
print("You cannot legally drink.")
else:
print("You are a minor.")
# Nested if-elif-else statement
num = -5
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
if num % 2 == 0:
print("Even")
else:
print("Odd")
else:
print("Zero")
Understanding conditional statements is fundamental to creating dynamic and responsive Python programs that can adapt to different situations and conditions.