If programs could just be run from bottom-down without possible detours they would achieve very little. Because of this, there are constructs (called conditionals) that can be used to take various paths inside code. Let's take our simple calculator and modify it so that the user can choose which operator to use.
a = input("Write the first number: ") b = input("Write the second number: ") op = input("Choose the operator (+, -, *, /) ") if op == '+': sum = int(a) + int(b) print("Their sum is " + str(sum)) elif op == '-': sub = int(a) - int(b) print("Their subtraction is " + str(sub)) elif op == '*': prod = int(a) * int(b) print("Their product is " + str(prod)) elif op == '/': quot = int(a) / int(b) print("Their quotient is " + str(quot)) else: print("Unknown operator")
Again, lots of stuff. Let's break it down a bit.
First, we ask the user to input the two operands and the operator. This is nothing new.
Then we start evaluating the various possibilities and act accordingly. The if
keyword introduces a conditional, that is a piece of code that gets executed only if some condition (or multiple conditions, as we'll see later) holds true. The general structure is:
if [condition]: [do something]
condition
is anything that can be evaluated to True
or False
. Usually, it is a comparison. So let's look at how comparisons work.
Comparing
There's a number of operators we can use for comparison. Let's take the equality (==
) operator as an example. Fire up the interpreter in interactive mode and let's do some tests.
>>> 5 == 5 True >>> 5 == 4 False >>> 5 == 'hello' False >>> 'hello' == 'hello' True
- In the first case, 5 is actually equal to 5, so the interpreter tells us the comparison holds true.
- In the second case, 4 is surely not equal to 5, so the interpreter yields
False
. - A number is clearly not the same as a string, so the result is
False
. - Finally, two strings containing the exact same characters, and only those characters, are practically the same string, so the comparison yields
True
.
Here's a list of the comparison operators available in Python.
== |
Operand on the left equals operand on the right |
!= | Operand on the left does not equal operand on the right |
> | Operand on the left is greater than operand on the right |
>= | Operand on the left is greater or equal operand on the right |
< | Operand on the left is lesser than operand on the right |
<= |
Operand on the left is lesser or equal operand on the right |
Back to the calculator
We can now go back to the general form of an if
statement.
if [condition]: [do something]
We already explained what the condition part is, so let's go on. After the condition, we put a colon and we go to a newline. At the beginning of the next line we put a certain number of spaces (4, by convention). From there on, everything that is indented by the same number of spaces will be executed if and only if the condition yielded True, up to a line with a lesser number of leading spaces. Let's use a simpler example to clarify.
if 5 == 5: print("5 equals 5") print("But we already knew it") print("You learned something today :)")
As silly as it is, this example shows us that the first two print
s would have been executed only if the condition (5 == 5
) yield True
, while the last print
would have been executed anyway. Let's see the counter-example.
if 5 != 5: print("5 equals 5") print("So you won't see these lines") print("I'll be printed anyway :)")
Only the last line will be printed this time because it's not part of the if
statement.
So, back to our simple calculator, if when asked the operator, the user put '+
' the condition of the if
statement would have been true and the following two lines (the one doing the addition and the one printing the result) would have been executed. Otherwise, they would have been ignored.
Since in this particular case the choices are mutually exclusive (the user couldn't have input both '+' and '-'), we could just get away with a series of if
s. But that wouldn't allow us to consider the alternative where the user didn't chose any of the supported operators. To achieve this, Python provides two statements: elif
and else
.
elif
is used when the condition from the previous if wasn't met but we want to provide another condition. That is, we're not simply saying 'otherwise', we are providing an alternative but with some other constraint. The form of an elif
statement is the same as the one for the if
statement. The only difference is that it has to be proceeded by an if
block (that is, an if
statement followed by the indented part).
On the other end, else
tells the interpreter "if none of the previous conditions were met, just do this". Because it's the last resort, it must me placed at the end of a conditions chain (that is, it can't be followed by another elif
or another else
). Also, notice that else
can be used after an if
, without there being elif
s, like in this (useless) program that checks if you are over 18:
age = input("How old are you? ") if int(age) > 18: print("Ok, you can enter") else: print("Come back when you're older!")