Creative Coding in Python - Sheena Vaidyanathan
Creative Coding in Python - Sheena Vaidyanathan
CODING IN
PYTHON
225269 - Creative Coding in Python_001-144.indd 1
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:1
CREATIVE
CODING IN
PYTHON
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 2
13/9/18 11:26 AM
Title:
Text
itle:
Page:2
CREATIVE
CODING IN
SHEENA VAIDYANATHAN
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:2
Text
Page:3
Quarry Books titles are also available at discount for retail, wholesale,
promotional, and bulk purchase. For details, contact the Special
Sales Manager by email at [email protected] or by mail at
The Quarto Group, Attn: Special Sales Manager, 100 Cummings
Center, Suite 265-D, Beverly, MA 01915, USA.
10 9 8 7 6 5 4 3 2 1
ISBN: 978-1-63159-581-3
eISBN: 978-1-63159-582-0
Printed in China
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:4
To my father,
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
itle:
Title:
T
225269 - Creative Coding in Python
itle:
Page:4
Text
Page:5
CONTENTS
INTRODUCTION
CREATE YOUR
8 What Is Coding?
OWN CHATBOTS
ART MASTERPIECES
8 Why Python?
38 Turtle Graphics
9 Installing Python
40 Loops
11 Python Functions
Project
23 Doing Math on the Computer
Understanding Errors
12 Problem Solving:
Project
Next Steps
Writing Algorithms
Next Steps
12 Pseudocode
12 Flowcharts
PYTHON
PYTHON
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:6
CREATE YOUR OWN
ADVENTURE GAMES
DICE GAMES
False
Random
and False
Project
On a Condition
Next Steps
Project
Keyboard Controls
Mouse Clicks
Next Steps
Project
Arcade-Style Game
Next Steps
136 Glossary
138 Resources
139 Acknowledgments
140 About the Author
141 Index
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:6
Text
Page:7
INTRODUCTION
ENGLISH?
PYTHON?
What Is Coding?
0100101?
PYTHON?
Why Python?
Coding allows artists and makers to create art and make There are
hundreds of computer programming languages, wonderful objects
that are only possible with code.
you to break down a problem into steps, use math and logic Python is
a popular language for several reasons, including: to develop a
solution, and then test and make changes to solve the problem.
Learning to code engages students of all 1 It’s easy to learn and use.
needed to do a task.
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
itle:
Page:8
internal ideas
or thoughts/
Used f
ate shape)
ed as needed (its a seper
ow can be adjust
or fur
ectional arr
Chat bubbles or c
ws ar
Windo
Installing Python
different font from the rest of the text. Comments programmers. There
are also a few online
In places where the code does not fit in one line, a \ the screenshots
and examples in this book
uses Python 3.
Pseudocode
this is pseudocode
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:8
Text
Page:9
The First Line of Code
Once you’ve installed Python IDLE, run the application. You should
see the Python shell window. The window shown at left is from a
Mac, but versions on other platforms will look similar.
>>>
You’ll use the Python shell to test and learn the Python code that’s
listed in the Big Ideas sections in this book. For the projects, you’ll
use IDLE to enter code into a file that can be saved, changed, and
run multiple times.
parentheses.
PARTS OF CODE
following:
parts of the code in different colors. For example, the color of “hello,
world”, which is a Python string, print('hello, world')
The computer should reply with “hello, world.” It will then return to the
prompt, waiting for more. Go ahead and type in more print
statements.
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:10
‘HELLO’
FUNCTION
HELLO
Information on what to
Python Functions
was not used exactly as it is defined; the error has to do with the
syntax of the language.
Understanding Errors
is either a helpful colored line next to the error or the error Type in the
print code from before again, but this time make message explains
what the computer does not understand.
may still not run as expected. This kind of an error is called a runtime
error. It is due to a mistake in the way the code
fix, and others can take a long time. Finding and fixing these
to code.
>>>
INTRODUCTION ::/ 11
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
itle:
Title:
T
225269 - Creative Coding in Python
itle:
Page:10
Text
Page:11
Page:
Problem Solving:
Pseudocode
For example, here is pseudocode for setting the table for four To
solve problems and write good code, computer
people.
Pseudocode
flowcharts.
Here is pseudocode for adding ten numbers entered by the user and
printing them to the screen.
Pseudocode
Set total to 0
The instructions that are indented are repeated. In the latter example,
the two indented steps—getting a number from the user and adding it
to the total—are repeated 10 times.
The computer then prints the total after the repetition is completed.
12 /:: CREATIVE CODING IN PYTHON
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:12
Flowcharts
the program
Rectangle = Process
output of information
Diamond = Decision
Parallelogram = Data
a password.
Is password equal
Yes
to “Python“?
password is correct.
No
STOP
INTRODUCTION ::/ 13
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 13
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:12
Text
Page:13
Print
customized
messages
based on user
input.
Create custom
calculators
to do your
math chores.
Use your
creativity
to generate
silly stories
or fun songs.
13/9/18 11:26 AM
Text
customized
messages
based on user
input.
Use variables
to store
information
from the user.
CREATE
YOUR OWN
CHATBOTS
Crunch
numbers with
powerful math
functions.
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:14
Text
Page:15
BIG IDEA
STORING DATA
WITH VARIABLES
I need to store
0
the player’s
Value of the
variable
a variable.
player_score
Name of the
variable
13/9/18 11:27 AM
Title:
Text
itle:
Page:16
assigned any value, you will get an error. So in the Storing Variables
in Python
example on this page, you will get an error if you In Python, a simple
equal sign is used to store data in a misspell the name of the
variable. If you enter
variable.
NESTING QUOTES
player_score = 0
If the text uses single or double quotes, you must use the other kind
of quotation mark around it.
s = "Shelly's house"
As the game runs, the score changes, so the value in the action =
'She shouted "Go away!"'
player_score = player_score + 1
For example:
can just type in the variable name in the Python shell. It will
>>> player_score = 0
>>> player_score
>>> player_score
name = 'Zoe'
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:16
Text
Page:17
CHOOSE A GOOD NAME
being used.
playerScore.
Zyxo
This will not work because the variable name has spaces. You will get
a syntax error—Python telling you that it does not understand.
name?
alienName = 'Speedy'
alien_name = 'Speedy'
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:18
BIG IDEA
GETTING DATA
This is the name of the variable that will get the information entered
by the user. The information is always a string.
To get information from the user via the keyboard, use the input
function. This function takes the prompt given to the user and returns
the information received from the user into a variable. For example:
Then, type in your name and press Enter. If you type the variable
name in the Python shell, you can see that the value stored in it is the
information you entered. See below on how this works.
>>> name
'Nico'
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:18
Text
Page:19
BIG IDEA
OUTPUTTING DATA
ON A SCREEN
hello, world!
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:20
Outputting Data in Python
For strings:
print("Shelly's friend")
print(23)
>>> print('Your final score is', player_score) Your final score is 100
>>> print('Nice to meet you', username, '.') Nice to meet you Zoe .
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:20
Text
Page:21
BIG IDEA
ADDING COMMENTS
TO YOUR CODE
code do?
I forget!
comments.
In this book, all comments will be shown using bold text. As you’re
trying out the example code on your computer, you do not have to
enter the comments.
You will find far more comments in the code in this book than what an
average programmer may use because here they are used as a
teaching tool to explain more about the code.
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:22
BIG IDEA
DOING MATH
ON THE COMPUTER
Calculating in Python
The Python shell can be used as a powerful calculator. Type the
following into the Python shell to experiment with basic math
operations. Remember, you do not need to type in the comments—
anything after and including #.
34 * 45 # multiplication is denoted by *
57 / 2 # division is denoted by /
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Title:
itle:
Page:22
Text
Page:23
777
867
>>> 34 * 45
1530
>>> 57 / 2
28.5
>>> 57 // 2
28
>>> 57 % 2
1
>>> 3 ** 2
>>> round(100/3, 2)
33.33
>>> (100 - 5 * 3) / 5
17.0
For example:
width = 100
height = 20
Please note that the above variables have numbers without a decimal
point (known as integers).
You can also use numbers with decimal points, known as floats. Try
the following in the Python shell:
distance = 102.52
speed = 20
time
24 /:: CREATIVE CODING IN PYTHON
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:24
When the user enters information, it is always text, even if it looks like
a number!
number + number
can see it by entering number in the Python shell to see that it For
example, to convert the variable in this example to an has quotation
marks around it. In the example shown, the user integer and store it
again in the same variable, number, entered 2, and it appears as ‘2.’
So adding two strings results in do the following: concatenating the
strings (combining two pieces of text); the
number = int(number)
'22'
number = int(number)
number + number
'22'
>>> number
'2'
>>> number
2
>>> number + number
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:24
Text
Page:25
PROJECT
You can change the actual text of the chatbot responses or questions
to customize it.
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:26
I love chocolate and I also like trying out new kinds of food How about
you? What is your favorite food?: pizza
So far, we have used the Python shell to try out a few lines of code.
Now that we are making a project that we want to save and edit
easily, we will use a file to enter the code.
3 Click on File > Save As and save it on your computer with the name
Chatbot.py (or any other name; this is just a suggestion).
4 You can run the code by clicking on Run > Run Module.
The file ending in .py indicates that it is a Python file. You can run this
Python file by clicking on Run > Run Module and also from a
command line interface on any computer that has Python installed.
For example, you can run the project from a terminal window on Unix
or Mac using python3 Chatbot.py.
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:26
Text
Page:27
Step 3:
I will be 100
be 100.)
name?
in 2104
Pseudocode
Step 2:
To start, the chatbot introduces itself using print statements and asks
the user for their name using an input statement. The Python Code
at End of Step 3
name entered by the user is stored in a variable called name and
used again later to print a custom message.
Pseudocode
number: ')
# chatbot introduction
print('I like animals and I love to talk about food') myage = int(myage)
Add the code above to your file and then test it by clicking on nyears)
Add the code above to your file and then test it by clicking on Run >
Run Module.
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:28
Step 4:
Template Responses
We can now ask and respond to the user on a few topics, using the
data entered by the user where possible in the conversation. Here is
an example of a conversation on food and another one on animals.
Notice how the responses entered by the user are stored in variables
and reused in the print statements.
I will be 100
in 2104
# food conversation
print('I love chocolate and I also like trying out new kinds of food')
food = input('How about you? What is your favorite food?: ') print('I
like', food, 'too.')
howoften = input(question)
# animal conversation
print('I wonder if a', animal, 'likes to eat', food, '?') Add the code above
to your file and then test it by clicking on Run > Run Module.
Yummy!
I like chocolate.
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:28
Text
Page:29
Step 5:
Add the code above to your file and then test it by clicking on Run >
Run Module.
feeling?
Step 6:
# goodbye
GOODBYE
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:30
How Can You Make This Chatbot Better?
One of the biggest problems with this project’s code is that the
computer does not have any choice on what output to give.
USEFUL CHATBOTS
a human’s voice.
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:30
Text
Page:31
NEXT STEPS
Experiment 1:
Mad Libs
Using the idea of storing user input into variables and using them in
new output, you can create a version of the classic Mad Libs game.
MAD LIBS
Pseudocode
by Stern and Price. One player asks others for a list Print Mad Lib
sentences using responses
then reads out the usually funny or silly story or Name an object in
this room: table
sentence. Stern and Price’s original Mad Libs book What kind of food
do you like?: pizza
into his convertible (noun) and drove off with his (adjective) wife.”
restaurant.
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 32
13/9/18 11:26 AM
Title:
Text
itle:
Page:32
Experiment 2:
Pseudocode
Sample Run
-------------------
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:32
Text
Page:33
Experiment 3:
Unit Converter
Pseudocode
Print cm
Get pounds from user
Experiment 4:
Ask the user for the total of the restaurant bill, what Print kg
percentage tip they want to give, and the number of people Get
fahrenheit from user
the bill is to be shared between. Give the total tip and total Convert
fahrenheit to integer
amount, followed by the tip amount per person and total of the Set
celsius to fahrenheit - 32 / (9/5)
Print celsius
Pseudocode
Sample Run
Print tip per person , tip amount / number of people Print total
per person , total amount / number of people Sample Run
--------------------------
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:34
Experiment 5:
Paint Calculator
Ask the user for the length, width, and height of a room in feet and
ask for the number of doors and windows. Give them the total area to
be painted and the amount of paint needed for the walls, assuming
you can subtract 20 square feet for each door and 15 square feet for
each window and that the paint coverage is 350 square feet per
gallon.
Pseudocode
Print PaintArea
Sample Run
13/9/18 11:27 AM
13/9/18 11:26 AM
Title:
Title:
itle:
Page:34
Text
Page:35
Use a list
of colors
to create
rainbow art.
Use the
Python turtle
to create
artwork.
Experiment
with shapes,
backgrounds.
itle:
Page:36
Use a list
Use loops to
of colors
to create
create intricate
rainbow art.
geometric
patterns that
in code.
CREATE YOUR
OWN ART
MASTERPIECES
Use your
creativity
to make
drawings of
faces, houses,
and more.
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
T
itle:
Title:
itle:
Page:36
Text
Page:37
BIG IDEA
TURTLE GRAPHICS
import turtle
Using turtle graphics is a fun way to learn Python and create artwork
using code.
for the turtle. In the examples in this book, we call our turtle
➜ Changing colors
“shelly,” but you can use any word or name as the variable.
shelly = turtle.Turtle()
WHY A TURTLE?
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:38
y axis
CHANGING THE
x = −400, y = 300
x = 400, y = 300
TURTLE’S SHAPE
turtle by entering:
x = 0, y = 0
x axis
shelly.shape('turtle')
x = −400, y = −300
x = 400, y = −300
LOCATION IN TURTLE
following Python functions into the Python shell one line at a time to
see what You can always find out where you are by
they do. To make it easier, move the windows so you can see the
Python shell printing out the current coordinates.
window and the turtle graphics window next to each other and watch
the drawing change as you enter each line of code.
print(shelly.xcor(), shelly.ycor())
shelly.forward(100) # moves shelly forward 100 steps Computer
screens can vary, so some of
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:38
Text
Page:39
BIG IDEA
LOOPS
Pseudocode
shelly.forward(100)
shelly.left(90)
the variable i and runs it again. Here’s what your code move 100
steps forward
for i in range(4):
shelly.left(90)
The code above is repetitive. Do you see the pattern? There are two
lines that are repeated 4 times, one for each side of the square.
called a loop.
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
T
225269 - Creative Coding in Python
Text
itle:
Page:40
This is a variable that’s a counter in the loop. It’s called i in this
example, but you can use any variable name.
shelly.forward(100)
the next line of code must be indented to show that it’s the code that
repeats.
You should see the turtle draw a square in the turtle graphics Adding
Color
window again and print the numbers 0, 1, 2, and 3 in the To color in
the square, you must call the function begin_fill Python shell, as
shown below.
and set a color before the shape is drawn and then end with an
end_fill function.
can enter this in the Python shell line by line or create a new file 2
# red square
shelly = turtle.Turtle()
for i in range(4):
shelly.forward(100)
shelly.left(90)
Move forward
Turn left
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:40
Text
Page:41
Python Turtle Graphics
Nested Loops
Look at this shape. Can you see it is a series of squares, each turned
a little (exactly 60 degrees, actually)? To make this, we can use the
loop above to make the square and then repeat that loop six times,
with a 60 degree turn in between each repetition. We will repeat
something that itself repeats.
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
T
225269 - Creative Coding in Python
Text
itle:
Page:42
HOW TO FORCE YOUR CODE
TO STOP RUNNING
If your code is running and you must stop it at any time, you can
move your mouse to the Python shell and enter a Control+C to break
out and force an abrupt stop of the program. This is helpful when you
realize you have made a mistake in the turtle graphics program and
you do not want it to finish, or as we will learn in Chapter 3, you
create an infinite loop and the program is never going to stop.
Move forward
Turn left
Here is the pseudocode to draw this shape. As you can see, the loop
for the square is inside the loop that repeats 6 times.
Pseudocode
for n in range(6):
for i in range(4):
shelly.forward(100)
shelly.left(90)
shelly.right(60) # add a turn before the next square Experiment by
changing the numbers in the code above. Instead of the outer loop
repeating 6 times, what happens if you change it to 100 times? What
else will you need to change to make the squares closer together?
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:42
Text
Page:43
BIG IDEA
STORING DATA
IN LISTS
To get the color red, the computer can then access item 0 in the list.
Computers number items in a list starting at 0. The first item is the 0th
item in the list.
I must
remember
all these
colors. I will
make a list!
red
green
blue
Red een
Gr Blue
COLORS
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Page:44
How to Set Up a List in Python
To get each color in order, you need to get the 0th color, 1st color,
2nd color, and so on—basically the color corresponding to the
counter in the loop. If the counter in our loop is colors = ['red', 'green',
'blue']
i, we
Notice how the list is enclosed with square brackets and how each
item, in this case name of color, is separated by a comma.
shelly.color(colors[i])
Because each color name is a piece of text, it is written in quotation
marks.
Try this by entering the following code. You should see three lines,
one for each color printed in the Python shell.
for i in range(3):
shelly.color(colors[i])
shelly.forward(50)
print(colors[i])
colors[0]
colors[1]
Note: Python lists are very powerful, and we can use them in many
ways. We will learn more about using lists in Chapter 4.
>>> colors[0]
'red'
>>> colors[1]
'green'
You can change the color for your turtle by taking a color from the list.
For example, to get red you would use:
shelly.color(colors[0])
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:44
Text
Page:45
PROJECT
To begin any turtle project, import the turtle module so Python Turtle
Graphics
you can use the functions. You must also create a turtle (see page
38).
Start a new file called Art.py, enter the following code, and run it to
make sure you get a turtle. Add a comment line on the top to remind
you of the project. Adding comments is good programming practice.
import turtle
shelly = turtle.Turtle()
Pseudocode
import turtle
shelly = turtle.Turtle()
for i in range(6) :
shelly.forward(100)
shelly.left(60)
46 /:: CREATIVE CODING IN PYTHON
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:46
Step 2: Repeat the Hexagon
Now that we have a hexagon using a loop, we can put You can select
the for loop code from your previous project this hexagon code inside
another loop that repeats, to get and press Tab to indent it (or select
and click on Format > a number of hexagons arranged in a circle,
each slightly Indent Region on IDLE).
overlapping each other.
Then, add the for n in range(36): on top and the Modifying the
pseudocode from Step 1, we can turn each shelly.right(10) below it
to handle the other part of the hexagon just 10 degrees from the
previous one. To complete pseudocode.
Pseudocode
To complete Step 2, your Python code should look like this: repeat 36
times the following:
import turtle
shelly = turtle.Turtle()
for n in range(36):
for i in range(6) :
shelly.forward(100)
Python Turtle Graphics
shelly.left(60)
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:46
Text
Page:47
Step 3:
shelly.color(colors[i])
can store related items in a list—like a list of colors. We also saw how
colors[0] gives the first item in the list, colors[1]
give the second item, and so on. We can use the loop to go import
turtle
from item 0 to item 1 and print all the colors in the list. The “i”
in the for loop is a counter, which starts at 0 and stops before colors =
['red', 'yellow', 'blue', 'orange', \
'green', 'red']
shelly = turtle.Turtle()
for i in range(6):
shelly.left(60)
shelly.right(10)
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:48
Python Turtle Graphics
Step 4:
Add the following code to the end of the code in Step 3: Step 4:
nested loop hexagon with background, rainbow colors, and small
white circles
shelly.penup()
shelly.color('white')
for i in range(36):
shelly.forward(220)
shelly.pendown()
shelly.circle(5)
shelly.penup()
shelly.backward(220)
shelly.right(10)
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:48
Text
Page:49
NEXT STEPS
Experiment 1:
squares:
Pseudocode
Move forward 20
Turn left 90
Put pen up
Move forward 30
Hide turtle
Experiment 3:
get you started, here’s the code for making one eye:
shelly.goto(-30,100)
shelly.begin_fill()
shelly.color('white')
shelly.circle(30)
shelly.end_fill()
shelly.begin_fill()
shelly.color('black')
shelly.circle(20)
shelly.end_fill()
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:50
Experiment 2:
Start with the following code, which creates one filled gray Python
Turtle Graphics
square and one filled red triangle:
# make a house
import turtle
turtle.bgcolor('blue')
shelly = turtle.Turtle()
shelly.color('gray')
for i in range(4):
shelly.forward(100)
shelly.left(90)
shelly.penup()
shelly.color('red')
shelly.left(60)
shelly.forward(140)
shelly.right(120)
shelly.forward(140)
shelly.right(120)
shelly.forward(140)
# make a window
shelly.penup()
shelly.pendown()
for i in range(4):
shelly.forward(20)
shelly.left(90)
shelly.hideturtle()
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:50
Text
Page:51
Experiment 4:
Overlapping Circles
Change the code at the end of Step 2 in this chapter’s project Python
Turtle Graphics
Pseudocode
Experiment 5:
Circle of Circles
Pseudocode
Lift pen
Repeat 6 times
Put pen up
Move back 20
Hide turtle
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:52
More to Explore
Can you make one or more of these images? Some are related to the
other challenges in this chapter.
24/9/18 1:08 pm
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:52
Text
Page:53
Run code
based on
user’s
choice.
Repeat
tasks until
you are
ready to
quit.
Title:
Page:54
Use your
creativity and
interactive
fiction.
Make a
custom quiz
game for
friends and
family.
CREATE
YOUR OWN
ADVENTURE
GAMES
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Page:54
Text
Title:
Page:55
BIG IDEA
COMPUTERS UNDERSTAND
Python is
simple to
True.
learn.
24 is an
even
True.
number.
312 is
less than
123.
False.
Computers use this true and false value to determine which part of
the algorithm (which code) must be executed.
In the Introduction, we saw how decisions can be shown using a
diamond shaped box. In this example, based on whether BOOLEAN
VALUES
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:56
True
R is equal to 0.
False
STOP
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:56
Text
Page:57
Comparing Items in Python
We use two equal signs (see below) to compare two items. The result
is the value True if they are indeed the same or the value False if
they are not.
>>> name = 'Zoe' # set the variable name to the value Zoe
False
>>>
True
False
BOOLEAN
EXPRESSIONS
True
Any statement that evaluates to
expression or a condition.
True
x<2
choice == 'yes'
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:58
BIG IDEA
Take an umbrella.
AND
I have an
AND OPERATOR
umbrella.
OR OPERATOR
NOT OPERATOR
If we know that “It is warm outside” is false (it is NOT true), we can
decide that we should take a jacket.
So ”take jacket” is true if “it is warm outside” is false; it is the opposite.
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:58
Text
Page:59
For example: The game can proceed if both the number of lives
(stored in variable lives) and amount of time left in game (stored in
variable game_time) are greater than 0.
# game proceeds only if there are lives and time left We can also
use the OR operator (or) to combine two Booleans.
For example: The game must end if either number of lives (stored in
variable lives) is equal to 0 or if there is no time left; that is, the
amount of time left in the game (stored in variable game_time) is
equal to 0.
True and False are recognized in Python as Boolean values, and they
are case sensitive. Try the following in the Python shell:
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 60
13/9/18 11:26 AM
Title:
Text
itle:
Page:60
BIG IDEA
CODE BASED ON
CONDITIONS
True . . . If block of c
ode
(both have to be true), I will make a fried egg for breakfast and then
sit down and eat it. Else, I will take a granola bar to
eat on the way. Based on the condition being true or false, you do
different actions.
Make
an
egg?
Make
True
instant
oatmeal?
False
Take a
granola
bar to
go?
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:60
Text
Page:61
work.”
>>> day = input('enter day of the week ') Try this in the Python shell:
alarm = 'OFF'
>>> if raining:
print('It is a weekend - sleep in!')
else:
alarm = 'ON'
print('Take an umbrella')
It is wet outside
Take an umbrella
>>>
Run the above code again, and this time set raining to be False.
INDENTED CODE
Once you type in the colon in the conditional statement, all the lines
of code after it must be indented to denote it as the block of code that
must be run.
if
else
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:62
Nested Conditionals
Often, we may check on another condition after the first one and then
decide further. There are no eggs or there is not enough time to make
fried eggs for breakfast, so we now check to see if there is time to
make oatmeal. We can add an if-else statement inside another one.
True
refrigerator AND
False
True
of time.
False
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:62
Text
Page:63
Nested Conditionals
Here is a simple number guessing game that you can try by creating
a new file called guessNumber.py and entering the following code. In
this example, there is an if-else statement inside the else part of the
code; if the number entered by the user is not equal to the secret
number, then it checks to see if it is lower or higher to give the user
the appropriate message.
secret_number = 87
else:
else:
number.
83?
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:64
Elif Statements
It depends on the
In the example below, a set of code is run for Monday and day of the
week.
alarm = '7.30am'
carpool = True
coding_class = True
Monday X X
gym = False
Tuesday X
Wednesday X
alarm = '7.30am'
Thursday X X
carpool = False
Friday X X X
coding_class = False
Saturday X
gym = True
Sunday X
alarm = '6.30am'
carpool = True
coding_class = False
gym = False
else:
alarm = 'OFF'
carpool = False
coding_class = False
gym = True
BOOLEAN VALUES
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:64
Text
Page:65
BIG IDEA
COMPUTERS CAN LOOP
BASED ON A CONDITION
Too
high
Unlike the for loop in Chapter 2, which is used to run code a fixed
number of times, this kind of loop is used when the exact number of
times to run the code is not known. It runs until Too
low
For example, in the guessing game on page 64, we may want to keep
playing the game so long as the user has not guessed the number.
Instead of specifying a fixed number of tries (a 83?
fixed number of times to run the loop), we will let the code Guess the
run until they guess the number. We use these kind of loops
number?
In this example, we do not know how many turns it will take 27? the
user to guess the number.
The flowchart at right has a loop—you can see the line going back.
The decision box at the top of the loop is the condition to be tested in
the conditional loop.
Here is the code for the flowchart. Enter it in a new file called
guessNumberVersion2.py.
condition from the block of code that will run when this condition is
true. Python expects the block to
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:66
Set secret_number
True
n equals secret_number?
Print “done”
STOP
False
True
n > secret_number?
False
SAMPLE RUN
secret_number = 87
n = input('Guess the secret number between 1 and 100 ') 1 and 100
89
n = int(n) # convert user input into an integer Your guess was too
high
and 100 12
if n > secret_number:
and 100 29
else:
and 100 99
n = input('Make another guess between 1 and 100 ') Your guess was
too high
You got it !
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:66
Text
Page:67
Forcing User Input with While Loops
A while loop can be used to force a certain input from the user. For
example, if the only choices that should be entered are “yes” and
“no”, the while loop can run code to keep asking the user to enter
input again if their input is something else.
# end of while loop, code entered here runs when input is valid
STRUCTURE OF A
CONDITIONAL LOOP
Pseudocode
Change condition
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:68
PROJECT
CREATING AN
ADVENTURE GAME
nested conditionals.
tains and hears a sound. She gets lost and SAMPLE RUN OF THE
GAME
*************************************************
Do you start running (r) or stop to make a call (c)?: c to make sure it
works.
The call does not go through.
Do you want to run (r) or try calling again (c)?: c The call does not go
through.
Do you want to run (r) or try calling again (c)?: r ERROR CHECKING
for errors.
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:68
Text
Page:69
Step 1:
Add an Introduction and Have the User
Make a Choice
print statements and get the user to pick an item to take on the
adventure by using an input.
Print introduction
# adventure game
print('You can pick one item to take with you - ') print('map(m),
flashlight(f), chocolate(c), rope(r), or stick(s): ') item = input('What do
you choose?: ')
Yes
No
Print-you return;
else:
print('The sound is behind you and is getting louder. You panic! ') 70
/:: CREATIVE CODING IN PYTHON
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:70
Step 2:
Add a Loop
?
Now that we have created two different possibilities, we will add more
code to extend the story. In this step, we add to the else section (in
which the user starts walking back and the sound gets louder).
We give the user a choice to run or call for help, but using a while
loop, we only let them proceed if they choose to run.
After the else part in Step 1, that is, right after this line of code:
print('The sound is behind you and is getting louder. You panic! ') Add
the following code:
action = input('Do you start running (r), stop to make a call (c)?: ')
while action == 'c':
action = input('Do you want to run (r), or try calling again (c)?: ') Here
is the code for this step.
# adventure game
print('You can pick one item to take with you - ') print('map(m),
flashlight(f), chocolate(c), rope(r), or stick(s): ') item = input('What do
you choose?: ')
print('You hear a humming sound.')
Action = c?
if choice1 == 'y':
Yes
print('The sound is behind you and is getting louder. You panic! ')
CREATE YOUR OWN ADVENTURE GAMES ::/ 71
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:70
Text
Page:71
Which
way?
Which
way?
Which
way?
Step 3:
In the if part of Step 1 (when the user follows the sound), we can ask
for a choice of direction once the sound stops.
Get direction
Yes
Yes
North?
Reach cabin
Map?
No
No
Yes
West?
STOP
You lose.
STOP
No
You win.
No
Yes
Yes
South?
Reach bridge
Rope or stick?
No
No
Yes
Reach highway
Flashlight?
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:72
After the if part in Step 1, that is, right after this line of code: print('You
try to call on your phone, there is no signal!') Add the following code:
if item == 'm':
else:
print('If you had a map, you could find your way from here.') print('---
You are still lost. You lost the game.---') elif direction == 'south':
print('You chose an item that can fix the bridge.') print('You fix the
bridge, cross over, and find your way home')
print('CONGRATULATIONS! You won the game.')
else:
print('If you had a rope or a stick, you could fix the bridge.') print('---
You are still lost. You lost the game.---') elif direction == 'west':
print('You are walking and trip over a fallen log.') print('You have hurt
your foot. You sit down and wait for help.') print('This could be a long
time. You are still lost.') STOP
You win.
else:
print('If you had a flashlight, you could signal for help.') print('---You
are still lost. You lost the game.--') CREATE YOUR OWN
ADVENTURE GAMES ::/ 73
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
Page:72
Text
Page:73
STOP
woman appears.
You win.
What is my favorite
programming language?
Yes
Step 4:
Yes
Python?
Chocolate
Add a puzzle or quiz question that the user must answer correctly No
No
to determine the next action. Add this after the user is running fast,
after the code in Step 2.
STOP
You lose.
After this while loop, when you are running fast, that is, after the line:
print('You are running fast and then the sound gets really loud') Add
this code:
print('She rides away, leaving you alone and lost.') print('You lost the
game.')
else:
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:74
PYTHON?
STOP
pyt
You win.
ho
Step 5:
n?
Python?
working.
We can improve the step at which the user must type in “python” by
allowing them to type in the answer using uppercase, lowercase, or a
combination—that is,
Chocolate
if answer == 'python':
to:
This will work but seems repetitive. Instead, you can convert the
user’s response to The best way to work on any coding
if answer.lower() == 'python':
to run better.
We can also add some basic error checking. Using what we learned
in the previous section, we can add a while loop and force the user to
retry if they do not type in MANIPULATING
the correct answer. When we ask the user to make the first choice
between y and n, we can check that they actually type one of them.
The Boolean condition (choice1
TEXT
the start of the while loop. The new code for this section is as follows:
ways to manipulate text (strings)
to do this.
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:74
Text
Page:75
Step 7:
Step 6:
To make the game run better, you can slow down the output by
inserting a 1 Change the actual text of the story to a
pause. This allows the user to read and makes it more dramatic. For
example, better story.
in the beginning of the story, just before you tell the user they are lost,
you can 2 Change or add more items to choose in
the beginning.
To insert this pause, use the sleep function, which is part of another
Python 3 Change or add more questions asked
actions.
import time
Then, at any place you want to pause, enter the following code. The
number in input is valid.
and no.
time.sleep(3)
if choice1 == 'y':
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:76
NEXT STEPS
Experiment 1:
Password Checker
Create a password checking program that lets the user keep trying
until they get it correct. Use any password to test your program.
Pseudocode
Print incorrect
Get password from user
Print Correct
Sample Run
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
T
225269 - Creative Coding in Python
itle:
Page:76
Text
Page:77
Experiment 2 :
Many people multiply the age of a dog by 7 to get the equivalent age
in human years. A more accurate calculation for the age of dogs and
cats in human years is as follows.
Dogs:
■ 1st dog year = 12 human years
Cats:
Using this information, write a program that asks the user if the
animal is a dog or cat, along with its current age, and prints out age of
the animal in human years.
Sample Run
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:78
Experiment 3:
Quiz Game
Pseudocode
Set score to 0
if answer is correct
Print Correct
Increase score by 1
else
Print Incorrect
Print score.
Your score is 1
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 79
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:78
Text
Page:79
Experiment 4:
Set n to 0
Print n
Increase n by count by
SAMPLE RUN
14
21
28
Enter return to continue or q to quit:
35
42
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:80
Experiment 5:
Sample Run
13/9/18 11:28 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:80
Text
Page:81
Build smart
strategies
for your
Generate
computer
poems that
games.
surprise your
friends.
Create art
that changes
program runs.
Use your
creativity
and create
your own
games of
chance.
13/9/18 11:26 AM
Text
functions to
reuse code in
powerful ways.
CREATE YOUR
OWN DICE
GAMES
Challenge
your friends
to your
custom word
games.
13/9/18 12:08 PM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:82
Text
Page:83
BIG IDEA
CREATING
block of code that must be indented below it. Again, IDLE will A
simple example is the code we wrote in Chapter 2 for auto-indent any
line after entering : .
creating a square with the turtle. If we name the code square, Let us
look at the example of creating a square using the turtle.
we (or anyone who uses our code) can create a square at any We
saw the following code in Chapter 2:
import turtle
shelly = turtle.Turtle()
1 Defining the function. Think of this as teaching the computer a
new word. In the example above, we teach the computer how to
respond to the word square by making a for i in range(4):
square.
shelly.forward(100)
shelly.left(90)
2 Calling the function. Think of this as using the new word that you
have made.
We can take the code that draws the square and give it the In
addition to making reusing code easier, functions help us name
square using the keyword def. We can then call this organize our
code and share it with others.
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:84
# my functions
import turtle
shelly = turtle.Turtle()
def square():
for i in range(4):
shelly.left(90)
is more organized and easier to read, and we can reuse the code for
the square easily multiple times.
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 85
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:84
Text
Page:85
Functions with Parameters
it did not take any information. This always makes a square of size
100. We can change that by adding a size as a parameter so that it is
more flexible and can make squares of any size.
Copy the code from the previous project into a new file called
myfunctions2.py and change the square function to use a size as a
parameter. See the code below. The name of the parameter in this
example is s, but you can pick any name. Inside the code for the
function, s is used instead of a fixed number 100, so it draws a
square on any size that is given to it as a parameter.
To use the square, you must now enter the size needed as a
parameter. So square(100) makes a square of size 100; square(200)
makes a square of size 200.
import turtle
shelly = turtle.Turtle()
def square(s):
for i in range(4):
for i in range(25):
square(i)
shelly.forward(i)
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:86
Functions with Return Values
Sometimes, a function returns something that the rest of the code can
use.
For example, we can create a function that takes a list of scores and
returns their average. In a new file called myfunctions3.py, enter and
run the following:
averageScore = average(scores)
cardno = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', \
'K', 'A']
def make_cards():
cards = [] # start with empty list and add cards for s in suits:
return cards
my_cards = make_cards()
print(my_cards)
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 87
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:86
Text
Page:87
BIG IDEA
AT RANDOM
import random
random.randint(1,100)
use random.choice(listname).
>>> random.choice(fruit)
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:88
BIG IDEA
LOOPING THROUGH
A LIST OR A STRING
For any list of items (for example, names, phone numbers, or scores),
we often want to create a loop in which the computer goes through
the list and executes a fixed amount of code for each item.
hello
user or in a text-based project such as a word game.
Trisha
Kyle
hello
Nico
KYLE
NICO
TRISHA
NAMES
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
T
225269 - Creative Coding in Python
itle:
Page:88
Text
Page:89
This is the variable that will become each item in the list for each time
the loop runs; it is called j here, but you can use a different variable
name.
The : is important; it separates the block of code that will run for the
loop, and this must be indented.
for j in <nameoflist> :
number of times. For example, to say hello ten times, alex, then i =
bob, and so on as it executes the code. Try the we can use:
print('Hello')
Strings work in a similar way: the loop is per character in the For
example:
>>> s = 'Python'
>>> for i in s:
print(i)
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:90
PROJECT
CREATING YOUR OWN
DICE GAME
Let us make a dice game in which the computer and the user take
turns rolling a fixed number of dice to see who can get the highest
total. Each gets one chance to roll again and can decide which of the
dice rolled must be held or rerolled.
In the sample run below, the game is for six dice. The user gets a roll
of 4, 6, 5, 6, 2, and 5 and decides to hold all except the 2. They enter
choices using ”-“ to hold and “r” to roll again.
After the user gets a new roll, the computer rolls, following a strategy
in which anything below 5 must be rerolled. In this game, the
computer wins.
We can also change the objective of the game from highest total to
lowest total or the highest number of 6s rolled or something else.
Because the computer and the user make similar moves, we will use
functions where possible to reuse the code.
ARTIFICIAL INTELLIGENCE
User total 29
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 91
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:90
Text
Page:91
Step 1:
# dice game
ready = input('Ready to start? Hit any key to continue') Run the above
program and make sure it works.
CHOOSING GOOD
FUNCTION NAMES
programmers use lower case with “_” where needed for readability, so
in this book we will use names like find_
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:92
Step 2:
list as a variable called dice (the empty list is indicated by [], which is
the Functions must be defined before they are
open [ followed by the closed ]) and then add to this list by appending
used. It is best to define these at the top of
do this inside a for loop as many times as the number of dice in the
game that uses these function with a comment
below.
To create a list for the computer or the user, we will use a function
that So any program file will be of the type:
takes the number of dice as a parameter and then returns this dice
list.
This is the code to be added to the top of the file (it will be above the
code import …
in Step 1).
def function1():
...
import random
def function2():
def roll_dice(n):
...
dice.append(random.randint(1,6))
return dice
We can then use the above function for the user and for the
computer.
user_rolls = roll_dice(number_dice)
Sample Run
computer_rolls = roll_dice(number_dice)
Computers turn
13/9/18 11:29 AM
Title:
itle:
Title:
itle:
Page:92
Text
Page:93
Step 3:
Before adding the rest of the game, let’s write the function that
decides on the winner. This function takes the lists of dice for the user
and the computer, gets the sum of the each, and prints out who wins
or if it is a tie.
The sum function for lists makes finding the sum of a list of numbers
easy. Once we have the total for the computer and the user, we can
use a conditional statement to determine and print the winner. Add
this function below the function roll_dice.
user_total = sum(udice_list)
print('User total',user_total )
print('User wins')
print('Computer wins')
else:
print('It is a tie!')
Now, call this function just after the code in Step 2 in the main
program area using:
find_winner(computer_rolls,user_rolls)
Sample Run
Computers turn
User total 21
User wins
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:94
Step 4:
Step 5:
We can now ask the user if they want to hold or roll each of Now that
we have the user choices as a string, we can use the dice after their
initial roll. We will use a string for this user that string and the original
dice roll, which was stored as a list, input; the user enters a - to hold
and r to roll. We can loop to create a new version of the list. Because
we will do this for through this user input to decide which dice must
be rerolled both the user and the computer, we will again use a
function.
other functions.
Here is the code to be added after the code for the user rolls, just
before the computer rolls.
time.sleep(3)
for i in range(len(choices)):
dice_list[i] = random.randint(1,6)
time.sleep(3)
while len(user_choices) != number_dice:
Now that we have a roll again function, call this function after
'choices')
roll_again(user_choices, user_rolls)
Run the program. The user can now decide what to hold and what to
reroll, and this determines the next roll.
Sample Run
Computers turn
User total 22
It is a tie!
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:94
Text
Page:95
Step 6:
Use a Strategy to Determine the Computer’s Choices Now that
the user’s choices have been made and the dice have been rerolled,
we must allow the computer to make its choice on what dice to hold
and what to roll again. We can use different strategies to do this. Here
are two possibilities: Strategy 1: Roll everything, so the choice string
is just a series of rs.
Strategy 2: Roll only if the number is less than 5; we will need to use
an if-else statement here.
def computer_strategy1(n):
time.sleep(3)
return choices
def computer_strategy2(n):
time.sleep(3)
if computer_rolls[i] < 5:
choices = choices + 'r'
else:
return choices
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:96
Now, just after the computer rolls, call one of these strategies to
create a new list of choices and use it in the roll_again function as
follows. Add this code just before the call to find_winner, which you
added in Step 3. Remember, finding the winner is the last line in the
project. Check the complete project code online (see page 138) to
make sure you have added the code in the right order.
# step 6
■ Run the entire game inside a loop, to allow three rounds of the
game to determine a final winner.
■ Is < 5 the best strategy to decide on a reroll? Modify the code for
the strategy or add more strategies and/or give the user a choice of
difficulty level to determine which strategy will be used by the
computer.
■ Add some better formatting and/or ASCII art to make the text-based
game look better.
This dice game is yours. You can customize it and make it unique
using your creativity and some Python code.
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:96
Text
Page:97
NEXT STEPS
Experiment 1:
squares to create abstract art that is different each time you run the
program.
Pseudocode
Create turtle
and 360
Draw square using square function with size End filling color of
square
20 and 100
5 and 30
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:98
Python Turtle Graphics
Experiment 2:
is run.
Pseudocode
Create turtle
shelly.right(90)
shelly.forward(30)
shelly.end_fill()
shelly.left(60)
shelly.forward(40)
shelly.right(120)
shelly.forward(40)
shelly.right(120)
shelly.forward(40)
shelly.end_fill() # end fill of color for roof CREATE YOUR OWN
DICE GAMES ::/ 99
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:98
Text
Page:99
Experiment 3:
Experiment 4:
Generate Poems
make_cards function.
Enter any key for another poem or enter q to quit Use the function
-------------------------------
card is higher. (Note that this function assumes you are using There
once was a girl called Serena
the code from the Big Idea section on creating a card deck.) who
wanted to be a ballerina.
whether the first card is the same, lower, or higher than the and made
friends with a cat,
second card. If the cards are not identical, it finds the first part And
ended up lost in Pensylvina.
of the card name (which is the card number), then the order
-------------------------------
in the list of card numbers, and then returns higher or lower Enter any
key for another poem or enter q to quit based on this position.
-------------------------------
if card1 == card2:
-------------------------------
order2 = cardno.index(cpos2)
return 'higher'
elif order1 < order2:
return 'lower'
return 'same'
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:100
Experiment 5:
letters = list(w)
random.shuffle(letters)
scramble_word = ''
for i in letters:
python!
scramble_word = scramble_word + i
return scramble_word
Other Experiments
Try to make:
■ A fortune teller
to 0
ytponh????
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:100
Text
Page:101
Use your
creativity to
special arcade
games.
Create apps
that have
windows,
buttons,
images, and
more.
13/9/18 11:26 AM
Text 5
13/9/18 11:29 AM
Title:
itle:
Page:102
Write code to
handle keyboard
and mouse
controls.
CREATE YOUR
GAMES
Give a
graphical
interface to
projects.
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Page:102
Text
Title:
Page:103
BIG IDEA
GRAPHICAL USER
INTERFACES (GUI)
PRESS HERE
GUI programs are different from the other programs The games in
Chapters 3 and 4 allowed only text-based input in that they have to
respond to external events—for from the user. In this chapter, we
learn how to use GUI in our example, a user clicking on a button,
pressing a key, or games and apps.
13/9/18 11:29 AM
Title:
Text
itle:
Page:104
BIG IDEA
Because a program that uses GUI may change any part of the screen
and be able to react to any events, it must be constantly checking to
see if the screen must be updated and refreshed. It must also listen
to the events (keyboard controls or mouse clicks) and handle them by
calling the event handlers.
The Tkinter module has a GUI event loop called the main loop, and it
should be the last line of code in any GUI project. It loops
continuously, listening and handling events and updating the screen
until the user closes the window (or the program calls a window
destroy function). Assuming the name of the variable for the window
is window, this is the last line that must be added.
window.mainloop()
Window update or
Response to
monitors events
window or cause
handlers
other actions
Events are
Event
generated
handler
function
Functions known
computer using
as event handlers
mouse or keyboard
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
T
225269 - Creative Coding in Python
itle:
Title:
itle:
Page:104
Text
Page:105
BIG IDEA
A WINDOW
Any GUI must start with a window that contains everything in the
game or application. It holds the icons, graphic images, text, buttons,
menus, and so on for the application. The GUI program also should
call the main event loop to constantly listen for events.
The final step as mentioned before is to call the main event loop—this
must be the LAST line in the code.
window.mainloop()
My First GUI
window = Tk()
You should see a window that looks like any other window on similar
to other Windows
your computer.
applications. If it’s on
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:106
BIG IDEA
CLICKABLE
BUTTONS
2 A label widget used as a display text area on the screen where the
text is shown.
We must also connect the button to the code that will run when the
user clicks on it. This code will place information into the display area
on the window.
For the above example, we will have a Click Me button that, when
clicked, prints “Hello, World” to a display area on the screen.
function that runs when the button is clicked. Let’s call this TWO
STEPS
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
Page:106
Text
Page:107
Now, we can add code to create the widgets and then place them on
the screen.
Here is the complete code. Enter it into a file called FirstGUI.py and
run it.
window = Tk()
"black")
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 108
13/9/18 11:26 AM
Title:
Text
itle:
Page:108
Text to be written
on the button
be defined before the button.
created earlier.
My First GUI
Click Me
function hello_function.
Hello, World
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:108
Text
Page:109
BIG IDEA
canvas.pack()
USING IMAGES
Add the above to the FirstGUI.py file before the final GUI main event
loop line, and run IN YOUR CODE:
WHERE IS THAT
Add the following code just after this canvas creation code to create a
circle, a rectangle, text, and an image on this canvas. The comments
explain the various GREEN CHAR?
parameters, including x, y, and color, that must be specified to create
each object.
My First GUI
Click Me
img = PhotoImage(file="greenChar.gif")
Hello, World
Run the file. You should get a red circle, a blue rectangle, “Welcome”
text, and a green character image on the screen. See the note on the
left to find out where to get and place the green character image.
Welcome
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:11
Page: 0
11
BIG IDEA
MOVING OBJECTS
Just like we did for the button, we need to create a function to For
example, let’s say the red circle moves to the right and left How to
Display Objects on the Screen in Python
functions are called event handlers. The association of this for this
widget and then use pack() to display it on the screen.
negative amount.
Here is the code for this function. Add this after the canvas.pack()
Add the above to the FirstGUI.py file before the final GUI main event
loop line, and run it. You should get a blank open canvas area.
def move_circle(event):
Add the following code just after this canvas creation code to create a
circle, a key = event.keysym
canvas.move(circle,10,0) # change x
canvas.move(circle,-10,0) # change x
circle = canvas.create_oval(100,200,130,230, fill = 'red') Now, we
connect or bind this move_circle function to the
canvas.bind_all('<Key>', move_circle)
Add this canvas bind code just before the final GUI main loop.
Run the FirstGui.py file and see if the circle moves with the img =
PhotoImage(file="greenChar.gif")
arrow keys.
Run the file. You should get a red circle, a blue rectangle, “Welcome”
text, and a green character image on the screen. See the note on the
left to find out where to get and place the green character image.
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:11
Page: 0
Text
Page:111
BIG IDEA
MOVING OBJECTS
canvas.coords(mychar,event.x,event.y)
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
T
Text
itle:
Page:11
Page: 2
11
BIG IDEA
GETTING DATA
To get data from the user, an entry widget must be created as follows:
user_data = Entry(window,text='') # initial entry is blank
user_data.pack()
def convert():
if inch_data.get() != "":
cm_display.configure(text = cm_string)
window = Tk()
window.title('Inch to cm Converter')
Inch to cm Converter
100|
254.0
cm_display.pack()
Convert to cm
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
Page:11
Page: 2
Text
Page:11
Page: 3
11
BIG IDEA
CODE TO RUN
Before the call to the mainloop, schedule any other actions using the
after function. For example:
window.after(100, move_candy)
13/9/18 11:29 AM
Title:
Text
itle:
Page:11
Page: 4
11
BIG IDEA
EXITING
A GUI PROGRAM
We can add an Exit button that can be clicked to exit the program.
We will need a function and to connect it to a button as follows.
window.destroy()
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:11
Page: 4
Text
Page:11
Page: 5
11
PROJECT
ARCADE-STYLE GAME
Let’s make a classic arcade-style game with the GUI concepts in this
chapter. We will make The Candy Monster Game with the following
features:
■ The player must catch the candy that falls and the score ARCADE-
STYLE GAMES
■ As the score increases, the candy falls faster and the games very
little puzzle solving and rely on a player’s skill in gets more difficult.
moving accurately, making quick decisions, and hand-eye
coordination. Games usually get more difficult as Obviously, you can
change any aspect of the game—the the play advances.
character, the object that falls, the scoring method, and so on.
Step 1:
The player character is created using a file of image format GIF (ends
in gif). This file should be placed in the Pseudocode
same folder as the Python file. The size of the file should Import
Tkinter and random modules
not be very large (in the examples provided, they are just Create
window, and canvas object
4KB). You can download the sample gif file for this game, Create
game title and instructions text object
file that is copyright free for your use. You can also create Create
score_display widget to show score
your own character using any bitmap editor. Please note Set level to
1
the example in this chapter use gif files because they are Create
level_display widget to show level
the simplest to use in Tkinter. Make sure the file type is gif.
In Tkinter, to use any image on the canvas or in buttons, Call the GUI
main event loop as the last line of code for example, you must first
create an object of type PhotoImage and then use it in the widgets.
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:11
Page: 6
11
The Candy Monster Game
import random
# make window
window = Tk()
Score: 0
Level: 1
score = 0
level = 1
player_image = PhotoImage(file="greenChar.gif")
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
T
itle:
Title:
itle:
Page:11
Page: 6
Text
Page:11
Page: 7
11
Step 2:
Pseudocode
• Set candy_speed to 2
Set y to 0
Increase y
Here is the code for this step. Add this to GUIGame.py before the
final GUI main event loop and test it. Because we have not yet
scheduled the make_candy and move_candy functions, nothing will
change from the first step.
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:11
Page: 8
11
'white']
def make_candy():
candy_color = random.choice(candy_color_list)
bad_candy_list.append(candy)
window.after(1000, make_candy)
canvas.move(candy, 0, candy_speed)
xposition = random.randint(1,400)
window.after(50, move_candy)
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:11
Page: 8
Text
Page:11
Page: 9
11
Step 3:
Here is the code for this step. Add this to the end of the code from the
last step, again making sure it is before the last GUI Pseudocode
main event loop line. Because these functions have not been Define
function update_score_level()
update yet.
If score > 10
def update_score_level():
If score > 20
Increase candy_speed
score = score + 1
score_display.config(text="Score :" + \
str(score))
candy_speed = candy_speed + 1
level = 2
level_display.config(text="Level :" + \
str(level))
candy_speed = candy_speed + 1
the code within the function can access it. The variable str(level))
is not available after the function (outside the def) has run. Variables
that are created outside the function are
cannot modify them unless they are declared global inside the
function. Because the variables score, level,
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:120
Step 4:
Add Code to Check If
Here is the code for this step; add this to the file once again before
the last GUI main when the character touches the candy
event line. Because these functions are not being called yet, there will
be no change and delete it from the list of candy. If it
the game.
return overlap
between items
# checks if character hit bad candy, schedule end_game_over
Set y to vertical difference
def check_hits():
y < distance
Return overlap
candy_list
window.after(2000, end_game_over)
return
Schedule end_game_
over
Else
candy_list.remove(candy)
update_score_level()
window.after(100, check_hits)
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Title:
itle:
Page:120
Text
Page:121
Step 5:
We must now add code to control the player character with Here is
the pseudocode for this step.
the arrow keys. If we call a function each time the arrow key is
pressed, the control will not be smooth. Instead, we determine
Pseudocode which direction the character should move when the
arrow Set move_direction to 0
keys are first pressed, we keep track of this move direction in Define
function check_input(event)
direction value, checking that it does not go off the edge of Set
move_direction to left
the screen.
Define move_character()
Increase character x
Here is the code for this step. Add this code to your file again
FRAMES PER SECOND
just before the final GUI main event loop line. Because the
move_character function has not been scheduled, there will Frames
Per Second (FPS) is an indication of how quickly again be no change
when the program is run.
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:122
global move_direction
key = event.keysym
if key == "Right":
move_direction = "Right"
move_direction = "Left"
global move_direction
move_direction = "None"
Finally, make sure the main game loop is still the last line of code, so
all events are handled.
Here is the additional code for this step. Make sure it is added before
the final GUI main event loop line.
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Title:
itle:
Page:122
Text
Page:123
NEXT STEPS
Experiment 1:
Experiment 2:
Python file. You can get this image from the website listed on Set up
word list and separators list
make_password function
command = create_song)
Code Hint
button.pack()
window.configure(bg="MediumPurple1")
I like kittens
You can also set the same color in the labels using: But not as much
as I love dancing with you!
+ str(random.randint(0,100)) + random. \
top_label = Label(window,text='',bg="MediumPurple1")
top_label.pack()
Password Generator
Generate Password
phone$jump64!
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:124
Experiment 3:
robins
mittens
kittens
Voting App
dancing
Cat person?
I like kittens
Dog person?
Cat lovers = 2
Dog lovers = 3
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:124
Text
Page:125
The Spider Survival Game
Experiment 4:
A new graphic for the player; for example, you could use the stick
figure gif file available at the website listed on page 138
Time: 0
mychar = canvas.create_image(200,360,image = \
player_image)
Use a spider graphic instead of the canvas objects that were used to
make the candy. Place this code outside the make_spiders function
(which is a version of the make_candy The Spider Survival Game
function).
spider = canvas.create_ \
image(0,yposition,image = spider_image)
spider_list.append(spider)
Here is the additional code you will need to add so the player can
move in all four directions and cannot escape into the Time: 9
if key == "Up":
move_direction = "Up"
move_direction = "Down"
13/9/18 11:29 AM
Title:
Text
itle:
Page:126
Experiment 5:
● Turn the Spider Survival game into a Road Crossing game, in def
move_character():
which you update the score only if player can move across if
move_direction == "Right" and canvas. \ the screen, avoiding spiders
and/or other objects, and reach coords(mychar)[0] < 400:
canvas.move(mychar, 10,0)
coords(mychar)[0] > 0 :
When the player reaches a portal icon, the background and
canvas.move(mychar, -10,0)
canvas.
window.after(16, move_character)
● Add a laser or missile launch feature for when you press the
Change the movement so the spiders appear on the left and Space
key. You can create a new canvas object that starts at move to the
right. Note the spiders do not come back once the player and add it to
a new laser list and then schedule they reach the edge.
a function that moves items in the laser list and checks if it hits other
items in the game.
canvas.move(spider, spider_speed, 0)
window.after(50, move_spider)
Change the way the score updates, so it updates every second and
not when there are hits.
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
T
225269 - Creative Coding in Python
itle:
Page:126
Text
Page:127
WHAT’S NEXT?
Now that you have learned to code several projects in Python, what’s
next? Here are some ways to use your powerful new skill and expand
your knowledge of coding in Python.
pressed, and then turns the light off and displays an X when button B
is pressed. In addition, if the micro:bit is shaken, it Pressing
Pressing
this Button
this Button
You could use a micro:bit project like this to build your own A turns
ON
B turns OFF
displays a
displays
check
GND
an X
from microbit import *
import random
May need
to add a
display.show(Image.NO)
resistor here,
LED
depending
on the type
if accelerometer.was_gesture("shake"):
of LED
roll = random.randint(1,6)
elif button_a.is_pressed():
connected to
connected to
pin 1
GND
elif button_b.is_pressed():
display.show(Image.NO)
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:128
What can
I code
next?
led = LED(17)
button = Button(2)
while True:
if button.is_pressed:
led.on()
else:
led.off()
fun and/or useful items that come alive with spinning motors, blinking
lights, and more.
::/ 129
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:128
Text
Page:129
Expand Your Knowledge of Python with These
Additional Concepts
Dictionaries
These are lists that are not ordered and each item is a key-value
pair.
pw
lic e
The key is the name of the player and the value is the score. This is
much a b
ion
files
dlin
exception
try:
machine
physical
learning
computing
print('Candy per person is', int(candy) // int(persons)) except:
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:130
Files
Your project may need to save and read information to a computer file
to be used next time it is run (for example the high score of the
player). Python has many ways to create, read, and modify different
kinds of files. Here is a very simple example that opens a file
containing high scores and prints out the information.
app w
ab
print(scores)
ns
fhandle.close()
advanced
games
There are several modules in the Python Standard Library and are
part of the Python a
alysi
download. We have already used the following in this book: s
machine
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
T
itle:
Title:
itle:
Page:130
Text
Page:131
Coding Easier
While using IDLE, you must have noticed how it helps you write
Python programs by indenting code as needed, color coding different
parts of Python, and highlighting syntax errors. Here are some other
tools in IDLE that can make programming even easier.
Debugger
For most of the projects in this book, if you add a small amount of
code at every step as suggested, and then test each step before
going to the next, you probably won’t come across errors that are too
difficult to find or fix. However, to make coding easier, especially on
larger projects, you should learn to use a debugger. A debugger is a
tool that helps test and find bugs in your code in many ways. For
example, it lets you run the code one line at a time, stop the code
running when it reaches a certain line, and displays the value of the
variables in the program at any point. IDLE has a debugger built in,
which you can find in Python Shell by clicking on Debug On.
>>> s = 'hello'
remember the exact name and usage of the functions, and you can
discover new functions as you code. This assisted
>>> s.
casefold
autocomplete in IDLE, enter the name of the variable and the center
‘.’ and wait for IDLE to prompt with all the possible functions.
count
on the string ‘s’. Once you select the function and enter the endswith
first ‘(‘, IDLE prompts with the list of parameters needed for
expandtabs
the function.
find
format
dir function to find all possible functions. For example, if you have a
string s, type in dir(s) in the Python Shell to list all the ways you can
manipulate the string.
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:132
>>> s = 'hello'
>>> dir(s)
>>> s.capitalize()
'Hello'
>>>
Go Even Further by Using Powerful Third-Party Python
Packages Since Python is a popular and open source language,
there is an active community of users and contributors who have
created software for a variety of applications. They make their
software available for free as packages (collections of modules) for
other Python developers. You can check what is available at the
Python Package Index at pypi.org. Here is a small list of some
popular third-party Python packages that you can look at next.
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
T
itle:
Title:
itle:
Page:132
Text
Page:133
to access the offline Help pages for Python. You can either
Python documentation.
Overflow).
like NumPy and Matplotlib. There are also Python libraries available
that can handle specific kinds of scientific data; for Expand Your
Coding Skills by Learning
example, the Biopython Project provides Python tools for Object-
Oriented Programming
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 134
13/9/18 11:26 AM
Title:
Text
itle:
Page:134
HAPPY
CODING!
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
T
225269 - Creative Coding in Python
itle:
Page:134
Text
Page:135
GLOSSARY
called floats.
algorithm
coding easier
computer
> 5 is false
in Python
program)
known as integers.
to stop
13/9/18 11:29 AM
Title:
Text
itle:
Page:136
program is displayed
Python turtle
sentence
Object-oriented programming: A
parameter
an application.
understands
or is not fixed
::/ 137
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:136
Text
Page:137
RESOURCES
Python
Download Python for free, get help with Python problems and
questions, and learn more about programming.
www.python.org
Quarto Knows
View and download the complete code for all of the projects in
this book, as well as images used in the projects, from the
publisher’s website.
www.quartoknows.com/page/creativecoding
www.computersforcreativity.com
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:138
ACKNOWLEDGMENTS
::/ 139
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 139
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:138
Text
Page:139
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:140
INDEX
importance of, 8
incremental steps, 75
indentation, 62
begin_fill function, 41
abstract art, 98
text color, 10
binding, 111
color
error checking, 75
colored squares, 50
improvement ideas, 76
Boole, George, 56
introduction code, 70
introduction to, 69
text color, 10
buttons
loops, 71
turtle graphics, 41
pauses in, 76
comments, 22
Convert, 113
comparisons, 58
Exit, 115
conditions
user question, 74
combined conditions, 59
flowcharts, 13
pseudocode, 12
calculations, 23–25
definition of, 58
animation, 134
elif statements, 65
changing landscapes, 99
chatbot project
extending, 81
80
ending, 120
feelings comments, 30
file creation, 27
goodbye code, 30
improving, 31
introduction code, 28
introduction to, 26
math functions, 28
response templates, 29
def keyword, 84
circle of circles, 52
code
dice selection, 92
definition of, 8
font for, 9
improvement options, 97
force-stopping, 43
introduction to, 91
::/ 141
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:140
Text
Page:141
reroll function, 95
reroll, 95
roll function, 93
song lyrics generators, 33, 124
strategies, 96–97
sleep, 76
dictionaries, 130
square, 84–85, 86
sum, 94
elif statements, 65
Feurzeig, Wally, 38
files, 131
background color, 48
end characters, 21
hexagon, 46
end_fill function, 41
floats
nested loop, 47
errors
calculating, 24
rainbow colors, 48
repeated hexagon, 47
flowcharts, 13
white circles, 49
forced stops, 43
gif files, 110, 116
runtime errors, 11
functions
Google, 134
begin_fill, 41
binding, 111
calling, 84
experiments
choices, 96–97
abstract art, 98
creating, 84–87
defining, 84, 93
dir, 132
exiting, 115
changing landscapes, 99
end_fill, 41
chatbot extension, 81
circle of circles, 52
find_card_order, 100
loops, 114
colored squares, 50
input, 19
numbers, 80
int, 25
widgets, 107
lower( ), 75
window, 106
makeSpiders, 126
Mad Libs, 32
H
overlapping circles, 52
move_circle, 111
hashtag (#), 22
paint calculator, 35
move_coins, 114
password checker, 77
naming, 84, 92
parameters, 84, 86
quiz game, 79
13/9/18 11:29 AM
Title:
Text
itle:
Page:142
lower( ) function, 75
not operator, 59
environments), 9, 132
Environment)
machine learning
O
autocomplete feature, 132
games and, 91
definition of, 9
operators
and, 59, 60
Mad Libs, 32
imports
modules, 93
math operations
not, 59
chatbot project, 28
or, 59
turtle graphics, 38
overlapping circles, 52
indentation, 62
paint calculator, 35
input function, 19
installation, 9
packages, 133
integers
paint calculator, 35
calculating, 24
Papert, Seymour, 38
converting, 25
micro:bit, 128
password checker, 77
MicroPython, 128
int function, 25
modules
print function
interpreter, 9
CSV, 131
end characters, 21
datetime, 131
importing, 93
loops and, 40
math, 131
projects
random, 88
statistics, 131
time, 76
chatbot, 26–31
lists
webbrowser, 131
unit converter, 34
definition of, 12
loops
font for, 9
PyCharm, 132
PyGame, 133
names
Python
functions, 84, 92
creation of, 8
underscore ( _ ) and, 92
interpreter, 9
variables, 19
name origin, 8
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
itle:
Title:
itle:
Page:142
Text
Page:143
popularity of, 8
shell window, 10
versions, 9
text
values
color, 10
Booleans, 56
comments, 22
False, 56–58
loops, 89–90
True, 56–58
manipulation options, 75
variables
strings, 17, 75
quiz game, 79
time module, 76
naming, 17, 18
Tkinter module
spelling and, 17
imports, 104
user data, 19
widgets, 107
value of, 16
reroll function, 95
turtle graphics
color function, 41
functions, 38, 39
widgets
importing, 38
Canvas, 110
location coordinates, 39
loops, 40–41
shell window, 10
sleep function, 76
Solomon, Cynthia, 38
underscore ( _ ), 92
unit converter, 34
strings
concatenation, 25
converting to integer, 25
definition of, 17
looping, 90
lower method, 75
manipulation options, 75
sum function, 94
syntax errors, 11
13/9/18 11:29 AM
13/9/18 11:26 AM
Title:
Text
itle:
Page:144
Document Outline
Cover
Half Title
Title
Copyright
Dedication
Contents
INTRODUCTION
What Is Coding?
Why Learn to Code?
Why Python?
Installing Python
The First Line of Code
Python Functions
Computers Are Picky: Understanding Errors
Problem Solving: Planning Your Code by Writing
Algorithms
Pseudocode
Flowcharts
1 CREATE YOUR OWN CHATBOTS
Big Ideas
Storing Data with Variables
Getting Data from the User
Outputting Data on a Screen
Adding Comments to Your Code
Doing Math on the Computer
Project
Creating Your Own Chatbot
Next Steps
Experiment and Extend
2 CREATE YOUR OWN ART MASTERPIECES
Big Ideas
Turtle Graphics
Loops
Storing Data in Lists
Project
Creating Geometric Art
Next Steps
Experiment and Extend
3 CREATE YOUR OWN ADVENTURE GAMES
Big Ideas
Computers Understand True and False
Computers Can Combine True and False
Code Based on Conditions
Computers Can Loop Based On a Condition
Project
Creating an Adventure Game
Next Steps
Experiment and Extend
4 CREATE YOUR OWN DICE GAMES
Big Ideas
Creating Your Own Functions
Computers Can Pick Items at Random
Looping Through a List or a String
Project
Creating Your Own Dice Game
Next Steps
Experiment and Extend
5 CREATE YOUR OWN APPS AND GAMES
Big Ideas
Graphical User Interfaces (GUI)
GUI Event Loop
GUI Starts with a Window
Clickable Buttons
Adding Shapes, Text, and Image Objects on the
Screen
Moving Objects Based on Keyboard Controls
Moving Objects Based on Mouse Clicks
Getting Data from the User
GUI Can Schedule Code to Run
Exiting a GUI Program
Project
Creating Your Own Arcade-Style Game
Next Steps
Experiment and Extend
What’s Next?
Glossary
A
B
C
D
E
F
G
I
L
M
N
O
P
R
S
V
W
Resources
Acknowledgments
About the Author
Index
A
B
C
D
E
F
G
H
I
K
L
M
N
O
P
Q
R
S
T
U
V
W