1 of 137

Welcome to GPN!

Perth Term 1 2026

Connect to UWA WiFI

1. Select UnifiGuest wireless network�2. Enter the username and password

Username: perthgpn

Password: Gt88.mk?

3. Accept the Terms of Use.�4. Click the "Log in" button.

Connect to UWA WiFi

2 of 137

Welcome to GPN

3 of 137

Thank you to our Sponsors!

Platinum Sponsor:

Gold Sponsor:

4 of 137

Who are the tutors?

5 of 137

Log on

Log on and jump on the GPN website

girlsprogramming.network/workshop

Click on your node location

Click on your room.

From this page you can see:

  • These slides (to take a look back or go on ahead).
  • A link to your workbook in EdStem
  • Other helpful bits to use through the day!

6 of 137

Tell us you’re here!

Click on the

Start of Day Survey

and fill it in now!

7 of 137

Today’s project!

Markov Chains!

8 of 137

What is a Markov Chain?

A Markov chain is a simple Artificial Intelligence!

Let’s play a game with some cups to help explain it

9 of 137

Let’s play the cups game!

Let’s generate some text in the style of

Green Eggs & Ham by Dr Seuss

Do you like green eggs and ham?

I do not like them, Sam-I-am.

I do not like green eggs and ham.

Would you like them here or there?

I would not like them here or there.

I would not like them anywhere.

10 of 137

Let’s play the cups game!

  • Each cup is labelled with a word from Green Eggs and Ham

  • Each cup contains the words that follow the "label" word in Green Eggs and Ham

We’re going to write some text by randomly choosing a next word based on the word before it

11 of 137

Let’s play the cups game!

Read the outside of your cup!

If someone shouts the word on the outside of your cup:

  1. Pick a piece of paper from inside your cup
  2. Shout out the word on the piece of paper
  3. Put the piece of paper back in your cup

A tutor will write the words called out on the board

12 of 137

Today we’ll be making Markov Chains!

Markov chains are exactly what we just did with the cups!

Today we’ll make the computer do it to make some crazy stories!!

Here’s one we made from some Shakespeare!�

Imagine if you used one of these to do your homework!!

doth stay! All days when I compare thee to unseeing eyes be blessed made By chance, or eyes can see, For all the top of happy show thee in dark directed. Then thou, whose shadow shadows doth stay! All days when I compare thee in your self in inward worth nor outward fair, Can make bright, How would thy shade Through heavy sleep on the eye of life repair, Which this, Time's pencil, or my pupil pen, Neither in the living day, When in eternal lines of that fair from fair thou grow'st, So should the lines to a summer's day?

13 of 137

Introduction to Edstem

14 of 137

Log on

Click on your Workbook link to take you into EdStem

15 of 137

Signing up to Edstem

Log in if you already have a an “Edstem” account from a past GPN

If you haven’t got an account, let’s make one:

  1. Type in your Full Name
  2. Type in your personal email
  3. Click Create Account
  4. Go to your email and verify your new account
  5. Create a password

Click Join Course

The name of your course will be at the top :

If you don’t have access to your email account, ask a tutor for a GPN Edstem login

16 of 137

Signing up to Edstem

We are shifting all our courses to a new website called “Edstem” so here’s an overview of how to sign up and how to use it.

First let’s go through how to create an account.

  1. Follow this link: https://edstem.org/au/join/afrJT9
  2. Type in your name and your personal email address
  3. Click Create Account
  4. Go to your email to verify your account
  5. Create a password
  6. It should then take you to the courses home page.
  7. Click on the one we will be using for this project:

17 of 137

Getting to the lessons

  1. Once you are in the course, you’ll be taken to a discussion page.
  2. Click the button for the lessons page (top right - looks like a book)

18 of 137

The set up of the workbook

The main page:

  1. Heading at the top that tells you the project you are in

  1. List of “Chapters” called something like 1:Welcome Message They have an icon that looks like this:

  1. To complete your project, work through the chapters one at a time

19 of 137

Inside a Chapter

Inside a Chapter there are two main types of pages:

  • Lessons where you will do your coding.
    • They have this icon:

  • Checkpoints

Each chapter has a checkpoint to complete to move to the next chapter. Make sure you scroll down to see all the questions in a checkpoint.

There may also be Bonus Lessons to try if you want to or if you are waiting for the next lecture

