Python Programming - A Visual Jo - Kaare Erlend Jorgensen
Python Programming - A Visual Jo - Kaare Erlend Jorgensen
PYTHON PROGRAMMING:
A VISUAL JOURNEY FOR
THE BEGINNER
WITH SIMPLE APPLICATIONS IN
MATHEMATICS
Second Edition
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).
Any enquiry about the present work may be adressed using: [email protected]
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.
I The Basics 1
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
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
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.
ix
The following two alternative websites are worth mentioning:
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.
x
PART I
The Basics
CHAPTER 1
The First Instructions
1.1 The Creation
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.
3
c) Write the following code to create Tom the Turtle.
Code
Correct Wrong
Correct Wrong
shape 'turtle')
shape("turtle") shape(turtle')
shape('turtle') shape(`turtle`)
shape('Turtle')
4
1. The First Instructions
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.
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
b) Write the code, and run the program. Press Run or Ctrl + Enter (Mac:
Cmd + Enter ) to run the program.
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
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
8
1. The First Instructions
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' .
9
1.7 Summary of Chapter 1
Python English
To fill figures with a color, you must first set a fillcolor. For example: Write
fillcolor('brown') , then follow these three steps:
Note
10
1. The First Instructions
1.8 Exercises
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
11
1.8.4 Follow the Recipe
120
Recipe
Follow the recipe above, and translate to Python-code. What is the resulting
figure?
1.8.5 Parallelogram
120
60°
Write code to draw figure 1.16. Use the colors 'red' , 'gold' and 'black' .
12
CHAPTER 2
Repetitions and Patterns
The code above uses a for-loop. We use for-loops when we want Python to
repeat instructions.
13
Correct Wrong
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)
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.
14
2. Repetitions and Patterns
A gentle reminder: Always guess the result of each small change to the code.
15
2.3 Angles and Regular Polygons
121
Code
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.
3 120
4 90
6 60
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?
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.
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
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
g) Finish the code to draw figure 2.7. The recipe above shows how you can
split this problem into three parts.
18
2. Repetitions and Patterns
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
The two final instructions are “walk 199 steps forward” and “turn 89 degrees
left”.
19
2.6 Summary of Chapter 2
Python English
An overview of available commands for Python Turtle is listed on the web page
docs.python.org/3/library/turtle.html.
Note
20
2. Repetitions and Patterns
2.7 Exercises
Write the code above, and run the program. Correct the mistakes such that
the result is a square.
100
200
Figure 2.10: Rectangle.
Draw a rectangle with length 200 and width 100. See figure 2.10.
Repeat 8 times:
Turn 45 degrees left
Walk 50 steps forward
Turn 90 degrees right
Walk 50 steps forward
21
2.7.4 Cones with Icecream
123
Write a program which draws figure 2.11. Do this by writing the lines above
in the correct order.
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
When we are satisfied with our smile, we can store it as a function like this:
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.
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.
24
3. Storing Code in Functions
Code Recipe
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
f) Finally, change the code such that the cogwheel’s teeth face outward.
See figure 3.6b.
26
3. Storing Code in Functions
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
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
28
3. Storing Code in Functions
Code
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)
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
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.
30
3. Storing Code in Functions
Python English
Here is an example of how to create a function with more than one parameter:
smile(100, 'blue')
Note
def smile():
setheading(-90) # Inside of the function
circle(50, 180) # Outside of the function
31
3.7 Exercises
Write the code above, and run the program. Change the code to produce the
letter T.
3.7.2 Polygon-function
126
Code
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
Write a function which draws a pink heart. See figure 3.13. You may need the
following lines of code:
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
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
?
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
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
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:
2 The code side = side * 0.9 can also be written like this: side *= 0.9.
36
4. More Possibilities
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
37
4.3 The Circumscribed Circle of a Triangle
129
Code
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.
38
4. More Possibilities
4.4 Bullseye
130
Code
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:
40
4. More Possibilities
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.
Code Recipe
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
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:
Little John usually walks more than just 5 steps. By writing while True: ,
we can create a loop which repeats forever.
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
Python English
Here is an example of how you can control the code with if and else :
43
4.7 Exercises
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
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.4 A watch
132
45
4.7.5 Treasure Hunting with a Compass
?
Code
46
CHAPTER 5
Mathematics in Python
5.1 Add, Subtract, Multiply and Divide
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 .
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 .
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
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
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
Jerry can calculate square roots when we use the command sqrt 2
49
√
b) Calculate 4 by writing sqrt(4) .
√
c) Calculate 9 by writing sqrt(9) .
√ √
16 5− 25
√ p
10 1/4
a=3
a
3
a+2
5
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.
e) Calculate 3b − 2a, but first set a = 5 and b = −3. You should get −19.
50
5. Mathematics in Python
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
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.
Not everyone identifies with the title Mister. We will therefore let the user tell
us his sex, in addition to his name.
If the user answers “Hanan” and then “female”, then the output should look
like this:
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”.
52
5. Mathematics in Python
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.
53
5.8 The Multiplication Master
133
Code
1 numberA = 3
2 numberB = 4
3 answer = numberA * numberB
4 print(f'{numberA} * {numberB} = {answer}')
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 ...
55
5.9 Summary of Chapter 5
Python English
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.')
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 * .
56
5. Mathematics in Python
5.10 Exercises
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
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.
To test your program, enter the number 983. The output should be 100 USD.
57
5.10.4 Temperature Check
134
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:
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
• 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.
59
PART II
Applications in Mathematics
CHAPTER 6
Number Patterns
Learning Goals
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, ... .
1 monkeys = 4
2 # Double the number of
,→ monkeys
3 monkeys *= 2
4 print(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.
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)
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:
h) Finish writing the code so that the program also prints out the number
of years it takes until the population reaches 5 million.
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
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
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
67
Code
Remember to guess the result after each change, before you rerun the program.
68
6. Number Patterns
1 + 2 + 3 + . . . + 99 + 100
101
Figure 6.7: The sum as a triangle.
69
6.7 Rectangle Pattern
137
Code
70
6. Number Patterns
Recipe
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
yes
Stop
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
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
72
6. Number Patterns
6.9 Exercises
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.
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)
s1 s2 s3 s4
Figure 6.10: Number pattern with figures.
73
6.9.4 Number Pattern by Recipe
138
Recipe
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.
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.
74
6. Number Patterns
1 15,0 0,067
2 14,8 0,134
3 14,6 0,201
... ... ...
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?
75
CHAPTER 7
Powers and Square Roots
Learning Goals
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
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 .
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.
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:
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
k) Do you see a correlation between the negative exponent and the answer?
Explain!
80
7. Powers and Square Roots
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.
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.
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
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.
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 + . . .
Did you get the sum 18 446 744 073 709 551 615?
82
7. Powers and Square Roots
Python English
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:
Note
83
7.6 Exercises
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
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
y
(2, 3)
3
y=3
2
1
x=2
x
-2 -1 0 1 2 3
-1
-2
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
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:
86
8. The Coordinate System
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
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:
87
8.4 Parallel Lines
142
Code
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
Python English
Note
89
8.6 Exercises
Write the code above. Place the lines of code in the correct order to produce
the letter T.
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)
90
8. The Coordinate System
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.
91
CHAPTER 9
Functions
Learning Goals
Code
1 price_per_cup = 4
2 cups = 3
3 price = price_per_cup * cups
4 print(f'Price: {price}')
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.
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.
e) Read the code below, and guess the result. Replace all lines below line
4 with this code, then run the program.
f) Delete the print -command inside the for-loop. Add the following lines
and place them correctly in the code.
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
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.
95
9.4 Seats in a Cinema
145
1 3
2 7
3 11
Code
1 def seats(row_nr):
2 return 4*row_nr - 1
3
4 # Prints seats on row number 1
5 print(seats(1))
96
9. Functions
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?
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.
0 400
10 386
20 372
... ...
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))
98
9. Functions
1 def f(x): 20
−3 −2 −1 1 2 3 4 5
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
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.
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.
100
9. Functions
Python English
def f(x):
f (x) = 3x − 2
return 3*x - 2
def g(x):
return -2*x**2 + 5
g(x) = −2x2 + 5
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
101
9.9 Exercises
1 df f(x)=
2 3x + 1
3
4 print(f(2))
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.
1 900
2 450
3 300
... ...
Tabell 9.4: Price per friend.
102
9. Functions
9.9.3 Cannon
147
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.
def c(x):
return 9500 / (1 + 2.718**(-0.1*x + 2.5))
103
CHAPTER 10
Probability
Learning Goals
Code
105
1 from random import choice
2
3 for i in range(10):
4 baby = choice(['boy', 'girl'])
5 print(baby)
106
10. Probability
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
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! .
else:
print(f'Too bad, you only got {die1}.')
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.
108
10. Probability
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)?
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
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”?
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
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?
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
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
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
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
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
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.
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
4 We presume uniform probability here, i.e. equal probability for every outcome.
115
10.10.4 Penalty Kick
152
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
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.
116
APPENDIX A
Løsninger
A.1 Chapter 1 – The First Instructions
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()
118
A. Løsninger
119
1.8.3 Zorro
1.8.5 Parallelogram
120
A. Løsninger
121
2.4 Staircase Up and Staircase Down
122
A. Løsninger
3.1 My smile
123
16 forward(400)
17 left(90)
18 forward(100)
19 smile()
20 smile()
124
A. Løsninger
3.4 Tunnel in 3D
125
3.7.1 A Function to Draw the Letter T
3.7.2 Polygon-function
3.7.3 A heart
126
A. Løsninger
13 heart()
14 hideturtle()
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()
128
A. Løsninger
129
21
22 # Draw the triangle
23 goto(B)
24 goto(C)
25 goto(A)
4.4 Bullseye
130
A. Løsninger
17 break
18 elif distance(home) > 80:
19 Screen().bgcolor('yellow')
20 print('Mild warning')
4.7.2 Volume-symbol
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
132
A. Løsninger
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)
134
A. Løsninger
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
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
136
A. Løsninger
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
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
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
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
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)
139
7.2 Explore Powers of 10
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
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
141
8.3 Explore y-coordinates with Python Turtle
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)
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)
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')
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
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.
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
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
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)
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
1 def f(x):
2 return 3*x + 1
3
4 print(f(2))
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
147
A.10 Chapter 10 – Probability
148
A. Løsninger
149
10.6 Balls in a Box – without Replacement
150
A. Løsninger
151
10.10.2 Rock Paper Scissors
10.10.3 Twins
152
A. Løsninger
10.10.5 Smarties
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.
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:
All this can be safely be deleted, before you start writing your program.
155
d) Begin by writing the code below.
Code
This program plots a line segment from the point (0, 1) to the point (2, 3).
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]
−1
−2
0 1 2 3 4 5
156
B. Plotting Graphs in Python with Spyder
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
Code of FigureB.2
158
B. Plotting Graphs in Python with Spyder
Code
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.
40
30
20
10
0
0 1 2 3 4 5 6 7 8
Time (s)
159
B.5 Complete Example with Two Graphs
Code
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
Code
0.25
0.00
−0.25
−0.50
−0.75 ( ) = sinx
f x
−1.00 ( ) = cosx
g x
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.
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
164
C. The Learning Philosophy
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.
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
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
2n + 1, where n is a natural A = 2 · n + 1 · 1 = 2n + 1
number.
166
C. The Learning Philosophy
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.
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:
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
168
List of Images
Description Page Source
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
170
List of Figures
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
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
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
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