0% found this document useful (0 votes)
191 views

Python Programming - A Visual Jo - Kaare Erlend Jorgensen

Uploaded by

Minh Duc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
191 views

Python Programming - A Visual Jo - Kaare Erlend Jorgensen

Uploaded by

Minh Duc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 187

Kaare Erlend Jørgensen

Stein Alexander Dahl

PYTHON PROGRAMMING:
A VISUAL JOURNEY FOR
THE BEGINNER
WITH SIMPLE APPLICATIONS IN
MATHEMATICS

Second Edition

Jorgensen Matematiske Ressurser


© Second Edition, Jørgensen Matematiske Ressurser 2021

ISBN 978-82-692219-5-4

All rights reserved. No part of this book may be used, transmitted or reproduced
in any manner whatsoever without written permission except in the case of brief
quotations embodied in critical articles and reviews. For information, address the
copyright managing authority (www.kopinor.no).

This book has its own webpage: www.kaareskokebok.no

Any enquiry about the present work may be adressed using: [email protected]

Illustrations and graphical production: Kaare E. Jørgensen & Stein A. Dahl


Fonts: Computer Modern 10/12, pdflatex/TikZ/tcolorbox
Acknowledgements
“Of all the characteristics needed for both a happy and morally decent
life, none surpasses gratitude. Grateful people are happier, and grateful
people are more morally decent.”
Dennis Prager 1

These wise words of Dennis Prager reminds me that I have a lot to be grateful
for, and I owe gratitude to many people. I want to begin with thanking my
dear wife, Inna Jørgensen, for never loosing faith in my book-project. She
was always willing to step up to manage our home and our children. My
co-author, Stein A. Dahl, has been indispensable in solving technical and de-
sign problems. He has authored several parts of the book, and gone through
the academics with a precision few can match. I want to give thanks to my
mother, Turid Jørgensen, for being a great support during busy days, helping
out with the kids and being a great listener. I also want to thank my father,
Åge J. Marthinsen, for all the important values he taught me such as hard
work, discipline and perseverance.
Further I want to thank Ellen Egeland Fløe for recommende me as a programming-
instructor to other teachers. Through BRO AOF I was able to travel around
Norway, giving programming seminars to teachers, which all gave important
knowledge and experience on how students ideally should learn programming.
A thank you goes to Nina Sundmark for useful feedback early on. I give thanks
to Thomas F. Sturm2 , who has been of great help with the design of all the
colored boxes throughout the book. His impressive manual of 525 pages has
been a blessing of discovery and learning. A thanks goes to Tantau3 for his
help with graphs and figures produced with Tikz. His manual of 1318 pages
is truly a piece of art. I want to thank Master Books Publisher for giving me
permission to use examples and exercises from the great geometry book by
Harold R. Jacobs4 . Finally, a thanks to Inga Stener Olsen for useful feedback
to the introduction, to Audun Åby for the suggestion of creating a thourough
index, and to Isabella Dahl for the final round of proofreading.

Kaare Erlend Jørgensen

1 Prager, Happiness is a serious problem [6]


2 Sturm, The tcolorbox package [12]
3 Tantau, The Tikz and PGF manual [13]
4 Jacobs, Geometry: Seeing, Doing, Understanding [4]
Contents
Introduction ix

I The Basics 1

1 The First Instructions 3


1.1 The Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 The First Small Steps . . . . . . . . . . . . . . . . . . . . . . 5
1.3 Triangle Recipe . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Square and Rectangle . . . . . . . . . . . . . . . . . . . . . . 7
1.5 Drawing with Coordinates . . . . . . . . . . . . . . . . . . . . 8
1.6 Circles and Fillcolors . . . . . . . . . . . . . . . . . . . . . . . 9
1.7 Summary of Chapter 1 . . . . . . . . . . . . . . . . . . . . . 10
1.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2 Repetitions and Patterns 13


2.1 Two repetitions . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Three or More Repetitions . . . . . . . . . . . . . . . . . . . 15
2.3 Angles and Regular Polygons . . . . . . . . . . . . . . . . . . 16
2.4 Staircase Up and Staircase Down . . . . . . . . . . . . . . . . 17
2.5 Experimenting with a For-loop . . . . . . . . . . . . . . . . . 19
2.6 Summary of Chapter 2 . . . . . . . . . . . . . . . . . . . . . 20
2.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

3 Storing Code in Functions 23


3.1 My smile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.2 Cogwheel and Squares . . . . . . . . . . . . . . . . . . . . . . 25
3.3 Varying the Size of Squares . . . . . . . . . . . . . . . . . . . 27
3.4 Tunnel in 3D . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.5 Triangle-pattern with Midpoints . . . . . . . . . . . . . . . . 30
3.6 Summary of Chapter 3 . . . . . . . . . . . . . . . . . . . . . 31
3.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

4 More Possibilities 35
4.1 A Wheel with Triangles . . . . . . . . . . . . . . . . . . . . . 35
4.2 Random Angles . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.3 The Circumscribed Circle of a Triangle . . . . . . . . . . . . 38
4.4 Bullseye . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.5 Distance Alarm . . . . . . . . . . . . . . . . . . . . . . . . . . 41

v
4.6 Summary of Chapter 4 . . . . . . . . . . . . . . . . . . . . . 43
4.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

5 Mathematics in Python 47
5.1 Add, Subtract, Multiply and Divide . . . . . . . . . . . . . . 47
5.2 Powers and Parentheses . . . . . . . . . . . . . . . . . . . . . 49
5.3 Square Root . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.4 Some Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.5 Variables and Rounding . . . . . . . . . . . . . . . . . . . . . 51
5.6 A Polite Greeting . . . . . . . . . . . . . . . . . . . . . . . . 52
5.7 Calculator Program . . . . . . . . . . . . . . . . . . . . . . . 53
5.8 The Multiplication Master . . . . . . . . . . . . . . . . . . . 54
5.9 Summary of Chapter 5 . . . . . . . . . . . . . . . . . . . . . 56
5.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

II Applications in Mathematics 61

6 Number Patterns 63
6.1 Basic Number Patterns . . . . . . . . . . . . . . . . . . . . . 63
6.2 A Fast-Growing Monkey Population . . . . . . . . . . . . . . 64
6.3 Sums of Odd Numbers . . . . . . . . . . . . . . . . . . . . . . 65
6.4 Sum of a Geometric Pattern . . . . . . . . . . . . . . . . . . 66
6.5 Number Pattern with Circles . . . . . . . . . . . . . . . . . . 67
6.6 The First 100 Natural Numbers . . . . . . . . . . . . . . . . 69
6.7 Rectangle Pattern . . . . . . . . . . . . . . . . . . . . . . . . 70
6.8 Summary of Chapter 6 . . . . . . . . . . . . . . . . . . . . . 72
6.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

7 Powers and Square Roots 77


7.1 Practice Powers of 2 . . . . . . . . . . . . . . . . . . . . . . . 77
7.2 Explore Powers of 10 . . . . . . . . . . . . . . . . . . . . . . . 79
7.3 Guess the Square Root . . . . . . . . . . . . . . . . . . . . . 81
7.4 Rice and Chess . . . . . . . . . . . . . . . . . . . . . . . . . . 82
7.5 Summary of chapter 7 . . . . . . . . . . . . . . . . . . . . . . 83
7.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

8 The Coordinate System 85


8.1 The Coordinate System – a Small Overview . . . . . . . . . . 85
8.2 Explore x-coordinates with Python Turtle . . . . . . . . . . . 86
8.3 Explore y-coordinates with Python Turtle . . . . . . . . . . . 87
8.4 Parallel Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
8.5 Summary of Chapter 8 . . . . . . . . . . . . . . . . . . . . . 89

vi
Contents

8.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

9 Functions 93
9.1 Kaare on the Café – without a Function . . . . . . . . . . . . 93
9.2 Kaare on the Café – with a Function . . . . . . . . . . . . . . 94
9.3 Price per Workout . . . . . . . . . . . . . . . . . . . . . . . . 95
9.4 Seats in a Cinema . . . . . . . . . . . . . . . . . . . . . . . . 96
9.5 The School Road . . . . . . . . . . . . . . . . . . . . . . . . . 97
9.6 Deciding the Minimum . . . . . . . . . . . . . . . . . . . . . 99
9.7 A Piece of Modern Art . . . . . . . . . . . . . . . . . . . . . 100
9.8 Summary of Chapter 9 . . . . . . . . . . . . . . . . . . . . . 101
9.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

10 Probability 105
10.1 Simulation of 100 Births . . . . . . . . . . . . . . . . . . . . . 105
10.2 Counting the Girls . . . . . . . . . . . . . . . . . . . . . . . . 106
10.3 Two Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
10.4 Many Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
10.5 Balls in a Box – with Replacement . . . . . . . . . . . . . . . 109
10.6 Balls in a Box – without Replacement . . . . . . . . . . . . . 110
10.7 Two Goats and a Car . . . . . . . . . . . . . . . . . . . . . . 111
10.8 Shooting Range – Visual Simulation . . . . . . . . . . . . . . 113
10.9 Summary of Chapter 10 . . . . . . . . . . . . . . . . . . . . . 114
10.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

Appendices 117

A Løsninger 117
A.1 Chapter 1 – The First Instructions . . . . . . . . . . . . . . . 117
A.2 Chapter 2 – Repetitions and Patterns . . . . . . . . . . . . . 121
A.3 Chapter 3 – Storing Code in Functions . . . . . . . . . . . . 123
A.4 Chapter 4 – More Possibilities . . . . . . . . . . . . . . . . . 128
A.5 Chapter 5 – Mathematics in Python . . . . . . . . . . . . . . 132
A.6 Chapter 6 – Number Patterns . . . . . . . . . . . . . . . . . 135
A.7 Chapter 7 – Powers and Square Roots . . . . . . . . . . . . . 139
A.8 Chapter 8 – The Coordinate System . . . . . . . . . . . . . . 141
A.9 Chapter 9 – Functions . . . . . . . . . . . . . . . . . . . . . . 144
A.10 Chapter 10 – Probability . . . . . . . . . . . . . . . . . . . . 148

B Plotting Graphs in Python with Spyder 155

C The Learning Philosophy 163

List of Images 169

vii
List of Figures 170

Python-words 173

Bibliography 175

viii
Introduction
What is this book about?
This book teaches you the basic concepts of programming in the language
Python. The first part of the book takes you on a visual tour through the basic
programming concepts. The second part of the book applies these concept to
explore selected mathematical topics. We teach you the required math as we
go along, so math knowledge is not a prerequisite to study programming with
this book.

Who is this book for?


This book is for you who have never programmed before. You don’t even know
what a program or programming is? That’s perfect. This book is for you.
The book is also for students who need to use programming in math class.
Recommended age-group is 12+. Teachers may find this book very useful,
because the knowledge of good ways to teach programming from scratch is
scarce in schools around the world. This book is written also for the classroom,
specifically the math classroom. We have also written this book with parents
in mind. If you are a parent who wants to help your child with programming,
but you never learned programming yourself, then this book is for you too! For
teachers, we recommend you read our appendix C to understand the learning
principles behind this book.

How should I read this book?


This book is designed to teach you programming in a linear fashion. Hence,
it is very important that you read the bok in order. Chapter 1, Chapter 2,
Chapter 3, and so on. The skills you learn in Chapter 1 are applied in Chapter
2. The skills you learn in the first four chapters, are applied in Chapter 5, and
so on. After you completed the first five chapters, you will have a good grasp
of the concepts used in chapters 6 through 10. Therefore it is possible to jump
between chapters after you read through the first part of the book.

Where Can I Write the Code?


You do not need to install any software to get going with programming. All
the examples in this book are written on the website replit.com. Here we
use two versions of Python: Python (with Turtle) and Python3.

ix
The following two alternative websites are worth mentioning:

• Python Turtle: trinket.io/features/pygame and


pythonandturtle.com/turtle. Note that on these two websites, all
Turtle-programs must finish with the command done() .
• Python3 : trinket.io and pythonandturtle.com. On the first men-
tioned website, choose New Trinket Python3 to get started.

What is new in the second edition?


The second edition contains many structural and design improvements, in
addition to the following:

• All chapters now end with both a summary and exercises.


• Most chapters are extended with many new and exciting exercises.
• There are now complete solutions to almost all exercises. The solu-
tions are in the back of the book.
• We have included a list of figures, a rich index over all Python-words
and keyword list over all a lot of the book’s English words.

What do the symbols in the margin mean?


133
In the margin you will often see a page number in a purple box. This tells you
on which page you will find the solution to the current exercise/section.

The star-symbol means that this exercise is considered challenging, and that
? you will not find a solution in the back of the book. We want our students to
feel a sense of great accomplishment, when they master these challenges.

The turtle-symbol means that the code must be written with the language
Python Turtle. Go to replit.com, create a new file and select the language
Python (with Turtle). If this symbol is not present, the code is to be written in
the language Python. You can also use these links: replit.com/new/python_turtle
og replit.com/new/python3.

Good luck on your programming-journey!


Kaare Erlend Jørgensen

Stein Alexander Dahl

x
PART I

The Basics
CHAPTER 1
The First Instructions
1.1 The Creation

Figure 1.1: A real turtle.

We will start by telling our computer to create a turtle. We call our turtle
Tom, and he’s going to do exactly what we instruct him to do. Tom does not
understand English, only Python: this book’s programming language.
a) Open the webpage replit.com. Create a new user, and log in. We
recommend the browsers Brave and Chrome.
b) Create a new file by clicking on the top right. Choose the language
“Python (with Turtle)”, and then select “Create repl”. See figure 1.2.

Figure 1.2: Create a new file on replit.com.

3
c) Write the following code to create Tom the Turtle.

Code

1 from turtle import *


2 shape("turtle") Figure 1.3: The result of the code.

To run the program, press Run , or press the keys


Ctrl + Enter (Mac: Cmd + Enter ) on the keyboard. Do you see a turtle
now, like figure 1.3 shows, or did you get an error message?
d) If you do see the turtle, move to e) now. If you got an error message,
check below and see if you recognize your mistake. Correct your code
and run the program again.

Correct Wrong

from Turtle import *


from turtle import*
from turtle import *
from turlte import *
from import turtle *

Correct Wrong

shape 'turtle')
shape("turtle") shape(turtle')
shape('turtle') shape(`turtle`)
shape('Turtle')

Notice that you can write shape("turtle") or shape('turtle') .


e) Congratulations! You have now created Tom the Turtle and you’re ready
to give him instructions.

4
1. The First Instructions

1.2 The First Small Steps


117
Code

1 from turtle import *


2 shape('turtle')
3 speed(1)
4 forward(50)
5 left(30)

Tom the Turtle understands the instructions forward and left . He does
not understand “walk over there!” or “turn hard left now!”.

a) Read the code above. What do you think the result of the code will be?

b) Copy the code, and run the program. Press Run or Ctrl + Enter (Mac:
Cmd + Enter ) to run the program.

c) Let forward(50) and left(30) switch lines. Guess the result, and then
run the program.
d) Add the following instructions at the bottom of the code. Guess the
result, and then run the program.

left(-30)
forward(50)

e) Let left(30) and left(-30) switch lines. Guess the result, and then
run the program.
f) Finally, finish writing the code so that the result is figure 1.4.

Figure 1.4: Drawing with lines.

In the back of the book you will find solutions to the exercises. The solution
to this section, section 1.2, you will find on page 117. This pagenumber is
marked in the margin as 117 .

5
1.3 Triangle Recipe
117
Code Recipe

1 from turtle import * Create the turtle


2 shape('turtle') Set the shape to a turtle
3 color('blue') Set the color to blue
4 forward(75) Walk 75 steps forward
5 left(60) Turn 60 degrees left
6 forward(75) Walk 75 steps forward

Writing code can be compared to writing a recipe. The code is in Python,


whereas a recipe is in English.

a) Read the code above. Guess the result.

b) Write the code, and run the program. Press Run or Ctrl + Enter (Mac:
Cmd + Enter ) to run the program.

c) Color Tom with your favourite color1 by changing color('blue') to


another color. For example color('brown') .
d) Change left(60) to left(120) , and run the program.
e) Add the lines left(120) and forward(75) in the correct order so that
the program produces figure 1.5.

Figure 1.5: An equilateral triangle. Figure 1.6: Two equilateral triangles.

f) Add the line hideturtle() to the bottom of the code.


g) Expand the program so that the result becomes figure 1.6.
h) Compare your solution to the one you find in the book on page 117. This
pagenumber is also marked in the margin as 117 .

1 On
the web page trinket.io/docs/colors, you can select a color and see the name of that
color in Python Turtle.

6
1. The First Instructions

1.4 Square and Rectangle


117
Code

1 from turtle import *


2 shape('turtle')
3 forward(200)
4 left(90)
5 # And so on ...
Figure 1.7: A square.

On line 5 we have made a comment by writing # before the text. Comments


are useful to explain the meaning of the code.

a) Write the code above, and run the program.


b) Continue writing the instructions 2 forward(200) and left(90) enough
number of times and in the right order, until you finish drawing a square.
See figure 1.7.
c) Add the line speed(7) directly below shape('turtle') .3 What is the
result of this? The possible numbers are 0 to 10.
d) Change two of the numbers in the code so that the result becomes a
rectangle with width 100 and length 200. See figure 1.8.

Figure 1.8: Rectangle.

e) Add code to draw figure 1.9.

Figure 1.9: Rectangle split in two halves.

Use color('red') to color the center vertical line segment red.

2 The
terms command, line and instruction are used interchangeably.
3 The
weg page docs.python.org/3/library/turtle.html contains an overview of available
commands in Python Turtle.

7
1.5 Drawing with Coordinates
118
Code

1 from turtle import *


2 shape('turtle')
3 penup()
4 goto(100, 0)
5 pendown()
6 goto(0, 100)

Tom understands the instructions goto , penup() and pendown() .


a) Read the code above, and guess the result.
b) Write the code, and run the program.
When we want to test what happens if we remove a line of code, we can use a
comment, like #penup() , instead of deleting the whole line.
c) Examine what happens if the line penup() is removed from the code.
Do this by changing the line to #penup() .
d) Change #penup() back to penup() . Let penup() and pendown()
switch lines. Remember to always guess the result, before you rerun the
program.
e) Add the line goto(-100, 0) to the bottom of the code.
f) Complete the code to produce figure 1.10.

Figure 1.10: A rhombus.

g) Add more goto -commands to draw figure 1.11.

Figure 1.11: A rhombus in a square.

8
1. The First Instructions

1.6 Circles and Fillcolors


119
Code Recipe

1 from turtle import * Create the turtle


2 shape('turtle') Set the shape to turtle
3 fillcolor('red') Select red fillcolor
4 begin_fill() Begin the paint job
5 circle(50) Draw a circle with radius 50
6 end_fill() Finish the paint job

Tom can draw circles and fill figures with colors.


a) Read the code above, and then read the recipe. Guess the result.
b) Write the code, and run it. Change the fillcolor to light blue. That is,
change line 3 to fillcolor('lightblue') .
c) Switch the number tallet 50 with other numbers like 120 and 300. Ex-
amine what happens if you try a negative number, for example −120.

d) Change the circle-command back to circle(50) , and add the following


code on the bottom of the program:

fillcolor('yellow')
begin_fill()
circle(90)
end_fill()

Note: Did you remember to guess the result before you ran the program?
e) Let the colors 'yellow' and 'lightblue' switch lines.
f) Switch the numbers 50 and 90. What is the result of this?
g) Draw an eye similar to figure 1.12. Use the colors 'lightgray' , 'lightblue'
and 'black' .

Figure 1.12: The all-seeing eye.

9
1.7 Summary of Chapter 1

Python English

from turtle import * Import turtle-commands


forward(150) Move 150 steps forward
backward(40) Move 40 steps backwards
left(60) Turn 60 degrees left
right(70) Turn 70 degrees right
circle(120) Circle with radius 120
shape('turtle') Set the shape to a turtle
penup() Pen up
pendown() Pen down
hideturtle() Hide the turtle
goto(40, 80) Go to the point (40, 80)
speed(8) Set the speed to 8
color('yellow') Set yellow color
fillcolor('blue') Set blue fillcolor
begin_fill() Begin fillcolor
end_fill() End fillcolor

Tabell 1.1: Dictionary for chapter 1.

To fill figures with a color, you must first set a fillcolor. For example: Write
fillcolor('brown') , then follow these three steps:

1) Write the line begin_fill() .


2) Draw a closed figure. For example a circle, a triangle, or a rectangle.
3) End the code with the line end_fill() .

Note

Every program with Python Turtle needs to begin with


from turtle import * .

10
1. The First Instructions

1.8 Exercises

1.8.1 Correct Order


119
forward(200) forward(200)
shape('turtle') left(45)
from turtle import *
Figure 1.13: An angle.

Draw figure 1.13. Do this by ordering the lines above correctly.

1.8.2 Correct the Mistakes


119
Code

1 from turtle import *


2 shape(turtle)
3 Forward(300)
4 left[-180]
5 forwrad 300

Write the code above, and run the program. You will get at least one error
message. Keep correcting the mistakes until the program runs without error
messages.

1.8.3 Zorro
120

Figure 1.14: Zorro. Fencing champion and nobleman.

Write code to draw the Zorro-mark Z. Use the color color('gold') .


Write pensize(8) to increase the thickness of the lines.

11
1.8.4 Follow the Recipe
120
Recipe

Create the turtle


Go 150 steps forward
Turn 120 degrees left
Go 150 steps forward
Turn 120 degrees left
Go 150 steps forward
Turn 120 degrees left
Turn 60 degrees right
Draw a circle with radius 87

