ubuntu2004
Making decisions I - conditional statements
Whatever task we're writing our program to perform, it won't be long before we need it to make decisions. To make a decision we use what are called conditional statements which test whether a condition is met or not. If it is met the code does one thing, and if it is not met the code does another thing or nothing at all.
if
A simple example in the following code shows how to make a decision.
Run the code and input a number for a height of a brown bear, any number will do. (Do not enter "cm" after the number otherwise you'll get an error.)
Run the code several times entering different heights above and below 110.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-2-42783363d943> in <module>
3
4 # Input the height of an observed brown bear and assign to the numerical variable height.
----> 5 height = int( input('Height of brown bear: ') )
6
7 # Test if the height of an observed brown bear is larger than the average height of brown bears.
ValueError: invalid literal for int() with base 10: 'ar'
We first set the average height of brown bears to 110 cm. Next we ask for the height of a particular brown bear. The entered height (which is a string) is cast to an integer using the int()
function so that it can be compared to the integer stored in average_height
.
The line
is the condition. Notice the colon at the end of the condition and that the print()
statements below it are indented (whitespace at the beginning of a line).
If the value of height
is greater than the value of average_height
then the condition is True and any code indented below the condition is executed.
If the value of height
is not greater than the value of average_height
then the condition is False and nothing happens:
The "greater than" symbol >
is called a comparison operator. More on those below.
Indentation matters: IndentationError
Python requires us to indent statements within an if
statement. Indentation makes code easier to read.
If we forget to indent code then Python will complain with an IndentationError
.
In the code above, un-indent the two print statements so the code looks like this:
and run it.
We get an IndentationError: expected an indented block
.
There's a quick way to indent and un-indent code.
First select the lines of code you want to (un)-indent either with your mouse or using Shift-down arrow.
Press Ctrl-] to indent the selected lines or Ctrl-[ to un-indent the selected lines.
if
... else
But maybe we want to print something if the condition is False, i.e., if the height of the bear is below the average height. We can do this by using else:
followed by some indented print()
statements.
When this code is run and height
is less than or equal to average_height
the condition
is False. The program ignores the first two print()
statements and skips to the else:
statement and executes the two indented print()
statements just below it.
Notice that the line
occurs twice; it is executed when the condition is both True or False. Our code would be more compact and readable if we moved this print()
statement above the condition like so:
if
... elif
... else
It is possible to chain many tests together like so:
The first line
tests if height
is equal to average_height
. If it is then only the indented print()
statement just below it is executed.
If it is not equal the program skips to the line
which tests if height
is greater than average_height
. If it is then only the indented print()
statement just below it is executed.
If it is not greater the program skips to the line
and the indented print()
statement just below it is executed.
The command elif
is short for "else if". It is Python's way of saying "if the previous condition is not True, then try this condition".
Depending on the task, you can have many elif
conditions. You'll see some examples in the Exercises.
Double equals symbol, ==
The double equals symbol ==
is a comparison operator. It tests if the value on its left equals the value on its right. This has a completely different meaning to the single equal symbol =
which means assign the value on the right to the variable on the left.
So
means assign the value of 10 to the variable called a
. Whereas
means test if the value of a
equals 10. If it is then the condition is True otherwise it is False.
There is also the not equal to comparator !=
, e.g.,
which tests if the value of a
is not equal to 10.
Testing strings
Test the value of a string
As with numbers we can test if a string variable is equal to (==
) or not equal to (!=
) another string.
The code asks for input of a letter. If the letter you entered was "a" then the first condition is True and the code prints You entered "a"
. Otherwise the first condition is False and the code jumps to else:
and prints 'You did not enter "a"
.
As well as testing for individual characters we can test for any number of characters or even none. For example
Test if a character is in a string
We can test if a character is in, or is not in, a string using the in
and not in
membership operators.
Test if a word is in a string
Similarly, you can test if a substring is in a string.
Tables of operators
Here are tables of the different operators.
comparison operator | meaning |
---|---|
== | equal to |
!= | not equal to |
> | greater than |
>= | greater than or equal to |
< | less than |
<= | less than or equal to |
membership operator | meaning |
---|---|
in | in a string or list |
not in | not in a string or list |