Introduction
Conditional statements help a program make choices. They let the program do different things based on different situations.
Jump into concepts and practice - no test required
Conditional statements help a program make choices. They let the program do different things based on different situations.
if condition: # do something elif another_condition: # do something else else: # do something if no conditions above are true
Use if to check the first condition.
Use elif for additional conditions.
else runs if no conditions are true.
if temperature > 30: print("It's hot outside!")
if age >= 18: print("You can vote.") else: print("You are too young to vote.")
if score >= 90: print("Grade A") elif score >= 80: print("Grade B") else: print("Grade C or below")
This program checks the temperature and prints a message based on its value.
temperature = 25 if temperature > 30: print("It's hot outside!") elif temperature > 20: print("The weather is nice.") else: print("It's a bit cold.")
Indentation is important in Python to show which code belongs to each condition.
Conditions must be something that can be true or false.
Conditional statements let programs make decisions.
They help run different code depending on the situation.
Use if, elif, and else to handle choices.
if in Python?def.if statement in Python?if syntaxif syntax [OK]age = 18
if age >= 18:
print('Adult')
else:
print('Child')age >= 18if block runs and prints 'Adult'. The else block is skipped.number = 10
if number > 5
print('Big number')if statement syntaxif condition line.if number > 5, causing a syntax error.if condition [OK]if condition [OK]ifif, elif, and elseelif correctly and covers all hour ranges without overlap.if statements causing multiple prints; if hour < 12:
print('Good morning')
else if 12 <= hour <= 18:
print('Good afternoon')
else:
print('Good evening') uses invalid 'else if' syntax; if hour < 12:
print('Good morning')
elif hour > 12 and hour < 18:
print('Good afternoon')
else:
print('Good evening') misses equality for 12 and 18 in afternoon range.if, elif, and else and correct ranges -> Option Delif for multiple conditions [OK]elif for multiple exclusive conditions [OK]if causing multiple outputs