Follow the recipe above, and translate to Python-code. What is the resulting
figure?

1.8.5 Parallelogram
120

60°

Figure 1.15: Parallelogram.

Draw a parallelogram. See figure 1.15. A parallelogram consists of two pairs


of sides which are parallel and equal in length.

1.8.6 Two Squares and a Circle


?

Figure 1.16: A circle between two squares.

Write code to draw figure 1.16. Use the colors 'red' , 'gold' and 'black' .

12
CHAPTER 2
Repetitions and Patterns

Figure 2.1: A railroad: repeating pattern.

2.1 Two repetitions


121
Code

1 from turtle import *


2 shape('turtle')
3
4 for i in range(2):
5 circle(50)
6 forward(100)

The code above uses a for-loop. We use for-loops when we want Python to
repeat instructions.

a) Read the code, and guess the result.


b) Write the code, and run the program. Notice that the command circle(50)
is indented inward. Press either Tab once or Space twice, before you
write circle(50) . Did you receive an error message when you ran the
program? Check the list of usual mistakes on the next page.

13
Correct Wrong

for i in range(2): for i in range(2):


circle(50) circle(50)
forward(100) forward(100)

Wrong

for i in range(2)
circle(50)
forward(100)

You will now be asked to make some small changes to your program. Remem-
ber to always guess the result after each small change, before you rerun the
program.
c) Add the line speed(7) directly below shape('turtle') .
d) Indent the command forward(100) inward like this:

for i in range(2):
circle(50)
forward(100)

e) Let the commands circle(50) and forward(100) swap places.


f) Add the command circle(25) in the beginning of the for-loop like this:

for i in range(2):
circle(25)
forward(100)
circle(50)

g) Change the order of the lines inside the for-loop to produce figure 2.2.

Figure 2.2: Big and small circles.

14
2. Repetitions and Patterns

2.2 Three or More Repetitions


121
Code Recipe

1 from turtle import * Create the turtle


2 shape('turtle') Set the shape to a turtle
3
4 for i in range(3): Repeat three times:
5 forward(150) Walk 150 steps forward
6 backward(150) Walk 150 steps backward
7 left(25) Turn 25 degrees left

a) Read the code above, and guess the result.


b) Write the code, and run the program.

A gentle reminder: Always guess the result of each small change to the code.

c) Add the line speed(6) above the for-loop.


d) Change range(3) to range(6) .
e) Change left(25) to left(45) .
f) Change the number of repetitions in order to produce figure 2.3a.
g) Add code below the for-loop to draw figure 2.3b. The commands circle(150) ,
forward(150) and left(90) may be useful.

(a) Without a circle. (b) With a circle.

Figure 2.3: A pizza.

15
2.3 Angles and Regular Polygons
121
Code

1 from turtle import *


2 shape('turtle')
3 speed(5)
4
5 for i in range(3):
6 forward(100)
7 left(120)

a) Read the code above, and guess the result.

The algorithm above can be illustrated with a flowchart. See figure 2.5 on
page 17.
b) Write the code, and run the program.
c) Let lines 6 and 7 swap places. What happens?
d) Draw a square by changing the numbers 3 and 120.

Figure 2.4: A hexagon.

e) Change the numbers in the commands left and range to produce


figure 2.4 (a hexagon).

Number of sides Angle size

3 120
4 90
6 60

Tabell 2.1: Number of sides versus angle size.

f) Use the pattern shown in table 2.1 to draw a 18-sided polygon.1 Increase
the drawing speed by writing speed(9) . Set the side length to 50.
1 Tip:
The product is always 360°. For a rectangle we have 4 · 90 = 360 and for
a hexagon 6 · 60 = 360, and so on.

16
2. Repetitions and Patterns

Flowchart

Walk 100
Start Turn 120 degrees
steps forward

no

Triangle yes
Stop
done?

Figure 2.5: Flowchart for a for-loop. Equilateral triangle.

The use of a flowchart is a good way to visualize the flow of the code. It
can improve our understanding of the code. A flowchart can also help
us communicate the code that we have created to others.

2.4 Staircase Up and Staircase Down


122
Code

1 from turtle import *


2 shape('turtle')
3 speed(5)
4
5 for i in range(5):
6 forward(25)
7 right(60)
8 forward(25)
9 left(60)

The code above is our first attempt to draw a staircase.


a) Read the code above, and guess the result. Is the staircase moving
upward or downward?
b) Write the code, and run the program.
c) Edit the code to produce 90-degree angles.

17
d) Change the for-loop such that it only repeats once. Do this by changing
range(5) to range(1) . This will help you understand exactly what is
being repeated.

Height

Depth

Figure 2.6: Stairs down.

e) Change back to range(5) . Write code such that the depth of a stair is
twice that of the height of a stair. See figure 2.6.
f) Change the code such that the stairway is moving upward instead of
downward.

Recipe

Draw staircase moving upward


Move a few steps forward
Draw staircase moving downward

g) Finish the code to draw figure 2.7. The recipe above shows how you can
split this problem into three parts.

Figure 2.7: Stairs up and stairs down.

18
2. Repetitions and Patterns

2.5 Experimenting with a For-loop

Figure 2.8: Experimenting with a for-loop.

Now you have your chance to experiment with a for-loop and see what kind of
art you are able to create. When you change the command forward(50) to
forward(i) , many things can happen. Figure 2.8 is an example of this. Use
the code below as inspiration, write your own code and save your artwork as
a desktop background.

Code Recipe

1 from turtle import * Walk 0 steps forward


2 shape('turtle') Turn 89 degrees left
3 speed(0) Walk 1 step forward
4 Turn 89 degrees left
5 for i in range(200): Walk 2 steps forward
6 forward(i) Turn 89 degrees left
7 left(89) ...

The two final instructions are “walk 199 steps forward” and “turn 89 degrees
left”.

19
2.6 Summary of Chapter 2

Python English

for i in range(3): Repeat 3 times


for i in range(25): Repeat 25 times

Tabell 2.2: Dictionary for chapter 2.

Here is an example of how we make a for-loop repeat something 6 times:

1 from turtle import *


2
3 for i in range(6):
4 circle(20)
5 forward(40)
6 circle(20)

The result of the code is figure 2.9.

Figure 2.9: Seven circles.

An overview of available commands for Python Turtle is listed on the web page
docs.python.org/3/library/turtle.html.

Note

Only indented lines of code will be repeated in a for-loop. The two


pieces of code below do exactly the same thing.

for i in range(2): forward(50)


forward(50) left(75)
left(75) forward(50)
forward(100) left(75)
forward(100)

20
2. Repetitions and Patterns

2.7 Exercises

2.7.1 Draw a Square


122
Code

1 from turtle import *


2
3 for i range(4)
4 forward('100')
5 left(90)

Write the code above, and run the program. Correct the mistakes such that
the result is a square.

2.7.2 Draw a Rectangle with a For-loop


122

100
200
Figure 2.10: Rectangle.

Draw a rectangle with length 200 and width 100. See figure 2.10.

2.7.3 A Secret Figure


123
Recipe

Repeat 8 times:
Turn 45 degrees left
Walk 50 steps forward
Turn 90 degrees right
Walk 50 steps forward

Translate the recipe above to Python-code. What is the resulting figure?

21
2.7.4 Cones with Icecream
123

left(36) from turtle import *


hideturtle() speed(9)
circle(26) for i in range(10):
forward(80) backward(80)

Figure 2.11: Icecream cones.

Write a program which draws figure 2.11. Do this by writing the lines above
in the correct order.

2.7.5 The Railroad


?

Figure 2.12: A railroad with colors.

Draw figure 2.12. In addition to for-loops, here are some commands you might
find useful:
fillcolor('brown') penup() pendown()
begin_fill() end_fill()

22
CHAPTER 3
Storing Code in Functions
3.1 My smile
123
Code

1 from turtle import *


2
3 # Set direction upward
4 setheading(90)
5 # Draw a half-circle
6 circle(50, 180)

Figure 3.1: A smiling lady.

The code above is an attempt to draw a smile.


a) Read the code above, and guess the result.
b) Write the code, and run the program. Can you explain the result?
c) Change the number 90 to other numbers like 0, 180, −45 or 270.
d) Change the number in the command setheading such that the program
produces a smile.

When we are satisfied with our smile, we can store it as a function like this:

1 from turtle import *


2
3 # Store the function smile
4 def smile():
5 setheading(-90) # Set heading downward (south)
6 circle(50, 180) # Draw a half-circle with radius 50
7
8 # Smile once
9 smile()
10 # Smile once more
11 smile()

23
e) Write the code above, and run the program.
f) Add two new lines with the command smil() . Finish with the line
home() . Guess the result, before you run the program.

1 from turtle import *


2
3 # Recipe of a smile
4 def smile():
5 setheading(-90) # Set heading downwards (south)
6 circle(50, 180) # Draw a half-circle with radius 50
7
8 def pout():
9 setheading(90) # Set heading upward (north)
10 circle(50, 180)
11
12 smile()
13 pout()
14 pout()
15 pout()

We expand the program with a function to draw a pout.

g) Add the new code above to your program. Guess the result, then run
the program.
h) Change the order of the instructions on line 12 to 15 to produce figure 3.2.

Figure 3.2: A smile and pouts. Figure 3.3: An awning.

i) Draw an awning as depicted in figure 3.3. Below are some commands


which may be of use.
forward left backward
right smile() pout()

24
3. Storing Code in Functions

3.2 Cogwheel and Squares


124

Figure 3.4: A cogwheel. Used in a mechanical watch.

We are going to create a program to draw a cogwheel.

a) Read the code below, and guess the result.

Code Recipe

1 from turtle import * Draw a square


2 Walk 100 steps backward
3 def square(): Draw a square
4 for i in range(4):
5 forward(50)
6 left(90)
7
8 square()
9 backward(100)
10 square()

b) Write the code, and run the program.


c) Let the lines 8 and 9 swap places. Run the program.

25
d) Use the code below as a starting point to draw figure 3.5. Change the
order of the commands square() , left(45) and forward(120) to ac-
complish this.

Code

1 from turtle import *


2 speed(9)
3
4 def square():
5 for i in range(4):
6 forward(50)
7 left(90)
8
9 square()
10 forward(120)
11 square() Figure 3.5: A part of a cogwheel.
12 left(45)
13 left(45)
14 square()
15 forward(120)

e) Write code to complete the cogwheel. See figure 3.6a.


Tip: Consider which instructions are repeated. Use a for-loop to repeat
these instructions.

(a) Teeth facing inward. (b) Teeth facing outward.

Figure 3.6: Cogwheels.

f) Finally, change the code such that the cogwheel’s teeth face outward.
See figure 3.6b.

26
3. Storing Code in Functions

3.3 Varying the Size of Squares


124
Code Recipe

1 from turtle import * Draw a square with side 50


2 speed(7) Draw a square with side 60
3 Draw a square with side 70
4 def square(side):
5 for i in range(4):
6 forward(side)
7 left(90)
8
9 square(50)
10 square(60)
11 square(70)

When we define a function such as def square(side) , we call side a param-


eter.
a) Read the code above, and guess the result.
b) Write the code, and run the program.
c) Add the commands square(150) and square(-150) at the bottom of
the program. What happens?
d) Change the code to produce figure 3.7a, where the smallest square has
side 50.

(a) Three squares. (b) Four squares – growing.

Figure 3.7: Two square-patterns.

e) Finish your code to produce the four squares in figure 3.7b. You may
also need the commands forward or backward .

27
3.4 Tunnel in 3D
125
Code

1 from turtle import *


2 speed(0)
3
4 def square(side):
5 for i in range(4):
6 forward(side)
7 left(90)
8
9 sidelength = 200 # Side length starts at 200
10 while True:
11 square(sidelength)
12 sidelength -= 10 # Decrement side length by 10

We create a variable for the side length, and we assign it the value 200 by
writing sidelength = 200 . To create a loop which repeats forever, we can
write while True: .
a) Read the code above, and guess the result.
b) Write the code, and run the program.
c) Change the line while True: to while sidelength > 50: . This pro-
gram can be visualized by the flowchart drawn in figure 3.8.
d) Change the line sidelength -= 10 to sidelength -= 50 . Guess the
result before you run the program.

Decrement
Start Draw the square
side by 10

yes

no
Set side to 200 Is side > 50 ? Stop

Figure 3.8: Flowchart while-loop. Decreasing squares.

28
3. Storing Code in Functions

Code

sidelength = 200 # The side length starts at 200


while sidelength > 10:
square(sidelength)
change = sidelength * 0.09
sidelength -= change

The code above results in the variable sidelength decreasing by 9 % per


repetition.1

e) Change the while-loop as shown in the code above. Guess the result,
before you run the program.
f) Change the number 0.09 to 0.25, and then to 0.03. Rerun the program
after each change.
g) Add the following three lines of code inside the while-loop. Place them
in the correct order to produce figure 3.9a.

forward(change * 2) setheading(0)
setheading(45)

h) Change the command forward(change * 2) such that the result is fig-


ure 3.9b. Do this by replacing the number 2 with other numbers.

(a) Tunnel. A bird’s-eye view. (b) Tunnel. Ground perspective.

Figure 3.9: Tunnels.

1 To reduce the value of a variable by 9 %, you can also write sidelength *= 0.91.

29
3.5 Triangle-pattern with Midpoints
125
Code

1 from turtle import *


2 speed(9)
3
4 def triangle(side):
5 for i in range(3):
6 forward(side)
7 left(120)
8
9 length = 300
10 triangle(length)
11 length /= 2 # Halve the length
Figure 3.10: Equilateral triangles.
12 left(60)
13 triangle(length)

a) Read the code above, and guess the result.


b) Write the code, and run the program.
c) Add the command forward(length) on the correct line to produce fig-
ure 3.10.

The triangle-pattern continues in such a way that the corners of a new triangle
are the midpoints of the sides in the previous triangle.

d) Add code to draw the first three triangles.


e) Use a for-loop to draw the first seven triangles in this pattern. The result
should look like figure 3.11.

Figure 3.11: Triangle-pattern with midpoints.

30
3. Storing Code in Functions

3.6 Summary of Chapter 3

Python English

def Define a function


def square(): Define a function with the name square
square() Run the square-function
def square(side): Define a square-function with side as
a parameter
def square(side, color): Define a square-function with side and
color as parameters
circle(50, 90) Draw a quarter circle with radius 50
circle(50, 180) Draw a half circle with radius 50
while side > 10: Repeat as long as side is greater than 10

Tabell 3.1: Dictionary of chapter 3.

Here is an example of how to create a function with more than one parameter:

def smile(radius, my_color):


color(my_color)
setheading(-90)
circle(radius, 180)

smile(100, 'blue')

Note

Only indented lines become part of the function.

def smile():
setheading(-90) # Inside of the function
circle(50, 180) # Outside of the function

31
3.7 Exercises

3.7.1 A Function to Draw the Letter T


126
Code

1 from turtle import *


2 speed(1) # Low speed to see each instruction better
3
4 def draw_T():
5 forward(100)
6 backward(30)
7 right(70)
8 forward(150)
9
10 # Draw T by calling on the function
11 draw_T()

Write the code above, and run the program. Change the code to produce the
letter T.

3.7.2 Polygon-function
126
Code

1 from turtle import *


2 speed(8)
3
4 df polygon("edges")
5 angle = 360 / edges
6 for i in range(edges):
7 forward(40)
8 left(angle)
9
10 polygon(8) Figure 3.12: An octagon.

Write the code above, and run the program. Correct all mistakes, and finish
the code in order to produce figure 3.12.

32
3. Storing Code in Functions

3.7.3 A heart
126

Figure 3.13: A pink heart.

Write a function which draws a pink heart. See figure 3.13. You may need the
following lines of code:

circle(100, 90) circle(50, 180)

3.7.4 Eye Monster


127
Code

1 from turtle import *


2 speed(9)
3
4 def eyemonster():
5 circle(25)
6 fillcolor('gray')
7 begin_fill()
8 circle(15)
9 end_fill()
10 fillcolor('black')
11 begin_fill()
12 circle(10)
Figure 3.14: A monster with four eyes.
13 end_fill()
14
15 eyemonster()

Use the code above as a starting point, then finish the code to draw figure 3.14.

33
3.7.5 Chessboard – The First Three Squares
127
Code

1 from turtle import *


2
3 # TODO: complete the
,→ function
4 def square(color):
5 fillcolor(color)
6 # Draw the square
7 # Color the square Figure 3.15: Three squares.
8
9 # Test the function
10 square('brown')

Write a program which draws the first three squares of a chessboard. Use the
code above as a starting point. Set the side length of the square to 50. See
figure 3.15.

3.7.6 Chessboard
?

Figure 3.16: A chessboard.

Write a program to draw a chessboard similar to figure 3.16.

Tip: Begin with the first row. Create new functions if you need, for example
draw_even_row and draw_odd_row .

34
CHAPTER 4
More Possibilities
4.1 A Wheel with Triangles
128
Code Recipe

1 from turtle import * Store position as point A


2 speed(9) Walk 80 steps forward
3 Turn 45 degrees left
4 A = pos() Walk 80 steps forward
5 forward(80) Go to point A
6 left(45)
7 forward(80)
8 goto(A)

The command A = pos() stores the position of the turtle in the variable A .
a) Read the code above, and guess the result.
b) Write the code, and run the program.
c) Change the command left(45) by trying other numbers, for example
30, 140 and 270. Are you able to find several numbers which produce
right-angled triangles?1

Figure 4.1: A wheel with triangles.

1A right-angled triangle: A triangle where one of the angles is 90°.

35
Some numbers in the command left will result in not getting a triangle. Can
you find these numbers?

d) Add the line side = 80 directly below A = pos() . Change both forward -
commands to forward(side) . Run the program.
e) Change the value of the variable side by writing for example side = 40
or side = 150 . Try negative values, too. Do they work? Always guess
the result, before you run the program.
f) Write a for-loop to repeat the drawing of the triangle several times. Begin
like this:

side = 80
for i in range(3):
A = pos()
forward(side)
left(45)
# And so on

g) Change the command range(3) such that the triangles make a whole
round.
h) Add the line side = side * 0.9 at the bottom of the for-loop.2 Change
to 30 repetitions. To explore this further, try numbers other than 0.9.
i) Add the line forward(side) at the bottom of the for-loop. Guess how
this will change the result. Run the program.
j) Draw figure 4.1. Here are some commands you may find useful:

circle penup() fillcolor('brown')


pendown() begin_fill() fillcolor('gold')
end_fill()

2 The code side = side * 0.9 can also be written like this: side *= 0.9.

36
4. More Possibilities

4.2 Random Angles


129
Code

1 from turtle import *


2 from random import randint
3 speed(2)
4
5 angle_v = randint(10, 100) u =?
6 print(angle_v) v = 55°
7 forward(100)
8 backward(100) Figure 4.2: Supplementary angles.
9 left(angle_v)
10 forward(100)

The result of the command randint(10, 100) is a random integer from 10 to


100, both included.3
a) Read the code above, and guess the result.
b) Write the code, and run the program 5 times.
c) Change the command randint(10, 100) to randint(90, 135) .
d) Change the command randint to randint(20, 130) .
e) Add the following lines of code in the correct order to produce figure 4.2.

print(angle_u) left(angle_u)
forward(100) backward(100)
angle_u = 180 - angle_v

Run the program several times. Notice the output. It may look like this:

75
105

What is the relationship between these two angles? That is, what is their
sum?4

3 The word randint is short for “random integer”.


4 Euclid, Euclids Elements [2]

37
4.3 The Circumscribed Circle of a Triangle
129
Code

1 from turtle import * C B


2 from random import randint
3
4 shape('circle')
5 u = randint(0, 180)
6 print(u)
7 A = pos()
8
9 circle(100, u)
A
10 B = pos()
11 stamp() Figure 4.3: The circumscribed circle.

The command circle(100, u) draws an arc with radius 100 and angle u.
a) Read the code above, and guess the result.
b) Write the code, and run the program.
c) Create a new random angle v in the same way we created angle u. Use
the print -command to see the value of the angle v.
d) Draw a new arc in the same way we drew the first arc, but the size of
the angle is now v. Add the line C = pos() to store the position and
add the line stamp() to mark the point.
e) Draw the final arc, such that you end up at the same point where the
drawing began. Tip: The angle is 360 − u − v.
f) Finish the code to draw the triangle inside the circle. See figure 4.3. The
command goto(B) may be useful here.

Figure 4.4: The circumcircle in architecture.

38
4. More Possibilities

4.4 Bullseye
130

Figure 4.5: Archery and bullseye.

We are going to do draw a bullseye as shown in figure 4.5.

a) Read the code below, and guess the result.

Code

1 from turtle import *


2
3 radius = 50
4 increase = 25
5 circle(radius)
6 radius += increase
7 circle(radius)

b) Write the code, and run the program. Are we on the right track?

Between each circle we need to move a bit downwards. This distance is marked
on figure 4.6.

distance
Figure 4.6: Bullseye. Distance between circles.

39
# Draw the first circle # Draw the first circle
distance = 15 distance = 15
right(90) sety(ycor() - distance)
forward(distance) # Draw the second circle
left(90)
# Draw the second circle

Above you see two options to code this distance. The value of distance is
not entirely correct, but we will correct this later.

c) Choose one of the two options above, and write the code. This code
should be placed before you draw the second circle.
d) Expand the program such that it draws three circles. Change the com-
mand avstand = 15 such that the distance between the circles looks
about right.
e) Is it strictly necessary to use the variable distance ? Could you have
produced the same result by only using the variables radius and increase ?
Try it!
f) Use a for-loop to draw the five circles. Use the following code as a starting
point:

