Conditional statements allow your program to make decisions based on certain conditions. In Python, we use if
, elif
, and else
statements.
if condition:
# code to execute if condition is True
elif another_condition:
# code to execute if another_condition is True
else:
# code to execute if no conditions are True
Let's write a program that checks if a number is positive, negative, or zero:
Click "Run Code" to see the output here.
Python uses indentation to define code blocks. Make sure to use consistent indentation (4 spaces is recommended) for your if
statements.
Write a program that takes a student's score (0-100) as input and prints their grade based on the following criteria:
I'm confused about when to use elif vs multiple if statements. Can someone explain?
Great question! Use elif
when the conditions are mutually exclusive (only one can be true). Use multiple if
statements when multiple conditions could be true and you want to check all of them.