The Python tutorials are written as Jupyter notebooks and run directly in Google Colab—a hosted notebook environment that requires no setup. Click the Run in Google Colab button.
Colab link - Open colab
Welcome! This notebook will teach you about the condition statements in the Python Programming Language. By the end of this lab, you'll know how to use the condition statements in Python, including operators, and branching.
a
a value of 5. Use the equality operator denoted with two equal == signs to determine if two values are equal. The case below compares the variable a
with 6.
# Condition Equal
a = 5
a == 6
The result is False, as 5 does not equal to 6.
Consider the following equality comparison operator i > 5
.
If the value of the left operand, in this case the variable i, is greater than the value of the right operand, in this case 5, then the statement is True.
Otherwise, the statement is False. If i is equal to 6, because 6 is larger than 5, the output is True.
# Greater than Sign
i = 6
i > 5
Set i = 2
. The statement is false as 2 is not greater than 5:
# Greater than Sign
i = 2
i > 5
Let's display some values for i
in the figure. Set the values greater than 5 in green and the rest in red. The green region represents where the condition is **True**, the red where the statement is **False**. If the value of i
is 2, we get **False** as the 2 falls in the red region. Similarly, if the value for i
is 6 we get a **True** as the condition falls in the green region.
The inequality test uses an exclamation mark preceding the equal sign, if two operands are not equal then the condition becomes **True**. For example, the following condition will produce **True** as long as the value of i
is not equal to 6:
# Inequality Sign
i = 2
i != 6
When i
equals 6 the inequality expression produces False.
# Inequality Sign
i = 6
i != 6
See the number line below. when the condition is **True** the corresponding numbers are marked in green and for where the condition is **False** the corresponding number is marked in red.
If we set i
equal to 2 the operator is true as 2 is in the green region. If we set i
equal to 6, we get a **False** as the condition falls in the red region.
We can apply the same methods on strings. For example, use an equality operator on two different strings. As the strings are not equal, we get a **False**.
# Use Equality sign to compare the strings
"ACDC" == "Michael Jackson"
If we use the inequality operator, the output is going to be **True** as the strings are not equal.
# Use Inequality sign to compare the strings
"ACDC" != "Michael Jackson"
Inequality operation is also used to compare the letters/words/symbols according to the ASCII value of letters. The decimal value shown in the following table represents the order of the character:
For example, the ASCII code for ! is 21, while the ASCII code for + is 43. Therefore + is larger than ! as 43 is greater than 21.
Similarly, the value for A is 101, and the value for B is 102 therefore:
# Compare characters
'B' > 'A'
When there are multiple letters, the first letter takes precedence in ordering:
# Compare characters
'BA' > 'AB'
Note: Upper Case Letters have different ASCII code than Lower Case Letters, which means the comparison between the letters in python is case-sensitive.
Branching allows us to run different statements for different inputs. It is helpful to think of an **if statement** as a locked room, if the statement is **True** we can enter the room and your program will run some predefined tasks, but if the statement is **False** the program will ignore the task.
For example, consider the blue rectangle representing an ACDC concert. If the individual is older than 18, they can enter the ACDC concert. If they are 18 or younger than 18 they cannot enter the concert.
Use the condition statements learned before as the conditions need to be checked in the **if statement**.
The syntax is as simple as if condition statement :
, which contains a word if
, any condition statement, and a colon at the end.
Start your tasks which need to be executed under this condition in a new line with an indent. The lines of code after the colon and with an indent will only be executed when the **if statement** is **True**.
The tasks will end when the line of code does not contain the indent.
In the case below, the tasks executed print(“you can enter”)
only occurs if the variable age
is greater than 18 is a True case because this line of code has the indent. However, the execution of print(“move on”)
will not be influenced by the if statement.
# If statement example
age = 19
#age = 18
#expression that can be true or false
if age > 18:
#within an indent, we have the expression that is run if the condition is true
print("you can enter" )
#The statements after the if statement will run regardless if the condition is true or false
print("move on")
Try uncommenting the age variable
It is helpful to use the following diagram to illustrate the process. On the left side, we see what happens when the condition is True.
The person enters the ACDC concert representing the code in the indent being executed; they then move on.
On the right side, we see what happens when the condition is False; the person is not granted access, and the person moves on.
In this case, the segment of code in the indent does not run, but the rest of the statements are run.
The else
statement runs a block of code if none of the conditions are **True** before this else
statement. Let's use the ACDC concert analogy again. If the user is 17 they cannot go to the ACDC concert, but they can go to the Meatloaf concert.
The syntax of the else
statement is similar as the syntax of the if
statement, as else :
. Notice that, there is no condition statement for else
.
Try changing the values of age
to see what happens:
# Else statement example
age = 18
# age = 19
if age > 18:
print("you can enter" )
else:
print("go see Meat Loaf" )
print("move on")
The process is demonstrated below, where each of the possibilities is illustrated on each side of the image.
On the left is the case where the age is 17, we set the variable age to 17, and this corresponds to the individual attending the Meatloaf concert.
The right portion shows what happens when the individual is over 18, in this case 19, and the individual is granted access to the concert.
The elif
statement, short for else if, allows us to check additional conditions if the condition statements before it are False.
If the condition for the elif
statement is True, the alternate expressions will be run.
Consider the concert example, where if the individual is 18 they will go to the Pink Floyd concert instead of attending the ACDC or Meat-loaf concert.
The person of 18 years of age enters the area, and as they are not older than 18 they can not see ACDC, but as they are 18 years of age, they attend Pink Floyd. After seeing Pink Floyd, they move on. The syntax of the elif
statement is similar in that we merely change the if
in if
statement to elif
.
# Elif statment example
age = 18
if age > 18:
print("you can enter" )
elif age == 18:
print("go see Pink Floyd")
else:
print("go see Meat Loaf" )
print("move on")
The three combinations are shown in the figure below. The left-most region shows what happens when the individual is less than 18 years of age. The central component shows when the individual is exactly 18. The rightmost shows when the individual is over 18.
Look at the following code:
# Condition statement example
album_year = 1983
album_year = 1970
if album_year > 1980:
print("Album year is greater than 1980")
print('do something..')
Feel free to change album_year
value to other values -- you'll see that the result changes!
Notice that the code in the above indented block will only be executed if the results are True.
As before, we can add an else
block to the if
block. The code in the else
block will only be executed if the result is False.
Syntax:
if (condition):
# do something
else:
# do something else
If the condition in the if
statement is False, the statement after the else
block will execute. This is demonstrated in the figure:
# Condition statement example
album_year = 1983
#album_year = 1970
if album_year > 1980:
print("Album year is greater than 1980")
else:
print("less than 1980")
print('do something..')
Feel free to change the album_year
value to other values -- you'll see that the result changes based on it!
Sometimes you want to check more than one condition at once. For example, you might want to check if one condition and another condition is **True**. Logical operators allow you to combine or modify conditions.
and
or
not
These operators are summarized for two variables using the following truth tables:
The and
statement is only **True** when both conditions are true. The or
statement is true if one condition is **True**. The not
statement outputs the opposite truth value.
Let's see how to determine if an album was released after 1979 (1979 is not included) and before 1990 (1990 is not included).
The time periods between 1980 and 1989 satisfy this condition. This is demonstrated in the figure below.
The green on lines a and b represents periods where the statement is **True**. The green on line c represents where both conditions are **True**, this corresponds to where the green regions overlap.
The block of code to perform this check is given by:
# Condition statement example
album_year = 1980
if(album_year > 1979) and (album_year < 1990):
print ("Album year was in between 1980 and 1989")
print("")
print("Do Stuff..")
To determine if an album was released before 1980 (~ - 1979) or after 1989 (1990 - ~), an **or** statement can be used. Periods before 1980 (~ - 1979) or after 1989 (1990 - ~) satisfy this condition.
This is demonstrated in the following figure, the color green in a and b represents periods where the statement is true. The color green in **c** represents where at least one of the conditions are true.
The block of code to perform this check is given by:
# Condition statement example
album_year = 1990
if(album_year < 1980) or (album_year > 1989):
print ("Album was not made in the 1980's")
else:
print("The Album was made in the 1980's ")
The not
statement checks if the statement is false:
# Condition statement example
album_year = 1983
if not (album_year == '1984'):
print ("Album year is not 1984")