for i in range(5):
circle(radius)
radius += increase
# TODO: Lift the pen up
# TODO: Move downwards
# TODO: Set the pen down

g) Finish the code to color the bullseye as shown on figure 4.5. We see that
the colors are yellow, red, blue, black and gray. We can change the for-
loop such that it repeats itself for each of these colors. Use the following
code as a starting point:

for color in ['yellow', 'red', 'blue', 'black', 'gray']:


fillcolor(color)
begin_fill()
# TODO: Draw a circle
end_fill()
# TODO: Lift the pen up, and so on ...

40
4. More Possibilities

4.5 Distance Alarm


130

Figure 4.7: Little John exploring the outdoors..

Maria has installed GPS-tracking on her son, Little John. The GPS-signals
transmit to an app on her mobile phone. We will code a simplified simulation
of how this might work.

a) Read the code below, and guess the result.

Code Recipe

1 from time import sleep Sett shape to a circle


2 from turtle import * Set speed to 1
3 from random import randint Repeat 5 times:
4 shape('circle') Walk 30 steps forward
5 speed(1) Sleep 1 second
6
7 for i in range(5):
8 forward(30)
9 sleep(1)

b) Write the code, and run the program.


c) Change sleep(1) to sleep(2) . Explore the sleep -command further
by trying more numbers, such as 4 or 0.5.
d) Change sleep to sleep(randint(0, 3)) . What happens?

Little John is not allowed to move farther from home than 140 steps. If this
should occur, mom will receive a message on her mobile phone. We presume
Maria will call on her son, and that he will always come home whenever she
calls on him.

41
Code Recipe

print(distance(home)) Print the distance home


if distance(home) > 140 : If distance is greater than
print('Come home!') ,→ 140:
home() Print “Come home!”
break John walks home
Cancel the for-loop

e) Write the code above, and place it at the end of the for-loop. Run the
program.

Maria would like a mild warning whenever Little John is more than 80 steps
away from home. To accomplish this, we write the following code:

if distance(home) > 140:


print('Come home!')
home()
break
elif distance(home) > 80:
print('Mild warning')
Figure 4.8: Color zones.

The word elif is short for “else if”.

f) Read the code above, and guess the result.


g) Add the new code, and run the program.
h) Add the command left(randint(0, 359)) directly above the forward -
command. Guess the result, then run the program.

Little John usually walks more than just 5 steps. By writing while True: ,
we can create a loop which repeats forever.

i) Change for i in range(5): to while True: .


Maria wants the app to change color depending on how far away from home
John is.

j) Finish the program such that the background color changes depending
on Johns distance from home. You need to use the command
Screen().bgcolor('red') , among others. See figure 4.8.

42
4. More Possibilities

4.6 Summary of Chapter 4

Python English

print(distance(home)) Print the distance from turtle to (0, 0)


print('Come home!') Print the text “Come home!”
home() Go home and set heading toward the right
Screen().bgcolor('yellow') Set the background color to yellow
stamp() Stamp the current shape of the turtle
sleep(2) Sleep 2 seconds
from time import sleep Required in order to use the command sleep
randint(2, 4) Produce a random integer from 2 to 4
from random import randint Required in order to use the command randint
while True: A loop with infinite repetitions
break Cancels a loop
ycor() Turtle’s y-coordinate
sety(50) Set the y-coordinate to 50
pos() Give Turtle’s position
radius = 50 Store 50 in the variable radius
radius += 30 Increment radius by 30
if if
elif else if
else else

Tabell 4.1: Dictionary of chapter 4.

Here is an example of how you can control the code with if and else :

if ycor() > 300: # If y is greater than 300


home()
elif ycor() >= 200: # Else if y is greater than or equal to 200
forward(25)
else: # Else: Here else means y less than 200
forward(50)

43
4.7 Exercises

4.7.1 Scaling with a Variable


131

Figure 4.9: Two colored circles.

Write a program which draws figure 4.9. Do this by placing the commands
below in the correct order.
forward(radius * 3) from turtle import *
radius = 100 penup()
dot(radius, 'blue') dot(radius * 2, 'brown')

4.7.2 Volume-symbol
131
Code

1 from turtle import *


2
3 width(5)
4 radius = 30
5
6 for i in range(8):
7 penup()
8 circle(radius, 30)
9 pendown()
10 circle(radius, 120)
11 penup()
12 circle(radius, -150)
13 # TODO: change the radius
14 sety(ycor() - 15) Figure 4.10: Volume-symbol.

Write the code, and run the program. Write code on line 13 such that the
program produces figure 4.10.

44
4. More Possibilities

4.7.3 One Circle and 100 Chords


131
Recipe

Set maximum drawing speed


Draw a circle with radius 100
Repeat 100 times:
Draw an arc with a random angle (0-180)
Store the position as A
Draw an arc with a random angle (0-180)
Store the position as B
Go to point A
Go to point B

A chord is a line segment between two points on a circle. Write a program


which draws 100 chords in a circle. See figure 4.11. Use the recipe above as a
starting point. You will also need the following commands:

circle(100, randint(0, 180))


from random import randint
B = pos()
goto(A)

Figure 4.11: 100 chords.

4.7.4 A watch
132

Figure 4.12: A watch. Figure 4.13: A watch drawn with


Python.

Draw a watch similar to figure 4.13.

45
4.7.5 Treasure Hunting with a Compass
?
Code

1 from turtle import *


2 from random import randint
3 from time import sleep
4 shape('turtle')
5 penup()
6
7 # Place the treasure on a random spot
8 goto(randint(-200, 200), randint(-150, 150))
9 dot(20, 'gold')
10 treasure = pos()
11 home()
12 pendown()
13
14 # The treasure hunt begins
15 print(distance(treasure)) # Distance to the treasure
16 print(towards(treasure)) # Direction to the treasure
17
18 while distance(treasure) > 20:
19 heading_treasure = towards(treasure)
20
21 if heading_treasure > -45 and heading_treasure <= 45:
22 setheading(0) # Set direction east
23 elif heading_treasure > 45 and heading_treasure <= 135:
24 setheading(90) # Set direction north
25 # TODO: Add more directions
26 forward(20)
27 sleep(1)
28
29 print('Treasure found!')

Use the code above as a starting point. Finish


the code such that the turtle always finds the
treasure. The turtle is only allowed to move
in one of the four directions north, south, east
or west.

Figure 4.14: A compass.

46
CHAPTER 5
Mathematics in Python
5.1 Add, Subtract, Multiply and Divide

Figure 5.1: The console on replit.com.

We’re going to have a live chat about mathematics with the computer. We will
need to speak the language Python. We will call the computer by the name
Jerry1 .

a) First, open the web page replit.com/new/python3.

The console is located in the black area of the screen. See figure 5.1.

b) Go to the console, and write your first message to Jerry. For example,
try writing Hello, Jerry . Press Enter to send the message. Jerry
will reply to you immediately.

Hello, Jerry
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Hello' is not defined

Notice that Jerry is telling us that “Hello” is not defined, and he calls
the error a NameError .

1 Jerry is inspired by the American science fiction thriller Sphere.

47
c) Write the message 'Hello, Jerry' with the single quotation marks.
What happens?
d) Ask Jerry to calculate 3 + 5 by writing 3+5 . If you did this correctly,
your console should look like this:

3+5
8

e) Write these three messages to Jerry: 3-5 , 3*5 and 3/5 . Re-
member to press Enter after each message. If you did this correctly, your
console should look like this:

3-5
-2
3*5
15
3/5
0.6

Note that 3/5 betyr 3 ÷ 5 = 0.6.


f) Press clear on the top right of the console to delete the content.
g) Ask Jerry to complete the three calculations below.

2·3−6 10 ÷ 5 + 12 1/2 + 3/2

After you are done, check your answers against the solution below.

2*3-6
0
10/5+12
14.0
1/2+3/2
2.0

48
5. Mathematics in Python

5.2 Powers and Parentheses

2**2 22 = 4
4
2**3
8 23 = 8
2**4
16
24 = 16

Above you can see how we tell Jerry to calculate powers, such as 24 .
a) Use the console (the black area), and write the following three messages
to Jerry: 2**2 , 2**3 and 2**4 . You should get results equal
to those shown above.
b) Use the console to calculate 34 . You should get 81.
c) Write (3-5)**2+3 to calculate (3 − 5)2 + 3. You should get 7.
2
d) Calculate (1/5) by writing (1/5)**2 . This should yield the following
result:

(1/5)**2
0.04000000000000001

e) Calculate (5 − 2 · 3)4 . You should get 1.

5.3 Square Root

from math import sqrt √


sqrt(4) 4=2
2
sqrt(9) √
9=3
3

Jerry can calculate square roots when we use the command sqrt 2

a) Go to the console and write from math import sqrt .

2 The word sqrt is short for “square root”.

49

b) Calculate 4 by writing sqrt(4) .

c) Calculate 9 by writing sqrt(9) .

d) Calculate the following:

√ √
16 5− 25

√ p
10 1/4

5.4 Some Algebra

a=3
a
3
a+2
5

The console above shows how we can store values in variables.


a) Write the three expressions (messages) a=3 , a and a+2 . The
result should be as shown above.
b) Write a=-2 and then a+2 . Guess the result, before you press
Enter .

c) Write b=5 and then a+b . Guess the result, before you press Enter .

Note: If you clear the console by pressing clear , Jerry will forget the
variables a and b.

d) Calculate 3b − 2a by writing 3*b-2*a .

e) Calculate 3b − 2a, but first set a = 5 and b = −3. You should get −19.

50
5. Mathematics in Python

5.5 Variables and Rounding

Figure 5.2: Red apples.

Below you see an example of using variables in a practical problem.

Apples cost 1.10 $/lb. unitprice = 1.10


How much does 2.7 lb of apples pounds = 2.7
cost? price = unitprice * pounds
price
2.9700000000000006

a) Write the four messages above in the console.


b) Write round(price) . What happens?

c) Write round(price,3) . What happens? Try numbers other than 3.

Suppose the price the next day increases to 1.24 $/lb. Continue working in the
same concole. Don’t clear the console!
d) Now calculate the new price for 2.7 lb of apples. Write the following in
the console. Remember to press Enter after each command.

unitprice = 1.24
price = unitprice * pounds
price
3.3480000000000003

e) Add the message round(price,2) . Guess the result, before you press
Enter .

51
5.6 A Polite Greeting
132
Code

1 print('Hello! What is your name?')


2 name = input() # Let the user type in his name
3 print('Hello, Mr. X')

Note: We have left the console (the black area) and are now writing the code
in the white area again, just like we did in the first four chapters.

a) Read the code above, and guess the result.


b) Write the code on the web page replit.com/new/python3, and run the
program.3 When you run the program, it will wait for you to write your
name in the console. Write your name, then press Enter .
c) Change print('Hello, Mr. X') to print(f'Hello, Mr. {navn}') .

Not everyone identifies with the title Mister. We will therefore let the user tell
us his sex, in addition to his name.

d) Add the line sex = input('What is your sex? (male/female): ')


directly below navn = input() .

If the user answers “Hanan” and then “female”, then the output should look
like this:

Hello! What is your name?


Hanan
What is your sex? (male/female): female
Hello, Ms. Hanan

e) Add the following lines of code such that the result of the program looks
like the output above, assuming the user answered “Hanan” followed by
“female”:
print(f'Hello, Ms. {navn}') if sex == 'female':

f) Expand the program such that the output will be Hello, Mr. Armstrong ,
if the user answers “Armstrong” and then “male”.

3 We are now using Python 3, not Python Turtle.

52
5. Mathematics in Python

5.7 Calculator Program


133
Code

1 numberA = input('Enter a number: ')


2 numberB = input('Enter a number: ')
3 thesum = numberA + numberB
4 print(f'{numberA} + {numberB} = {thesum}')

a) Read the code above, and guess the result. Note that we use the variable
name thesum , because sum is a built-in Python-function and should
therefore be avoided as a variable name.
b) Write the code on the web page replit.com/new/python3, and run the
program.

To convert a string (text) to a whole number, we use the command int .4


c) Change lines 1 and 2 as shown below.

1 numberA = int(input('Enter a number: '))


2 numberB = int(input('Enter a number: '))

To subtract, multiply and divide we use - , * or / respectively.


d) Change the program such that it calculates the product. Hence, use *
instead of + .
e) Rerun the program, and try to write in decimal numbers. For example
2.35 or 0.72.
We use the command float to convert to a decimal number.
f) Change the lines with input as shown below. Run the program, then
enter a decimal number such as 3.59 or 10.234.

numberA = float(input('Enter a number: '))


numberB = float(input('Enter a number: '))

g) Add the line quotient = numberA / numberB to calculate the quotient.


Run the program. Try to enter 0 as a value for numberB . What happens?
4 The word int is short for “integer”.

53
5.8 The Multiplication Master
133
Code

1 numberA = 3
2 numberB = 4
3 answer = numberA * numberB
4 print(f'{numberA} * {numberB} = {answer}')

a) Read the code above, and guess the result.


b) Write the code, and run the program.

Let’s assign a random value to numberA .

c) Change the code as shown below.

1 from random import randint


2 # Generate a random integer between 0 and 10
3 numberA = randint(0, 10)
4 numberB = 4
5 answer = numberA * numberB
6 print(f'{numberA} * {numberB} = {answer}')

Run the program three times.

d) Change the last four lines in the code like this:

answer = numberA * numberB


print(f'{numberA} * {numberB} =')
user_answer = int(input('Your answer: '))
print(f'The correct answer is {answer}')

Run the program twice.

54
5. Mathematics in Python

Assign random
Start values to numberA Calculate answer
and numberB

Print Input:
Corrrect
“Wrong user
no answer?
answer” answer

yes

Print
Stop “Correct
answer”
Figure 5.3: Flowchart: random product.

Let’s check if the user provides a correct answer or not, and give feedback. A
flowchart of the program we wish to code, is shown in figure 5.3.

e) Change the program as shown in the flowchart in figure 5.3. You may
need the commands if user_answer == answer: and else: .
f) Create a for-loop which repeats the instructions in e) 10 times. Begin
like this:

for i in range(10):
numberA = randint(0, 10)
# And so on ...

Remember: All code which belongs to the for-loop must be indented.


If you forgot to indent the code, select all the code below the line
for i in range(10): , and press Tab .

55
5.9 Summary of Chapter 5

Python English

round(price, 2) Round to 2 decimals


text = input() Read input as a text
number = int(input()) Read input as a whole number
desimal_number = float(input()) Read input as a decimal number
print('My program') Print the text “My program”
2**3 Calculate 23
p
sqrt(1/4) Calculate 1/4.
Tabell 5.1: Dictionary of chapter 5.

The program will stop whenever it reads a line of code with input() . It will
wait for the user to type a text or a number, and then to press Enter . All input
is interpreted as a text (string). That’s why we often need to convert input to
either a whole number or a decimal number. See table 5.1. Use the command
print(f'...') when you want to print text combined with the value from a
variable. Here is an example:

temp = 15
print(f'The temperature is {temp} degrees.')

The result of the code is The temperature is 15 degrees.

Note

• To use the command sqrt , it’s necessary that you first write the
line from math import sqrt .
• When you need several math functions5 , for example sqrt ,
sin , cos or log , you can import all of them by writing
from math import * .

5 Tosee a complete list of available math functions in Python, see


docs.python.org/3/library/math.html.

56
5. Mathematics in Python

5.10 Exercises

5.10.1 The Average of Two Numbers


133
Code Enter a number:
3
1 print('Enter a number:') Enter another number:
2 number1 = float(input()) 5
3 print('Enter another The average is:
,→ number:') 4.0
4 number2 = float(input())

Write the code above, then add the following commmands in the correct order.
The result should look like the output shown above right, if you enter the
numbers 3 and 5.
print('The average is:') print(average)
average = thesum / 2 thesum = number1 + number2

5.10.2 How Old Am I?


134
1 print('Enter your year of birth (e.g. 1982): ')
2 year = input()
3 age = year - 2021
4 print(f'You will be {age} years old this year.')

Write a program where the user can enter his year of birth. The output will
be how old the user is this year. Use the code above as a starting point, and
correct the mistakes.

5.10.3 Currency Converter


134
Write a program where the user can enter the amount in NOK (Norwegian
kroner). The output will be the same amount, but in USD (American dollars).
Use the following conversion rate:

1 USD = 9.83 NOK

To test your program, enter the number 983. The output should be 100 USD.

57
5.10.4 Temperature Check
134

Figure 5.4: A thermometer.

A thermometer, as shown in figure 5.4, measures the temperature. Write a


program where the user can enter the temperature (in °C). If the temperature
is below 0 °C, the program should print Brr . If the temperature is 0 °C or
higher, the program should print Getting warmer! .

5.10.5 Map Scale


134

Figure 5.5: A map of a small Norwegian town.

Mustafa is an orienteer. He uses a map with the map scale 1 ÷ 20 000. This
means that 1 inch on the map corresponds to 20 000 inches in the terrain. He
runs with an average speed of 4.3 miles per hour.
Mustafa wants a program where he can enter the distance he measures on the
map. The output should be both the distance in the terrain, and approximately
how much time he’s going to spend running. Here are some lines of code you
may find useful:

speed = 4.3 distance_map_inches = float(input())


distance_terrain_inches = distance_map_inches * 20000

Tip: If the distance on the map is 5 inches, then the real distance in the terrain
is 100 000 inches. To convert inches to miles, we calculate
100000 ÷ 63360 = 1.578 miles.

58
5. Mathematics in Python

5.10.6 Recognizing Growth Factors


?
Code

1 from random import randint


2
3 # Random whole number between 0 and 100
4 percent = randint(0, 100)
5 growth_factor = 1 + percent/100
6 growth_factor = round(growth_factor, 2) # Round to 2 decimals
7
8 print(f'Enter the growth factor of {percent} percent increase:')
9 answer = input()
10 answer = float(answer) # Convert to decimal number

If the price of a product increases by 15 %, the growth factor is calculated like


this:
15
growth factor = 1 +
100
The code above shows the beginning of a program where a student can practice
recognizing the relationship between the growth factor and the increase in
percent. Finish writing the program and fulfill the following requirements:

• The user is given a random increase in percent. For example 27 percent


increase.
• The user can enter the growth factor. For example he can enter 1.36.
• Upon answering correctly, the user will get the feedback Correct! .
• If the answer is wrong, the feedback should be in the form of
Wrong answer. The correct answer was 1.27 .

• The program shall continue to give new exercises until the end of the
world. Tip: Use a loop to make this happen.

You may also find the following lines of code useful, to add a small pause
between each exercise given to the user.

from time import sleep sleep(1)

59
PART II

Applications in Mathematics
CHAPTER 6
Number Patterns
Learning Goals

• Using programming to explore and produce number patterns.


• Using algorithmic thinking and programming to solve problems
involving number patterns.

6.1 Basic Number Patterns


135
Code Recipe

1 number = 0 Assign 0 to number


2 for i in range(10): Repeat 10 times:
3 print(number) Print the value of number
4 number += 2 Increment number by 2

a) Read the code above, and guess the result.


b) Write the code on the webpage replit.com/new/python3, and run the
program.1 Was the result as expected?

Remember to guess the result after each small change to the code, before you
rerun the program.
c) Let number start on −4 insted of 0.
d) Change line 3 to print(number, end=', ') .
e) Change the number 10 to 50.
f) Change line 4 to number -= 3 .
g) Let number start on 1 and change line 4 to number *= 2 .
h) Change the code to produce the output 3, 6, 12, 24, ... .
1 You may also go to replit.com, and then create a new file (repl) with the language
Python.

63
i) Change the code to produce the output 3, 6, 9, 12, ... .

j) Change the code to produce the output 100, 95, 90, ... . Also, change
the number of repetitions such that 0 is the final number in the output.
k) Change the code to produce the output 100, 50, 25, 12.5, ... .

6.2 A Fast-Growing Monkey Population


135
Code

1 monkeys = 4
2 # Double the number of
,→ monkeys
3 monkeys *= 2
4 print(monkeys)

Figure 6.1: Two monkeys.

A monkey population grows such that it doubles during the course of a year.
We will examine how long it will take until the population reaches 5 million
individuals.

a) Write the code above, and run the program.


b) Copy lines 3 and 4, and paste them at the bottom of the code. Run the
program. In the console you should see the output 8 followed by 16 .

To repeat this growth process over many years, we declare a variable year
which will increment by 1 for each year that passes.

1 monkeys = 4
2 year = 1
3
4 for i in range(10):
5 monkeys *= 2
6 print(monkeys)

c) Change the code as shown above. Run the program.

64
6. Number Patterns

d) Add the line print('Year Monkeys') above the for-loop, and add the
line print(f'{year} \t {monkeys}') inside the for-loop.2
e) Change the for-loop to correspond to a period of 30 years.
f) Add the line year += 1 on the right place in the code, so that the years
increase.
g) Add the following code inside the for-loop:

if monkeys >= 5000000:


print('Above 5 million!')
break # Cancel the loop

h) Finish writing the code so that the program also prints out the number
of years it takes until the population reaches 5 million.

6.3 Sums of Odd Numbers


135
Code

1 number = 1
2 thesum = 0
3 for i in range(5): 1 + 3 + 5 + 7 + 9 = 25
4 thesum += number
5 number += 2
6 print(thesum)

