Up until now, every line of code we have written runs (except for comments). This makes for very narrow programs that run the same every time.
It is very powerful to create sections of code that run conditionally. They run only if a certain condition is met. To do this, we will use an if statement. If blocks have two parts:
if condition:
#code that only runs if condition is true
For example:
if number > 0:
print(str(number) + "is positive")
If the number is greater than 0, the message will print. If it's not, it won't.
The else statement is used in conjunction with the if statement to show what code will run if the if condition is false.
An else statement does not need a condition! It runs if the preceding conditions are false.
if condition:
#code that only runs if condition is True
else:
#code that only runs if condition is False
For example:
if number > 0:
print(str(number) + "is positive")
else:
print(str(number) + "isn't positive")
If the number is greater than 0, the message will say it's positive, if not, it will say it's not.
Note: The if and else indentation must match so Python can establish which if statement the else statement belongs with!
Note: You don't have to put an else statement if your code doesn't require it!
Sometimes, we want there to be more than 2 possibilities. If that is the case, you need to use if/elif/else statements. In Python elif is short for else if.
You can use any number of elif statements after an if statement. You can have an else statement after your if and elifs that will run if every condition is false, but it is not required.
if condition1:
#do this if condition1 is True
elif condition2:
#do this if condition1 is False and condition2 is True
elif condition3:
#do this if previous conditions are False and condition3 is True
else:
#do this if all previous conditions are False
Example:
if number > 0:
print(str(number) + "is positive")
elif number < 0:
print(str(number) + "is negative")
else:
print(str(number) + "is zero")
Categorize A Person By Age (Only One Possibility)
Non-Working Examples