Welcome!
Join our coding community
Ā© 2024 Ace Coding Academy
Code Examples
Example 1
First, we check if it's sunny. Only if that's true do we then check the temperature. Since both conditions are met (sunny AND > 25), we get "Perfect day for the beach!" Notice the extra indentation for the nested if.
weather = "sunny"
temperature = 28
if weather == "sunny":
if temperature > 25:
print("Perfect day for the beach!")
else:
print("Sunny but a bit cool for swimming.")
else:
print("Not a sunny day.")
Example 2
This has nested conditions in both the if AND else blocks. We first evaluate the grade, then within each path, we check the effort level. This creates four possible outcomes based on different combinations.
grade = 85
effort = "high"
if grade >= 80:
print("Good grade!")
if effort == "high":
print("Excellent work ethic too!")
else:
print("But you could try harder next time.")
else:
if effort == "high":
print("Your effort is great, keep it up!")
else:
print("You need to improve both grade and effort.")
Example 3
This shows three levels of nesting. Each condition must be true to proceed to the next check. Only when all three conditions are met (correct username AND correct password AND active account) does login succeed.
username = "alice"
password = "secret123"
is_active = True
if username == "alice":
if password == "secret123":
if is_active:
print("Login successful! Welcome Alice!")
else:
print("Account is inactive. Contact admin.")
else:
print("Wrong password for Alice.")
else:
print("Username not found.")