Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
10327 views
ubuntu2004
Kernel: Python 3 (system-wide)

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.

  1. 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.)

  2. Run the code several times entering different heights above and below 110.

# Assign the average height-to-shoulder (in cm) of brown bears to the numerical variable average_height. average_height = 110 # Input the height of an observed brown bear and assign to the numerical variable height. height = int( input('Height of brown bear: ') ) # Test if the height of an observed brown bear is larger than the average height of brown bears. if height > average_height: # If it is execute these print statements. print( f"The height of the brown bear is {height} cm" ) print( "This brown bear is taller than the average brown bear" )
Height of brown bear:
--------------------------------------------------------------------------- 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

if height > average_height:

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:

if height > average_height: # If it is execute these print statements. print( f"The height of the brown bear is {height} cm" ) print( "This brown bear is taller than the average brown bear" )

and run it.

We get an IndentationError: expected an indented block.

There's a quick way to indent and un-indent code.

  1. First select the lines of code you want to (un)-indent either with your mouse or using Shift-down arrow.

  2. 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.

Try this with the code below.
average_height = 110 height = int( input('Height of brown bear: ') ) if height > average_height: # If it is execute these print statements. print( f"The height of the brown bear is {height} cm" ) print( "This brown bear is taller than the average brown bear" ) else: # If it isn't execute these print statements. print( f"The height of the brown bear is {height} cm" ) print( "This brown bear is shorter than the average brown bear" )
Height of brown bear:
The height of the brown bear is 90 cm This brown bear is shorter than the average brown bear

When this code is run and height is less than or equal to average_height the condition

if height > average_height:

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

print( f"The height of the brown bear is {height} cm" )

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:

average_height = 110 height = int( input('Height of brown bear: ') ) # Move this print statement out of the condition because it is executed irrespective of the condition being True or False. print( f"The height of the brown bear is {height} cm" ) if height > average_height: print( "This brown bear is taller than the average brown bear" ) else: print( "This brown bear is shorter than the average brown bear" )
Height of brown bear:
The height of the brown bear is 90 cm This brown bear is shorter than the average brown bear

if ... elif ... else

It is possible to chain many tests together like so:

average_height = 110 height = int( input('Height of brown bear: ') ) print( f"The height of the brown bear is {height} cm") # Test if the height of an observed brown bear is equal to, # larger than or smaller than the average height of brown bears. if height == average_height: print( "This brown bear has the same height as the average brown bear" ) elif height > average_height: print( "This brown bear is taller than the average brown bear" ) else: print( "This brown bear is shorter than the average brown bear" )
Height of brown bear:
The height of the brown bear is 110 cm This brown bear has the same height as the average brown bear

The first line

if height == average_height:

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

elif height > average_height:

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

else:

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

a = 10

means assign the value of 10 to the variable called a. Whereas

if a == 10:

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.,

if a != 10:

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.

Run the following code to see how this works.
x = input('Enter a letter: ') if x == 'a': print('You entered "a"') else: print('You did not enter "a"')
Enter a letter:

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 for a word if word == 'Hello':
# Test for an empty string if dna_seq == '':

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.

Try different characters in the following code to see how it works.
sentence = 'Hello, world!' if 'e' in sentence: print( f'The letter "e" is in {sentence}') if 'f' not in sentence: print( f'The letter "f" is not in {sentence}')
The letter "e" is in Hello, world! The letter "f" is not in Hello, world!

Test if a word is in a string

Similarly, you can test if a substring is in a string.

sentence = 'Hello, world!' if 'world' in sentence: print( f'"world" is in {sentence}') if 'sun' not in sentence: print( f'"sun" is not in {sentence}')
"world" is in Hello, world! "sun" is not in Hello, world!

Tables of operators

Here are tables of the different operators.

comparison operatormeaning
==equal to
!=not equal to
>greater than
>=greater than or equal to
<less than
<=less than or equal to
membership operatormeaning
inin a string or list
not innot in a string or list

Exercise Notebook

Next Notebook