The code above calculates the sum of the first five odd numbers. Why do we
use the variable name thesum and not sum ? See the summary on page 72
for explanation.
a) Write the code above, and run the program.
b) Change the line number = 1 to calculate 5 + 7 + 9 + 11 + 13. You should
get 45.
c) Add the line print(number) at the beginning of the for-loop. What
happens?
d) Change the last line to print(f'Sum = {thesum}') .
e) Finally, change the code to calculate the sum 1+3+5+7+9+11+13+15.
Did you get 64?
2 In Python, using \t gives a space similar to a press on Tab .

65
6.4 Sum of a Geometric Pattern
136
Code 1/256
1/1024
1/4096

1/2048
1/16384

1/8192
...

1/512
1/64
1/128
1/16
1 # The first denominator is 2 1/32
2 denom = 2 1/4
3 for i in range(5): 1/8
4 print(denom)
5 # Double the denominator
denom *= 2
6
1/2
Figure 6.2: A geometric pattern.

Figure 6.2 shows a square with side length 1. The numbers on the figure repre-
sents the areas of the ever smaller rectangles. We notice that the denominators
in the fractions form the number pattern 2, 4, 8, 16 and so on.
a) Read the code above, and guess the result.
b) Write the code, and run the program.
We will now create the number pattern 1/2, 1/4, 1/8, 1/16 and so on.

1 denom = 2
2 for i in range(5):
3 area = 1 / denom
4 print(area)
5 denom *= 2

c) Change the code as shown above, and run the program.


d) Use the for-loop to calculate 1/2 + 1/4 + 1/8 + 1/16 + 1/32. Do this by adding
the following lines of code and placing them correctly:

print(thesum) thesum += area thesum = 0

Let’s examine what happens with the sum of the areas, if we include many
more terms of the same number pattern.
e) Delete the line print(area) , and place the line print(thesum) inside
the for-loop. Change the number of repetitions to 60. Finally, determine
the sum: 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + . . ..

66
6. Number Patterns

6.5 Number Pattern with Circles


136

Figure 6.3: Number patterns (fractals).

The image above shows a beautiful mathematical image created with number
patterns and programming.

Decrement
Start Draw a circle
radius by 10

yes

no
Set radius to 100 Is radius > 0 ? Stop

Figure 6.4: Flowchart. A circle pattern.

a) Read the flowchart in figure 6.4. Guess the result.


b) What number pattern is formed by the variable radius ?

67
Code

1 from turtle import *


2 speed(9)
3 radius = 100
4 while radius > 30:
5 circle(radius)
6 radius -= 10

c) Read the code above, and guess the result.


d) Write the code on the webpage replit.com/new/python_turtle, and
run the program.

Remember to guess the result after each change, before you rerun the program.

e) Change radius = 100 to radius = 50 .


f) Change while radius > 30: to while radius > 0: .
g) Change radius -= 10 to radius -= 5
h) Change while > 0: so that the program draws circles with the following
radiuses:
100, 90, 80, . . . , −90, −100
You should get figure 6.5a.
i) Finish the code and create a program which produces figure 6.5b. You
may need the commands circle(-radius) and forward .

(a) Circles with positive and negative ra-


dius. (b) Circles forward.

Figure 6.5: A circle pattern.

68
6. Number Patterns

6.6 The First 100 Natural Numbers


136
Code

1 from turtle import *


2
3 penup()
4 backward(200)
5 pendown()
6
7 for number in range(30):
Figure 6.6: Natural numbers.
8 print(number)
9 sety(number)
10 sety(0)
11 forward(5)

a) Read the code above, and guess the result.


b) Write the code on the webpage replit.com/new/python_turtle, and
run the program.
c) Change the forward -command to forward(10) . Guess the result be-
fore you run the program.
d) Change sety(number) to sety(50) . Guess how this will effect the
height of the bars, then run the program.
e) Change sety(50) back to sety(number) .
f) Change range(30) in order for the final number to be 100. To increase
the drawing speed, write the line speed(9) directly above penup() .
g) Change the forward -command such that the bars are displayed right
next to each other. What kind of figure do you get?
100

1 + 2 + 3 + . . . + 99 + 100
101
Figure 6.7: The sum as a triangle.

h) Calculate 1 + 2 + 3 + . . . + 98 + 99 + 100 by using the triangle in figure 6.7.


Tip: Area of a triangle is 1/2 · b · h, where b is the base and h is the height.

69
6.7 Rectangle Pattern
137
Code

1 from turtle import *


2 speed(8)
3 fillcolor('orange')
4
5 def rectangle(width, height):
6 begin_fill()
7 for i in range(2):
8 forward(width)
9 left(90)
10 forward(height)
11 left(90)
12 end_fill()
13
14 # Draw a rectangle with width 10 and height 20
15 rectangle(10, 20)

a) Read the code above, and guess the result.


b) Write the code on the webpage replit.com/new/python_turtle, and
run the program.
c) Change the code to draw a rectangle with width 30 and height 90.

Figure 6.8: A rectangle pattern.

70
6. Number Patterns

Recipe

Draw a rectangle with width 10 and height 20


Lift the pen up
Walk 20 steps forward
Put the pen down
And so on ...

d) Use the recipe above as a starting point, and then complete it so that
the result of the recipe will be figure 6.8.
e) From the recipe you just created, write code to draw the three rectangles.
The commands penup() and pendown() will be useful.

Set
Start Draw rectangle
height to 20

no

Finished with Increment Walk 20


8 rectangles? height by 30 steps forward

yes

Stop

Figure 6.9: Flowchart. A rectangle pattern.

f) Using the pattern you analyzed in d) and e), write to code to draw the
8 first rectangles of the same pattern. See the flowchart in figure 6.9.

71
6.8 Summary of Chapter 6

Python English

print(number, end=',') Output ends with a comma


print(number, end=' ') Output ends with a space
print(number) Output ends with a linebreak
print(f'{year} \t {monkeys}') \t produces a space equal to Tab
while radius > 20: Loop repeats itself as long as radius > 20
break Cancels a loop
number *= 2 Doubling of number
number /= 2 Halving of number
number -= 5 Decrement number by 5

Tabell 6.1: Dictionary of chapter 6.

We have seen how we can add numbers of a number pattern. For example, to
add the first 50 numbers in the pattern 2 + 6 + 10 + 14 . . . we write:

1 number = 2
2 thesum = 0
3 for i in range(50):
4 thesum += number
5 number += 4
6 print(thesum)

Note

We recommend avoiding the use of the variable name ’sum’, because


sum is already a built-in Python-function that is used to sum up the
elements of a list.

72
6. Number Patterns

6.9 Exercises

6.9.1 The 4 Times Table


137
Code 4
8
1 for number in range(0, 9): 12
2 product = number + 4 ...
3 print(product) 36
40

Create a program which prints the the answers of the 4 times table. Use the
code above as a starting point. Correct all the mistakes such that the output
is equal to what is shown above next to the code.

6.9.2 Number Pattern with 100 Terms


137
Look at the following number pattern

10, 13, 16, 19, 22, . . .

Here the first term is 10, the second term is 13 and so on. Create a program
which prints the first 100 terms in this number pattern. Do this by placing
the commands below in the correct order.
number = 10 number += 3
for term_nr in range(1, 101): print(term_nr, number)

6.9.3 Dots in Circles


138

s1 s2 s3 s4
Figure 6.10: Number pattern with figures.

Figure 6.10 shows a number pattern with figures, where s1 = 1, s2 = 2 and


so on. Create a program which prints the number of dots in each of the first
15 circles. Determine s15 , that is, what is the number of dots in circle number
15?

73
6.9.4 Number Pattern by Recipe
138
Recipe

Set number = 100000


Repeat as long as number >= 0.1:
Print number
Halve the value of number

Create a program which follows the algorithm of the recipe above. Then
expand the program to decide the number of times you need to halve 100 000,
until the value gets below 0.1.

6.9.5 Number of Terms in the Sum


138
The sum of the numbers in the 7 times table can be written as

7 + 14 + 21 + . . .

Write a program to decide the number of terms we need to include such that
the sum will be greater than 200 000.

6.9.6 Sum of an Infinite Number of Terms


138
A number pattern with an infinite number of terms is such that the first term
is 1000, the second term is 1000 · 0.9 = 900, the third term is 900 · 0.9 = 810
and so on. The sum of these numbers can be expressed like this:

1000 + 900 + 810 + . . .

Create a program which calculates this sum.

6.9.7 To Run a Marathon with Decreasing Speed


139

Figure 6.11: A runner.

74
6. Number Patterns

Kilometer number Speed in km/h Time in hours

1 15,0 0,067
2 14,8 0,134
3 14,6 0,201
... ... ...

Tabell 6.2: Speed and time data from the marathon.

Stein, a Norwegian, is running a marathon. The length of one marathon


is approximately 42 km (kilometers). He runs the first kilometer at speed
15.0 km/h (kilometers per hour), the second kilometer at speed 14.8 km/h, the
third kilometer at speed 14.6 km/h and so on. See table 6.2.
Create a program to decide how long time Stein will spend to complete the
marathon.
Tip: If he runs 1 km at the speed of 5 km/h, we calculate the time spent like
this: 1 ÷ 5 = 0.2. Hence, he uses 0.2 hours (12 minutes) on this kilometer.3

6.9.8 Saving under the Mattress and Buying Kebab


Fran follows a weird savings plan. The first three months he saves (and spends) ?
his money in the following way:

• The first month he puts 1000 $ in his mattress, but he spends 1 % of


these savings on kebab.
• The second month he puts 1100 $ in his mattress, but he spends 2 % of
these savings on kebab.
• The third month he puts 1200 $ in his mattress, but he spends 3 % of
these savings on kebab.

Fran continues to save his money in the same pattern. After some time, when
he spends more than 100 % of the monthly savings on kebab, he needs to
withdraw extra money from his mattress.

Create a program to examine how this savings plan will work out in the long
run. What is the maximum amount of money he will ever have in his mattress?
Will he ever spend all his savings? If yes, when will this happen?

3 0.2 hours in minutes is calculated like this: 0.2 · 60 = 12 minutes.

75
CHAPTER 7
Powers and Square Roots
Learning Goals

• Programming with powers and square roots to explore patterns


and solve problems.
• Using programming as a tool to better understand powers and
square roots.

Figure 7.1: Rubik’s cube. The 33 -edition.

7.1 Practice Powers of 2


139
Code

1 from random import randint


2 print('Test yourself in powers of 2')
3 base = 2
4 exponent = 3
5 print(f'{base} ^ {exponent} = ')
6 answer = base ** exponent
7 print(f'Correct answer: {answer}')

4
z }| {
A way of expressing 2 multiplied by itself 4 times, is 24 = 2 · 2 · 2 · 2 = 16,
where 2 is the base and 4 is the exponent.
a) Read the code above, and guess the result.
b) Write the code on the webpage replit.com/new/python3, and run
program.

77
c) Change exponent = 3 to exponent = 4 . Guess the result, before you
run the program.
d) Change exponent to exponent = randint(-2, 5) . Guess the result,
then run the program several times.
e) Change line 5 to print(f'{base} ^ {exponent} = ', end='') . Add the
code user_answer = float(input()) directly below. Run the program
a few times. Remember that you need to enter a number in the console,
and then press Enter .

if user_answer == answer:
# Correct answer
# TODO: Write feedback
else:
# Wrong answer
# TODO: Write feedback

Let us check whether the answer is right or wrong. The code above is a starting
point for doing this.

f) Add the code above at the correct place in your program. You should
replace lines starting with # TODO with a proper print -command.
Run the program a couple of times.
g) Use while True: such that the program creates a new exercise after the
user answers.
h) Finally, add code so that the program stops when the user has answered
correctly 5 times. The following output should then be produced:
Congratulations! You answered correctly 5 times!

78
7. Powers and Square Roots

7.2 Explore Powers of 10


140
Code

1 print('Exploration of powers of 10.') # A headline


2 print() # Create a blank line
3 base = 10
4 exponent = 3
5 number = base ** exponent
6 answer_text = f'{base} ^ {exponent} = {number}'
7 print(answer_text)

Powers of 10 have base 10 and follow a specific pattern.


a) Read the code above, and guess the result.
b) Write the code, then run the program.
c) Change the line exponent = 3 so that the program calculates 104 . Now
try the exponents 5 and 10. Do you see a pattern?

1 print('Exploration of powers of 10.') # A headline


2 print() # Create a blank line
3 base = 10
4 for exponent in range(2, 7):
5 number = base ** exponent
6 answer_text = f'{base} ^ {exponent} \t = \t {number}'
7 print(answer_text)

Let us now use a for-loop to further explore this pattern. The code \t
produces a space corresponding to the press of key Tab .

d) Read the code above, and guess the result.


e) Write the code, then run the program.

The result of the code range(2, 7) is that the loop repeats 5 times, but the
values of the variable exponent vary from 2 to 6, both inclusive.

f) Change range(2, 7) so that the program calculates all powers of 10


from 101 to 109 . Do you see a relationship between the exponent and
the number of zeroes? Explain!

79
g) Let us now explore negative exponents. Change the range -command so
that you calculate powers of 10 from 10−15 to 10−1 . Some of the answers
look weird:1
10 ^ -5 = 1e-05
10 ^ -4 = 0.0001
10 ^ -3 = 0.001

h) Add the line answer = f'{number:.10f}' and then change the line with
answer_text like this:

answer = base ** exponent


answer = f'{answer:.10f}'
answer_text = f'{base} ^ {exponent} \t = \t {answer}'

Run the program again. How many decimals are now present in the
answers?
i) Change the number 10 in answer = f'{answer:.10f}' so that the first
line of the output becomes:
10 ^ -15 = 0.000000000000001

j) Finally, it is possible to prettify the output by calculating the number of


decimals from the exponent. Add the line decimals = exponent * (-1) ,
then change the line you added in h) to answer = f'{answer:.{decimals}f}' .2
You should get the following output:
10 ^ -15 = 0.000000000000001
10 ^ -14 = 0.00000000000001
10 ^ -13 = 0.0000000000001
10 ^ -12 = 0.000000000001
10 ^ -11 = 0.00000000001
10 ^ -10 = 0.0000000001
10 ^ -9 = 0.000000001
10 ^ -8 = 0.00000001
10 ^ -7 = 0.0000001
...

k) Do you see a correlation between the negative exponent and the answer?
Explain!

1 The notation 1e-05 is called “scientific notation” and means 10−5 .


2 When the exponent is −4, we get 10−4 = 0, 0001. Hence, we need −4 · (−1) = 4
decimals.

80
7. Powers and Square Roots

7.3 Guess the Square Root


140
Recipe

Create a random number


Let answer be the square root of this number
Ask the user to guess the square root
Output the correct answer

Above you see a recipe for a program where the user can guess the square root
of different numbers.

a) Write the code below, and run the program a few times.

1 from random import randint


2 from math import sqrt
3 number = randint(1, 101)
4 answer = sqrt(number)
5 print(f'Guess the square root of {number}: ')
6 guess = float(input())
7 print(f'You guessed {guess}. Correct answer: {answer}.')

b) Use the code below as a starting point. Finish writing it so that the user
will know whether he guessed correctly, too high or too low.

if guess < answer:


# TODO: Print output
elif guess > answer:
# TODO: Print output
else:
# TODO: Print output

When we calculate the square root of a number, we frequently get an answer


with many deciamls, like 6.234456341234. It is unrealistic to expect the user
to answer with such precision. We would like to accept the answer 6.2.
c) Add the command answer = round(answer, 1) directly below the line
answer = sqrt(number) to round off the answer to one decimal.

d) Use a for-loop so that the user can continue guessing until the user guesses
correctly. After each attempt, the program should tell the user whether
the guess was correct, too high or too low.

81
7.4 Rice and Chess
140

Figure 7.2: Rice on a chessboard.

On a chessboard, We put one grain of rice on the first square, two grains on
the second square and four grains on the third square. We continue adding
grains of rice in the same pattern, as shown in figure 7.2.

a) Read the code below, and guess the result.

1 for square_nr in range(8):


2 print(sqaure_nr)

b) Write the code, and run the program.

We can write the numbers 1, 2, 4, . . . as powers of 2: 20 , 21 , 22 and so on.

c) Add the line rice = 2 ** square_nr at the correct place in the code.
Change the print -command so that you output the number of grains
of rice. Do you get the numbers 1, 2, 4, . . . , 128?

Let us now calculate the sum of all the grains of rice on the chessboard. The
sum looks like this:

1 + 2 + 4 + 8 + . . . = 20 + 21 + 22 + 23 + . . .

d) Change range(8) so that you get the correct number of repetitions to


include all 64 squares. Then add the following lines in the correct places:

thesum+= rice print(thesum) thesum= 0

Did you get the sum 18 446 744 073 709 551 615?

82
7. Powers and Square Roots

7.5 Summary of chapter 7

Python English

print(2**4) Outputs the answer of 24


print() Creates a blank line
for i in range(2, 7) : i is given the values 2, 3, 4, 5 and 6
print(f'{answer:.{3}}') Outputs answer rounded to 3 decimals
answer = round(answer, 1) Rounds to 1 decimal
number = randint(1, 101) Gives a random integer from 1 to 101

Tabell 7.1: Dictionary of chapter 7.

We have seen how we can create a practice program to practice math subjects
such as powers and square roots. We use a loop to produce new exercises.
Each new exercise can be created randomly by using the command randint
or similar. Here is an example of writing user feedback:

if guess < answer:


print('You guessed too low.')
elif guess > answer:
print('You guessed too high.')
else:
print('You guessed correctly!')

Note

• We calculate the square root with the command sqrt .


This requires you to first import the command by writing
from math import sqrt .

• To round off in the output, you can use the command


print(f'...') like this:

answer = 0.12345566456 0.12


print(f'{answer:.{2}}') 0.1235
print(f'{answer:.{4}}')

83
7.6 Exercises

7.6.1 Square Numbers


141
Place the following lines of code correctly to create a program which outputs
the first 20 square numbers, that is the numbers 12 , 22 , 32 , . . . , 202 .

number = base ** 2 for base in range(1, 21):


print(number)

7.6.2 Cubic Numbers


141
Code

1 term_nr = 1
2 cubic = term_nr ** 3
3 while cubic < 1000000:
4 # TODO: Print the cubic number
5 # TODO: Increment term_nr by 1
6 # TODO: Calculate the next cubic number

The code above is a starting point to print the cubic numbers 13 , 23 , 33 , . . ..


Once the cubic number hits or exceeds 1 million (1 000 000), the code should
stop printing cubic numbers. Complete the code. Add a print -command
below the loop to print the first term number which produces a cubic number
of 1 million or greater.

7.6.3 Danish Dan’s DanPark


? Danish Dan is a manager for the parking company DanPark. Customers who
park their car at DanPark must pay 5 $ per hour. If the car is parked for at
least 24 hours, the total price is calculated using the formula
p
hours · 5 − hours3
Hence, if a customer is parked for 26 hours, the price is found by computing

26 · 5 − 263
During the course of a particular week, 80 cars were parked at DanPark. The
first car was parked for 1 hour, the second car for 2 hours, the third car for 3
hours and so on.

Create a program which outputs the price that each of the 80 customers needed
to pay. Also, calculate the total income for Danish Dan’s DanPark that week.

84
CHAPTER 8
The Coordinate System
Learning Goals

• Using visual programming as a tool to increase understanding of


the coordinate system.
• Using visual programming as a tool to distinguish between x- and
y-coordinates, and explore and solve problems involving the coor-
dinate system.

This chapter also contains important prerequisite knowlegde to the subject of


functions.

8.1 The Coordinate System – a Small Overview

y
(2, 3)
3
y=3
2

1
x=2
x
-2 -1 0 1 2 3
-1

-2

Figure 8.1: A coordinate system with x- and y-axis.

Above you see a coordinate system. The point (2, 3) has x-coordinate 2 and
y-coordinate 3. In other words, the point (2, 3) means that x = 2 and y = 3,
as shown in figure 8.1.

85
8.2 Explore x-coordinates with Python Turtle
141
Code

1 from turtle import *


2 shape('arrow')
3
4 def draw_xaxis():
5 circle(10) # Draw a point where x = 0
6 setx(-220)
7 setx(220)
8 stamp() # Place the arrow for the x-axis
9
10 draw_xaxis() # Run the lines 5 through 8

a) Read the code above, and guess the result.


b) Write the code on the webpage replit.com/new/python_turtle, and
run the program.
c) Add the instruction setx(-100) on the line below draw_xaxis() .

for i in range(3):
print('Enter a x-coordinate (-200 to 200):')
x_coord = int(input())
setx(x_coord)

d) Write the code above, at the bottom of your program. Run the program,
and enter numbers such as 150, −100 or 0.
e) Add code such that the program draws a circle with radius 10, after
turtle moves to the x-coordinate the user entered. If x is negative, make
the circle red. If x is positive, make the circle blue. See figure 8.2. You
may find the collowing lines of code useful:

dot(10, 'red') dot(10, 'blue')


if x_coord < 0: else:

Figure 8.2: Three x-coordinates. Positive and negative.

86
8. The Coordinate System

8.3 Explore y-coordinates with Python Turtle


142
Code

1 from turtle import *


2 shape('arrow')
3
4 def draw_yaxis():
5 sety(-120)
6 sety(150)
7 stamp()
8
9 draw_yaxis()
Figure 8.3: y-axis. Red and blue.

a) Read the code above. Guess how the y-axis will look like.
b) Write the code, and run the program.
c) Add either left or right with the correct angle, such that the y-axis
looks correct. Add this command inside the function draw_yaxis .
d) Add the line sety(0) below the line draw_yaxis() . This is how we
move the arrow back to the origin.1