20 of 137

Inside a Chapter

Inside a Chapter there are two main types of pages:

  • Lessons where you will do your coding.
    • They have this icon:

  • Checkpoints

Each chapter has a checkpoint to complete to move to the next chapter. Make sure you scroll down to see all the questions in a checkpoint.

There may also be Bonus Lessons to try if you want to or if you are waiting for the next lecture

21 of 137

How to do the work

In each Lesson there is:

  1. A section on the left with instructions
  2. A section on the right for your code

You will need to copy your code from the last lesson, then follow the instructions to change your code

There are also Hints and Code Blocks to help you

22 of 137

Hints

Sometimes in a lesson, there’s some code we want you to do that might be a bit tricky, to help you out we’ve added some hints. They look like this:

If you press the blue run button it will show you what that code does, you can even change the code to see if/how it changes.

These are just hints make sure you’re not copying the hint into your code as it will likely end up breaking. They are just to show you the kinds of things you can do.

23 of 137

Running your code…

Click in the bottom right hand corner

Your code will run and any output will display in the Console

Don’t worry if you forget. Tutors

will help!

24 of 137

Some shortcuts…

There are a couple things you can do to make copying your code from one page to another easier.

  1. Ctrl + A

  1. Ctrl + C

  1. Ctrl + V

Pressing these keys together will select all the text on a page

Pressing these keys together will copy anything that’s selected

Pressing these keys together will paste anything you’ve copied

On Macs use Command (⌘) instead of Ctrl

25 of 137

Project time!

You now know all about the EdStem!

You should now sign up and join our EdStem class.

Remember the tutors will be around to help!

26 of 137

Intro to Python

Let’s get coding!

27 of 137

Let’s make a mistake!

Click on Chapter 1 ‘Welcome message’

The first lesson ‘1.1 Print a message’ will open. It looks like this

28 of 137

Let’s make a mistake!

Type by button mashing the keyboard here - type anything you want

Click Run here to run your code!

Did you get a big ugly error message?

29 of 137

Mistakes are great!

Good work you made an error!

  • Programmers make A LOT of errors!
  • Errors give us hints to find mistakes
  • Run your code often to get the hints!!
  • Mistakes won’t break computers!

AttributeError: 'NoneType' object has no attribute 'foo'

TypeError: Can't convert 'int' object to str implicitly

ImportError: No module named humour

KeyError: ‘Hairy Potter’

SyntaxError: Invalid Syntax

30 of 137

Write some code!!

This is the first bit of code we will do. What do you think it does?��print('hello world')

31 of 137

Write some code!!

This is the first bit of code we will do. What do you think it does?��print('hello world')

It prints the words “hello world” onto the screen!

32 of 137

Variables

Variables are useful for storing things that change

(i.e. things that "vary" - hence the word "variable")

You can think of it like putting information in a box and giving it a label

friend

33 of 137

Variables

When coding, we can make a variable called friend and set it to a value like this

friend = “Alex”

friend

Alex

34 of 137

Variables

Instead of writing the word “Alex”, we can write friend (the variable’s name).

The computer will substitute the current value of friend.

It’s like we’re getting the value out of the box!

print(friend)

friend

Alex

35 of 137

Variables

Instead of writing the word “Alex”, we can write friend (the variable’s name).

The computer will substitute the current value of friend.

It’s like we’re getting the value out of the box!

print(friend)

friend

Alex

Alex

36 of 137

Reusing variables

We can replace values in variables:

animal = "dog"

print("My favourite animal is a " + animal)

animal = "cat"

print("My favourite animal is a " + animal)

animal = animal + "dog"

print("My favourite animal is a " + animal)

What will this output?

37 of 137

Reusing variables

We can replace values in variables:

animal = "dog"

print("My favourite animal is a " + animal)

animal = "cat"

print("My favourite animal is a " + animal)

animal = animal + "dog"

print("My favourite animal is a " + animal)

My favourite animal is a dog

My favourite animal is a cat

My favourite animal is a catdog

What will this output?

38 of 137

Asking a question!

It’s more fun when we get to interact with the computer! ��Let’s get the computer to ask us a question!

my_name = input('What is your name? ')

print('Hello ' + my_name)

  1. Computer prints ‘What is your name?’
  2. Computer waits for you to type in your name
  3. Computer prints ‘Hello Maddie’

