Conditionals, if, elif, and else
Programs would quickly get useless if they couldn't cater for a range of different circumstances, and that's why all programming languages have some sort of conditional operator. This allows to choose between a range of logical paths.
For example, say our user is using our program to look at prices of chairs. If the price is very high, we want to tell them to not buy the chair. If it is low, we want to tell them to buy the chair:
>>> price = 100
>>> if price < 500:
print("Buy the chair!")
else:
print("Do not buy the chair!")
The first thing to notice is that the else is unindented. This is so Python can know that the if part of this code and the else part of this code correspond to one another.
What the code does is check if the conditional clause in the if statement is True. If it is not True, then it executes the code under the else part.
In this case, price < 500 would evaluate to True, so the program would print "Buy the chair!".
Try this yourself:
>>> def should_i_buy():
price = int(input("Enter price: "))
if price < 200:
print("Buy!")
else:
print("Do not buy!")
This allows the program to choose between two logical paths: if the price is low or if it isn't. However, sometimes we may want our program to choose between more logical paths.
For example, to do something if the user presses the 'W' key, or something else if they press 'A', 'S', or 'D'.
It could look something like this:
...
>>> if key == 'W':
print("Moving forwards")
elif key == 'A':
print("Moving left")
elif key == 'S':
print("Moving down")
elif key == 'D':
print("Moving right")
else:
print("Unknown command")
In this case, we have four conditional comparisons, checking whether a variable key (which would've gotten a value assigned to it previously in our program) is equal to 'W', in which case we print 'Moving forwards', or any of 'A', 'S', or 'D', and we print the appropriate message. Finally, if the key was not equal to any of 'W', 'A', 'S', or 'D', we print 'Unknown command'.
If we wanted to not print 'Unknown command', we could just skip the else part of that code.
But again we can use these conditional terms at any point in our programs, to choose between two or more outcomes.
Remember we can also just use the if term:
...
>>> if price < 100:
print("You've got a great deal!")
But there is no need to include any of the else or elif terms if they are not suitable.
However, we cannot use else or elif if there is not first an if term.