Recipe

Set the y-coordinate to -120


Set the direction to the right
Repeat 6 times:
Store the y-coordinate
Walk y steps forward
Walk y steps backward
Increment the y-coordinate with 20

e) Translate the recipe above to Python code, and write this code at the bot-
tom of your program. Tip: To store the y-coordinate, write y = ycor() .
To increment y by 20, write sety(y + 20) .
f) Change the code accordingly to produce figure 8.3. Here are some lines
of code which may be useful:

color('black') color('red') color('blue')


if y > 0: elif y < 0: else:
1 The origin is the point where both x and y is 0, i.e. the point (0, 0).

87
8.4 Parallel Lines
142
Code

1 from turtle import *


2
3 setx(200)
4 sety(50)
5 setx(0)
6 sety(100)
7 setx(200)
Figure 8.4: Parallel lines. Horizontal.

a) Read the code above, and guess the result.


b) Write the code, then run the program.
c) Change the program to produce three parallel lines as shown in figure 8.4.
You will need the commands penup() and pendown() .

Recipe

Pen up
Set y to -150
Repeate 10 times:
Pen down
Set x to 200
Set x to 0
Pen up
Increment the y-coordinate
Figure 8.5: 9 x 9 grid.
,→ with 30

d) Change the program such that you draw 10 parallel lines. See the recipe
on the above left. Here are some lines of code you may find useful:

penup() pendown()
for i in range(10): sety(ycor() + 30)

e) Add code to draw 10 vertical parallel lines, to produce the resulting grid.
See figure 8.5.

88
8. The Coordinate System

8.5 Summary of Chapter 8

Python English

sety(100) Set the y-coordinate to 100


setx(-50) Set the x-coordinate to −50
print(xcor()) Output the x-coordinate
setx(xcor() + 30) Increment the x-coordinate by 30
sety(ycor() - 20) Decrement the y-coordinate by 20
shape('arrow') Set the shape on turtle to an arrow

Tabell 8.1: Dictionary of chapter 8.

In this chapter we used Python Turtle to explore x- and y-coordinates. When


we write for example setx(50) , we move the turtle to a position where x = 50,
without changing the y-coordinate. This works similarly for sety(40) .
Here is an example:

1 from turtle import *


2
3 color('blue')
4 setx(50)
5 sety(-50)
6 setx(0)
7 color('red')
8 sety(ycor() + 100)
9 setx(xcor() - 50)
10 sety(0)
11 home() Figure 8.6: Red and blue squares.

Note

• The commands in this chapter are only available on the webpage


replit.com/new/python_turtle.
• The line from turtle import * must be the first line of your
program, for the turtle-commands to work.

89
8.6 Exercises

8.6.1 The Letter T – Again


143
Code

1 from turtle import *


2
3 setx(45)
4 sety(100)
5 setx(-45)
6 hideturtle()

Write the code above. Place the lines of code in the correct order to produce
the letter T.

8.6.2 An Unknown Geometric Figure


143
Recipe

Read x from the user


Read y from the user
Go to the point (x , y )
Set y -coordinaten to -y
Go to the point (0, -2 * y )
Go back to the origin, i.e. the point (0, 0)

Translate the recipe above to Python code. You may find the following lines
of code useful:
y = float(input()) print('Enter the y-coordinate:')
goto(0, -2 * y) sety(-y)

What is the resulting geometric figure?

Figure 8.7: Geometric figures.

90
8. The Coordinate System

8.6.3 The Distance to a Point


143
Create a program where the user can enter a point by entering the x- and y-
coordinates. The program should draw a line to this point. Then the program
should calculate and print the distance d to this point (from the origin) by
using the formula below. See figure 8.8.
p
d = x2 + y 2

In this exercise you may need the command sqrt . This command is imported
by first writing from math import sqrt .

2
y
2 +
p x
y
d =

x
Figure 8.8: The distance to a point from the origin.

8.6.4 Random Points


Create a program which produces a random point, where x varies between ?
−200 and 200, and y varies between −100 and 100. If both x and y are
positive, then draw with a blue color. Else, draw with a red color. On the
point itself, draw a small circle. Repeat all this 100 times. The result should
look similar to figure 8.9. You must only use the commands setx and sety
to move the turtle. You are not supposed to use goto in this exercise.

Figure 8.9: Random points. Red and blue.

91
CHAPTER 9
Functions
Learning Goals

• To explore mathematical functions and their patterns using pro-


gramming.
• To explore common relationships between variables found in the
real world using programming.
• To program simple algorithms to find a specific function value.

9.1 Kaare on the Café – without a Function


144

Code

1 price_per_cup = 4
2 cups = 3
3 price = price_per_cup * cups
4 print(f'Price: {price}')

Figure 9.1: A cup of coffee.

Kaare goes to a café to drink coffee. The price of a cup of coffee is 4 $. The
code above calculates the price he needs to pay, when he buys three cups of
coffee.

a) Read the code above, and guess the result.


b) Write the code on the webpage replit.com/new/Python3, then run the
program.

One day Kaare bought six cups of coffee.

c) Change the code such that it calculates the price of six cups.
d) Change the code such that the user can enter the number of cups in
the console, when the program is running. You will need the command
input .

93
9.2 Kaare on the Café – with a Function
144
Code

1 def calculate_price(cups):
2 return cups * price_per_cup
3
4 price_per_cup = 4
5 price = calculate_price(3) # The price for 3 cups
6 print(price)

We create a function by using the Python word def . In the code above, we
call cups an argument or a parameter.

a) Read the code above, and guess the result.


b) Write the code on the webpage replit.com/new/Python3, and run the
program.
c) Change the number 3 in price = calculate_price(3) to 5. Guess the
result, before you run the program.
d) Add code to output a text such as:
5 cups of coffe cost 20 dollars.

e) Read the code below, and guess the result. Replace all lines below line
4 with this code, then run the program.

for my_cups in range(1, 10):


price = calculate_price(my_cups)
print(f'{my_cups} cups cost {price} dollars.')

f) Delete the print -command inside the for-loop. Add the following lines
and place them correctly in the code.

print('Kopper\t Pris i kr') print(f'{kopper}\t {pris} ')

g) Add the code \t several more times until you are satisfied with how
the table looks like. Finally, change range(1, 10) such that the final
line in the output shows what 80 cups of coffee cost.

94
9. Functions

9.3 Price per Workout


145
Code

1 def y(x):
2 return 30 / x
3
4 workouts = 2 # Two workouts
5 price = y(workouts)
6 print(f'Price per workout: {price}
,→ dollars.')
Figure 9.2: Walter is working out.

Walter pays 30 $ monthly as a member of a training facility. The price per


workout, y, is given by the function
30
y=
x
where x is the number of workouts during a month.

a) Read the code above, and guess the result.


b) Read the code, and run the program.
c) Change the code such that you calculate the price per workout, if the
number of workouts is 12.

The price per month now increases to 50 $.


d) Change the program to accomodate for the new price. Set the number
of workouts to 2, and you should get the result 25 $ per workout.
e) Examine what happens with the price per workout when you double the
amount of workouts. Here is a recipe to do this:

Print a headline “Number of workouts, Price per workout”


Let workouts start at 1
Repeat 5 times:
Calculate price per workout
Print the number of workouts and the price per workout
Double the amount of workouts

Translate the recipe to Python. To double the amount of workouts, you


can write workouts *= 2 . What is the relationship between the number
of workouts and the price per workout?

95
9.4 Seats in a Cinema
145

Figure 9.3: A young lady in a cinema.

The number of seats in a cinema on a specific row is decided by the following


pattern:

Row number Number of seats

1 3
2 7
3 11

Tabell 9.1: Row number vs seats.

a) Read the code below, and guess the result.

Code

1 def seats(row_nr):
2 return 4*row_nr - 1
3
4 # Prints seats on row number 1
5 print(seats(1))

b) Write the code, and run the program.

96
9. Functions

c) Add code to print the number of seats on row number 5.


d) Select the correct of these lines of code, such that you print how many
more seats you find on row 11 compared to row 10.

print(seats(10) - seats(11)) print(seats(11 - 10))


print(seats(11) - seats(10)) print(seats(10 - 11))

Sanna is sitting on a row with 219 seats.


e) Write a for-loop which searches through the first 99 rows and attempts
to find the row on which Sanna is sitting. You may have use for the
following lines of code:

for row in range(1, 100): if seats(row) == 219:

9.5 The School Road


145
Code

1 def distance_sara(time): # Distance to the school for Sara


2 return 400 - 1.4*time
3
4 print(distance_sara(100)) # Distance after 100 seconds

Sara walks to school every day. She has created the program above to calculate
the distance remaining to the school, when she knows how much time has
passed since she left home. The time is given in seconds.
a) Write the code above, and run the program. Add the line print(distance_sara(60)) .
What the output of this mean?

Figure 9.4: Two girls on their way to school.

97
b) Guess the result if you add the code print(distance_sara(0)) . How
long is Sara’s school road?
c) Guess the result of the following lines of code. What do these answers
tell you?

print(distance_sara(9) - distance_sara(10))
print(distance_sara(99) - distance_sara(100))

d) Write a for-loop to produce a simple table which shows the distance to the
school, every tenth second. See table 9.2. Use the table to approximate
how long time Sara spends walking to her school.

Time (s) Distance to school (m)

0 400
10 386
20 372
... ...

Tabell 9.2: Time vs distance to school.

Pia rides her bike to school with the speed 4,2 m/s. She rides along the same
school road as Sara, and starts riding at the same time Sara starts walking.
The distance from Pia’s house to the school is 600 m.

e) Write a function which calculates the distance to school for Pia. Use
the code below as a starting point, and correct it such that the output
of print(avstand_pia(100)) gives 180. Tip: Look at the function for
Sara’s distance to the school.

def distance_pia(tid):
return 4.2*tid + 600 # TODO: correct the calculation

print(distance_pia(100))

f) Decide Pia’s distance to school after 50 seconds. What is the distance


between Pia and Sara at this point?
g) Finally, write code to decide approximately when Pia and Sara meet.

98
9. Functions

9.6 Deciding the Minimum


146
Code
y

1 def f(x): 20

2 return x**2 - 2*x + 3 f (x) = x2 − 2x + 3


3 15

4 # Print some points


5 print('(x, y)') 10

6 for i in range(-3, 5):


7 print(i) 5
A
x

−3 −2 −1 1 2 3 4 5

Figure 9.5: A parabola.

Figure 9.5 shows the graph of the function f (x) = x2 − 2x + 3.


a) Read the code above, and guess the result.
b) Write the code, and run the program.
c) Add the code y = f(i) inside the for-loop. Then change the command
print(i) to print(i, y) , such that both x- and y-values are printed.

d) To print the values in the format of a point, change the print -command
inside the for-loop to print(f'({i}, {y})') .

Recipe

Set minimum = f(-4)


Repeat for i = -3, -2, -1, ..., 4:
Set y = f(i)
If y < minimum:
Set minimum = y
Print the value of minimum

The recipe above shows an algorithm for finding the minimum1 of the function.
e) Use the recipe above as a starting point, and finish writing the program
such that it finds the minimum.
f) Add the line x_min = -4 before the for-loop. Use this variable to print
the x-coordinate of the minimum, together with the minimum value.
1 The minimum here means the lowest y-value on the graph of the function f (x).

99
9.7 A Piece of Modern Art
146
Code

1 def value(years):
2 return 500*0.85**years V (x) = 5000 · 0, 85x
3
4 buying_price = verdi(0)
5 print(buying_price)

Maya buys a modern painting for 500 $. Experts say that the value of the
painting will decrease by 15 % every year. The value follows the function
V (x), where V (x) is the value in $, x years after Maya bought the painting.
a) Read the code above, and guess the result.
b) Write the code, and run the program.
The command print(value(1)) gives the value after 1 year, print(value(2))
gives the value after 2 years and so on.
c) Add code to decide the value of the painting after 5 years.

x = 0 # x here means the number of years


while verdien(x) >= 100:
# TODO: Increment x by 1
# TODO: Print x

Maya wishes to keep her painting as long as the value is at least 100 $. Once
the value drops below that, she will sell it.
d) Write the code above, and complete it such that the program decides
how long Maya will keep her painting.

Figure 9.6: Modern art. A painting.

100
9. Functions

9.8 Summary of Chapter 9

Python English

def Define a function


return Exits the function
return 2*5 Exits the function and returns 10

Tabell 9.3: Dictionary of chapter 9.

We have seen how we define typical mathematical functions in Python. Here


are a few examples:

def f(x):
f (x) = 3x − 2
return 3*x - 2

def g(x):
return -2*x**2 + 5
g(x) = −2x2 + 5

def h(x): 500


return 500/x h(x) =
x

def s(x):
s(x) = 4000 · 1, 023x
return 4000*1.023**x

To use the function s(x) above, we can write for example print(s(5)) . The
result is the y-coordinate of the graph of s(x) when x = 5.

Note

• In programming we often use descriptive names on functions in-


stead of f (x), g(x) and so on.
• For example, if a function calculates a price for a certain amount
of apples, a descriptive name of the function would be
def calculate_price(amount_of_apples): .

101
9.9 Exercises

9.9.1 Syntax Error in the Function


147
Code

1 df f(x)=
2 3x + 1
3
4 print(f(2))

The code above is an attempt to define the function


f (x) = 3x + 1
Correct all the (syntax) errors in the code, and run the program. If the output
gives you 7, you did it correctly.

9.9.2 Split the Cost Evenly


147

Figure 9.7: A wooden cabin.

Some friends want to rent a cabin. They have decided to split the price evenly.
The price is 900 $. Create a program which prints the price per friend, when
the number of friends varies from 1 to 20. See table 9.4.

Number of friends Price per friend

1 900
2 450
3 300
... ...
Tabell 9.4: Price per friend.

102
9. Functions

9.9.3 Cannon
147

Figure 9.8: Two cannons.

A cannon fires a shot. The height of the cannon ball is given by the function
h(x) = −4, 9x2 + 40x + 1, 2
where h is the height above the ground in meters, and x is the number of
seconds passed after the cannon fired the shot.
Create a program which decides approximately when the cannon ball hits the
ground.

9.9.4 The CCP-Virus Spreads


A model2 for the spread of the CCP-virus in a certain village, is given by: ?
9500
c(x) =
1 + 2.718−0.1x+2.5
where c is the total cases of CCP-virus infections, x days after the testing
began. To determine the number of new infections the first day, calcculate
c(1) − c(0). The number of new infections on the fifth day is c(5) − c(4) and
so on. Create a program which prints the day number and the number of new
infections every day, for the first 120 days. Examine the numbers closely, and
explain how the virus spread.
Tip: This is how you define the function in Python:

def c(x):
return 9500 / (1 + 2.718**(-0.1*x + 2.5))

2 Rimmer, Logistics growth model for COVID-19 [8]

103
CHAPTER 10
Probability
Learning Goals

• Program simulations of random events.


• Explore random events and calculate the probabilities of events,
using programming.

Figure 10.1: Good luck.

10.1 Simulation of 100 Births


148
We will create a program to simulate 100 births. We assume the probability
of getting a boy, is the same as the probability of getting a girl.

a) Read the code below, and guess the result.

Code

1 from random import choice


2
3 baby = choice(['boy', 'girl'])
4 print(baby)

b) Write the code on the webpage replit.com/new/python3, and run the


program.

105
1 from random import choice
2
3 for i in range(10):
4 baby = choice(['boy', 'girl'])
5 print(baby)

We can repeat a trial by using a for-loop.


c) Change the code as shown above. Run the program several times and
notice how the output changes.
d) Change print(baby) til print(baby, end=' ') . Run the program..
e) Finally, change the for-loop such that you simulate 100 births.

10.2 Counting the Girls


148
Code

1 from random import choice


2
3 for i in range(10): # Simulate 10 births
4 baby = choice(['boy', 'girl'])
5 if baby == 'girl': # If the baby is a girl
6 print(baby)

a) Read the code above, and guess the result.


b) Write the code, then run the program five times.

Figure 10.2: A boy and a girl.

106
10. Probability

1 from random import choice


2
3 girls = 0
4 for i in range(10):
5 baby = choice(['gutt', 'girl'])
6 if baby == 'girl':
7 girls += 1
8
9 print(f'Girls: {girls}')

c) Add the changes in the code as shown above. Run the program a few
times.
d) Add the lines of code below at the correct place in the code, such that
you also count and print the number of boys.
boys += 1 boys = 0
else: print(f'boys: {boys}')

e) Change range(10) to simulate 10000 births. Let boys and girls start
at 1, not 0 (to avoid division by 0). Then calculate and print the ratio
girls/boys inside the for-loop. What happens with this ratio when we keep

increasing the number of births?

10.3 Two Dice


148
Code

1 from random import randint


2
3 die1 = randint(1, 6)
4 print(die1)

Figure 10.3: A die.

a) Read the code above, and guess the result.


b) Write the code on the webpage replit.com/new/python3. Run the
program three times.

107
c) Add the following code, and guess the result.

if die1 == 6:
print('Hurray, you got six!')

Run the program until you see the output Hurray, you got six! .

d) Add the following code, and guess the result.

else:
print(f'Too bad, you only got {die1}.')

e) Add the commands die2 = randint(1, 6) and print(die1, die2) at


the bottom of your code. Delete the command print(die1) . Run the
program.
f) Change the if-command to if kast1 == kast2: to examine whether the
dice show an equal number of eyes. Print the output Two equals!
whenever this happens.
g) Change the output in the else-part, such that if you get two unequal, an
output such as 3 and 4, unequal is printed.

10.4 Many Dice


149
Code

1 from random import randint


2
3 throws = 0
4 while throws < 100:
5 die = randint(1, 6)
6 throws += 1
7 print(f'Number of throws: {throws}')

To calculate the probability of an event, we must examine how often the event
occurs. Firstly, we need to be able to count the number of die-throws.

a) Read the code above, and guess the result.


b) Write the code, and run the program.

108
10. Probability

c) Change such that you throw the die 200 times.


d) Add the line sixes = 0 above the while-loop.
e) Add code such that sixes increments by 1 each time the die shows 6.
Print the number of times you got 6. These pieces of code may be useful:
if die == 6: sixes += 1

print(f'Number of sixes: {sixes}')

To approximately calculate the probability of getting a six, we can examine


the ratio
sixes
throws
when we throw the die many times.

f) Add the line print(sixes / throws) inside the while-loop. Run the
program.
g) Examine what happens with this ratio if the number of throws is 10, 100
and 2000.
h) By calculating 1/6 on a calculator, we get 0.16666666666666666.
How does this correspond with the output you got in g)?

10.5 Balls in a Box – with Replacement


149

Figure 10.4: Red and blue balls in a box.

We put 2 blue and 3 red balls in a box. We are going to pick two balls at
random, with replacement. This means that each time we pick a ball, we put
it back into the box before we pick again. Let us now use programming to
determine the probability of the event “at least one red ball”.1

1 Since we are picking two balls, the event “at least one red ball” is equivalent to “one
red ball or two red balls”.

109
a) Write the code below, and run the program a few times.

Code

1 from random import choice


2
3 balls = 3*['r'] + 2*['b']
4 print(balls)
5 ball1 = choice(balls) # Select one ball at random
6 print(ball1)

b) Pick another ball by adding the line ball2 = choice(balls) .


c) Replace the line print(ball1) with print(ball1, ball2) .
d) Write a for-loop to repeat this trial 10 times.
e) Create a headling by adding the command print('Ball1 \t Ball2')
before the loop. Change the print -command inside the for-loop to
print(f'{ball1} \t \t {ball2}') to create a nicer looking table:

Ball1 Ball2
r r
r b

f) Use the line if ball1 == 'r' or ball2 == 'r': to determine if the event
“at least one red” occured.2 Move print(f'{ball1} \t \t {ball2}')
inside the if-statement.
g) Change the loop to 1000 repetitions, then count the number of times the
event occurs. What is the probability “at least one red ball”?

10.6 Balls in a Box – without Replacement


150

Figure 10.5: Red, blue and green balls in a box.

We put 2 blue, 3 red and 4 green balls. Let us pick two balls at random,
without replacement. We will explore the event “second ball is not green”.
2 Note that the events “at least one red ball” and “zero blue balls” are equivalent.

110
10. Probability

a) Write the code below, and run the program a few times..

Code

1 from random import choice


2
3 balls = 2*['b'] + 3*['r'] + 4*['g']
4 print(balls) # The balls before the 1. pick
5 ball1 = choice(balls)
6 balls.remove(ball1) # Remove the ball from the box
7 print(balls) # The balls after the 1. pick

b) Add the lines ball2 = choice(balls) and balls.remove(ball2) at the


end of the program, to pick another ball.
c) To see what balls are remaining in the box, add the command print(balls) .
d) Add the line if ball2 == 'g': to determine if the second ball was
green. Print Second ball was green. , if the event occured.
The code not ball2 == 'g' means “second ball is not green”.
e) Change the if-statement to if not ball2 == 'g': , and change the cor-
responding output to Second ball was not green.

f) Delete all former print -commands, but add the command print(ball1, ball2)
inside the if-statement.
g) Create a loop to repeat this trial 100 times. An outcome where the
second ball is not green, is for example g b . How many different such
outcomes do you see in the output?

10.7 Two Goats and a Car


150

Figure 10.6: Three dors, two goats and a car.

A game begins with a participant choosing one of three doors. Behind two of
the doors is a goat, and behind the final door is a car.

111
a) Write the code below, then run the program.

Code

1 from random import choice