This is what happens …

What is your name? Maddie

Hello Maddie

39 of 137

Breaking it down

my_name = input('What is your name? ')

print('Hello ' + my_name)

What do you think happens?

What is your name? Maddie

Hello Maddie

Store the answer in the variable my_name

40 of 137

Breaking it down

my_name = input('What is your name? ')

print('Hello ' + my_name)

What do you think happens?

What is your name? Maddie

Hello Maddie

Store the answer in the variable my_name

Writing input tells the computer to wait for a response

41 of 137

Breaking it down

my_name = input('What is your name? ')

print('Hello ' + my_name)

What do you think happens?

What is your name? Maddie

Hello Maddie

Store the answer in the variable my_name

Writing input tells the computer to wait for a response

This is the question you want printed to the screen

42 of 137

Breaking it down

my_name = input('What is your name? ')

print('Hello ' + my_name)

What do you think happens?

What is your name? Maddie

Hello Maddie

Store the answer in the variable my_name

Writing input tells the computer to wait for a response

This is the question you want printed to the screen

We can use the answer the user wrote that we then stored later!

43 of 137

Breaking it down

my_name = input('What is your name? ')

print('Hello ' + my_name)

SPACE 🙂

What is your name? Maddie

Hello Maddie

Big Tip : Put a space at the end of the question so it won’t be squished together with your answer - it looks nicer!

NO SPACE 🙁

What is your name?Maddie

Hello Maddie

44 of 137

Adding a comment!

Sometimes we want to write things in code that the computer doesn’t look at! We use comments for that! �Use comments to write a note or explanation of our code

Comments make code easier for humans to understand

We can make code into a comment if we don’t want it to run (but don’t want to delete it!)

# This code was written by Sheree

# print(“Goodbye world!”)

45 of 137

Project time!

You now know all about printing, variables and input!

Let’s put what we learnt into our project

Try to do Lessons 1 & 2

Don't forget to copy your code when you move to a new Lesson!

The tutors will be around to help!

46 of 137

If Statements and Lists

47 of 137

Conditions!

Conditions let us make decision.

First we test if the condition is met!

Then maybe we’ll do the thing

If it’s raining take an umbrella

Yep it’s raining

…... take an umbrella

48 of 137

Conditions

So to know whether to do something, they find out if it’s True!

fave_num = 5

if fave_num < 10:

print("that’s a small number")

49 of 137

Conditions

So to know whether to do something, they find out if it’s True!

fave_num = 5

if fave_num < 10:

print("that’s a small number")

What do you think happens?>>>

50 of 137

Conditions

So to know whether to do something, they find out if it’s True!

fave_num = 5

if fave_num < 10:

print("that’s a small number")

What do you think happens?>>> that’s a small number

51 of 137

Conditions

How about a different number???

fave_num = 9000

if fave_num < 10:

print("that’s a small number")

What do you think happens?>>>

52 of 137

Conditions

How about a different number???

fave_num = 9000

if fave_num < 10:

print("that’s a small number")

What do you think happens?>>>

Nothing!

53 of 137

If statements

word = "GPN"

if word == "GPN":

print("GPN is awesome!")

What happens?

54 of 137

If statements

word = "GPN"

if word == "GPN":

print("GPN is awesome!")

What happens?

>>> GPN is awesome!

:

At end of each if line to say you have finished writing your condition

==

When testing for equals in your condition

Remember …

55 of 137

If statements

word = "GPN"

if word == "GPN":

print("GPN is awesome!")

What happens?

>>> GPN is awesome!

56 of 137

If statements

word = "GPN"

if word == "GPN":

print("GPN is awesome!")

What happens?

>>> GPN is awesome!

But what if we want something different to happen if the word isn’t "GPN"

57 of 137

Else statements

word = "Chocolate"

if word == "GPN":

print("GPN is awesome!")

else:

print("The word isn’t GPN :(")

What happens?

else

statements means something still happens if the if statement was False

58 of 137

Else statements

word = "Chocolate"

if word == "GPN":

print("GPN is awesome!")

else:

print("The word isn’t GPN :(")

What happens?

