In [ ]:

Conditionals and Flow Control

Dr. Chris Gwilliams

gwilliamsc@cardiff.ac.uk

Overview

  • Conditionals
  • Comparison Operators
    • Less than
    • More than
    • Equality
    • is and is not
  • Combining statememnts
  • If statements
  • Else if

Comparison Operators

Remember (*, / and +)?

These are not the only operators you can use on types. Ever heard of carets?

Less Than (<)

Try typing 3<10 in the interpreter

and now 10<3. What type is the result?

Greater Than (>)

Guess what this one does?

Equality Operators

pints = 3

One equals is for assigning a name to a literal.

Two equals checks if two variables (or literals) are equal.


In [9]:
name = "Chris"
print(name == "Chris")
print(2 == 5)


True
False

Comparison Operators

We can combine equality operators with comparison operators. What benefit is this?

Less Than or Equal To (<=)

2 <= 5

Greater Than or Equal To (>=)

2 >= 5

Exercise

What operator(s) could I have used to get these results?

2 ?? 5 #false
"a" ?? "b" #True
3.33 ?? 7 #False
400 ?? 1000 #True
1000 ?? 1000 #True

In [10]:
2 > 5
"a" < "b"
3.33 > 7
3.33 == 7
3.33 >= 7
400 <= 1000
400 < 1000
1000 == 1000
1000 <= 1000
1000 >= 1000


Out[10]:
True

If you want to know more about comparing strings like this, then look at this

Equality Operators

So, how do we know when something is not equal?


In [11]:
print(name != "Bob")


True

Is and Is not

== and != are not the only ways to check for equality.


In [12]:
print(2 is 2)
name = "Chris"
print(name is not name)


True
False

What? I hear you ask, how is this any different to ==?

Hold your horses and let's find out.

Identity vs Equality

== is equality comparison (checking if two values are the same)

is is identity comparison (checking if 2 objects are the same)


In [13]:
a = "chris"
b = "chris"
print(a is b) # identity (True)
print(a == b) # equality (True)


True
True

In [14]:
a = [] # we will learn about these soon!
b = []
print(a is b) # identity (False)
print(a == b) # equality (True)


False
True

These are both comparing the same thing? Why is one True and the other is False?

Equality comparison is only concerned with the value

Identity comparison is only concerned with the object. If 2 objects have the same value but are not stored in the same memory address then they are not equal. This can be explained further by...

Immutable vs Mutable

What does this mean?

Immutable means that something cannot be changed after it is created

Mutable means that something can be changed after it is created

Exercise

Give me 2 examples of immutable things

Give me 2 examples of mutable things

Immutable and Mutable in Python

Strings are immutable in Python (and other languages).

Mutable types are beneficial because you can make changes in place.

WARNING: if you reference that mutable variable from another variable and make a change then ALL references change. We will come back to this


In [15]:
string_var = "fdjklhd" #immutable
print(string_var) #fdjklhd
s = string_var
s += "ueoureo"
print(string_var) #fdjklhd
print(s) #fdjklhdueoureo

list_var = [] # mutable and we are still learning about these later
print(list_var) #[]
l = list_var # l is a reference to list_var
l.append(1) 
print(list_var) #[1]
print(l) #[1]


fdjklhd
fdjklhd
fdjklhdueoureo
[]
[1]
[1]

Combining Comparisons

What if we want to know more than one thing about a value? What if I want to know if someone is more than 18 but also under 25?

We could do this:


In [16]:
age = 21
age < 15
age > 25


Out[16]:
False

But there must be a better way! What do you think?

AND/OR

There is a better way!

age > 15 and age < 25 # only true if both are true
age > 15 or age < 10 # true if either are true

The and keywords allow you to chain multiple conditionals together and react only if all of them are true

OR

We can use the or to allow multiple different scenarios.

Exercise

What is the output of these conditionals? Try it in your head first.


In [1]:
make = "Tesla"
capacity = 80000
year = 2016
zero_to_sixty = 3

print(make == "Tesla" or make == "tesla")
print(make == "Tesla" and make == "tesla")
print(capacity < 80000 and capacity > 60000)
print(capacity > 60000 or capactity < 100000 and year == 2014 or  year == 2016)


True
False
False
True

Chained Comparison

So, we can write:

age > 15 and age < 25

Can you think of a way this could be shorter?


In [18]:
15 < age < 25


Out[18]:
True

Conditionals

What do you think a conditional is? Let's use these comparisons for good!

When we check if something is less than something else or for equality, just printing True or False is not always helpful. This is where conditionals come in.

If statements to the rescue!


In [19]:
no_hours_slept = 3
if no_hours_slept < 5:
    print("Good Lord, turn Netflix off")
print("This print statement does not care how many hours you slept")


Good Lord, turn Netflix off
I do not care how many hours you slept

Take note of the structure

  • COLON : at the end of the if statement
  • indent (4 spaces) for code you want to run only if the statement is true
  • unindent to go back to the normal running ### Exercise What are the benefits of if statements? What kind of control is this? Write an if statement that prints hello and the name if the name variable is equal to Winston Churchill

Flow Control

Python is interpreted.

What we have written so far runs your code line by line. This is known as the flow of the program