2
3 doors = ['goat', 'goat', 'car']
4 door = choice(doors) # A random door is picked
5 print(door)

b) Use the line if door == 'car': to print the output


Congratulations! You won a car! , if the participant wins the car.

c) Add code such that if the participant does not win the car, the program
prints Unfortunately, you won a goat. .
After the participant has chosen a door, the game host opens a different door
with a goat behind it. The game host then asks the participant if he wants
to switch his choice to the other door, or keep his original choice. After the
participant makes his final choice, the door he chose is opened.3

doors.remove('goat') # The host opens a door with a goat


doors.remove(door) # Remove the participant's choice
door = choice(doors) # Choose the remaining door

d) Add the code above below the line print(door) . Run the program a
few times.

e) Write a loop to repeat this trial 20 times. Print an output in every loop,
for example You won a car/goat. .

f) Create the variable cars , and use it to count the number of times the
participant wins a car. Print the result after the loop.
g) Change the number of repetitions to 1000. Calculate the ratio below,
and print it out.
Number of cars
1000
What fraction does this ratio approach?

Finally, what do you think is the best strategy for winning the car? Keep,
switch or does it not matter what the participant does?
3 Based on the game show “Let’s make a deal” with the host Monty Hall.

112
10. Probability

10.8 Shooting Range – Visual Simulation


151
Code

1 from turtle import *


2 from random import random
3
4 hitrate = 0.6
5 dot(20, 'black')
6
7 if random() < hitrate: Figure 10.7: Shooting range.
8 print('Hit')
9 dot(10, 'white')
10 else:
11 print('miss')

On a shooting range they fire a serises of five shots on five targets.We will
create a program to simulate this. In the code above the hit rate is set to 0.6,
that is the probability of hitting the target, is 60 %.
a) Read the code above, and guess the result. The command random()
produces a random number between 0 and 1.
b) Write the code on the webpage replit.com/new/python_turtle, and
run the program a few times.
c) Add code such that if the shot is a miss, the program shall draw a red
circle, instead of a white one.
d) Add code to draw another target. Then write code to simulate shooting
on the two targets.
Tip: Use forward(40) before you draw target number 2.
e) Finish the program such to simulate the shooting at five targets. We
presume the shooter spends two seconds to aim, before he shoots. The
result of the program should look like figure 10.7. You may have use for
these lines of code:
from time import sleep sleep(2)
for i in range(5): forward(40)

113
10.9 Summary of Chapter 10

Python English

randint(1, 6) Random integer between 1 and 6


random() Random number between 0 and 1
choice(['a', 'b', 'c']) Returns one of the elements a, b or c
with equal probability
genders = ['boy', 'girl'] A list with two elements
balls = 3*['red'] + 2*['blue'] List with 3 ’red’ and 2 ’blue’
choice(balls) Choose a random element from balls
balls.remove('red') Remove one ’red’ from balls
and And
or Or
not Not: the opposite

Tabell 10.1: Dictionary of chapter 10.

We have seen how to use if-statements to determine if an event occurs. Here


are a few examples. We presume the variables used, are already defined.

if die1 == 5: if die1 == 6 or die2 == 6:


print('5 dots') print('At least one 6')
else: else:
print('Not 5 dots') print('No sixes')

if die1 == die2: if die1 == 5 and die2 == 5:


print('Two equal') print('Two fives')

Note

Write from random import randint at the top of the code, to use the
command randint . Do similarly for random and choice . You
can also import all the commands from the random-library by writing
from random import * .

114
10. Probability

10.10 Exercises

10.10.1 Sum of Two Dice


151
from random import randint print(f'The sum is {thesum}')
thesum = die1 + die2 die1 = randint(1, 6)
die2 = randint(1, 6)

Write a program to simulate the throwing of two dice. The program should
add the dots (eyes) together, and print the sum. Place the lines of code above
in the correct order to accomplish this.

10.10.2 Rock Paper Scissors


152
Code

1 from random import chåise


2 the_choices : [rock, 'paper'. 'scissors']
3 my_choice = choice(theChoices)
4 print(f'You chose {My_choice}')

Write a program which picks either rock, paper or scissors at random.4 Use the
code above as a starting points, and correct the errors. The program should
print for example You picked rock .

10.10.3 Twins
152
Recipe

Repeat 9999 times:


Get pregnant
If twins:
Stop getting pregnant

Print the number of children the mother has given birth to

Approximately 1 % of births result in twins. A family wishes to have twins,


and have decided to continue having new babies until it finally happens. Write
a program which follows the recipe above, to simulate this plan. We presume
the mother does not give birth to triplings, quadruplings and so on.

4 We presume uniform probability here, i.e. equal probability for every outcome.

115
10.10.4 Penalty Kick
152

Figure 10.8: Football.

Joe is going to kick 100 penalty kicks. He claims he scores with a 90 % proba-
bility. Write a program to simulate the 100 penalty kicks. A possible output:
hit
hit
miss
...

10.10.5 Smarties
153

Figure 10.9: Smarties.

In a bowl lies 5 red and 3 green Smarties. Write a program which simulates that
you pick two Smarties from this bowl at random, without replacement. If you
get two of equal color, print out Two equal! , else print out One of each .
Repeat the same trial 1000 times, then decide an approximate value for the
probability of getting two Smarties of equal color.

10.10.6 Multiple Choice Test


? A teacher has created a multiple choice test with 20 questions. Each question
has four alternative answers, of which only one is correct. The student will
pass the test if he answers correctly on at least 5 questions. Write a program
which simulates a student taking this test, but he answers all the questions
by guessing wildly. How frequent will such a student, knowing nothing of the
subject, pass the test anyways?

116
APPENDIX A
Løsninger
A.1 Chapter 1 – The First Instructions

1.2 The First Small Steps

1 from turtle import *


2 shape('turtle')
3 speed(1)
4 left(-30)
5 forward(50)
6 left(30)
7 forward(50)
8 left(30)
9 forward(50)

1.3 Triangle Recipe

1 from turtle import *


2 shape('turtle')
3 forward(75)
4 left(120)
5 forward(75)
6 left(120)
7 forward(75)
8 left(60)
9 forward(75)
10 left(120)
11 forward(75)
12 hideturtle()

1.4 Square and Rectangle

1 from turtle import *


2 shape('turtle')
3 speed(7)
4 # Draw the rectangle

117
5 forward(200)
6 left(90)
7 forward(100)
8 left(90)
9 forward(200)
10 left(90)
11 forward(100)
12 left(90)
13
14 # Draw the red line segment
15 forward(100)
16 left(90)
17 color('red')
18 forward(100)
19 hideturtle()

1.5 Drawing with Coordinates

1 from turtle import *


2 shape('turtle')
3 # Draw the rhombus
4 penup()
5 goto(100, 0)
6 pendown()
7 goto(0, 100)
8 goto(-100, 0)
9 goto(0, -100)
10 goto(100, 0)
11
12 # Draw the square
13 goto(100, 100)
14 goto(-100, 100)
15 goto(-100, -100)
16 goto(100, -100)
17 goto(100, 0)
18 hideturtle()

118
A. Løsninger

1.6 Circles and Fillcolors

1 from turtle import *


2 shape('turtle')
3 # Draw the largest eye first
4 fillcolor('lightgray')
5 begin_fill()
6 circle(75)
7 end_fill()
8 # Draw the light blue eye
9 fillcolor('lightblue')
10 begin_fill()
11 circle(50)
12 end_fill()
13 # Finally, draw the small black eye
14 fillcolor('black')
15 begin_fill()
16 circle(25)
17 end_fill()
18 hideturtle()

1.8.1 Correct Order

1 from turtle import *


2 shape('turtle')
3 forward(200)
4 left(45)
5 forward(200)

1.8.2 Correct the Mistakes

1 from turtle import *


2 shape('turtle')
3 forward(300)
4 left(-180)
5 forward(300)

119
1.8.3 Zorro

1 from turtle import *


2 color('gold')
3 pensize(8)
4 forward(100)
5 left(-140)
6 forward(150)
7 left(140)
8 forward(120)

1.8.4 Follow the Recipe

1 from turtle import *


2 shape('turtle')
3 forward(150)
4 left(120)
5 forward(150)
6 left(120)
7 forward(150)
8 left(120)
9 right(60)
10 circle(87)

1.8.5 Parallelogram

1 from turtle import *


2 forward(100)
3 left(60)
4 forward(130)
5 left(120)
6 forward(100)
7 left(60)
8 forward(130)
9 left(120)
10 hideturtle()

120
A. Løsninger

A.2 Chapter 2 – Repetitions and Patterns

2.1 Two repetitions

1 from turtle import *


2 shape('turtle')
3
4 for i in range(2):
5 circle(50)
6 forward(100)
7 circle(25)

2.2 Three or More Repetitions

1 from turtle import *


2 shape('turtle')
3 speed(6)
4
5 # Draw the pizza slices
6 for i in range(8):
7 forward(150)
8 backward(150)
9 left(45)
10
11 # Draw the circle
12 forward(150)
13 left(90)
14 circle(150)

2.3 Angles and Regular Polygons

1 from turtle import *


2 shape('turtle')
3 speed(9)
4
5 for i in range(18): # 18 edges
6 forward(25) # Side length 25
7 left(20) # Angle 20 degrees

121
2.4 Staircase Up and Staircase Down

1 from turtle import *


2 shape('turtle')
3 speed(5)
4
5 # Draw stairway going up
6 for i in range(5):
7 left(90)
8 forward(25)
9 right(90)
10 forward(50)
11
12 # Walk a little forward
13 forward(50)
14
15 # Draw stairway going down
16 for i in range(5):
17 forward(50)
18 right(90)
19 forward(25)
20 left(90)

2.7.1 Draw a Square

1 from turtle import *


2
3 for i in range(4):
4 forward(100)
5 left(90)

2.7.2 Draw a Rectangle with a For-loop

1 from turtle import *


2
3 for i in range(2):
4 forward(200)
5 left(90)
6 forward(100)
7 left(90)

122
A. Løsninger

2.7.3 A Secret Figure

1 from turtle import *


2
3 for i in range(8):
4 left(45)
5 forward(50)
6 right(90)
7 forward(50)

2.7.4 Cones with Icecream

1 from turtle import *


2 speed(9)
3
4 for i in range(10):
5 forward(80)
6 circle(26)
7 backward(80)
8 left(36)
9 hideturtle()

A.3 Chapter 3 – Storing Code in Functions

3.1 My smile

1 from turtle import *


2
3 # The recipe of a smile
4 def smile():
5 setheading(-90) # Set heading downward (south)
6 circle(50, 180) # Draw a semicircle with radius 50
7
8 def pout():
9 setheading(90)
10 circle(50, 180)
11
12 smile()
13 smile()
14 forward(100)
15 left(90)

123
16 forward(400)
17 left(90)
18 forward(100)
19 smile()
20 smile()

3.2 Cogwheel and Squares

1 from turtle import *


2 speed(9)
3
4 def square():
5 for i in range(4):
6 forward(50)
7 right(90)
8
9 for i in range(8):
10 square()
11 forward(120)
12 left(45)

3.3 Varying the Size of Squares

1 from turtle import *


2 speed(7)
3
4 def square(side):
5 for i in range(4):
6 forward(side)
7 left(90)
8
9 square(50)
10 backward(25)
11 square(100)
12 backward(25)
13 square(150)
14 backward(25)
15 square(200)
16 hideturtle()

124
A. Løsninger

3.4 Tunnel in 3D

1 from turtle import *


2 speed(0)
3
4 def square(side):
5 for i in range(4):
6 forward(side)
7 left(90)
8
9 sidelength = 200 # Side length begins at 200
10 while sidelength > 10:
11 square(sidelength)
12 change = sidelength * 0.03
13 sidelength -= change
14 setheading(45)
15 forward(change * 0.707) # The factor is really sqrt(2)/2
16 setheading(0)

3.5 Triangle-pattern with Midpoints

1 from turtle import *


2 speed(9)
3
4 def triangle(side):
5 for i in range(3):
6 forward(side)
7 left(120)
8
9 length = 300
10 for i in range(7):
11 triangle(length)
12 length /= 2 # Halve the length
13 forward(length)
14 left(60)

125
3.7.1 A Function to Draw the Letter T

1 from turtle import *


2 speed(1)
3
4 def draw_T():
5 forward(100)
6 backward(50)
7 right(90)
8 forward(120)
9
10 # Draw T by calling the function
11 draw_T()

3.7.2 Polygon-function

1 from turtle import *


2 speed(8)
3
4 def polygon(edges):
5 angle = 360 / edges
6 for i in range(edges):
7 forward(40)
8 left(angle)
9
10 polygon(8)

3.7.3 A heart

1 from turtle import *


2
3 def heart():
4 fillcolor('pink')
5 begin_fill()
6 circle(100, 90)
7 circle(50, 180)
8 right(180)
9 circle(50, 180)
10 circle(100, 90)
11 end_fill()
12

126
A. Løsninger

13 heart()
14 hideturtle()

3.7.4 Eye Monster

1 from turtle import *


2 speed(9)
3
4 def eyemonster():
5 circle(25)
6 fillcolor('gray')
7 begin_fill()
8 circle(15)
9 end_fill()
10 fillcolor('black')
11 begin_fill()
12 circle(10)
13 end_fill()
14
15 eyemonster()
16 forward(75)
17 eyemonster()
18 penup()
19 right(90)
20 forward(50)
21 left(90)
22 pendown()
23 eyemonster()
24 backward(75)
25 eyemonster()
26 hideturtle()

3.7.5 Chessboard – The First Three Squares

1 from turtle import *


2 speed(0)
3
4 def square(color):
5 fillcolor(color)
6 begin_fill()
7 for i in range(4):

127
8 forward(50)
9 left(90)
10 end_fill()
11
12 square('brown')
13 forward(50)
14 square('white')
15 forward(50)
16 square('brown')
17 hideturtle()

A.4 Chapter 4 – More Possibilities

4.1 A Wheel with Triangles

1 from turtle import *


2 speed(9)
3
4 side = 80
5 # Draw the circle
6 fillcolor('brown')
7 begin_fill()
8 circle(side)
9 end_fill()
10 penup()
11 left(90)
12 forward(side)
13 pendown()
14
15 # Draw the triangles
16 fillcolor('gold')
17 begin_fill()
18 for i in range(8):
19 A = pos()
20 forward(side)
21 left(45)
22 forward(side)
23 goto(A)
24 end_fill()

128
A. Løsninger

4.2 Random Angles

1 from turtle import *


2 from random import randint
3 speed(2)
4
5 # Draw angle v
6 angle_v = randint(20, 130)
7 print(angle_v)
8 forward(100)
9 backward(100)
10 left(angle_v)
11 forward(100)
12
13 # Draw angle u
14 backward(100)
15 angle_u = 180 - angle_v
16 print(angle_u)
17 left(angle_u)
18 forward(100)

4.3 The Circumscribed Circle of a Triangle

1 from turtle import *


2 from random import randint
3
4 # Draw the circumscribed circle
5 shape('circle')
6 u = randint(0, 180)
7 print(u)
8 A = pos()
9
10 circle(100, u)
11 B = pos()
12 stamp()
13
14 v = randint(0, 180)
15 print(v)
16 circle(100, v)
17 C = pos()
18 stamp()
19
20 circle(100, 360 - u - v)

129
21
22 # Draw the triangle
23 goto(B)
24 goto(C)
25 goto(A)

4.4 Bullseye

1 from turtle import *


2
3 radius = 150
4 increase = -25
5 for color in ['gray', 'black', 'blue', 'red', 'yellow']:
6 fillcolor(color)
7 begin_fill()
8 circle(radius)
9 end_fill()
10 penup()
11 sety(ycor() - increase)
12 pendown
13 radius += increase
14 hideturtle()

4.5 Distance Alarm

1 from time import sleep


2 from turtle import *
3 from random import randint
4 Screen().bgcolor('green')
5 shape('circle')
6 speed(1)
7
8 while True:
9 left(randint(0, 359))
10 forward(30)
11 sleep(randint(0, 3))
12 print(distance(home))
13 if distance(home) > 140:
14 Screen().bgcolor('red')
15 print('Come home!')
16 home()

130
A. Løsninger

17 break
18 elif distance(home) > 80:
19 Screen().bgcolor('yellow')
20 print('Mild warning')

4.7.1 Scaling with a Variable

1 from turtle import *


2
3 radius = 100
4 dot(radius, 'blue')
5 penup()
6 forward(radius * 3)
7 dot(radius * 2, 'brown')

4.7.2 Volume-symbol

1 from turtle import *


2
3 width(5)
4 radius = 30
5
6 for i in range(8):
7 penup()
8 circle(radius, 30)
9 pendown()
10 circle(radius, 120)
11 penup()
12 circle(radius, -150)
13 radius += 15
14 sety(ycor() - 15)

4.7.3 One Circle and 100 Chords

1 from turtle import *


2 from random import randint
3 speed(0)
4
5 circle(100)

131
6 for i in range(100):
7 circle(100, randint(0, 180))
8 A = pos()
9 circle(100, randint(0, 180))
10 B = pos()
11 goto(A)
12 goto(B)

4.7.4 A watch

1 from turtle import *


2 speed(0)
3 shape('circle')
4
5 radius = 100
6 length = radius/4
7 for i in range(12):
8 circle(radius, 360/12)
9 left(90)
10 forward(length)
11 backward(length)
12 right(90)
13
14 penup()
15 left(90)
16 forward(radius)

A.5 Chapter 5 – Mathematics in Python

5.6 A Polite Greeting

1 print('Hello! What is your name?')


2 name = input() # Let the user type in his name
3 sex = input('What is your sex? (male/female): ')
4
5 if sex == 'female':
6 print(f'Hello, Ms. {navn}')
7 elif sex == 'male':
8 print(f'Hello, Mr. {navn}')
9 else: # In case the user misspelled male or female
10 print(f'Hello, {navn}')

132
A. Løsninger

5.7 Calculator Program

1 # Read two numbers from the user as decimal numbers (float)


2 numberA = float(input('Enter a number: '))
3 numberB = float(input('Enter another number: '))
4
5 # Calculate sum, product and quotient
6 thesum = numberA + numberB
7 product = numberA * numberB
8 quotient = numberA / numberB
9
10 # Print the results
11 print(f'{numberA} + {numberB} = {thesum}')
12 print(f'{numberA} * {numberB} = {product}')
13 print(f'{numberA} / {numberB} = {quotient}')

5.8 The Multiplication Master

1 from random import *


2
3 for i in range(10):
4 numberA = randint(0, 10)
5 numberB = randint(0, 10)
6 answer = numberA * numberB
7 print(f'{numberA} * {numberB} = ')
8 user_answer = int(input('Svar: '))
9
10 if user_answer == answer:
11 print('Correct answer!')
12 else:
13 print('Wrong answer!')

5.10.1 The Average of Two Numbers

1 print('Enter a number:')
2 number1 = float(input())
3 print('Enter another number:')
4 number2 = float(input())
5
6 thesum = number1 + number2
7 average = thesum / 2

133
8 print('The average is:')
9 print(average)

5.10.2 How Old Am I?

1 print('Enter your year of birth (e.g. 1982): ')


2 year = int(input()) # Convert input to a whole number
3 age = 2021 - year
4 print(f'You will {age} years old this year.')

5.10.3 Currency Converter

1 print('Amount in NOK: ')


2 nok = float(input())
3 rate = 9.83 # The conversion rate between USD and NOK
4 usd = nok / rate
5 usd = round(usd, 2)
6 print(f'Amount in USD: {usd}')

5.10.4 Temperature Check

1 print('Enter the temperature:')


2 temp = float(input())
3
4 if temp < 0:
5 print('Brr')
6 else:
7 print('Getting warmer!!')

5.10.5 Map Scale

1 print('Enter distance on the map in inches: ')


2 distance_map_inches = float(input())
3 distance_terrain_inches = distance_map_inches * 20000
4 distance_terrain_miles = distance_terrain_inches / 63360
5 speed = 4.3 # Unit: miles per hour
6 hours = distance_terrain_miles / speed
7

134
A. Løsninger

8 minutes = round(hours * 60) # Round off to whole minutes


9 distance = round(distance_terrain_miles, 2)
10 print(f'Distance in the terrain: {distance} miles')
11 print(f'Time spent: {minutes} minutes')

A.6 Chapter 6 – Number Patterns

6.1 Basic Number Patterns

1 # Print the number pattern 100, 50, 25, 12.5, ...


2 number = 100
3 for i in range(10):
4 print(number)
5 number /= 2

6.2 A Fast-Growing Monkey Population

1 monkeys = 4
2 years = 0
3
4 for i in range(30): # Optional: use a while-loop
5 years += 1 # Increment years by 1
6 monkeys *= 2 # Double monkeys
7 if monkeys > 5000000: # Greater than 5 million
8 print(f'After {years} years') # 21
9 break # Cancel the for-loop

6.3 Sums of Odd Numbers

1 number = 1
2 thesum = 0
3 for i in range(8):
4 #print(number) # To check that the final number is 15
5 thesum += number
6 number += 2
7 print(thesum) # 64

135
6.4 Sum of a Geometric Pattern

1 denom = 2 # The first denominator is 2


2 thesum = 0
3 for i in range(60):
4 area = 1 / denom
5 thesum += area
6 print(thesum ) # The sum approaches 1
7 denom *= 2

6.5 Number Pattern with Circles

1 from turtle import *


2
3 speed(0)
4 radius = 100
5 while radius > 0:
6 circle(radius)
7 circle(-radius)
8 forward(radius)
9 radius -= 10
10 forward(radius)
11 hideturtle()

