Session 1 Recap#

A quick recap#

  • Fundamentals

  • Data structures: lists and dictionaries

  • Control flow: if, elif & else

  • Loops

  • Exercise: check your understanding

Fundamentals#

We can instantiate variables, and assign data values to them. Lets create some data about this flower, found in a lawn on campus.

Picture of a Lawn Daisy

name = "Lawn Daisy"
native_to = "Europe"
petal_colour = "White"
disc_floret_colour = "Yellow"
stem_height = 40
petal_count = 23
location = "Exeter"

print(f"This {name} was found in {location}. It has {petal_count} {petal_colour} petals, and a {stem_height} cm stem.")
This Lawn Daisy was found in Exeter. It has 23 White petals, and a 40 cm stem.

Each variable has a type. We did not have to declare this specifically: Python worked this out based on our data. Some common data types are string, float, and int. We can check the type of a variable using the built-in function, type:

print(type(petal_count), type(disc_floret_colour))
<class 'int'> <class 'str'>

We can write comments using the # symbol, or using triple quotes. Lines in these sections will not be executed. This is often indicated by the text colour.

# This line will not execute: species = "wrong species"

"""
Neither will these lines
species = "wrong species again"
"""

species = "B. perennis"

print(species)
B. perennis

Lists and dictionaries#

We can hold more than one piece of data in a data structure. We can use create lists using square brackets, as follows:

flower_info = [name, native_to, petal_colour, disc_floret_colour, stem_height, petal_count, location, species]

print(flower_info)
print(type(flower_info))
['Lawn Daisy', 'Europe', 'White', 'Yellow', 40, 23, 'Exeter', 'B. perennis']
<class 'list'>

We can access specific elements of a list using the elements index. Remember that indexing starts from 0.

element_2 = flower_info[1]

print(element_2)
print(type(element_2))
Europe
<class 'str'>

Data structures often have built-in functions, or methods, attached to them. These provide fast ways of achieving common tasks. We can use the .append method to insert an element at the final index plus one, of a list:

kingdom = "Kingdom: Plantae"
flower_info.append(kingdom)

print(flower_info)
['Lawn Daisy', 'Europe', 'White', 'Yellow', 40, 23, 'Exeter', 'B. perennis', 'Kingdom: Plantae']

We can update a list element, using the element’s index. Remember that a negative index counts from the end of the list, with an index of -1 indicating the final element index.

correct_kingdom = "Plantae"
flower_info[-1] = correct_kingdom

print(flower_info)
['Lawn Daisy', 'Europe', 'White', 'Yellow', 40, 23, 'Exeter', 'B. perennis', 'Plantae']

We can make a dictionary using key, values pairs. Dictionaries are useful when we want to return values, based on the name of the variable (i.e. its key), and not just an index. For example:

flower_dict = {
    "name": name,
    "native_to": native_to,
    "petal_colour": petal_colour,
    "disc_floret_colour": disc_floret_colour,
    "stem_height": stem_height,
    "petal_count": petal_count,
    "location": location,
    "species": species,
    "kingdom": kingdom,
}

print(flower_dict)
print(type(flower_dict))
{'name': 'Lawn Daisy', 'native_to': 'Europe', 'petal_colour': 'White', 'disc_floret_colour': 'Yellow', 'stem_height': 40, 'petal_count': 23, 'location': 'Exeter', 'species': 'B. perennis', 'kingdom': 'Kingdom: Plantae'}
<class 'dict'>

We can then access values based on their key. To access the value associated with the coolness percentage key:

print(flower_dict["disc_floret_colour"])
Yellow

We can add data to a dictionary in-place, as it is mutable.

new_stem_height = 35
flower_dict["stem_height"] = new_stem_height

print(flower_dict)
{'name': 'Lawn Daisy', 'native_to': 'Europe', 'petal_colour': 'White', 'disc_floret_colour': 'Yellow', 'stem_height': 35, 'petal_count': 23, 'location': 'Exeter', 'species': 'B. perennis', 'kingdom': 'Kingdom: Plantae'}