If statements will only run the block of code when the statement is true

This interrupts the flow of the program


In [2]:
name = "Homer"
age = 80

print("My name is " + name)
print("I am %d" % age)
print("I am over one hundred years old!") #is this true? With no flow control it will print anyway


My name is Homer
I am 80
I am over one hundred years old!

In [ ]:
name = "Homer"
age = 80

print("My name is " + name)
print("I am " + age)
if age > 100:
    print("I am over one hundred years old!") #is this true? With no flow control it will print anyway
    print("this will print if Homer is over 100, too") #as long as you stay indented, this is all part of the if
print("this will print regardless")

Exercise

  • Create a variable that holds the value 3
  • print EQUAL FOR ALL if it is equal to 3 using equality comparison
  • print IDENTITY FOR ALL if it is equal to 3 using identity comparison
  • Check if the variable exists at all
    • how many ways of doing that are there?
  • Create a variable that holds the value 10
  • print TEN AND THREE if the first variable is equal to 3 AND the second is equal to 10
    • how many ways could this be done?

In [ ]:
first_var = 3
if first_var == 3:
    print("EQUAL FOR ALL")
if first_var is 3:
    print("IDENTITY FOR ALL")
if first_var:
    print("I AM REAL")
if first_var is not None:
    print("I AM NOT NONE")
second_var = 10
if first_var == 3 and second_var == 10:
    print("TEN AND THREE")

Else

So, we can print when something is true, what about when it isn't?

Consider the situation of a nightclub app.


In [ ]:
age = 12
if age >= 18:
    print "come on in"

If the user is 18 or over then we print that they can come in. What about the users under 18? They get no output. How do we get around this?

Else

The else statement. This is the catch all statement for when the statement before is not true.

You should always have one!


In [ ]:
age = 12
if age >= 18:
    print("come on in")
else:
    print("I think this ID is fake")

Exercise

Declare and instantiate variables to store a users details (name, height and year of birth)

  • Print the name
  • Print their height if they are under 7ft or print Wow, just wow if they are 7ft or over
  • Calculate their (approximate, you do not have the month) age from the year of birth
  • Print their age if they are 30 or over or print YOUNGUN if they are under 30

In [ ]:
name = "Jill"
height = 8
yob = 1990
year = 2016
print(name)
if height < 7:
    print(height)
else:
    print("WOW, JUST WOW")
age = year - yob
if age >= 30:
    print(age)
else:
    print("YOUNGUN")

Elif

Any guesses as to what this stands for? How would you use it?

Look at the code below, where is the error?


In [1]:
age = 800
if age < 13:
    print("Child")
elif age > 13 and age < 20:
    print("Teenager")
elif age >= 21 and age < 140:
    print("Adult")
else:
    print("HOW HAVE YOU CHEATED DEATH?")
    print("YOU ARE A MACHINE")


HOW HAVE YOU CHEATED DEATH?
YOU ARE A MACHINE

Elif (else if)

We can use this to check multiple statements if something is in a range of options (age is a good example).

Else then serves as our default state, the block of code that will

Exercise

Create a variable to store a pet type and write an if/else if/else statement that prints:

  • four legged friend if the pet is a dog or cat
  • reptilian rapport if the pet is a lizard or dragon
  • aquatic amigo if the pet is a fish
  • what the smeg in any other situation

In [2]:
pet = "cat"
if pet == "fish":
    print("Aquatic amigo")
elif pet == "cat" or pet == "dog":
    print("four legged friend")
elif pet == "lizard" or pet == "dragon":
    print("reptilian rapport")
else:
    print("what the smeg")


four legged friend

Precedence

When you see if statements in most other languages you are probably used to seeing this:

if(x < 3)

Python does care about brackets but not in the same way.

if(x > 10):

is the same as

if x > 10:

Then what are brackets for?

Precedence, or order of evalutation, is exactly the same as BODMAS (Brackets, Order, Division, Multiplication, Addition and Subtraction) from GCSE Maths.


In [ ]:
print(5 + 6 * 9)
print((5 + 6) * 9) #see how the brackets change the order? This applies to if statements as well

Exercise

Add in brackets to make these statements give the answer printed:

  • 4 * 5 / 2 - 1 (Answer: 20)
  • 5 + 6 / 2 * 8 (Answer: 0.6875)
  • 4 /1 * 2 + 1 (Answer: 1.333333)

In [ ]:
4 * (5 / (2 - 1))
(5 + 6) / (2 * 8)
4 / ((1 * 2) + 1)

Precedence

Precedence is crucial when you are considering how your operations are going to be executed. Not only can it affect whether an if statement runs, it can actually the affect the output. As a final take home, consider this example:


In [4]:
print(1 + 1 == 1)
print(1 + (1 == 1)) #Why does this output what it does?


False
2

This is because adding boolean and integers adds the integer equiavalent of the boolean variable, which makes True equal to 1.

Exercise

Create some variables to store information about your direct debits.

Use if statements to print out comments based on those values. (i.e. "Whoa, you spend all the monies")

Add the cost of the debits together and print out different things based on the range (i.e. < 10, > 10 but < 30 etc)

Fin

Do the homework!

Make a cheat sheet of operators