6.6 The First 100 Natural Numbers

1 from turtle import *


2 speed(9)
3 penup()
4 backward(200)
5 pendown()
6
7 area_sum = 0
8 for number in range(101):
9 print(number)
10 # The area of a rectangle is number * 1 = number
11 area_sum += number
12 sety(number) # Draw the bar
13 sety(0) # Go back to the x-axis
14 forward(1)
15

136
A. Løsninger

16 print('The area is: ')


17 print(area_sum)

6.7 Rectangle Pattern

1 from turtle import *


2 speed(8)
3 fillcolor('orange')
4
5 def rectangle(width, height):
6 begin_fill()
7 for i in range(2):
8 forward(width)
9 left(90)
10 forward(height)
11 left(90)
12 end_fill()
13
14 height = 20
15 for i in range(8):
16 rectangle(10, height)
17 penup()
18 forward(20)
19 pendown()
20 height += 30

6.9.1 The 4 Times Table

1 for number in range(1, 11):


2 product = number * 4
3 print(product)

6.9.2 Number Pattern with 100 Terms

1 number = 10
2 # Term number from 1 to 100 (both inclusive)
3 for term_nr in range(1, 101):
4 print(term_nr, number)
5 number += 3 # Increment number by 3

137
6.9.3 Dots in Circles

1 s = 1
2 for term_nr in range(1, 16):
3 print(term_nr, s) # s_15 = 16384
4 s *= 2

6.9.4 Number Pattern by Recipe

1 number = 100000
2 halves = 0
3 while number >= 0.1:
4 #print(number) # Optional
5 number /= 2
6 halves += 1
7 #print(number) # Optional
8 print(f'Number of halves: {halves}') # 20

6.9.5 Number of Terms in the Sum

1 term_nr = 0
2 thesum = 0
3 while thesum <= 200000:
4 term_nr += 1
5 number = term_nr * 7
6 #print(number) # For testing purposes
7 thesum += number
8 print(term_nr) # 239

6.9.6 Sum of an Infinite Number of Terms

1 thesum = 0
2 number = 1000
3 while number > 10 ** (-15): # Stops once number gets tiny
4 thesum += number
5 number *= 0.9
6 print(thesum ) # 10000

138
A. Løsninger

6.9.7 To Run a Marathon with Decreasing Speed

1 distance = 42 # Kilometers
2 speed = 15 # Kilometers per hour
3 completed = 0 # Distance completed
4 hours = 0
5 while completed < distance:
6 completed += 1
7 hours += 1 / speed
8 print(hours)
9 speed -= 0.1
10
11 hours = round(hours, 2)
12 print(f'Stein spends {hours} hours.') # 3,27h (3h16min)

A.7 Chapter 7 – Powers and Square Roots

7.1 Practice Powers of 2

1 from random import randint


2 print('Test yourself in powers of 2')
3 base = 2
4 correct_answers = 0
5
6 while correct_answers < 5:
7 exponent = randint(-2, 5)
8 print(f'{base} ^ {exponent} = ', end='')
9 user_answer = float(input())
10 answer = base ** exponent
11 if user_answer == answer:
12 print('Correct!')
13 correct_answers += 1
14 else:
15 print('Wrong. ', end='')
16 print(f'Correct answer: {answer}')
17
18 print('Congratulations! You answered correctly 5 times!')

139
7.2 Explore Powers of 10

1 print('Exploration of powers of 10.') # A headline


2 print() # Create a blank line
3 base = 10
4 for exponent in range(-15, 0):
5 number = base ** exponent
6 decimals = exponent * (-1)
7 answer = f'{number:.{decimals}f}'
8 answer_text = f'{base} ^ {exponent} \t = \t {answer}'
9 print(answer_text)

7.3 Guess the Square Root

1 from random import randint


2 from math import sqrt
3
4 number = randint(1, 101)
5 answer = sqrt(number)
6 answer = round(answer, 1)
7 print(f'Guess the square root of {number}: ')
8
9 while True:
10 guess = float(input())
11 #print(f'You guessed {guess}. Correct answer: {answer}.')
12 if guess < answer:
13 print('You guessed too low.')
14 elif guess > answer:
15 print('You guessed too high.')
16 else:
17 print('Correct!')
18 break

7.4 Rice and Chess

1 thesum = 0
2 for square_nr in range(64):
3 rice = 2 ** square_nr
4 thesum += rice
5 #print(rice)
6 print(thesum)

140
A. Løsninger

7.6.1 Square Numbers

1 for base in range(1, 21):


2 number = base ** 2
3 print(number)

7.6.2 Cubic Numbers

1 term_nr = 1
2 cubic = term_nr ** 3
3 while cubic < 1000000:
4 print(cubic)
5 term_nr += 1
6 cubi = term_nr ** 3
7 print(term_nr) # 100, since 100*100*100 = 1 million

A.8 Chapter 8 – The Coordinate System

8.2 Explore x-coordinates with Python Turtle

1 from turtle import *


2 shape('arrow')
3
4 def draw_xaxis():
5 circle(10) # Draw a point where x = 0
6 setx(-220)
7 setx(220)
8 stamp() # Place the arrow for the x-axis
9
10 draw_xaxis() # Run the lines 5 through 8
11
12 for i in range(3):
13 print('Enter a x-coordinate (-200 to 200):')
14 x_coord = int(input())
15 setx(x_coord)
16 if x_coord < 0:
17 dot(10, 'red')
18 else: # Draw a blue circle if x is positive
19 dot(10, 'blue')

141
8.3 Explore y-coordinates with Python Turtle

1 from turtle import *


2 shape('arrow')
3
4 def draw_yaxis():
5 left(90)
6 sety(-120)
7 sety(150)
8 stamp()
9
10 draw_yaxis()
11 sety(0)
12 sety(-120) # Move the arrow to the bottom of the y-axis
13 setheading(0) # Set heading rightward
14
15 for i in range(14):
16 y = ycor() # Store y-coordinate in the variable y
17 if y < 0:
18 color('red')
19 else: # Blue color if y is positive
20 color('blue')
21 forward(y)
22 backward(y)
23 color('black') # Black color along the axis
24 sety(y + 20) # Increment y-coordinate by 20
25
26 hideturtle()

8.4 Parallel Lines

1 from turtle import *


2 speed(9)
3
4 # Draw horizontal lines
5 penup()
6 sety(-150)
7 for i in range(11):
8 pendown()
9 setx(300)
10 setx(0)
11 penup()
12 sety(ycor() + 30)

142
A. Løsninger

13
14 sety(150)
15 # Draw vertical lines
16 for i in range(11):
17 pendown()
18 sety(150)
19 sety(-150)
20 penup()
21 setx(xcor() + 30)

8.6.1 The Letter T – Again

1 from turtle import *


2
3 sety(100)
4 setx(45)
5 setx(-45)
6 hideturtle()

8.6.2 An Unknown Geometric Figure

1 from turtle import *


2
3 print('Enter the x-coordinate: ')
4 x = float(input())
5 print('Enter the y-coordinate: ')
6 y = float(input())
7
8 # Draw a parallelogram
9 goto(x, y)
10 sety(-y)
11 goto(0, -2 * y)
12 goto(0, 0)

8.6.3 The Distance to a Point

1 from math import sqrt


2 from turtle import *
3 speed(2)

143
4
5 print('Enter the x-coordinate: ')
6 x = float(input())
7 print('Enter the y-coordinate: ')
8 y = float(input())
9 goto(x, y)
10
11 distance = sqrt(x**2 + y**2)
12 print('Distance to the point: ')
13 print(distance)

A.9 Chapter 9 – Functions

9.1 Kaare on the Café – without a Function

1 price_per_cup = 4
2 print('How many cups of coffee do you want?')
3
4 cups = int(input()) # Convert input to whole number
5 price = price_per_cup * cups
6 print(f'Price: {price} dollars')

9.2 Kaare on the Café – with a Function

1 def calculate_price(cups):
2 return cups * price_per_cup
3
4 price_per_cup = 4
5 print('Cups\t Price in dollars')
6 for my_cups in range(1, 81):
7 price = calculate_price(my_cups)
8 #print(f'{my_cups} cups cost {price} dollars.')
9 print(f'{my_cups} \t\t {price} ') # 320 dollars for 80 cups

144
A. Løsninger

9.3 Price per Workout

1 def y(x):
2 return 50 / x
3
4 print('Number of workouts \t Price per workout')
5 workouts = 1
6 for i in range(5):
7 price = y(workouts)
8 print(f'{workouts}\t\t\t\t {price}')
9 workouts *= 2
10 # When you double the number of workouts, the price
11 # per workout is halved.

9.4 Seats in a Cinema

1 def seats(row_nr):
2 return 4*row_nr - 1
3
4 # Number of seats on row 1
5 print(seats(1))
6 # The number of extra seats on row 11 compared to row 10
7 print(seats(11) - seats(10))
8
9 # Search through row 1 to 99
10 for row in range(1, 100):
11 if seats(row) == 219:
12 print('Sanna is sitting on row number:')
13 print(row) # 55

9.5 The School Road

1 def distance_sara(time): # time in seconds


2 return 400 - 1.4*time
3
4 def distance_pia(time):
5 return 600 - 4.2*time
6
7 print('Time\t Distance between Sara and Pia')
8 for sec in range(80): # Where sec means seconds
9 distance_between = distance_pia(sec) - distance_sara(sec)

145
10 distance_between = round(distance_between, 1)
11 print(f'{sec}\t {distance_between}')
12 # Read the answer from the output: between 71 and 72 seconds

9.6 Deciding the Minimum

1 def f(x):
2 return x**2 - 2*x + 3
3
4 # Two variables for the coordinates
5 minimum = f(-4) # y-coordinate
6 x_min = -4 # x-coordinate
7
8 for i in range(-3, 5):
9 y = f(i)
10 if y < minimum:
11 minimum = y
12 x_min = i
13
14 print('The minimum is:')
15 print(f'({x_min}, {minimum})') # (1, 2)

9.7 A Piece of Modern Art

1 def value(years):
2 return 500*0.85**years
3
4 buying_price = value(0)
5 print(buying_price)
6 print(value(5)) # The value after 5 years
7
8 x = 0 # x represents the number of years passed
9 while value(x) >= 100:
10 x += 1 # Increment the number of years by 1
11 print(value(x)) # Optional line of code
12
13 print(x) # 10

146
A. Løsninger

9.9.1 Syntax Error in the Function

1 def f(x):
2 return 3*x + 1
3
4 print(f(2))

9.9.2 Split the Cost Evenly

1 def calculate_price(number_of_friends):
2 return 900 / number_of_friends
3
4 print('Number of friends \t Price per friend')
5
6 for friends in range(1, 21):
7 price = calculate_price(friends)
8 print(f'{friends}\t\t\t\t\t {price}')
9 #print(f'{friends}\t\t\t\t\t {price:.2f}') # Alternatively

9.9.3 Cannon

1 # h is the height above the ground in meters


2 # x is the number of seconds
3 def h(x):
4 return -4.9*x**2 + 40*x + 1.2
5
6 sec = 0 # Time in seconds
7 height = h(0) # Height in the beginning
8
9 while height > 0: # As long as the ball is airborne
10 sec += 0.1 # Increment the time by 0.1 seconds
11 height = h(sec) # Calculate the height again
12 #print(f'{sec}\t\t {height}') # Optional
13
14 print(f'The ball hits the ground after {sec:.2f} seconds.')
15 # Answer: 8.20 seconds
16 # tid:.2f rounds off to two decimal places

147
A.10 Chapter 10 – Probability

10.1 Simulation of 100 Births

1 from random import choice


2
3 for i in range(100):
4 baby = choice(['boy', 'girl'])
5 print(baby, end=' ')

10.2 Counting the Girls

1 from random import choice


2
3 girls = 1
4 boys = 1
5
6 for i in range(10000):
7 baby = choice(['boy', 'girl'])
8 if baby == 'girl':
9 girls += 1
10 else:
11 boys += 1
12 print(girls/boys) # The ratio approaches 1

10.3 Two Dice

1 from random import randint


2
3 die1 = randint(1, 6)
4 die2 = randint(1, 6)
5 print(die1, die2)
6
7 if die1 == die2:
8 print('Two equal!')
9 else:
10 print(f'{die1} and {die2}, two unequal.')

148
A. Løsninger

10.4 Many Dice

1 from random import randint


2
3 throws = 0
4 sixes = 0
5
6 while throws < 5000:
7 die = randint(1, 6)
8 throws += 1
9 if die == 6:
10 sixes += 1
11 print(sixes / throws)
12
13 print(f'Number of throws: {throws}')
14 print(f'Number of sixes: {sixes}')

10.5 Balls in a Box – with Replacement

1 from random import choice


2
3 balls = 3*['r'] + 2*['b']
4 print(balls)
5 counter = 0 # The number of times we get at least one red
6 trials = 1000
7 print('Ball1 \t Ball2')
8
9 for i in range(trials):
10 ball1 = choice(balls) # Pick a ball at random
11 ball2 = choice(balls)
12 print(f'{ball1} \t \t {ball2}')
13 if ball1 == 'r' or ball2 == 'r':
14 counter += 1
15
16 print(f'At least one red: {counter} times')
17 relative_frequency = counter / trials
18 print(f'Calculated probability: {relative_frequency}') # 0.83

149
10.6 Balls in a Box – without Replacement

1 from random import choice


2
3 for i in range(100):
4 balls = 2*['b'] + 3*['r'] + 4*['g']
5 ball1 = choice(balls)
6 balls.remove(ball1)
7 ball2 = choice(balls)
8 balls.remove(ball2)
9 if not ball2 == 'g':
10 print(ball1, ball2)
11 # 6 different outcomes: rr, rb, br, gr, gb and bb

10.7 Two Goats and a Car

1 from random import choice


2
3 cars = 0
4 trials = 1000
5
6 for i in range(trials):
7 doors = ['goat', 'goat', 'car']
8 door = choice(doors) # A random door is picked
9 #print(door)
10 doors.remove('goat') # The host opens a goat-door
11 doors.remove(door) # Remove the original choice
12 door = choice(doors) # Choose the remaining door
13
14 if door == 'car':
15 cars += 1
16 #print(f'You won a {door}') # Optional
17
18 print(f'Cars won: {cars}')
19 p = cars / trials
20 print(f'Win rate: {p}') # Close to the fraction 2/3

150
A. Løsninger

10.8 Shooting Range – Visual Simulation

1 from turtle import *


2 from random import random
3 from time import sleep
4
5 hitrate = 0.6
6 penup()
7 hideturtle()
8
9 # Draw the targets
10 for i in range(5):
11 dot(20, 'black')
12 forward(40)
13
14 home()
15 # Simulate the shooting
16 for i in range(5):
17 sleep(2)
18 if random() < hitrate:
19 print('Hit')
20 dot(10, 'white')
21 else:
22 print('Miss')
23 dot(10, 'red')
24 forward(40)

10.10.1 Sum of Two Dice

1 from random import randint


2
3 die1 = randint(1, 6)
4 die2 = randint(1, 6)
5 thesum = die1 + die2
6 print(f'The sum is {thesum}')

151
10.10.2 Rock Paper Scissors

1 from random import choice


2
3 choices = ['stein', 'saks', 'papir']
4 my_choice = choice(choices)
5 print(f'You chose {my_choice}')

10.10.3 Twins

1 from random import randint


2
3 children = 0
4
5 for i in range(9999):
6 pregnant = randint(1, 100)
7 children += 1
8 if pregnant == 100: # Twins, 1 of 100
9 children += 1 # Count the extra child
10 break
11
12 print(f'Number of children: {children}')

10.10.4 Penalty Kick

1 from random import random


2
3 hitrate = 0.9
4
5 for i in range(100):
6 if random() < hitrate:
7 print('hit')
8 else:
9 print('miss')

152
A. Løsninger

10.10.5 Smarties

1 from random import choice


2
3 equals = 0
4 trials = 1000
5
6 for i in range(trials):
7 smarties = 5*['r'] + 3*['g']
8 smartie1 = choice(smarties)
9 smarties.remove(smartie1)
10 smartie2 = choice(smarties)
11 smarties.remove(smartie2)
12 if smartie1 == smartie2:
13 print('Two equal!')
14 equals += 1
15 else:
16 print('One of each.')
17
18 p = equals / trials
19 print(f'Probability of two equal: {p}') # 0.46

153
APPENDIX B
Plotting Graphs in Python with
Spyder
B.1 Installation of Anaconda/Spyder
We will use the popular software Spyder to plot some graphs in Python. Spyder
is a part of the Anaconda-installation.
a) Open the webpage www.anaconda.com.
b) Navigate to the download link: Products Individual Edition Download .

c) Choose the download link dependant upon your operating system (Win-
dows, MacOS or Linux).
d) Install Anaconda.
When the installation of Anaconda is complete, you are ready to use Spyder.

B.2 Your First Python-program in Spyder


We will create a Python-program in Spyder to plot a graph through four points.
To plot graphs, we will use a library called matplotlib.
a) Open the program Spyder.
b) Create a new file from the menu like this: File New file... .

c) If you want to save your file, go to File Save as... . Note that the name
of Python-files must end with .py to work.
When you create a new file in Spyder, the start of the file looks like this:

1 # -*- coding: utf-8 -*-


2 """
3 Created on Sun Mar 14 13:37:42 2021
4
5 @author: thomassowell
6 """

All this can be safely be deleted, before you start writing your program.

155
d) Begin by writing the code below.

Code

1 import matplotlib.pyplot as plt


2
3 x_values = [0, 2]
4 y_values = [1, 3]
5 plt.plot(x_values, y_values)

This program plots a line segment from the point (0, 1) to the point (2, 3).

e) Save your program: File Save .

f) Run the program by pressing F5 , or use the menu: Run Run . You
should now see the line segment.
g) Add the point (3, −2) by changing the x_values and y_values :

x_values = [0, 2, 3]
y_values = [1, 3, -2]

Run the program.


h) Similarly, add the point (5, 0). The result should look like figure B.1.

−1

−2
0 1 2 3 4 5

Figure B.1: My first graph in Python.

156
B. Plotting Graphs in Python with Spyder

Code of Figure B.1

1 import matplotlib.pyplot as plt


2
3 x_values = [0, 2, 3, 5]
4 y_values = [1, 3, -2, 0]
5
6 plt.plot(x_values, y_values)

B.3 Draw the Graph of a Function


We will now see how we can draw the graph of a function. We choose the
function h(x) = −4, 9x2 + 40x + 1, 2 from exercise 9.9.3 on page 103.
a) Write the code below.

1 import matplotlib.pyplot as plt


2 import numpy as np
3
4 x_values = np.arange(1, 6)
5 print(x_values)

b) Save the file, then run the program.


From the numpy-library we can use the command arange . This command
can create many x-values.
c) Change np.arange to np.arange(-4, 5) . Guess the result, then run
the program.
d) Change np.arange to np.arange(-4, 5, 2) .
The line x_values = np.arange(-4, 5, 2) gives us the x-values −4, −2, 0, 2
and 4. The distance between the x-values is 2.
e) Calculate the corresponding y-values and plot the graph of the function
h(x) = −4, 9x2 + 40x + 1, 2 by adding the lines of code below.

y_values = -4.9*x_values**2 + 40*x_values + 1.2


plt.plot(x_values, y_values)

Maybe you notice that the curve is uneven. To draw a more even curve, the
distance between the x-values needs to be smaller.

157
f) Change np.arange to np.arange(-4, 5, 0.1) . Guess the result, before
you run the program.

The cannon ball was in the air for 8.2 seconds before it hit the ground. Hence,
the x-values should start at 0 and end at 8.2.

g) Change np.arange such that the graph is plotted only for the x-values
from 0 til 8.2. You should now get figure B.2.

The variable names x_values and y_values are useful in the beginning, to
understand that they contain not only one value, but several values. When
you feel comfortable with this, you can simplify the names to x y .

80
70
60
50
40
30
20
10
0
0 1 2 3 4 5 6 7 8

Figure B.2: The graph of a second degree polynomial.

Code of FigureB.2

1 import matplotlib.pyplot as plt


2 import numpy as np
3
4 x = np.arange(0, 8.2, 0.1)
5 y = -4.9*x**2 + 40*x + 1.2
6 plt.plot(x, y)

158
B. Plotting Graphs in Python with Spyder

B.4 Axis Grid and Title

Code

1 import matplotlib.pyplot as plt


2 import numpy as np
3
4 x = np.arange(0, 8.2, 0.1)
5 y = -4.9*x**2 + 40*x + 1.2
6 plt.plot(x, y)

We continue with the graph of the function h(x) = −4, 9x2 + 40x + 1, 2, where
h is the height of the ball in meters above the ground, and x is the number of
seconds. Let’s add axis, a grid and a title.
a) Add the line plt.xlabel('Time (s)') to create a label for the x-axis.
b) Add the line plt.ylabel('Height (m)') to create a label for the y-axis.
c) Create a grid by adding the line plt.grid() .
d) You can also add a descriptive title to your graph. Do this by adding
the line plt.title('The Trajectory of a Cannon Ball.') . You should
now see figure B.3.

The Trajectory of a Cannon Ball


80
70
60
50
Height (m)

40
30
20
10
0
0 1 2 3 4 5 6 7 8
Time (s)

Figure B.3: A plot with axis, a grid and a title.

159
B.5 Complete Example with Two Graphs

Code

1 import matplotlib.pyplot as plt