Finally, we can access just the keys, just the values, or the key, value pairs of a dictionary, using built-in methods:

flower_fields = list(flower_dict.keys())

print(flower_fields)
['name', 'native_to', 'petal_colour', 'disc_floret_colour', 'stem_height', 'petal_count', 'location', 'species', 'kingdom']

Control flow#

We can use if, elif and else statements to perform different tasks, based on data values. For example, imagine we are classifying different types of flowers, and we want to use a script to sort them into different groups for processing later on. Lets start by creating a second flower dictionary.

flower_dict_2 = {
    "name": "Bluebell",
    "native_to": "British Isles",
    "tepal_colour": "Blue",
    "stem_height": 12,
    "tepal_count": 6,
    "location": "Dartmoor",
    "species": "H. non-scripta",
    "kingdom": "Plantae",
}

Lets identify flowers above a certain stem height.

threshold_height = 18
daisy_height = flower_dict["stem_height"]

if daisy_height >= threshold_height:
    print("Daisy found above threshold height")
else:
    print("Daisy was not above threshold height")
Daisy found above threshold height

Lets write a piece of control flow using if, elif, and else, and using the and logical operator:

threshold_height = 10
bluebell_height = flower_dict_2["stem_height"]

if daisy_height >= threshold_height and bluebell_height >= threshold_height:
    print("Daisy and Bluebell found above threshold height")
elif daisy_height < threshold_height and bluebell_height >= threshold_height:
    print("Bluebell found above threshold height")
elif daisy_height >= threshold_height and bluebell_height < threshold_height:
    print("Daisy found above threshold height")
else:
    print("No flowers found above threshold height")
Daisy and Bluebell found above threshold height

Loops#

It is often very helpful to perform calculations over a number of items, usually stored in a data structure. If the data structure is iterable, then we can write a for loop to execute operations over each element. For example, lets print out every value in our flower_dict dictionary:

for value in flower_dict.values():
    print(value)
Lawn Daisy
Europe
White
Yellow
35
23
Exeter
B. perennis
Kingdom: Plantae

We can extract the key and the value at the same time, using dict.items(), and display them using the f-string syntax:

for key, value in flower_dict.items():
    print(f"{key}: {value}")
name: Lawn Daisy
native_to: Europe
petal_colour: White
disc_floret_colour: Yellow
stem_height: 35
petal_count: 23
location: Exeter
species: B. perennis
kingdom: Kingdom: Plantae

Lets try to multiply every value by 10. Why are some results strange?

for value in flower_dict_2.values():
    new_value = value * 10
    print(new_value)
BluebellBluebellBluebellBluebellBluebellBluebellBluebellBluebellBluebellBluebell
British IslesBritish IslesBritish IslesBritish IslesBritish IslesBritish IslesBritish IslesBritish IslesBritish IslesBritish Isles
BlueBlueBlueBlueBlueBlueBlueBlueBlueBlue
120
60
DartmoorDartmoorDartmoorDartmoorDartmoorDartmoorDartmoorDartmoorDartmoorDartmoor
H. non-scriptaH. non-scriptaH. non-scriptaH. non-scriptaH. non-scriptaH. non-scriptaH. non-scriptaH. non-scriptaH. non-scriptaH. non-scripta
PlantaePlantaePlantaePlantaePlantaePlantaePlantaePlantaePlantaePlantae

When we use an asterisk operator on a string we are overloading it. We are concatenating the strings 10 times! Note that the numerical calculations are still correct.

Exercise#

This is a famous (and now overused) programming task used in interviews. “Write a program that prints the numbers from 1 to 50. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.”

Give it a go!

Hint 1#

In Python, the modulo operator is %. This returns the remainder when dividing one number by another.

print(10 % 5)
0
print(10 % 3)
1

Hint 2#

Here is the control flow for the fizzbuzz problem. Note that the iterator variable is not called i in this flowchart (it is called fizzbuzz.) A flowchart of the control flow for the fizzbuzz problem