Conditional statements allow your program to make decisions based on conditions. They control the flow of your program by executing different code blocks based on whether a condition is true or false.
Execute code only if a condition is true:
age = 18
if age >= 18:
print("You are an adult")
# Output: You are an adult
Execute one block if true, another if false:
age = 15
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
# Output: You are a minor
Check multiple conditions:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
# Output: Grade: B
Used to compare values:
== - Equal to!= - Not equal to> - Greater than< - Less than>= - Greater than or equal to<= - Less than or equal tox = 10
print(x == 10) # True
print(x != 5) # True
print(x > 5) # True
print(x < 15) # True
print(x >= 10) # True
print(x <= 10) # True
Combine multiple conditions:
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive")
# Output: You can drive
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
# Output: It's the weekend!
is_raining = False
if not is_raining:
print("Let's go outside!")
# Output: Let's go outside!
Conditionals inside conditionals:
age = 20
has_money = True
if age >= 18:
if has_money:
print("You can buy a ticket")
else:
print("You need money")
else:
print("You are too young")
# Output: You can buy a ticket
number = -5
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")
number = 7
if number % 2 == 0:
print("Even")
else:
print("Odd")
Write programs that make decisions based on user input or variable values!
Open Code Editor