>>> The word isn’t GPN :(

else

statements means something still happens if the if statement was False

59 of 137

Elif statements

word = "Chocolate"

if word == "GPN":

print("GPN is awesome!")

elif word == "Chocolate":

print("YUMMM Chocolate!")

else:

print("The word isn’t GPN :(")

What happens?

elif

Means we can give specific instructions for other words

60 of 137

Elif statements

word = "Chocolate"

if word == "GPN":

print("GPN is awesome!")

elif word == "Chocolate":

print("YUMMM Chocolate!")

else:

print("The word isn’t GPN :(")

What happens?

>>> YUMM Chocolate!

elif

Means we can give specific instructions for other words

61 of 137

Lists

But we don’t store it on lots of little pieces of paper!

We put it in one big shopping list!

��

Bread

Ice Cream

Chocolate

Pizza

  • Bread
  • Chocolate
  • Ice Cream
  • Pizza

When we go shopping, we write down what we want to buy!

62 of 137

Lists

It would be annoying to store it separately when we code too

>>> shopping_item1 = "Bread"

>>> shopping_item2 = "Chocolate"

>>> shopping_item3 = "Ice Cream"

>>> shopping_item4 = "Pizza"

So much repetition!�

Instead we use a python list!

shopping_list = ["Bread", "Chocolate", "Ice Cream", "Pizza"]

63 of 137

List anatomy

shopping_list = ["Bread", "Chocolate", "Ice Cream", "Pizza"]

Stored in the variable shopping_list

64 of 137

List anatomy

shopping_list = ["Bread", "Chocolate", "Ice Cream", "Pizza"]

Made up of different items (these are strings)

Stored in the variable shopping_list

65 of 137

List anatomy

shopping_list = ["Bread", "Chocolate", "Ice Cream", "Pizza"]

Made up of different items (these are strings)

Stored in the variable shopping_list

The items are separated by commas

66 of 137

List anatomy

shopping_list = ["Bread", "Chocolate", "Ice Cream", "Pizza"]

Has square brackets either side

Made up of different items (these are strings)

Stored in the variable shopping_list

The items are separated by commas

67 of 137

What’s an index?

A list has many items, indexing lets us get one item from the list using its position number;

Shopping list

  • Apple
  • Banana
  • Candy
  • Chocolate
  • Crisps

What is the fourth item I need to buy?

68 of 137

What’s an index?

A list has many items, indexing lets us get one item from the list using its position number;

Shopping list

  • Apple 1
  • Banana 2
  • Candy 3
  • Chocolate 4
  • Crisps 5

What is the fourth item I need to buy?

chocolate!

69 of 137

How do I know how long

We use indexes (or the position number) to pick an item in a list

fruits = ["apple", "banana", "cherry"]

fruits[1]

The list we want to pick an item from

70 of 137

How do I know how long

We use indexes (or the position number) to pick an item in a list

fruits = ["apple", "banana", "cherry"]

fruits[1]

The list we want to pick an item from

The name of the list

71 of 137

How do I know how long

We use indexes (or the position number) to pick an item in a list

fruits = ["apple", "banana", "cherry"]

fruits[1]

The list we want to pick an item from

The name of the list

The index (position) of the item

72 of 137

But wait!

When we index, we start counting from 0

fruits = ["apple", "banana", "cherry"]

fruits[1]

0

2

1

So we are actually picking the item “banana”

73 of 137

Project Time!

You now know all about if and lists!

See if you can do Lesson 3

The tutors will be around to help!

74 of 137

Random!

75 of 137

That’s so random!

There’s lots of things in life that are up to chance or random!

Python lets us import common bits of code people use! We’re going to use the random module!

We want the computer to be random sometimes!

76 of 137

Using the random module

Let’s choose something randomly from a list!

This is like drawing something out of a hat in a raffle!

Try this!

  1. Import the random module!��
  2. Copy the shopping list into IDLE���
  3. Choose randomly! Try it a few times!

>>> import random

>>> shopping_list = ["eggs", "bread", "apples", "milk"]

>>> random.choice(shopping_list)

77 of 137

Using the random module

You can also assign your random choice to a variable

>>> import random

>>> shopping_list = ["eggs", "bread", "apples", "milk"]

>>> random_food = random.choice(shopping_list)

>>> print(random_food)

78 of 137

Project Time!

Raaaaaaaaaandom! Can you handle that?

Let’s try use it in our project!

Try to do Lesson 4�� The tutors will be around to

79 of 137

For Loops

80 of 137

For Loops

For loops allow you to do something a certain number of times.

We use them when we know exactly how many times we want to do something!

81 of 137

For Loops

number = 10

for i in range(number):

#Do something

82 of 137

For Loops

number = 10

for i in range(number):

#Do something

The for word tells python we want to use a loop

83 of 137

For Loops

number = 10

for i in range(number):

#Do something

The for word tells python we want to use a loop

This i is a temporary variable which will count how many times we have looped.

84 of 137

For Loops

number = 10

for i in range(number):

#Do something

The for word tells python we want to use a loop

This i is a temporary variable which will count how many times we have looped.

This part says we want to loop number amount of times (in this case, 10)

85 of 137

For Loops

number = 10

for i in range(number):

#Do something

The for word tells python we want to use a loop

This i is a temporary variable which will count how many times we have looped.

This part says we want to loop number amount of times (in this case, 10)

The code indented in the loop is what will happen every time.

86 of 137

Looping how many times?

We can loop through a list:

friends = 4

for i in range(friends):

print(“Hello friend!”)

What’s going to happen?

87 of 137

Looping how many times?

We can loop through a list:

friends = 4

for i in range(friends):

print(“Hello friend!”)

>>> Hello friend!

>>> Hello friend!

>>> Hello friend!

>>> Hello friend!

What’s going to happen?

88 of 137

Looping how many times?

We can loop through a list:

We do what’s in the for loop as many times as what is in the “range”

friends = 4

for i in range(friends):

print(“Hello friend!”)

>>> Hello friend!

>>> Hello friend!

>>> Hello friend!

>>> Hello friend!

What’s going to happen?

89 of 137

Project Time!

Now you know how to use a for loop!

Try to do Lesson 5

...if you are up for it!

The tutors will be around to help!

90 of 137

Dictionaries

91 of 137

Dictionaries!

92 of 137

Dictionaries!

Look up�Hello

Get back�A greeting (salutation) said when meeting someone or acknowledging someone’s arrival or presence.

You know dictionaries!

They’re great at looking up thing by a word, not a position in a list!

93 of 137

Looking it up!

There are lots of times we want to look something up!�

Phone Book

Vending Machine

Competition registration

Name → Phone number

Treat Name → Price

Team Name → List of team members

94 of 137

Looking it up!

Phone Book

Name → Phone number

Key

Value

We can use a dictionary for anything with a �key → value pattern!

95 of 137

Dictionaries anatomy!

This is a python dictionary!

This dictionary has Alex, Caitlin and Emma’s phone numbers

phone_book = {"Alex": 111, "Caitlin": 222, "Emma": 333}

96 of 137

Dictionaries anatomy!

This is a python dictionary!

This dictionary has Alex, Caitlin and Emma’s phone numbers

phone_book = {"Alex": 111, "Caitlin": 222, "Emma": 333}

Stored in the variable phone_book

97 of 137

Dictionaries anatomy!

This is a python dictionary!

This dictionary has Alex, Caitlin and Emma’s phone numbers

phone_book = {"Alex": 111, "Caitlin": 222, "Emma": 333}

Stored in the variable phone_book

Has squiggly brackets either side

98 of 137

Dictionaries anatomy!

This is a python dictionary!

This dictionary has Alex, Caitlin and Emma’s phone numbers

phone_book = {"Alex": 111, "Caitlin": 222, "Emma": 333}

Stored in the variable phone_book

Has squiggly brackets either side

Made up of pairs of information

99 of 137

Dictionaries anatomy!

This is a python dictionary!

This dictionary has Alex, Caitlin and Emma’s phone numbers

phone_book = {"Alex": 111, "Caitlin": 222, "Emma": 333}

Stored in the variable phone_book

Has squiggly brackets either side

Made up of pairs of information

The pairs are separated by commas

100 of 137

Dictionaries anatomy!

This is a python dictionary!

This dictionary has Alex, Caitlin and Emma’s phone numbers

phone_book = {"Alex": 111, "Caitlin": 222, "Emma": 333}

Stored in the variable phone_book

Has squiggly brackets either side

Made up of pairs of information

The pairs are separated by commas

Keys and values are separated by a colon

101 of 137

Dictionaries anatomy!

This is a python dictionary!

This dictionary has Alex, Caitlin and Emma’s phone numbers

phone_book = {"Alex": 111, "Caitlin": 222, "Emma": 333}

Stored in the variable phone_book

Has squiggly brackets either side

Made up of pairs of information

Each pair is made up of a key and value

The pairs are separated by commas

Keys and values are separated by a colon

102 of 137

Cups!!

Remember the cups activity from the start of the day?

103 of 137

A Single Cup!

The word “A”

can be followed by

Any of these words

Key

Value

104 of 137

A Single Cup!

The word “A”

can be followed by

Any of these words

['house', 'mouse', 'house', 'mouse', 'box', 'fox', 'box', 'fox', 'house', 'mouse']

We can store the slips of paper as a python list!

105 of 137

A Single Cup!

The word “A”

can be followed by

Any of these words

We want to look up the word “a” and get back the list!

{'a' :

}

['house', 'mouse', 'house', 'mouse', 'box', 'fox', 'box', 'fox', 'house', 'mouse']

106 of 137

A Single Cup!

{'a' :

}

['house', 'mouse', 'house', 'mouse', 'box', 'fox', 'box', 'fox', 'house', 'mouse']

So we get a Dictionary with a List value!�

��If you look up “A” you get back a list of all the words that can follow “a”

Key

Value

107 of 137

Cups → Dictionary with lists!

Here’s what it looks like for a few more cups!

You can get the whole cup dictionary from today's website!

cups = {'am': ['Sam', 'That'],

'In': ['a', 'a', 'a'],

'a' : ['house', 'mouse',

'house', 'mouse',

'box', 'fox', 'box',

'fox', 'house',

'Mouse']

....}

108 of 137

Is it there?

We can check if something is a key in a dictionary like this:

if current_word in cups:

cups = {'am': ['Sam', 'That'],

'In': ['a', 'a', 'a'],

'a' : ['house', 'mouse',

'house', 'mouse',

'box', 'fox', 'box',

'fox', 'house',

'Mouse']

....}

109 of 137

Project time!

You now know all about lists and dictionaries!

Let’s put what we learnt into our project

Try to do Lesson 6 & 7

The tutors will be around to help!

110 of 137

More Dictionaries and Lists!

111 of 137

Getting words from sample text

In order to be able to read in lots of text we need to be able to turn sentences into a list of words.

We can do this by using .split() on our text!

112 of 137

Using split

text = “a really cool sentence”

words = text.split()

print(words)

What do you think words will be?

113 of 137

Using split

text = “a really cool sentence”

words = text.split()

print(words)

What do you think words will be?

[“a”, “really”, “cool”, “sentence”]

114 of 137

More things you can do with lists!

There’s lots of cool things we can do with lists! Like:

Getting the length of a list

words = [“a”, “really”, “cool”, “sentence”]

print(len(words))

Adding new items to a list

words.append(“yay”)

print(words)

115 of 137

More things you can do with lists!

There’s lots of cool things we can do with lists! Like:

Getting the length of a list

words = [“a”, “really”, “cool”, “sentence”]

print(len(words))

Adding new items to a list

words.append(“yay”)

print(words)

4

116 of 137

More things you can do with lists!

There’s lots of cool things we can do with lists! Like:

Getting the length of a list

words = [“a”, “really”, “cool”, “sentence”]

print(len(words))

Adding new items to a list

words.append(“yay”)

print(words)

4

[“a”, “really”, “cool”, “sentence”, “yay”]

117 of 137

Accessing Lists!

This favourites list holds four strings in order:

faves = ['books', 'butterfly', 'chocolate', 'skateboard']

We can count out the items using index numbers!

0 1 2 3

Remember: Indices start from zero!

118 of 137

Accessing Lists

We access the items in a list with an index such as [0]:

>>> faves[0]

'books'

What code do you need to access the second item in the list?

>>> faves[1]

'butterfly'

0 [1] 2 3

119 of 137

Accessing Lists

We access the items in a list with an index such as [0]:

>>> faves[0]

'books'

What code do you need to access the second item in the list?

>>> faves[1]

'butterfly'

0 [1] 2 3

120 of 137

Going Negative

Negative indices count backwards from the end of the list:

>>> faves[-1]

'skateboard'

What would faves[-2] return?

>>> faves[-2]

'chocolate'

-4 -3 [-2] -1

121 of 137

Going Negative

Negative indices count backwards from the end of the list:

>>> faves[-1]

'skateboard'

What would faves[-2] return?

>>> faves[-2]

'chocolate'

-4 -3 [-2] -1

122 of 137

Falling off the edge

Python complains if you try to go past the end of a list

>>> faves = ['books', 'butterfly', 'chocolate',

'skateboard']

>>> faves[4]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: list index out of range

123 of 137

Updating our dictionaries!

We’ve seen how to use dictionaries - but how do we update existing ones? Let’s have a look at a phone book example!

>>> phone_book = {

"Alex": 111, "Caitlin": 222, "Emma": 333

}

  • We met Rowena! Let’s add her to our phone book

>>> phone_book["Rowena"] = 444

>>> phone_book

{ "Alex": 123, "Caitlin": 222, "Emma": 333,

"Rowena": 444 }

124 of 137

Lists in dictionaries!

We’ve been using lists as the values of our dictionary like this:

  • Let’s make some sports teams:

>>> team_members = {

"Sydney": ["Pauline", "Srishti", "Amara"],

"Perth": ["Crischell", "Ash", "Taylah"]

}

  • What happens if you do:

>>> team_members["Sydney"]

  • What if we did this?

>>> team_members["Perth"].append("Priya")

125 of 137

Lists in dictionaries!

We’ve been using lists as the values of our dictionary like this:

  • Let’s make some sports teams:

>>> team_members = {

"Sydney": ["Pauline", "Srishti", "Amara"],

"Perth": ["Crischell", "Ash", "Taylah"]

}

  • What happens if you do:

>>> team_members["Sydney"]

  • What if we did this?

>>> team_members["Perth"].append("Priya")

["Pauline", "Srishti", "Amara"]

126 of 137

Lists in dictionaries!

We’ve been using lists as the values of our dictionary like this:

  • Let’s make some sports teams:

>>> team_members = {

"Sydney": ["Pauline", "Srishti", "Amara"],

"Perth": ["Crischell", "Ash", "Taylah"]

}

  • What happens if you do:

>>> team_members["Sydney"]

  • What if we did this?

>>> team_members["Perth"].append("Priya")

["Pauline", "Srishti", "Amara"]

["Pauline", "Srishti", "Amara", "Priya"]

127 of 137

Project Time!

Now you know even more about Dictionaries and Lists!

You can now try 8-11 in the Second part of your workbook!

The tutors will be around to help!

128 of 137

Files

129 of 137

Opening files!

To get access to the stuff inside a file in python we need to open it!

That doesn’t mean clicking on the little icon!

f = open("test.txt")

You’ll now be able to read the things in f

If your file is in the same location as your code you can just use the name!

130 of 137

A missing file causes an error

Here we try to open a file that doesn't exist:

f = open('missing.txt')

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IOError: [Errno 2] No such file or directory: 'missing.txt'

131 of 137

You can read a whole file into a string

>>> f = open('haiku.txt')

>>> my_string = f.read()

>>> print(my_stirng)

Wanna go outside.

Oh NO! Help! I got outside!

Let me back inside!

haiku.txt

Wanna go outside.

Oh NO! Help! I got outside!

Let me back inside!

132 of 137

You can also read in one line at a time

You can use a for loop to only get 1 line at a time!

f = open('haiku.txt')

for line in f:

print(line)

Wanna go outside.��Oh NO! Help! I got outside!��Let me back inside!

Why is there an extra blank line each time?

133 of 137

Chomping off the newline

The newline character is represented by '\n':

print('Hello\nWorld')�Hello�World

We can remove it from the lines we read with .strip()

x = 'abc\n'

x.strip()

'abc'

x.strip() is safe as lines without newlines will be unaffected

134 of 137

Reading and stripping!

for line in open('haiku.txt'):

line = line.strip()

print(line)

Wanna go outside.�Oh NO! Help! I got outside!�Let me back inside!

No extra lines!

135 of 137

Using with!

This is a special trick for opening files!

with open("words.txt") as f:

for line in f:

print(line.strip())

It automatically closes your file for you!

It’s good when you are writing files in python!

136 of 137

Project Time!

Now you can read some stuff

You can now try the third section of your workbook!

The tutors will be around to help!

137 of 137

How did you go?

Click on the

End of Day Survey

and fill it in now!

girlsprogramming.network/workshop

Click on your node location