Skip to content

Conditional Statements

In python many variables that you create, whether they be basic ones or composite variables, need to be compared or evaluated at some point. If you have a variable in your code that isn't, then you probably don't need that variable.

Evaluation

In a python program, each line of the program is evaluated from top to bottom and left to right, unless order of precedents is in effect, with few exceptions. Common evaluations are things such as addition and subtraction, consider this code:

example-9.py from the beginning to the end
# example-9.py 
# Common evaluations and their outcomes
variable_1 = 4
variable_2 = 2
variable_3 = 3
variable_4 = 5

# Simple math functionality
print(variable_1 + variable_2)
print(variable_1 - variable_2)
print(variable_1 * variable_2)
print(variable_1 / variable_2) # / always becomes a floating number
print(variable_1 % variable_2)
print(variable_1 // variable_2)

# Let's do some type checking to prove it
print(type(variable_1 + variable_2))
print(type(variable_1 - variable_2))
print(type(variable_1 * variable_2))
print(type(variable_1 / variable_2))
print(type(variable_1 % variable_2))
print(type(variable_1 // variable_2))

# String concatination 
# this uses the + in an interesting way
string_1 = "hey"
string_2 = "you"
print(string_1 + " " + string_2 + "!")
print(type(string_1 + " " + string_2 + "!"))

# interesting evaluations that still happen from left to right
# mostly... 
print(variable_1 + variable_2 * variable_3 + variable_4)
print(variable_4 + variable_1 * variable_2 - variable_3)
Output
6
2
8
2.0
0
2






hey you!

15
10

The last few examples show how even though the order of precedence makes sure that multiplication and division happens before the addition and subtraction, but then immediately once they have been taken care of the evaluation happens from left to right again. As you can also see, the program executes from the top line to the bottom line of code. This creates a logical layout that we will utilise later.

Order of Precedence

Much like in math, python has an order to when an evaluation gets done. Here is a table:

Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
not Logical NOT
and Logical AND
or Logical OR

The higher something is on the table the sooner it gets done. Things in parenthesis get done first, mostly so you can force the order of precedence. There are a few gottcha's in this list that tend to get every programmer at least once, but for you guys the biggest one will be that logical AND is performed before logical OR. Consider this code fragment:

example-1.py from 1 to 10
# example-1.py first example
# Precedence of or & and
meal = "Spaghetti Carbonara"

money = 0

if meal == "Spaghetti Carbonara" or meal == "Lasagne" and money >= 2:
    print("Dinner is served!!")
else:
    print("Can't deliver dinner :( ")
Output
Dinner is served!!

The code as you can see, doesn't respond the way we might like. We would want the code to work out if we can have dinner firstly if we picked a valid dinner option and also had enough money, but as we don't have enough money why is it evaluating as True? It's because the AND evaluates first, evaluating to False, and then the OR evaluates. In the evaluation of True OR False, it always evaluates to True. We can fix this with the following modification:

example-1.py from 13 to 22
# example-1.py second example
# Fixed the order of precedents 
meal = "Spaghetti Carbonara"

money = 0

if (meal == "Spaghetti Carbonara" or meal == "Lasagne") and money >= 2:
    print("Dinner is served!!")
else:
    print("Can't deliver dinner :( ") 
Output
Can't deliver dinner :( 

The other order of precedence that you have to watch out for is that some evaluations start from the right, and others start from the left. Consider this code:

example-2.py from 1 to 18
# example-2.py
# Showing order of precedence through examples
# As all of these have the same precedence, 
# they get evaluated starting from left-right:
print(3 // 2 * 3)  
print(3 * 2 // 3)
print(3 * 2 % 6)
print(2 % 6 * 3)
print(6 + 3 - 7)
print(6 - 7 + 3)

# Right to left precedence happens with **
# Output: 512, since 2**(3**2) = 2**9
print(2 ** 3 ** 2)

# If 2 needs to be the first exponent evaluated, we need to use ()
# Output: 64, since (2**3)**2 = 8**2 
print((2 ** 3) ** 2) 
Output
3
2
0
6
2
2
512
64

You can see that depending on the type of evaluation used it will depend on whether it is evaluated from left to right. When in doubt you should test your code thoroughly and use parenthesis.

Literal Values

We've covered all of the basic types in python; the string, Boolean, integer, and floating point number. However, python also supports a lot of other literal values that aren't commonly used. Below is a more comprehensive list of literal values:

literal type sample
String literal "hello",'hey'
int literal 5
Long int literal 879564L (Only in python 2.x)
Floating point 3.1459
Complex Literals 12j
Boolean Literals True, False
Special Literals None
Unicode Literals u"Hello"
Byte Literals b"Hello"
Hex Literals 0x +hexValue
Octal Literals 0o +octValue
List Literals [] , [1, 2, 4, 5]
Tuple Literals () , (9, ) , (1, 2, "happy")
Dictionary Literals {} , {'x':7}
Set Literals {8, 9, 10}

For those interested in coding literals and some of the abstract ideas surrounding literal testing, you can find more reading on python 3 conventions here (WARNING: very advanced stuff!!). Here are some examples of the literals being used:

example-6.py from 1 to the end
# example-6.py
# examples of exotic literals at work 
string_literals = "this is a regular string"
integer_literals = 12
octal_literals = 0o11
hexadecimal_literals = 0x123 
set_literals = {2, 4, 7}    # Math sets 
complex_literals = 12J      # complex numbers
unicode_literals = u"this is the default in python 3"
byte_code_literals = b"this is a byte string"    
print(
    string_literals,
    integer_literals, 
    octal_literals, 
    hexadecimal_literals, 
    set_literals, 
    complex_literals, 
    unicode_literals, 
    byte_code_literals
) 
Output
this is a regular string 12 9 291 {2, 4, 7} 12j this is the default in python 3 b'this is a byte string'

Generally though, you will only use basic types unless you are purposely trying to obfuscate your code, or doing type conversion specifically. It's just a good idea to be familiar with the other literals so that you aren't confused if you encounter them in other peoples code. The long integer isn't in python 3.x anymore as all integers are now treated as if they are long integers in python, to learn more about how it gets converted and how python is interpreted you can find it in the documentation here.

Inequalities

To talk about inequalities, we must first need to talk about what an equality is. In python, equality is the symbol == and will directly check if one object is equal to another object. This is not the same as the 'is' keyword. Consider this code:

example-8.py from 1 to 15
# example-8.py first example 
# Showing the difference between the is keyword and the equality operator
list_1 = [10] 
list_2 = list_1        
list_3 = list(list_1)

# test all of the equalities
print(list_1 == list_2)
print(list_1 == list_3)
print(list_2 == list_3)

# test all of the is comparisons
print(list_1 is list_2)
print(list_1 is list_3)
print(list_2 is list_3) 
Output
True
True
True
True
False
False

Here you can see that the difference between the equality operator and the is statement quite apparent. The equality operator looks to see if the values inside the lists are the same, whereas the is operator looks to see if the labels point to the same object. Understanding this key difference will help you to write good evaluation statements that behave the way you intend them to. Inequalities cover the other types of comparisons you might want to accomplish, consider this table:

Symbol Meaning
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to

A comparison always evaluates from left to right in the sense that if you were to create a comparison such as:

print(variable_1 > variable_2) 
it would compare if variable_1 is greater than variable_2. This can be complicated by multiple evaluations however, consider this example:

print(variable_1 > variable_2 > variable_3)
Python handles this type of evaluation by taking the first two and then the last two variables and evaluating them separately. This makes it equivalent to;

print(variable_1 > variable_2 and variable_2 > variable_3)

Make sure you consider this behaviour when you write your own conditional statements.

Boolean Logic

All logic inside a computer boils down to True or False logic. True is either represented by its name or by the number 1, False is represented by its name or 0. All modern classical (Von Neumann architecture) computers are based off of Boolean logic and Boolean algebra, this means that all the components inside the machine have been developed to take 1's and 0's and represent them in every way we need to create useful data with. For the purposes of programming however, you need to understand how truth tables refer to AND, OR, NAND (not AND) and NOR (not OR) logic. Here are the truth tables for each of the logical comparisons

AND True False
True True False
False False False
OR True False
True True True
False True False
NAND True False
True False True
False True True
NOR True False
True False False
False False True

When considering your if statements, you need to consider how they will be evaluated with this logic. Read the selection section to find out more.