2 import numpy as np
3
4 x = np.arange(0, 200, 0.1)
5
6 # Calculate the y-values to each function
7 income = 120*x - 0.3*x**2
8 expenses = 0.15*x**2 + 40*x + 1700
9
10 # Plot the graphs of the functions
11 plt.plot(x, income, label = 'Income')
12 plt.plot(x, expenses, label = r'$K(x)=0.15x^2+40x+1700$')
13
14 # Add titles, grid and labels
15 plt.xlabel('Number of units')
16 plt.ylabel('Kr')
17 plt.grid()
18 plt.title('Income and Expenses')
19 plt.legend()

Income and Expenses


16000
Income
14000 K(x) = 0.15x 2 + 40x + 1700

12000
10000
8000
Kr

6000
4000
2000
0
0 25 50 75 100 125 150 175 200
Number of units
Figure B.4: Two graphs drawn in Python.

160
B. Plotting Graphs in Python with Spyder

B.6 Trigonometric Functions

Code

1 import matplotlib.pyplot as plt


2 import numpy as np
3
4 x_degrees = np.arange(0, 360, 0.1)
5 # Convert degrees to radians
6 x_radians = np.deg2rad(x_degrees)
7
8 # Calculate sine and cosine to all the angles
9 sin_values = np.sin(x_radians)
10 cos_values = np.cos(x_radians)
11
12 plt.plot(x_degrees, sin_values, label = r'$f(x)=\sin x$')
13 plt.plot(x_degrees, cos_values, label = r'$g(x)=\cos x$')
14
15 plt.xlabel(r'Angle ($\degree$)')
16 plt.ylabel('Function Value')
17 plt.grid()
18 plt.title('Sine and Cosine to the First 360 Degrees')
19 plt.legend()

Sine and Cosine to the first 360 degrees


1.00
0.75
0.50
Function value

0.25
0.00
−0.25
−0.50
−0.75 ( ) = sinx
f x

−1.00 ( ) = cosx
g x

0 50 100 150 200 250 300 350


Angle ( )
Figure B.5: The graphs of sine and cosine.

161
APPENDIX C
The Learning Philosophy
In this chapter we will present the learning philosophy of this book. First we
will tell you shortly about the programming language Python. Then we will
describe visual learning and the advantages with this. We present five good
tips for learning programming with this book. Finally, we will tell you more
in depth about the learning philosophy.

What is Python?
Python is a programming language created by Guido van Rossum in 1991. It
is one of the most popular languages, especially among the natural sciences in
universities, colleges and schools around the world. Python is well suited for
beginners, since the unique simple syntax focuses on readability.

Python Turtle
Python Turtle is a library which contains many functions and commands.
Turtle lets us control a pen which can draw on the computer screen. We can
draw lines, triangles, circles, railroads and whatever else we feel like drawing.
The first four chapters of this book use only Python Turtle to give the reader
a visual approach to learning, instead of a text-based approach.

Why Visual Learning?


In many programming courses or books, the first example program will often
look like this:

My First Program
class HelloWorldApp {
public static void main(string [] args) {
System.out.println("Hello, World!");
}
}

The result of the program is that it prints the text Hello, World! on the
screen. This is how foregår en text-based learning of programming works.
Visual learning by using Python Turtle, produces results of code as visual
figures, instead of text. See figure C.1.

163
Figure C.1: A drawing – my first program with Python Turtle.

Visual learning means that you can write just on line of code, and produce for
example a circle. This invites the reader to a whole new world of exploration
and experimentation. A Danish study showed that when the focus is on im-
mediate visual feedback, the students motivation and ability to solve problems
significantly increases.1

How can you learn programming with this book?


Here are five pieces of advice to get you started:
1) First read the example. Always try to guess the result of the code,
before you run the program.
2) Write the code provided in the example. It is very important you
write code yourself, to get the feel of it and get the coding fingers running
along. Then run the program.
3) Complete all the steps in the section. Each section has its own
recipe, which contains small steps you need to complete to improve your
programming skills.
4) Try and fail! Never be afraid to try out other numbers, commands and
codes than what is written in the book. We encourage you to experiment
with everything you learn, and try other approaches.
5) Be creative. Apply what you have learned to new situations. Did you
just learn the code to draw a rectangle? Can you apply this knowledge
to draw a triangle or a parallelogram?

1 Reng, [. . . ] Direct Visual Feedback [7]

164
C. The Learning Philosophy

Our Approach to Learning Programming


This book follows a structured approach to learning programming. In short,
the structure is called PRIMM 2 and this is what it means:
Predict. Read the code, and predict what the result will be.
Run. Write the code, then run the program. How did the result corre-
sponding to your earlier guess?

Investigate. In this step you will make small changes to the code, such as
changing a few values, or changing the order of two lines of code. When
you do this step, it is important that you once again repeat the first two
steps, that is to predict the result, then run the program again.

Modify. In this step you will make bigger changes to your code. You
will expand the program by adding several new lines of code, or you will
finish a program to solve a particular problem. You are now on your way
to creating your own program.

Make. We consider this step the highest level of achievement. Here you
are on your own, and will create your own program all by yourself.

Figure C.2: PRIMM-diagram.

The PRIMM-diagram3 shows how the students work their way through three
competency levels in programming. At first they are playing with a program
which is not theirs, and they read the code and test the program. In the next
phase they will make bigger changes to their code, and the program is now
partly theirs. Finally, they create a whole new program which is completely
their own product. This is the highest competency level.
2 Sentance, Primm - a structured approach to teaching programming [11]
3 Sentance, Exploring pedagogies for teaching programming in school [10]

165
Algorithmic Thinking and Different Representations

“Algorithmic thinking is a problem solving method. Algorithmic think-


ing involves approaching problems on a systematic way, both when we
formulate what we wish to solve and when we suggest possible solutions.”
Norwegian Directorate for Education and Training 4

This is how the Norwegian Directorate for Education and Training describes
the term algorithmic thinking. One of the systematic ways to approach prob-
lems, is to make use of different representations. We use the following number
pattern as an example:
3, 5, 7, 9, . . .
In figure C.3 we see typical mathematical representations of this.

Text Geometric
A number pattern begins at
3, then increases by 2 for
each number.
n

Numbers
1
3, 5, 7, 9, . . . 2 1

Formula The area is

2n + 1, where n is a natural A = 2 · n + 1 · 1 = 2n + 1
number.

Natural numbers are


1, 2, 3, 4, . . .

Figure C.3: Representations in mathematics.

4 Education and Training, Algoritmisk tenkning [1]

166
C. The Learning Philosophy

Programming and algorithmic thinking adds three new representations.

• Recipe/algorithm: A recipe, just like an algorithm, involves a set of


stepwise instructions. We write the recipe in English.
• Code: The code is written in Python, and consists of instructions we
give to the computer.
• Images and figures: The result of the code can be something visual,
such as an image or a figure.

These new representations in figure C.4.

Recipe (algorithm) Code

1 Let the number a start at 3 1 a = 3


2 Repeat step 3 and 4: 2 for i in range(10):
3 Print a 3 print(a)
4 Increment a by 2 4 a = a + 2

Figures

(a) Number pattern with rectangles. (b) Number pattern with circles.

The first rectangle has height 3, the next height 5 and so on.
The circles start with radius 3, then the radius increases by 2 for
each new circle.

Figure C.4: New representations in programming.

167
Problem Solving with Programming

“If you can’t solve a problem, then there is an easier problem you can
solve: find it.”
George Pólya 5

This book trains its readers to follow Pólyas advice. Here is an example from
chapter 2 where the reader is asked to draw a railroad track:

Figure C.5: A railroad track. Problem solving.

The problem the student is asked to solve, is to draw the railroad track. Many
students will not be able to solve this problem directly. But given the fig-
ure C.5, it becomes intuitive for the student to split the problem in smaller
and solvable parts. A smaller problem, is for example to draw the bottom
rectangle. Next, to complete all the horizontal rectangles. And, finally, color
all the rectangles.

Motivation
Finally we would like to share some motivating and inspiring words from an
author and professor, who first introduced us to the visual approach to pro-
gramming:

“This book tells a story. It’s a story of liberation, of taking the first
steps towards understanding the foundations of computing, writing your
own code, and creating your own media without the bonds of existing
software tools. This story is not reserved for computer scientists and
engineers. This story is for you.”
Daniel Shiffman 6

5 Pólya, Mathematical Discovery, Volume I [5]


6 Schiffman, Learning Processing 2nd Edition [9]

168
List of Images
Description Page Source

Road red/blue Cover Pixabay/Pexels


Turtle 3 Pixabay/Pexels
Zorro 11 ben.hannis/Flickr
Railroad 13 kalhh/Pixabay
Lady 23 3652586/Pixabay
Cogwheel 25 qimono/Pixabay
Jesus in a window 38 hans-2/Pixabay
Target 39 QuinceCreative/Pixabay
Boy in a raincoat 41 michael podger/Stocksnap
Watch 45 Jaelynn Castillo/Unsplash
Compass 46 OpenClipart-Vectors/Pixabay
Red apples 51 krishnam_moosaddee/Unsplash
Thermometer 58 publicdomainpictures-14/Pixabay
Two monkeys 64 Free-Photos/Pixabay
Fractals 67 realworkhard/Pixabay
Marathon runner 74 kinkate/Pixabay
Rubik’s cube 77 OpenClipart-Vectors/Pixabay
Chessboard and rice 82 McGeddon/WikiMedia
Cup of coffee 93 Free-Photos/Pixabay
Walter works out 95 wagjm/Pixabay
Cinema 96 fedotov_vs/Unsplash
Girls walking 97 MaBraS/Pixabay
Modern art 100 steve/Pexels
Wooden cabin 102 OpenClipart-Vectors/Pixabay
Two cannons 103 David Mark/Pixabay
Good luck 105 Alexas_Fotos/Pixabay
Boy and girl 106 kevinbgent/Unsplash
Die 107 glencarrie/Unsplash
Three dors 111 Cepheus/Wikimedia Commons
Football 116 S. Hermann & F. Richter/Pixabay
Nonstop 116 ChickenFalls/Wikimedia Commons
Turtle-symbol Many places vecteezy.com

169
List of Figures
1.1 A real turtle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Create a new file on replit.com. . . . . . . . . . . . . . . . . . . 3
1.3 The result of the code. . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Drawing with lines. . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 An equilateral triangle. . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6 Two equilateral triangles. . . . . . . . . . . . . . . . . . . . . . . . 6
1.7 A square. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.8 Rectangle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.9 Rectangle split in two halves. . . . . . . . . . . . . . . . . . . . . . 7
1.10 A rhombus. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.11 A rhombus in a square. . . . . . . . . . . . . . . . . . . . . . . . . 8
1.12 The all-seeing eye. . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.13 An angle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.14 Zorro. Fencing champion and nobleman. . . . . . . . . . . . . . . . 11
1.15 Parallelogram. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.16 A circle between two squares. . . . . . . . . . . . . . . . . . . . . . 12

2.1 A railroad: repeating pattern. . . . . . . . . . . . . . . . . . . . . . 13


2.2 Big and small circles. . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.3 A pizza. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.4 A hexagon. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.5 Flowchart for a for-loop. Equilateral triangle. . . . . . . . . . . . . 17
2.6 Stairs down. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.7 Stairs up and stairs down. . . . . . . . . . . . . . . . . . . . . . . . 18
2.8 Experimenting with a for-loop. . . . . . . . . . . . . . . . . . . . . 19
2.9 Seven circles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.10 Rectangle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.11 Icecream cones. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.12 A railroad with colors. . . . . . . . . . . . . . . . . . . . . . . . . . 22

3.1 A smiling lady. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23


3.2 A smile and pouts. . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.3 An awning. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.4 A cogwheel. Used in a mechanical watch. . . . . . . . . . . . . . . 25
3.5 A part of a cogwheel. . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.6 Cogwheels. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.7 Two square-patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.8 Flowchart while-loop. Decreasing squares. . . . . . . . . . . . . . . 28
3.9 Tunnels. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

170
List of Figures

3.10 Equilateral triangles. . . . . . . . . . . . . . . . . . . . . . . . . . . 30


3.11 Triangle-pattern with midpoints. . . . . . . . . . . . . . . . . . . . 30
3.12 An octagon. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.13 A pink heart. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.14 A monster with four eyes. . . . . . . . . . . . . . . . . . . . . . . . 33
3.15 Three squares. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.16 A chessboard. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

4.1 A wheel with triangles. . . . . . . . . . . . . . . . . . . . . . . . . 35


4.2 Supplementary angles. . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.3 The circumscribed circle. . . . . . . . . . . . . . . . . . . . . . . . 38
4.4 The circumcircle in architecture. . . . . . . . . . . . . . . . . . . . 38
4.5 Archery and bullseye. . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.6 Bullseye. Distance between circles. . . . . . . . . . . . . . . . . . . 39
4.7 Little John exploring the outdoors.. . . . . . . . . . . . . . . . . . 41
4.8 Color zones. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.9 Two colored circles. . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.10 Volume-symbol. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.11 100 chords. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.12 A watch. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.13 A watch drawn with Python. . . . . . . . . . . . . . . . . . . . . . 45
4.14 A compass. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

5.1 The console on replit.com. . . . . . . . . . . . . . . . . . . . . . . 47


5.2 Red apples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.3 Flowchart: random product. . . . . . . . . . . . . . . . . . . . . . . 55
5.4 A thermometer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
5.5 A map of a small Norwegian town. . . . . . . . . . . . . . . . . . . 58

6.1 Two monkeys. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64


6.2 A geometric pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . 66
6.3 Number patterns (fractals). . . . . . . . . . . . . . . . . . . . . . . 67
6.4 Flowchart. A circle pattern. . . . . . . . . . . . . . . . . . . . . . . 67
6.5 A circle pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
6.6 Natural numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.7 The sum as a triangle. . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.8 A rectangle pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.9 Flowchart. A rectangle pattern. . . . . . . . . . . . . . . . . . . . . 71
6.10 Number pattern with figures. . . . . . . . . . . . . . . . . . . . . . 73
6.11 A runner. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

7.1 Rubik’s cube. The 33 -edition. . . . . . . . . . . . . . . . . . . . . . 77


7.2 Rice on a chessboard. . . . . . . . . . . . . . . . . . . . . . . . . . 82

171
8.1 A coordinate system with x- and y-axis. . . . . . . . . . . . . . . . 85
8.2 Three x-coordinates. Positive and negative. . . . . . . . . . . . . . 86
8.3 y-axis. Red and blue. . . . . . . . . . . . . . . . . . . . . . . . . . 87
8.4 Parallel lines. Horizontal. . . . . . . . . . . . . . . . . . . . . . . . 88
8.5 9 x 9 grid. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
8.6 Red and blue squares. . . . . . . . . . . . . . . . . . . . . . . . . . 89
8.7 Geometric figures. . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
8.8 The distance to a point from the origin. . . . . . . . . . . . . . . . 91
8.9 Random points. Red and blue. . . . . . . . . . . . . . . . . . . . . 91

9.1 A cup of coffee. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93


9.2 Walter is working out. . . . . . . . . . . . . . . . . . . . . . . . . . 95
9.3 A young lady in a cinema. . . . . . . . . . . . . . . . . . . . . . . . 96
9.4 Two girls on their way to school. . . . . . . . . . . . . . . . . . . . 97
9.5 A parabola. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
9.6 Modern art. A painting. . . . . . . . . . . . . . . . . . . . . . . . . 100
9.7 A wooden cabin. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
9.8 Two cannons. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

10.1 Good luck. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105


10.2 A boy and a girl. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
10.3 A die. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
10.4 Red and blue balls in a box. . . . . . . . . . . . . . . . . . . . . . . 109
10.5 Red, blue and green balls in a box. . . . . . . . . . . . . . . . . . . 110
10.6 Three dors, two goats and a car. . . . . . . . . . . . . . . . . . . . 111
10.7 Shooting range. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
10.8 Football. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
10.9 Smarties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

B.1 My first graph in Python. . . . . . . . . . . . . . . . . . . . . . . . 156


B.2 The graph of a second degree polynomial. . . . . . . . . . . . . . . 158
B.3 A plot with axis, a grid and a title. . . . . . . . . . . . . . . . . . . 159
B.4 Two graphs drawn in Python. . . . . . . . . . . . . . . . . . . . . . 160
B.5 The graphs of sine and cosine. . . . . . . . . . . . . . . . . . . . . 161

C.1 A drawing – my first program with Python Turtle. . . . . . . . . . 164


C.2 PRIMM-diagram. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
C.3 Representations in mathematics. . . . . . . . . . . . . . . . . . . . 166
C.4 New representations in programming. . . . . . . . . . . . . . . . . 167
C.5 A railroad track. Problem solving. . . . . . . . . . . . . . . . . . . 168

172
Python-words
\t, 72, 79, 94, 101 indent, 13
*, 4, 48 input, 56
**, 49, 56 int, 53, 56
*=, 36, 43, 63, 95
+, 48 list, 114
+=, 43, 72, 82
-, 48 math, 49, 56, 81, 91
-=, 28, 43 cos, 56
/, 48 log, 56
/=, 30, 43 sin, 56
:, 13, 20, 31, 94, 101 sqrt, 49, 56, 81, 91
<, 31, 43 matplotlib.pyplot
<=, 43 label, 160
=, 28, 43 plt, 156
==, 55, 78, 106 plt.grid, 159
>, 31, 43 plt.legend, 160
>=, 43 plt.plot, 156
[ ], liste, 114 plt.title, 159
#, 7 plt.xlabel, 159
plt.ylabel, 159
and, 114
NameError, 47
break, 42, 65, 72 not, 111, 114
not defined, 47
def, 23, 31, 94, 101 numpy
np.arange, 157
elif, 42, 43 np.cos, 161
else, 43, 55 np.deg2rad, 161
end, 72 np.sin, 161

f’, 53 or, 114


File, 47
float, 53, 56, 78, 81 print, 37, 56, 83, 89, 93
for, 13, 20, 83 print(f’({...})), 53, 56, 77, 83
from, 4, 56
random, 37, 43, 77, 105
i, 20 choice, 105, 110, 114
if, 42, 43, 65, 97 randint, 37, 43, 78, 83, 107,
import, 4, 56 114
in, 13, 20, 41 random, 114

173
range, 13, 20, 83
remove, 111, 114
replace, 59
return, 94, 101
round, 51, 56, 81, 83

time, 41
sleep, 41, 43, 113
Traceback, 47
True, 28, 42, 43
turtle, 3, 4
backward, 10, 15
begin_fill, 9, 10, 70
bgcolor, 43
circle, 9, 10, 14, 36
color, 6, 10
dot, 44
end_fill, 9, 10, 70
fillcolor, 9, 10, 70
forward, 5, 10
goto, 8, 10, 38, 90
hideturtle, 6, 10, 90
home, 24, 43, 89
left, 5, 10
pendown, 8, 10, 69, 88
pensize, 11
penup, 8, 10, 69, 88
pos, 35, 36, 43
right, 10
Screen, 43
setheading, 23
setx, 69, 86, 89
sety, 43, 69, 86, 89
shape, 4, 10, 89
speed, 5, 7, 10
stamp, 43, 86, 87
width, 44
xcor, 87
ycor, 43, 87

while, 28, 31, 42, 68, 72, 100

174
Bibliography
[1] N. D. for Education and Training. Algoritmisk tenkning. [22.03.2021].
url: https : / / www . udir . no / kvalitet - og - kompetanse / profesjonsfaglig -
digital-kompetanse/algoritmisk-tenkning/.
[2] Euclid. Euclids Elements. [Translated by Thomas L. Heath]. Green Lion
Press, 2013.
[3] M. Goossens et al. The LATEX Companion. Reading, Massachusetts: Ad-
dison–Wesley, 1993.
[4] H. R. Jacobs. Geometry: Seeing, Doing, Understanding. Master Books,
2017.
[5] G. Pólya. Mathematical Discovery, Volume I. Ishi Press, 2009.
[6] D. Prager. Happiness is a serious problem. ReganBooks, 1998.
[7] L. Reng. [. . . ] Direct Visual Feedback. [22.03.2021]. Aalborg University.
url: https://vbn.aau.dk/files/78681073/Enhancing_Students_Motivation_
to_Learn_Programming_by_Using_Direct_Visual_Feedback_Innovations2012.
pdf.
[8] D. B. Rimmer. Logistics growth model for COVID-19. [22.03.2021]. url:
https://www.wolframcloud.com/obj/covid-19/Published/Logistic-Growth-
Model-for-COVID-19.nb.
[9] D. Schiffman. Learning Processing 2nd Edition. [22.03.2021]. url: http:
//learningprocessing.com/.
[10] S. Sentance. Exploring pedagogies for teaching programming in school.
[22.03.2021]. url: https://blogs.kcl.ac.uk/cser/2017/02/20/exploring-
pedagogies-for-teaching-programming-in-school/.
[11] S. Sentance. Primm - a structured approach to teaching programming.
[22.03.2021]. url: https : / / blogs . kcl . ac . uk / cser / 2017 / 09 / 01 / primm -
a-structured-approach-to-teaching-programming/.
[12] T. F. Sturm. The tcolorbox package. [22.03.2021]. Institut für Mathe-
matik und Informatik, Universität der Bundeswehr München. url: https:
//ctan.uib.no/macros/latex/contrib/tcolorbox/tcolorbox.pdf.
[13] T. Tantau. The Tikz and PGF manual. [22.03.2021]. Institut für Theo-
retische Informatik Universität zu Lübeck. url: https : / / ctan . uib . no /
graphics/pgf/base/doc/pgfmanual.pdf.

175

You might also like