Coding For Kids in Python Create Your First Game With Python
Coding For Kids in Python Create Your First Game With Python
MAP
The first checkpoint (boring adults call them chapters) you will encounter is
titled "the beginning." It would tell you why python should be the
programming language you will use for this adventure and not other
programming languages. Also, it explains how to download the python
application so you can use it on your computer.
Next, you will arrive at a checkpoint called "getting to know python-basic
skills and concepts." This is where you would be introduced to the computer
language. This stage is like the helicopter ride over the city where the
adventure will take place.
Next, you arrive at a checkpoint which contains the "levels." On each level,
you will encounter many villains (bad guys) which you will fight. They will
come in the form of exercises which you would solve (don't worry, they are
not like practices form school) and at the end of each level, you would
encounter a big evil villain which you would have to fight to finish the
degree.
The 1st level is the level of numbers and variables. At the end of this level,
you would earn the medal of courage and bravery, which would unlock level
2.
The 2nd level is the level of the Strings, lists, tuples, dictionaries, and loops
. The villains here are very nasty and will try to confuse you. At the end of
this level, you will earn the medal of wisdom, which unlocks level 3.
The 3rd level is the level of data flow where you will earn the medal of
creation, which unlocks the next level.
The 4th level is the level of functions and modules. At the end of this level,
you would earn the medal of persistence.
The 5th level is the level of the turtles. At the end of this level, you will earn
the medal of craft, which unlocks level 4.
The 6th and final level is the level where you finally begin to create your
games. To enter this level, you need the medals from levels 1to 4. At the end
of this level, you earn the wizard's badge, which shows that you now know
the basics of creating games.
Let's hurry and begin our adventure!!
© Copyright 2020 by Ellen Tale all rights reserved.
This document is geared towards providing exact and reliable information in regards to the topic and
issue covered. The publication is sold with the idea that the publisher is not required to render
accounting, officially permitted, or otherwise, qualified services. If advice is necessary, legal or
professional, a practiced individual in the profession should be ordered.
- From a Declaration of Principles which was accepted and approved equally by a Committee of the
American Bar Association and a Committee of Publishers and Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic
means or printed format. Recording of this publication is strictly prohibited and any storage of this
document is not allowed unless with written permission from the publisher. All rights reserved.
The information provided herein is stated to be truthful and consistent, in that any liability, in terms of
inattention or otherwise, by any usage or abuse of any policies, processes, or directions contained
within is the solitary and utter responsibility of the recipient reader. Under no circumstances will any
legal responsibility or blame be held against the publisher for any reparation, damages, or monetary
loss due to the information herein, either directly or indirectly.
Respective authors own all copyrights not held by the publisher.
This material is provided for educational purposes only and is not intended for medical advice,
diagnosis or treatment. The presentation of the information is without a contract or any type of
guarantee assurance.
The trademarks that are used are without any consent, and the publication of the trademark is without
permission or backing by the trademark owner. All trademarks and brands within this book are for
clarifying purposes only and are owned by the owners themselves, not affiliated with this document.
The information herein is offered for informational purposes solely and is universal as so. The
presentation of the information is without a contract or any type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of the trademark is without
permission or backing by the trademark owner. All trademarks and brands within this book are for
clarifying purposes only and are owned by the owners themselves, not affiliated with this document.
Contents
Introduction
MAP
Checkpoint 1
The beginning
After installing, search for and open IDLE.
Checkpoint 2
Getting to know python: basic skills and concepts
Checkpoint 3
Variables
Level 2
Strings, lists, tuples, dictionaries and loops
Lists
Tuples
Dictionaries
Loops
Trying Loops in a Real Program
Increment and Decrement
Built-in Packages
Generating Random Numbers
Flipping a Coin!
Using break to Exit a Loop
Using continue in a Loop
Running a Program several times
Creating an Infinite Loop
New Style of Building Loops: while True, and break
Level 3
Data Flow
Level 4
Functions and Modules
Modules
Copy Module
Turtle Module
Level 5
Turtle
Other things about the turtle module
Polka Dots Program
Key binding
Click Binding
Level 6
Ping Pong
Game objects
The Ball
Moving the paddles
Game loop
Final Notes
Checkpoint 1
The beginning
Welcome to this checkpoint! You may proceed:
Adventure tools
We introduce you to the means of your adventure.
Your computer: this is the most excellent tool of all for this beautiful
adventure. Your computer is like a gun in a war game; you can’t play without
it.
Computers are mighty but very dumb. They have the power to do beautiful
things, but they can’t do those beautiful things except you command them to
do it.
Computers like humans use languages. When you code, you talk to your
computer in a language it understands. If you know the language of the
machine, you can make it do almost anything you can think of.
There are several languages used by computers. Python is one of these
languages.
Python language has several advantages.
1. Several people use it: Several programmers use Python to “talk” to their computers.
It is used by big companies, too, like Google. This is very good because it means that
your work would quickly be compatible with those of others.
2. It is easy to understand: Python is easily understandable by humans, and this is very
helpful because you can tell your computer what you want it to do without confusing
it or yourself.
3. It has a library: Python has a library (a place where you borrow books or code in this
case) of code that has already been written. With this already written code, you can
have references for what you want to create yourself, or you can use this already
written code and create something more complex.
4. It’s a wonderful tool: with Python, you can create so many great things like games,
programs, interfaces, etc.
5. It has an interactive shell: Python has a platform on which you can test your code.
This is a playground of sorts to see if the computer understands what you are asking
it to do. This is a place where you can practice endlessly with lots of fun.
The End!
I am just kidding!
I hope you are all fired up because I am!
This is where you begin your adventure. You need to follow the following set
of instructions to go ahead.
Installation
You should check if your computer is 32 bit or 64 bit.
You check on Windows Os by going to my computer and making a left click
on your mouse. You then click on properties.
On Mac Os, you click on the Apple icon then click on about Mac.
You need to download python 3. To do this, download Python 3 for free
at https://python.org/.
Windows OS
Download the latest version of python three which should look like this –
Python 3.8.1 Windows x86MSI Installer
Python 3.8.1 Windows x86-64MSI Installer
Once done with the download, install the program. Once installed, open the
python folder and run IDLE.
Mac OS
Download the latest version of python three which should look like this –
Python 3.8.1 Mac OS X 64-bit... (Mac
OS X 10.6 and later)
Python 3.8.1 Mac OS X 32-bit... (Mac OS X 10.5 and later)
The file will be downloaded as a “.dmg” file.
Open the file and run the file python.mpkg. This will install the program.
Open the applications folder and then open Python then open IDLE.
Ubuntu Linux
Python comes pre-installed on Linux.
Click the button for the Software Center in the Sidebar (orange bag)
Enter Python in the search box in the top-right corner of the Software Center.
Select the latest version of IDLE (using python 3.8) and click Install.
After installing, search for and open IDLE.
Checkpoint 2
Getting to know python: basic skills
and concepts
Welcome, great adventurer! I see you have scaled the hurdles at the first
checkpoint. Congratulations. The difficulties here are of a different kind! Do
you think you have the strength to pass this checkpoint?
We shall see. This checkpoint takes place in an ancient town called Adak.
They used to have dragons, but they don't know. In this chapter, you would
get introduced to the people of Adak and their unique way of life.
Good luck, adventurer!
Python Package
Congratulations!! You have installed the python software. Usually, once
installed you find python comes with four things:
The IDLE or the interactive environment
The python interpreter
The python manual
The python module documents
We would use mainly the IDLE or interactive environment. You can ignore
the others for now.
Open your IDLE and let us begin.
IDLE is a unique text editor dedicated to the computer's needs, and it is
essential to a programmer. Other text editors are very fancy, but as a
beginner, you only need a straightforward programmer's text editor.
The IDLE or interactive environment or interactive shell shows you the result
of whatever you do on it almost immediately. Once you click Enter or
Return, it runs your program.
It should be titled Python 3.8.1 Shell and once open; it should look
something like this:
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32
bit (Intel)] on win32
Type "help", "copyright", "credits" or "license ()" for more information.
>>>
For the reason that you will be writing several lines of code, you would need
a text editor to write your code. Fortunately, IDLE comes with such a thing.
1. Once you have IDLE opened, go to file; you should see a list.
2. Click new file on that list,
Or simply press Ctrl + N (Command + N on Mac OS). This should open up a
blank text editing window named Untitled.
You can now type in your code like in the shell, but this time, it wouldn't
show a result immediately. Instead, when you click on Enter or Return, you
are taken to another line to continue your code.
Other advantages of the text editor include
You can use things like Cut, Copy, and Paste.
You can go through the lines of code using the up and down arrow keys.
You can scroll through your program
Don't worry if a lot of this is confusing. You will get the hang of it as you
read on and try what you see. You will make a lot of mistakes, but that is how
great programmers are made.
1st program
To write your first program, open your blank text editor, and follow the
following rules:
Rules
1. Type print: print should be in small letters all through – print and not
Print.
When you type the word print, IDLE colors it (usually purple), this is
because IDLE is telling you that print is a word it recognizes.
2. Type: Once upon a time in a faraway land should be in 'quotes' e.g.
'Once upon a time in a faraway land.'
Words in quotes are turned green in the IDLE shell or text editor; this its way
of telling you that it understands what you are saying it.
Dragon story.py
The city of Adak.py
Adventure in the forest.py
Error messages
There is the computer's way of telling you it does not understand what you
have said it.
There are two standard error types.
Syntax errors and Exception errors
At this stage, you are likely going t have syntax errors rather than exception
errors.
Syntax errors
These are errors that occur when you don't give the computer instructions
properly. Common syntax errors are
Typing Print (with capital letters) instead of print (with small
letters)
Not using brackets
hello tom
Not completing the quotation
PRACTICE
You have made it this far. Good of you. Before you go ahead, you need to go
through these practices to find out more about the lives of the peoples of
Adak. Don't skip this.
You should write a few more programs following the rules above.
There was a peaceful town called Adak.
Its inhabitants were easy-going people.
To a newcomer to the town, Adak would seem strange.
Why? There are these statues all over the place of strange huge
animals of various shapes and sizes.
These statues were made of funny materials that looked and feel
like straw.
Adak is surrounded by a thick forest of trees, which is usually
covered with mist.
The people of Adak are busy; everyone has something to do
Make sure you follow the rules and don't copy and paste, make sure you type
them in yourself so you can make your own mistakes and correct them
yourself.
If you successfully finished the practice, you have earned yourself two coins
form the land of Adak.
Data types
Everything you type into the text editor or the IDLE shell is data (or input).
When you use this data (or information) to form commands for the computer,
you are coding. What the computer displays for you after a command is
called the output.
Data or Input - Code – Output
There are many types of data, but we will deal with the basic four you need
1. Integers (int)
2. Floating-point numbers or floats
3. Strings or Text (str)
4. Booleans (bool)
Integers
These are whole numbers for example; 1,2,3,4,5,6,7, -1,-2,-3,-4,-756, 10456
etc.
They are used to express certain kinds of data like
Dates: 11-07-2014, 24-05-2017
Phone Numbers: 911, 122, 224
Score in a game: Foxes 5 Rabbits 0, Player 1 566 Player 2 5673, high score
234562
Time: 5:56pm, 11:18am etc.
Floating-point numbers
These are numbers with decimal points, for example, 1.75, 23.676, -12.45,
etc.
They are used to express data like
The value of pi - 3.14
Floats and integers are similar, but computers can't tell that. They see them as
related. Integers can become floats
1 -- 1.0
34 -- 34.0
Note: when using integers or floats, you don't need 'quotation.'
Strings
These are standard texts like the ones you are currently reading. For python
to recognize strings, they have to be 'quoted.' The quotation can be single (')
or double ("), but the single is easier to use.
Examples
'In Adak, there was no school.'
'Every child was expected to go with his parents to work daily.'
"At the age of 10, every child explores possible jobs by joining each work
unit for as long as he or she wants."
"At age 15, every child would have picked his or her field of work."
Boolean
These are statements that can either only be True or False.
Example
You are a boy: you are either a boy or a girl. If you are a boy, the Boolean is
exact. If you are a girl, the Boolean is false.
You are asleep: you are either sleeping or awake. Since you are currently
reading this book, you are hopefully awake; hence the Boolean is exact.
You have a goat: if you have a goat, the Boolean is exact, but if you don't
have a goat, the Boolean is false.
As you read further, you will understand the significance of each of these
data types.
The other data types include sound ('wav', mp3), picture (jpeg), videos ('.avi',
mp4), variables, lists, dictionaries, tuples etc.
You would come across them as time goes on.
You have reached the end of this checkpoint!
You have earned yourself five coins from Adak.
You may proceed
Checkpoint 3
Wow! You did it once again.
Welcome to this checkpoint, where you will face the levels.
It would be best if you had some Adak coins by now. As you would have
noticed, the Adak coins are shaped like dragon eggs. You will need them in
the subsequent chapters.
Level 1
Numbers and Variables
Welcome brave adventurer to the 1st level in this checkpoint. I hope you can
win this level to get the coveted medal of courage and bravery.
Numbers
Math Operations
Math operations are mathematical commands carried out by the computer.
For example:
2+3=5
2, 3, and 5 are integers while (+) is an operator that signaled the operation 2
plus 3, which gave 5.
If it seems complex, math operations are simple math you are used to.
For you to carry out math operations, you need operators, which are the plus
sign (+), minus sign (-), etc.
Operators
Operations
+ plus
Addition
- minus
Subtraction
/ slash
Division
* asterisk
Multiplication
% percent
Remainder
** double asterisk
Exponent
// double slash
Integer division
< less-than
Less-than
> greater-than
Greater-than
<= less-than or equal
Less-than or equal
>= greater-than or equal
Greater-than or equal
Order of Operations
Some math operators carry more weight than others and will be used first if
they are used with other fewer important ones.
The order of importance of operators:
Brackets (solve the Math in the brackets 1st)
Exponents
Division
Multiplication
Addition
Subtraction
Examples
10 + 20 * 40
810
Following the order of operators above, the computer will first multiply 20 by
40 = 800 then add 10, which will answer 810.
(10+20)*40
1200
The reason this answer is different is that the computer first adds the numbers
in the bracket since brackets are more important than multiplication.
(10+20)=30 then 30*40 =1200.
((10 + 20) * 40) / 5
240
For this example, the computer attends first to the innermost brackets.
(10+20)=30. It then attends to the bracket outside ((30)*40) = 1200. This is
then divided by 5 (1200)/5= 240.
The people of Adak can carry out their trade and daily activities by
calculating using the simple operations you have just learned. They can
figure how to much money to pay for chicken, cows, grass to feed cows and
goats, milk, etc.
It would help if you tried to understand the simple operations because you
will be tested on them later to win the medal of courage and bravery.
Number variables
This includes variables that store integers and floats.
An example of a number variable is this
a=5
b=6
a is the name of the variable that stores 5 in it.
b is the name of the variable that stores 6 in it.
On your text editor, type the following
a=5
b=6
total = a + b
print (total) You should get 11.
Total is a variable which stored the sum of 2 variables a and b
(This shows that variables can store other variables.)
You should also have noticed that when we asked total to print, we did not
put it in 'quotes'.
We didn't use quotes because variables are different from strings.
Once a word has something stored in it, it is no longer a string.
As a result, ('total') is now very different from (total) since (total) has a + b
stored in it.
NOTE: From now on, >>> will show what you should do in your text editor
and R will the results you should get in the interactive shell.
Don't type R or >>> into your text editor and don't expect the R to show also
when you run a program.
Examples:
A man has a weight of 67kg and a height of 1.86m. Calculate his body mass
index (BMI).
BMI= weight / height2
To solve this, set the variable of height and weight with the value given.
Type in your text editor:
Weight = 67
Height = 1.86
(Weight is now a variable containing 67 and Height a variable containing
1.86.)
>>> print (weight/(height*2))
It did not work? The reason is because
variables are case sensitive.
Try again with
>>> print (Weight / (Height*2))
18.01075268817204
Don't forget to add your units
18.01075268817204 kg/m2
The example we just worked with used both integer variables (Weight = 67)
and float variables (Height = 1.86)
Booleans will be discussed later. Thus we would move on to string variables.
String variables
String variables are variables with strings stored in them.
Example:
>>>Pet = 'cat' (remember that strings
must always be in 'quotation')
The variable pet has the string 'cat' stored inside of it.
String variables can be used to do a lot of beautiful things which we will
discuss later.
If you remember your operations, you will remember that we can do this:
>>>print (Pet + 'food') (don't forget capital and small
letters)
R: Catfood.
Now that you have seen the types of variables, you should know that
variables can have what is stored inside of them changed.
Type in the previous example,
>>>Pet = ‘cat’
>>>Pet = ‘dog’
>>>print (Pet)
R: dog
The reason for this is that you have replaced the string 'cat' with the string
'dog.'
Therefore, when you asked the computer to print Pet, it forgot about cat and
printed dog.
Think of it like this: a variable is like a man that can only remember one thing
at a time. If you tell this man "roses are red" he will remember "roses are red"
as long as you don't tell him anything else. Once you say "bananas are green
or yellow", the man immediately forgets "roses are red" and remembers only
"bananas are green or yellow".
The same thing works also happens with number variables.
Shoe_laces = 2
Shoe_laces = 3
print (Shoe_laces) will give you 3
The number variable has forgotten 2.
Multiple Assignments
You can store different values in different variables on the same line. This
helps shorten your programs and make them easier to read.
Example
>>> a, b, c = 4, 3, 2
>>> print (a)
>>> print (b)
>>> print (c)
You need to separate the variables with commas and do the same with what
you are storing in them.
When you run the above example, you will realize that the computer was able
to recognize each of the values you stored in each variable.
Always make sure that the number of variables matches the number of values
you want to store in them.
Constants
Remember how a variable is like a man who forgets anything he knew before
and remembers only what you just told him? A constant is like that man only
that a constant will only remember the first thing you tell him, and he will
never hear any other thing.
Well, python does not have such. In order not to mistakenly change the value
of your variable as you write a program, you should find ways to write the
name of your variable, so you don't make mistakes.
A common way to do this is to write out your variable in capital letters or to
use a lot of numbers in your variable.
Example
>>> NUMBER = 500
>>> n123umber = 450
This way, when you write want to assign (store) a new value to a variable,
you will not likely pick a variable name you have picked before.
You have earned five Adak coins and the medal of courage!
Level 2
Strings, lists, tuples, dictionaries and
loops
Welcome, o’ brave one!
Strings
We have discussed strings and what they are. We have also discussed how
operators can be applied to them (string concatenation). We would be
discussing strings a little more in this section.
In python, we use ‘quotation around stings to distinguish them from other
things like variables.
Example
>>> ‘The people of Adak are kind’ (single quotes)
>>> “the people of Adak work hard” (double quotes)
Quotations
When you don’t use the quotations correctly, you will get an error message
when you run your code. We have also discussed this earlier.
When you want to use more than one line of text for your code (called a
multiline string), use three single quotes (''')
Example
>>> print (‘“how old am I?
I am 23 years old!’”)
R: How old am I?
I am 23 years old!
The (’’’) 3 single quotes allow you to write multiple lines of code while
moving to the next line.
It can also be used with string variables.
Example
>>> green = '''I like the color green,
It reminds me of nature'''
>>>print (green)
R: I like the color green,
It reminds me of nature
Sometimes, you have to use quotations in the code you are going to write.
Example
>>> print (‘I can’t go to the movies’)
When you run the above example, you will get an error message. This is
because the computer (python interpreter) will only read the ‘I can’. The
other parts of the code will be left unread why?
The computer not being very smart, does not know that the sentence is
complete. The computer reads the apostrophe as a quotation mark. It thinks
that it has read what you want to type within the complete quotation around I
can. The other words outside are thus read as an error message.
The solution to the above problem is simple
>>> print(“I can’t go to the movies”)
The double (“) quotation is different from the single (‘) quotation hence the
computer reads the data between the 2 double quotation and ignores the
single quotation.
This solution also works in reverse if you have a sentence with (“) double
quotation in it.
>>> print (‘Paul said “I am going to school”’)
R: Paul said “I am going to school."
This will run very well.
How about when we have both single and double quotation in a sentence?
>>>print (“peter said “I can’t buy the shoe and the cup; I
can only buy the jug”)
>>>print (‘peter said “I can’t buy the shoe and the cup; I
can only buy the jug’)
In this example, using either the single quote or the double quote will not
work.
There are 2 solutions to this.
Its either we use the (’’’) 3 single quotes
>>>print (‘‘‘peter said “I can’t buy the shoe and the cup; I can only buy the
jug’’’)
R: peter said “I can’t buy the shoe and the cup; I can only buy the jug
Or we could escape!
An escape is a back slash (\). It is used before the quotation mark within the
string.
Example
>>> print (“peter said “I can\’t buy the shoe and the cup, I can only buy the
jug”)
What you are basically telling the computer (the python interpreter) is that
you want it to over look the quotation it is placed behind. It is kind of like a
shield for the quotation inside the string.
When you use the backslash this way, it would not show in your printed
code.
The 3 single quotes are however, better and easier to use, especially when
your code has many apostrophes.
len Function
You can find the number of characters in a string using the len function.
Examples
>>> country = 'Netherlands'
>>> x = len(country)
>>> print(x)
R:11
>>> c= ‘I am a boy and I love jumping.’
>>>print (len (c))
R: 30
Indexing Characters
If we think of a string as a list of characters, then we can think of each
character as an element.
The index is the position of an element in a list or the position of a character
in a string.
Using the earlier example, the string Netherlands has 11 characters.
N
e
t
h
e
r
l
a
n
d
s
0
1
2
3
4
5
6
7
8
9
10
-11
-10
-9
-8
-7
-6
-5
-4
-3
-2
-1
When the computer starts counting strings, it begins its counting at 0 thus to
the computer, N is 0.
Because of the fact that there are 11 characters in the string, the last character
is found at index 10.
You can also use negative index to access the characters in a string,
An index is the position (or number) of a character in a string. (It is
sometimes referred to as a subscript.)
Example:
N
e
t
h
e
r
l
a
n
d
s
0
1
2
3
4
5
6
7
8
9
10
Running number [11] gave an error. This is because Netherlands has only 11
numbers and python begins to count from 0 and thus has only up to index 10.
Negative indices start from -1. Why? There is nothing like -0.
If you remember your number line, you have
……….5, 4, 3, 2, 1, 0, -1, -2, -3, -4,
5…….
Example
>>> country = ‘Netherlands’
>>> print (country [-1])
>>> print (country [-3])
>>> print (country [-5])
>>> print (country [-7])
>>> print (country [-8])
>>> print (country [-11])
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32
bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
==================== RESTART: C:\Users\uf\Desktop\new.py
=====================
s
n
l
e
h
N
>>>
Using placeholders
%s is called a placeholder. It is used like an (underline) _________.
Whenever you type it, you are telling the Python interpreter to put an
underline which you will fill later.
This underline is filled later when you use the % sign. The % sign is placed in
front of what you want to place on the line you drew with the placeholder
(%s).
Example
>>> score = 1000
>>> report = 'I scored %s points'
>>> print (report % score)
R: I scored 1000 points
Here, you stored 1000 in the variable score and “I scored %s points” in the
variable report.
%s acted like as an underline giving this:
I scored _______ points.
On the next line, we use the % symbol to tell the Python interpreter what to
place on the ______ by putting % in front of the variable score. This puts the
content of the variable score on the line drawn by %s.
W e can also use different variables, as in this example:
>>> farm= '%s: are used on the farm '
>>> ab= 'sticks'
>>> cd = 'shovels'
>>> print(farm % ab)
R: sticks: are used on the farm
>>> print(farm% cd)
R: shovels: are used on the farm
Here, you made three variables. The first, farm, includes the string
with %s, which creates an underline. The other variables are ab and cd.
We can print the variable farm, and once again use the % operator to replace
it with the contents of the variables ab and cd to produce different messages.
You can also use more than one placeholder ( %s) in a string,
Example:
>>> r = ‘I ride my bicycle all day’
>>>s = ‘when it rains.’
>>> t = ‘%s, except %s’
>>>print (t %(r, s))
R: I ride my bicycle all day, except when
it rains.
When using more than one placeholder, be sure to wrap the replacement
values in parentheses, as shown in the example.
The order of the values is the order in which they’ll be used in the string.
F strings
This works like the placeholder, but it is much faster. It is used to insert a
variable’s value inside a string.
Example
>>> first_name = "Morris"
>>> last_name = "Johnson "
>>> full_name = f"{first_name} {last_name}"
>>> print(full_name)
To insert a variable’s value into a string, place the letter f just before the
opening quotation mark.
These strings are called f-strings. The f is for format.
You can also use f-strings to write complete sentenses using the information
associated with a variable,
Example:
>>> first_name = "Morris"
>>> last_name = “Johnson "
>>> full_name = f"{first_name} {last_name}"
>>> print(f"Hello, {full_name.title()}!")
R: Hello, Morris Johnson!
You can also store what you assign to F strings in variables.
>>> first_name = " Morris"
>>> last_name = "Johnson "
>>> full_name = f"{first_name} {last_name}"
>>> message = f"Hello, {full_name.title()}!"
>>> print(message)
R: Hello, Morris Johnson!
Format
This was the older and more stressful method of inserting values or variables
into strings or other variables before f strings came along.
Example:
full_name = "{} {}".format(first_name, last_name)
R: Morris Johnson
This method is too long and wastes a lot of time. It is better to use the f string
method.
Adding Whitespaces
Whitespaces are nonprinting characters, such as spaces, tabs, and end of line
symbols.
You can use whitespace to organize what you want to come out on the
interactive shell so that it will be easier for users to read.
To add a tab to your text, use the character combination \t
Exaample:
>>> print("volume")
R: volume
>>> print("\t volume ")
R: volume
To add a new line in a string, use the character combination \n:
>>> print ("Animals:\n goat \n cow\n pig")
Animals:
goat
cow
pig
You can also combine tabs and newlines in a single string. The string
"\n\t" tells Python to move to a new line, and start the next line with a tab.
The following example shows how you can use a one-line string to generate
four lines of output:
>>> print("Animals:\n \t goat \n\t cow\n\t pig")
Animals:
goat
cow
pig
Removing Whitespace
Extra whitespace can be confusing in your programs.
The computer can look for extra whitespace on the right and left sides of a
string.
To be sure that there is no whitespace at the right end of a string, use
the rstrip() method.
>>> play = ' '
>>> print (play)
R:
>>> favorite_language.rstrip()
R
>>> favorite_language
R
When you ask the computer for this value in a terminal session, you can see
the space at the end of the value.
When the rstrip() method acts on the variable favorite_language at the right,
this extra space is removed temporarily.
If you ask for the value of favorite_language again, you can see that the string
looks the same as when it was entered, including the extra whitespace.
To remove the whitespace from the string permanently, you have to associate
the stripped value with the variable name:
Example:
>>> favorite_language = ' '
>>> favorite_language = favorite_language.rstrip()
>>> favorite_language
R
To remove the whitespace from the string, you strip the whitespace from the
right side of the string and then associate this new value with the original
variable, as shown.
You can also strip whitespace from the left side of a string using the lstrip()
method, or from both sides at once using strip():
Example:
>>> favorite_language = ' '
>>> favorite_language.rstrip()
R
>>> favorite_language.lstrip()
>>> favorite_language.strip()
‘Max Weber’
‘James Jones’
‘Janet Simpson’
‘John Meyer’
‘Andrew Anthony’
0
1
2
3
4
-5
-4
-3
-2
-1
In a list, you can refer to and deal individually with each element.
Slicing lists
Like strings, lists can be indexed and sliced:
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
>>> squares [0] # indexing returns the item
1
>>> squares [-1]
25
>>> squares [-3:] # slicing returns a new list
[9, 16, 25]
When you slice, python returns a new list containing the requested elements.
>>> squares [:]
[1, 4, 9, 16, 25]
Lists can also be concatenated like strings.
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Example
>>> cars = ['ford', 'toyota', 'honda']
>>> x_car =cars.pop(0)
>>> print(f"The first car I owned was a {x_car.title()}.")
R: The first car I owned was a Ford.
Dictionaries
Another thing like a list or tuple is a dictionary (dict).
The difference between dictionaries and lists or tuples is that each item in a
dictionary has a key and a corresponding value.
Example
Sports played by people: 'Ronaldo' plays 'Football', 'Jordan' plays 'Basketball',
'Ruth' plays 'Baseball', 'Clarke' plays 'Netball', 'John' plays 'Badminton',
'Bridge' plays 'Rugby'.
When represented in a dictionary looks like this:
Loops
A loop is a piece of code that is repeated until certain conditions are met.
An example of a loop is this:
Wake up
Eat
Sleep
Repeat
A lot of us people carry out this loop daily.
In other words, a loop is a circle that goes on and on.
Another example of a loop is this.
Wake up
Dress up
Go to school
Go back home
Sleep
Except on Saturday and Sunday
Pseudocode
When you wish to write a program, pseudocode is what you first write down.
It is the expression of your code in standard English.
It allows you to think about how you want to solve the problem without first
worrying about the details of the code.
Example:
Pseudocode for a game:
# Introduction
# get a random number
# create a loop
# ask for programmer input
# tell user result
# ask user to play again
# congratulate user
For another game
# design interface
# create ball
# create bounce pads
# make ball move
# create scoring system
# create winning criteria.
Now under each of these sections, the code needed for the computer to carry
out these actions is written.
Pseudocode helps you to easily correct mistakes in your code as you can
easily find where an error or a glitch is coming from. It also helps your code
to be orderly and neat and also make it easy for other programmers to
understand your code.
When you use pseudocode inside your text editor, you need to make it
invisible to the computer or python interpreter. For this, you need the hash
sign.
Hash Sign and the triple comma
The hash sign and the triple comma are used to make things that you write in
your text editor invisible to your python interpreter.
Example
>>> #print (‘I love shopping’)
>>> print (“I love volley ball”)
R: the first print is not obeyed because it is invisible to the computer. The
most critical uses of this is writing pseudo code.
The (,,,) triple comma is used to make large blocks of code invisible to the
python interpreter.
Example
>>> ,,,
>>> #print (‘I love shopping’)
>>> print (“I love volley ball”)
>>> print (‘I will talk’)
>>> print (‘I will run’)
>>> ,,,
>>> print (‘football’)
R: football
This is because the parts of code in between the triple commas above and
below are invisible to the computer.
While Loops
The while loop consists of a ‘while’ statement and a piece of code that is to
run if the while statement is true.
The while statement is often a Boolean. The piece of code that follows the
while statement is commonly referred to as the body of the loop.
The bit of code that comes after the while statement is indented. This is
commonly done with 4 spaces rather than a tab.
When you type the while statement, however, IDLE automatically indents for
you.
When you are finished entering the statement(s) that make up the body of the
loop, you can press Backspace (Windows) or the Delete (Mac) key to move
the indenting level back four spaces.
Examples:
Example:
In the following code, we’ll ask the user to type the letter a, and we’ll keep
asking until the user types an a:
If we don’t have any code that changes the exit condition, we would have on
our hands an infinite loop (a loop that keeps running without stopping)
Trying Loops in a Real Program
The way the program works is this:
The program will ask the programmer for a number.
The program will then add all the numbers below the picked number to the
chosen number.
That is when the programmer enters 9; then the computer will add 1, 2, 3, 4,
5, 6, 7, and 8 to 9 and then give an answer.
#first loop program
x = input('Enter a target number: ')
x = int(target)
y=0
your_number = 1
while your_number <= target:
# add in the next value
y = y + your_number #add in the next number
your_number = your_number + 1
print('your answer to', x, 'is:', y)
First, we get a number from the programmer and get it converted to an
integer.
We then set y to 0; y is to hold the total of all the numbers.
We also set the your_number variable to 1. The your_number variable will be
used to add the numbers from 1 to the number that the programmer entered.
What followed was that they wrote our while statement.
We specified that the loop should keep going until the your_number is higher
than the number in x. When this happens, the while statement becomes False,
and the loop is exited.
In this method, you use the plus and the equals operators, and it gives you the
exact same thing as this your_number = your_number + 1.
If you do this, you will get screens and screens worth of documentation. In
you are truly interested in the details of all the functions, feel free to read
through this documentation. There are a large number of functions that you
can call in the random package. For now, we are interested in one specific
function named randrange.
The purpose of randrange is to generate a random integer number within a
given range. randrange is interesting because the range itself can be specified
in a number of different ways, with different numbers of arguments. Using
the most straightforward form, we’ll call the randrange function specifying
the range as two integers. Here is the way we call it:
random.randrange(<lowValue>, <upToButNotIncludingHighValue>)
You start by specifying the name of the package—in this case, the word
random. After the package name, you type a period (generally read as “dot”).
After the dot, you specify the function you want to call; in this case, you type
randrange to say that you want to use that specific function. In the preceding
line, randrange expects to be called with two arguments: a low-end value and
a high-end value. The low-end value is included in the range, but the high-
end value is not included in the range. The way that we say this is “up to but
not including” the high-end value. (We’ll see this “up to but not including”
concept many times in Python.)
The function returns an integer within the specified range. The most typical
way to use randrange is in an assignment statement, where you save the
returned value in a variable, like this:
<resultVariable> = random.randrange(<lowValue>,
<upToButNotIncludingHighValue>)
Here are some examples:
#random between 1 and 10
aRandomNumber = random.randrange(1, 11)
#random between 1 and 52, to pick a card number from a deck
anotherRandomNumber = random.randrange(1, 53)
The critical thing to remember (which may seem very odd) is that the second
argument needs to be one more than the top end of your intended range.
That’s because the number you specify here is not included in the range.
As an alternative syntax, you can call randrange with only a single argument:
the “up to but not including” high end. If you make this call with only the one
argument, randrange assumes that the low end of your range is zero:
#random between 0 and 8
myRandomNumber = random.randrange(9) # same as random.randrange(0,
8)
Flipping a Coin!
Now it’s time for a good example program that uses random numbers. We
will simulate flipping a coin a number of times. The program will run in a
loop. Each time through the loop, we randomly generate a 0 or 1. Then we’ll
do a mapping. That is, we’ll say that if we randomly get a 0, that means tails.
If we get a 1, that means heads. When the loop finishes, we report the results:
# Coin flip program
import random
nFlips = 0 # to count the number of flips
nTails = 0 # to count the number of flips that came up as tails
nHeads = 0 # to count the number of flips that came up as heads
maxFlips = input('How many flips do you want to do? ')
maxFlips = int(maxFlips)
while nFlips < maxFlips:
# Randomly choose 0 or 1, because a coin flip can only result in one of
two answers
# (heads or tails)
zeroOrOne = random.randrange(0, 2)
# If we get a zero, say that was a heads
# If we get a one, we say that was a tails
if zeroOrOne == 0:
nTails = nTails + 1
else:
nHeads = nHeads + 1
nFlips = nFlips + 1
print()
print('Out of', nFlips, 'coin tosses, we had:', nHeads, 'heads, and', nTails,
'tails.')
Notice that we didn’t randomly pick heads or tails directly. We randomly
picked from a range that encompasses all possible outcomes, and then
mapped the numeric answer to the outcomes we were looking for. In this
case, there are only two possible outcomes, so we get random values of 0 or
1, map 0 to tails, and 1 to heads.
Other Examples of Using Random Numbers
Another example of this approach is if we were writing a program to play the
game of rock-paper-scissors. In this case, there are three possible choices. To
make a random choice, we would generate a random number between 0 to 2
(or 1 to 3, or in fact, any range of three consecutive numbers), and use the
resulting number to make our choice:
import random
choiceNumber = random.randrange(0, 3) # to get a 0, 1, or 2
if choiceNumber == 0:
randomChoice = 'rock'
elif choiceNumber == 1:
randomChoice == 'paper':
else: # not zero and not one, must be 2
randomChoice == 'scissors'
Also, if you want to run the whole program a certain number of times, you
could modify the looping conditions to count the number of times through a
loop:
Example:
nTimes = 0
while nTimes < 4:
x1 = input('Enter a target number: ')
x1 = int(x1)
y1 = calculateSum(x1)
print('your answers to', x1, 'is:', y1)
nTimes = nTimes + 1
print('thank you')
This method allows the user loop to run four times, and this time, the user
will not be asked if he or she wants to go again.
So moving on, take for instance, Michael scored more than 10 points, which
is the requirement for getting candies, the if and else statements in the
previous lesson would tell Michael to try better next time. But Michael
scored higher than 10 points and left to me, and I think he deserves more
candies for scoring better.
This problem can be rectified by introducing an elif statement to the previous
if and else statements.
elif statement
elif statements perform alternative actions specified after the if statement.
Now let’s use the elif statement to make Michael get the reward he deserves
if he scores more than 10 points.
score = 11
if score == 10:
print(‘Give Michael candies’)
elif score > 10:
print(‘Give Michael extra candies’)
else:
print(‘Tell Michael to try better next time’)
Now Michael is getting the extra candies he deserves, and everyone is happy.
Let’s play a little game
Guessing game
This game is called the guessing game. We’ll have to write the code to
implement this game together using simple if, elif, and else statements and a
function called random.
Now let’s copy the following code into our python environment. Please make
sure you indent properly when it is necessary.
import random
print('TYPE A NUMBER BETWEEN 1 AND 9 INCLUDING 1 AND 9')
myNumber =int(input('Guess a number:'))
randomNumber = random.randint(1,9)
print(“Computer’s input is”, randomNumber, “and you guessed”,
myNumber)
if myNumber > randomNumber:
print ('You guessed too high')
elif myNumber < randomNumber:
print ('You guessed too low')
else:
print('Your guess is correct')
Now let’s test and see if it works.
Congratulations!! You have finished this level. You have earned 10 Adak
coins and the medal of creativity!!!
Level 4
Functions and Modules
Functions
Functions are the most basic program structure, which provides means of
maximizing code re-use, which also leads you to the broader notion of
program design, which is not within the scope of this group.
Statement or expression associated with functions
The call expression
The call expression is used to call an already existing function. For example,
if you have a function bakeCake(), the call expression can be used to call the
function.
Format of the call expression
bakeCake(‘egg’, ‘flour’, ‘milk’, ‘water’, ‘sugar’)
The def statement
The def statement is used to create a function object and assigns it to a name
The general format of the def statement
def name (argument1, argument2, …, argumentN):
statement
The return statement
The return statement sends a return object to the caller (user). When a
function computes a value, it sends back the result when the return statement
is called. A return without a value will return to the caller a None value,
which is the default result.
The general format of the return statement
def name (value1, value2):
return value3
Arguments
Arguments are passed into functions by assignment. Changing an argument
name does not change the corresponding name of the caller, but changing the
passed-in objects in place of the former objects can result in a change in the
result of the function.
Arguments are also passed-in by position unless you state otherwise.
Arguments are not declared ahead of time in a function. This rule also applies
to return values and variables. They are not declared ahead of time in a
function.
General format of arguments
def name (argument1, argument2, …, argumentN):
statement
A function will take as many arguments as you want.
Now it’s time to go to the practical aspect of this lesson.
Let’s print a function that accepts two arguments and return strings that are
common to those arguments in a list.
This should be fun
Follow me carefully in every step of this journey.
def intersect(arg1, arg2):
common = []
for x in arg1:
if x in arg2:
common.append(x)
return common
value = intersect('sing', 'sang')
print (value)
Do not panic, I’ll explain this later. But in the meantime, let us see the result
of this code in our python shell or any other python environment currently
been used.
Make sure you follow the indentation rule here strictly.
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32
bit (Intel)] on win32
Type "help", "copyright", "license()" for more information.
>>>
==================== RESTART: C:\Users\uf\Desktop\new.py
=====================
['s', 'n', 'g']
>>>
It worked perfectly. Now let me explain what happens in each line of code so
that you’ll be able to replicate it with ease next time.
The first line of codedef intersect(arg1, arg2):creates the function and
assigns it to the name ‘intersect’
The second line of code common = []assigns an empty list to the variable
name common
The third line of code for x in arg1: is a ‘for’ loop, which iterates through the
first argument, arg1.
The fourth line of the code if x in arg2:is an ‘if’ statement that checks
whether the strings in the first argument, arg1 are contained in the second
argument, arg2.
The fifth line of the code common.append(x) consist of a list operation,
append(), which adds the strings common to both arg1 and srg2 to the list
common.
The sixth line of the code return common is a return statement that returns the
value of the function ‘intersect’, which are all the strings common to arg1 and
arg2 in a list.
The seventh line of code is a blank space that is actually not required but used
to keep the code clean.
The eighth line of code value = intersect('sing', 'sang') is a call expression
which calls the function ‘intersect’ and passes two arguments (‘sing’ and
‘sang’ ) inside it to get the strings common to both cases. This call expression
is then assigned to the variable name value.
The ninth line of code print (value) prints or displays the value of call
expression.
As you can see, it isn’t anything complicated. It is simple and easy to
understand. You can try playing with the code by inserting your arguments
and see if it works perfectly.
Should we take another example before we leave this lesson?
Well, I heard you, I’ll take a final example.
Let’s write a function that takes an argument and finds the divisors of the
argument and returns a list of those divisors.
def divisors(number):
result = [ ]
for x in range(1, int(number/2)+1):
if number % x == 0:
result.append(x)
result.append(number)
return result
value = divisors(24)
print (value)
Just calm down. I’ll explain it. Let’s see the result of this in the python
environment.
Common modules
Time Module
To calculate the current date and time using a built-in module called time:
>>> import time
You have used the import command to tell Python that we want to use the
module time.
You can use the functions of the time module, using the dot.
(we can also call the features of other modules using dot)
Asctime function
asctime function of the time module shows the current date and time.
Example
>>> print(time.asctime())
R: 'Mon Nov 5 12:40:27 2012'
Localtime function
Unlike asctime, the function localtime brings out the current date and time as
an object.
If you print the object, you’ll see the name of the class, and each of the values
labeled as tm_year, tm_mon (for month), tm_mday (for day of the month),
tm_hour, and so on.
>>> import time
>>> print(time.localtime())
R: time.struct_time(tm_year=2020, tm_mon=1, tm_mday=17, tm_hour=15,
tm_min=38, tm_sec=53, tm_wday=4, tm_yday=17, tm_isdst=0)
Sleep function
The sleep function is used when you want to slow down a program.
Example
>>> import time
>>> for a in range(1, 360):
print(a)
time.sleep(1)
R: 1 to 360 will be printed out, but there will be a lag or pause between the
printing of each number.
Shuffle module
This shuffles the items in list.
>>> import random
>>> numbers = [23,34,56,78,89,788,686,5757,54,90]
>>> random.shuffle(numbers)
>>> print(numbers)
R: [23, 56, 788, 34, 78, 89, 54, 686, 90, 5757]
Keyword Module
A keyword in python is any word that is used in the language itself, such as
if, else, and for.
Some functions of the keyword module are
iskeyword
and
kwlist.
Iskeyword is a function which returns true if any string is a Python keyword.
Kwlist is a variable which returns a list of all Python keywords.
>>> import keyword
>>> print(keyword.iskeyword('else'))
R: True
>>> print(keyword.iskeyword('wanda'))
R: False
>>> print(keyword.kwlist)
R: ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
You can try using the iskeyword and kwlist for other words.
Copy Module
The copy module consists of functions for creating copies of objects. Usually,
when typing a program, you’ll make new objects and sometimes
it’s good to type a text of an
object, and then use that copy to
make a new object, particularly
when the process of creating an
the purpose takes several steps.
Example
>>> class school:
def __init__(name, term, number_of_students, uniform_color):
name.term= term
name.number_of_students = number_of_students
name.uniform_color=uniform_color
We could make a new object in the class school using the following code.
>>> h = school(3, 645, 'pink')
We can repeat the previous code over and over again, when we need it more
than once but that will be too stressful. We could instead use the copy
module:
Example
>>> import copy
>>> h = school(3, 645, 'pink')
>>> x = copy.copy(h)
>>> print(x.term)
R: 3
>>> print(h.term)
R: 3
sys Module
The sys module is used to control the python shell.
It contains functions such as
Exit, stdin and stdout objects, and version variable.
exit function
This function will shut down the python shell.
When you enter the code,
>>> import sys
>>> sys.exit()
You’ll be prompted with a message asking if you want to exit. Click Yes, and
the shell will close.
Version variable
You can find out the version of python you are using especially when you are
on an unfamiliar computer:
>>> import sys
>>> print(sys.version)
R: 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit
(Intel)]
Turtle Module
The turtle module is used to create a sort of canvas for drawing.
Example
>>> import turtle
>>> t = turtle.Pen()
Doing this will call the turtle module. We would discuss the turtle module
extensively at the next level.
Congratulations, you have finished this level. You have earned 12 Adak coins
and the medal of craft!!
Level 5
Turtle
Turtle graphics is a popular module for programming for kids (and adults).
You already know that to use turtle, you need to ‘import’ turtle. When you
import turtle, and you run it, nothing happens. This is okay.
The next thing you should know is how to bring up the turtle screen and edit
it to look anyhow you want. To do this, we would discuss a few functions of
the turtle module.
Bringing up the Screen
To bring up the screen, you need to use the turtle.Turtle () function (note that
the second T is capital).
You need to assign the turtle.Turtle () to a variable to make editing the screen
easy. Here we are assigning it to the variable sr.
Example
>>> import turtle
>>> sr = turtle.Turtle ()
R: you would see a screen come up with an arrow in the center.
Congrats, you have just opened up the turtle screen.
You can also use the turtle.Screen function. (note that the S in screen is in
capital letters)
>>> import turtle
>>> sr= turtle.Screen ()
Next, we change the background of the screen.
Changing the background of the screen
To change the background of the screen, we use the .bgcolor function.
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘red’)
This will cause the turtle screen to be red.
You can change the color by typing in any color you want.
We would use white as the background color as we go on.
Naming our Screen
We could name our turtle screen by using the function .title
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
This will cause the turtle screen to be named turtle screen. You could call
your turtle screen any name.
Turtle Setup
For the turtle setup, we will specify the size of the turtle. To do this, we use
the .setup function.
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
This makes the turtle screen 800 points wide and 500 points high.
This has a lot of significance which will become very obvious when we begin
to draw on the turtle screen.
Next, we move the turtle around.
Moving the turtle around
To move the turtle around, we would use the following functions:
turtle.forward (distance)
turtle.backward (distance)
turtle.left (angle)
turtle.right (angle)
turtle.forward
this is to move the turtle forward by a specific number of points or pixels
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
>>> turtle.forward (150)
R: this will move the turtle forward by 150 points to the direction the arrow is
facing.
We can accomplish the same by using
>>> turtle.fd (150)
turtle.backward (distance)
this moves the turtle in the opposite direction.
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
>>> turtle.backward (150)
R: this moves the turtle in the opposite direction.
We end up with the same result by using the turtle.bk () or turtle.back ()
turtle.left ()
this moves the turtle to the left across a the angle specified
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
>>> turtle.fd (150)
>>>turtle.left (60)
>>> turtle.fd (150)
R: you should have straight lines at right angles to each to other.
turtle.right ()
The turtle.right function moves the turtle in the direction opposite to that
which he turtle.left moved it.
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
>>> turtle.fd (150)
>>>turtle.right (60)
>>> turtle.fd (150)
Coordinates
You should notice that the turtle arrow usually starts in the middle with equal
spaces around it.
If you divide the turtle screen into 4 equal halves with two imaginary lines
going through the middle, the point the two lines meet is where you find the
turtle arrow.
The first line goes from up to down while the second line goes from right to
left.
The first line from up down is called the y axis, and the second line is called
the x axis.
The point where the lines meet is and where the turtle is the center. That point
also can be represented with numbers.
The point can be represented by the numbers 0,0. This means that where the
turtle is point 0 on the y axis and also point 0 on the x axis.
The part of the y axis above the turtle is positive, and the sections below the
turtle on the x axis are negative.
The part of the x axis to the right of the turtle is positive and to the left is
negative.
It is just like in trigonometry when you draw graphs.
When you move the turtle, you can always get its coordinates.
To do this use the function .position
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
>>> turtle.fd (150)
>>> print (turtle.position())
R: (150.00, 0.00)
The result will be seen in the python shell.
It means that the turtle arrow has moved 150 points on the x axis and 0 points
on the y axis.
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
>>> turtle.fd (150)
>>>turtle.right (60)
>>> turtle.fd (150)
>>>print (turtle.position ())
R: (225.00,129.90)
This means that the turtle has moved 225 points on the X axis and 129.9
points on the Y axis.
Note that because the angle is 60 degrees, the turtle moved extra on the X
axis as the second line was drawn. Also, the line drawn upwards is bent and
not straight; hence the turtle did not move the full 150 points upwards.
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
>>> turtle.bk (150)
>>>turtle.left (90)
>>> turtle.bk (150)
>>>print (turtle.position ())
R:
=============== RESTART: C:\ Users \ uf\ Desktop \ practice.py
===============
(-150.00,-150.00)
This means that the turtle moved -150 points on both the x and y axes.
The coordinates will come in very handy when we begin to develop our
game.
Pen up and Pen down
These turtle functions help to command the turtle pen to show or not show
some of the lines that it has drawn.
Pen up means that no line will show as the turtle moves while pen down
means the lines will come back.
The code for pen up = turtle.penup(), turtle.pu(), turtle.up() you can use any.
The code for pen down = turtle.pendown(), turtle.pd(), turtle.down()
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
>>> turtle.bk (150)
>>>turtle.left (90)
>>> turtle.bk (150)
>>> turtle.left (90)
>>> turtle.pu()
>>> turtle.bk(150)
>>> turtle.pd()
>>> turtle.left(90)
>>> turtle.bk(150)
The code above draws a square on the python screen we earlier created. The
square has its bottom missing.
This is because the pen up function was applied when the turtle was to draw
the bottom of the square. Hence the line did not show.
You can try to apply the pen up function on your own on any line and also
with lines drawn at various angles.
Pen width
The pen width controls the thickness of the lines drawn by the turtle. The
bigger the pen, the turtle pen is, the bigger the lines.
The code for changing the pen size = turtle.width, turtle.pensize.
You can increase the pen size from 0 (the thinnest) to as high as you want.
Note:
From here on, we will assign our turtle to the variable t.
Example
>>> t= turtle
Drawing a Rectangle
Drawing a rectangle is comparable to drawing a square.
Example
>>> import turtle
>>> sr = turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
>>> t.bk (200)
>>> t.left (90)
>>> t.bk (100)
>>> t.left (90)
>>> t.bk (200)
>>> t.left (90)
>>> t.bk (100)
This piece code tells the turtle to move backward by 200 points, then turn 90
degrees then to draw a line going down by 100 points then turn another 90
degrees then to move another 200 points then to turn another 90 degrees this
time upwards then draw another line 100 points in the distance. This gives us
or rectangle.
You can play with the code, changing the length of your lines.
Note that I am using a turtle speed of 8 for my drawing. You can use
whatever pace you fancy.
I am also using a pen width of 3 for my rectangle.
Drawing a Triangle
Drawing a triangle is a little different from drawing a square.
There are different types of triangles. We will attempt to draw 3 types.
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
>>> t.fd (200)
>>> t.left (120)
>>> t.fd (200)
>>> t.left (120)
>>> t.fd(200)
This code tells the turtle to move forward by 200 points, then to turn 120
degrees then move forward by 200 points, then to turn another 120 degrees
then move another 200 points giving us an equilateral triangle (a triangle
which has all its sides equal )
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
>>> t.fd (200)
>>> t.left (90)
>>> t.fd (200)
>>> t.left (135)
>>> t.fd(280)
This code draws a right-angled triangle.
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
>>> t.fd (140)
>>> t.left (110)
>>> t.fd (200)
>>> t.left (140)
>>> t.fd(200)
This code gives you an isosceles triangle. Two sides of the isosceles triangle
are equal.
You can vary thee parameters and get different results.
Circle
To draw a circle, you use the function turtle.circle (). In the parenthesis, you
input the radius of the circle you want to draw.
Example
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
>>> t.circle(50)
Stars
Remember the loop we used for drawing the square simpler? We can modify
the loop to give a star!
Example
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
>>> for i in range(1, 9):
t.forward(100)
t.left(225)
This code produces an eight-point star:
Unlike with thje square, we looped 4 times with the range (1,5), we loop this
we loop eight times with range(1, 9).
Also, we tell the turtle to move forward 100 points after each loop. We also
made the turtle turn 225 degrees to the left instead of 90 degrees.
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
>>> for i in range(1, 9):
t.forward(100)
t.left(145)
You can just keep changing the size of the angles and the distance the turtle
will travel each time.
Spiraling star:
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
>>> for x in range(1, 25):
t.forward(120)
t.left(95)
Coloring!
The color function in python has three main colors, which are specified by
numbers.
These colors are ‘red’, green, and ‘blue’. The default numbers are denoted by
= (0 to 1).
These colors are the primary colors on your computer. They all mix to form
all the colors you see on your computers.
We already learned how to change the background color of the screen. Next,
we will learn how to change the color of the pen and how to fill shapes.
Changing the pen colour
To change the pen color, you need to use the function; .pencolor
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘white’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
>>> t.pencolor (1,0,0)
>>> t.fd (300)
R: this will return a red line.
Using t.pencolor (0,1,0) will give green and t.pencolor (0,0,1) will give blue.
This is because the first number represents red, the second green, and the
third blue. Together, they form your computer’s basic colors.
You can use different quantities of these basic colors to get any color you
want.
Example
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
>>> t.pencolor (1,1,0)
>>> t.fd (300)
The above t.pencolor (1,1,0) mixes 100 % red and 100% green with )% blue
to form a yellow line.
This code tells the python interpreter to draw a blue pen color. It also tells it
to fill any shape to be filled with yellow (fillcolour ()). The code t.begin fill
and t.endfill allow the circle we have drawn to be filled.
You can play around with the function you just created and try using different
parameters.
Example
>>> filled_circle(150, 1, 0, 0)
>>> filled_circle(150, 0, 0.5, 0.5)
>>> filled_circle(100, 0.8, 0.5, 0.5)
>>> filled_circle(200, 0.9, 0.75, 0.0)
>>> filled_circle(400, 0.95, 0.7, 0.74)
>>> filled_circle(40, 0.9, 0.5, 0.0)
>>> filled_circle(50, 0.9, 0.5, 0.2)
>>> filled_circle(170, 0, 0.5, 0.4)
Creating Pure Black and White
To create black, you will turn off all the basic colors
Example
>>> filled_circle(100, 0,0,0)
This will give you a pure black circle.
To create white, you should use all colors fully.
Example
>>> import turtle
>>> sr= turtle.Screen ()
>>> sr.bgcolor (‘red’)
>>> sr.title (‘learning turtle’)
>>> sr.setup (width = 800, height = 500)
>>> t= turtle
>>> t.speed(0)
>>> t.width(3)
>>> def filled_circle (radius, red, green, blue):
t.color(red, green, blue)
t.begin_fill()
t.circle(radius)
t.end_fill()
>>> filled_circle(100, 1, 1,1)
For this, we changed the background color of the screen to read so the white
circle can be seen clearly.
A Square-Drawing Function
We can do what we did with the circle with almost any shape. We can do it
with Squares too. Let’s create a square drawing function.
Example
>>> t= turtle
>>> t.speed(0)
>>> t.width(3)
>>> t.penup()
>>> t.fd(200)
>>> t.pd()
>>> t.pencolor(1,0,0)
>>> def mysquare(size, angle):
for x in range(1, 5):
t.forward(size)
t.left(angle)
>>> mysquare (70, 90)
R: we get a golden circle and a square drawn with red.
We used the pen up and penned down functions to move the turtle 200 points
from the circle. We then created our square drawing function.
You can try drawing squares of different sizes 25, 50, 125, 75, and 100.
>>> mysquare(25)
>>> mysquare(50)
>>> mysquare(125)
>>> mysquare(75)
>>> mysquare(100)
You will notice that the squares don’t touch the circle.
Drawing Filled Squares
To draw a filled square, we simply upgrade our square drawing function:
Example
>>> def mysquare (size, angle, red, green, blue):
t.color (red, green, blue)
t.pencolor(1,0,0)
t.begin_fill ()
for x in range (1, 5):
t.forward(size)
t.left(angle)
t.end_fill()
mysquare (70, 90, 1, 1, 0)
R: you should get a yellow square with a red outline. We expanded our
function by adding in more parameters. We added in the red, green, and blue
and the function .color. After this, we specified a pen color. We need to add
the pen color into our function else the function will draw a yellow square
without the red line. We also added in the beginning and end fill functions.
You can play around with this square drawing function.
Let’s draw with our functions a golden circle with a pink outline and a pink
square with a golden outline.
Golden Circle with pink Outline and Pink Square with a Golden Outline
import turtle
>>> t= turtle
>>> t.speed(0)
>>> t.width(5)
>>> t.pencolor(1,0,0)
>>> t.penup()
>>> t.fd(200)
>>> t.pd()
>>> def mysquare (size, angle, red, green, blue):
t.color (red, green, blue)
t.pencolor(0.9, 0.7, 0.05)
t.begin_fill ()
for x in range (1, 5):
t.forward(size)
t.left(angle)
t.end_fill()
We have increased the thickness of the pen and also added a pen colour to the
circle drawing function.
Other than that, we just attributed the color parameters for pink and orange.
>>> t= turtle
>>> t.colourmode (255)
>>> t.pencolour (255,0,0)
>>> t.fd (300)
R: this will give you a red line. (0,255,0) will give a green line and (0,0,255)
will give a blue line.
Let’s get back to our star. To accomplish our goal of lines of different colors,
we will import random and use the random. randint function and the colour
mode function we just learned.
Example
>>> import turtle
>>> import random
>>> sr= turtle.Screen ()
>>> sr.bgcolor ('white')
>>> sr.title ('learning turtle')
>>> sr.setup (width= 800, height=500)
>>> t= turtle
>>> t.speed(0)
>>> t.width(5)
>>> def star (size, angle):
t.pencolor (random.randint (0,255), random.randint (0,255),
random.randint (0,255))
t.width (2)
for x in range (1, 100):
t.forward(size)
t.left(angle)
size= size - 1
>>> star (150, 200)
R: When you run this code, the color of the star changes each time. We
imported the random module and then used it random.randint function to pick
a random number between 0 and 255 for each of the primary colors.
We are getting close to our goal.
>>> import turtle
>>> import random
>>> sr= turtle.Screen ()
>>> sr.bgcolor ('white')
>>> sr.title ('learning turtle')
>>> sr.setup (width= 800, height=500)
>>> t= turtle
>>> t.speed(0)
>>> t.width(5)
>>> def star (size, angle):
t.pencolor (random.randint (0,255), random.randint (0,255),
random.randint (0,255))
t.width (2)
for x in range (1, 100):
t.forward(size)
t.left(angle)
size= size – 1
t.pencolor (random.randint (0,255), random.randint
(0,255), random.randint (0,255))
>>> star (150, 200)
With this, the colors of each line are different. Can you figure out how?
Other things about the turtle module
Turtle Movement
Set Position
Remember when we discussed the coordinates? Well, we can also make the
turtle go to wherever we want it to go by setting the specific coordinates we
wish.
There are several functions we can use for this and we will examine them one
after the other starting with these
turtle.goto (x, y)
turtle.setpos (x, y)
turtle.setposition (x, y)
· x – a number or zero
· y – a number or zero
Example
>>> sr= turtle.Screen ()
>>> sr.bgcolor ('white')
>>> sr.title ('learning turtle')
>>> sr.setup (width= 800, height=500)
>>> t= turtle
>>> t.fd (300)
>>> t.setpos(60,30)
>>> t.setpos (0,0)
This code will give you a triangle. We made the turtle draw a line of 300
points or pixels then asked it to go to coordinates x= 60 and y= 30. We then
asked it to return to coordinates x= 0 and y=0 where the turtle began. The
triangle created is scalene. No sides are equal.
We can also use the functions set position and goto to accomplish the same
task.
Example
>>> t= turtle
>>> t.fd (300)
>>> t.goto (60,30)
>>> t.goto (0,0)
Or
>>> t= turtle
>>> t.fd (300)
>>> t.setposition (60,30)
>>> t.setposition (0,0)
We can also set the x and y coordinates individually with the sets and sety
functions
turtle.setx(x)
x – a number (integer or float)
Example
>>> t= turtle
>>> t.setx (60)
This will give you a straight line which m0oved from coordinate x = 0, y = 0
to coordinate x = 60 and y = 0.
turtle.sety(y)
y – a number (integer or float)
Example
>>> t= turtle
>>> t.sety (50)
>>> t.setx(60)
>>> t.sety (-50)
>>> t.setx (0)
>>> t.sety (0)
This code creates a rectangle.
turtle.home()
this function returns the turtle to point 0,0 (x = 0, y = 0) no matter where the
turtle is on the screen.
Example
>>> t= turtle
>>> t.sety (50)
>>> t.setx(60)
>>> t.sety (-50)
>>> t.home ()
This code creates a trapezium. The turtle is made to go back to position 0, 0
(x = 0 , y= 0) from position 60,-50 (x = 60 , y = -50).
turtle.dot
This is a simpler way to create a filled-in circle. The turtle.dot function
allows you to specify both the size and color of the circle you want to draw
(picking a color is optional).
turtle.dot(size, *color)
· size – an integer >= 1 (if given)
· color – a colorstring or a numeric color tuple
Example
>>> t= turtle
>>> t.dot (100)
This will give a black circle with a diameter of 100 points.
You can confirm this with the following piece of code.
>>> t= turtle
>>> turtle.dot(100)
>>> t.pencolor('red')
>>> t.width (5)
>>> t.bk(50)
You will get the black circle with a red line of 50 forming its radius.
The radius is the length from the center of a circle to its edge. It is also ½ of
the diameter of a circle.
You can get the circle to be any color you wish
Example
>>> t= turtle
>>> turtle.dot(100, ‘blue’)
>>> t.pencolor('red')
>>> t.width (5)
>>> t.bk(50)
R: this gives you a blue circle with a red radius.
Example
>>> import turtle
>>> import random
>>> sr= turtle.Screen ()
>>> sr.bgcolor ('white')
>>> sr.title ('learning turtle')
>>> sr.setup (width= 800, height=500)
>>> t= turtle
>>> t.colormode (255)
>>> t.dot(100, (200,100,50))
>>> t.pencolor('red')
>>> t.width (5)
>>> t.bk(50)
You will have a lot of fun with the dot code and create multiple dots with
different colors.
Let’s have some fun with it.
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(8)
>>> a = 15
>>> b = ‘red’
>>> t.dot (a, b)
When you run this, you get a red dot with a diameter of 15.
The next thing to do is to import the random module.
>>> import turtle
>>> import random
>>> sr= turtle.Screen ()
>>> sr.bgcolor ('white')
>>> sr.title ('learning turtle')
>>> sr.setup (width= 800, height=500)
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(8)
>>> a = 15
>>> b = ‘red’
>>> t.dot (a, b)
After importing the random module, we set the diameter to a random value.
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(8)
>>> a = random.randint (5, 30)
>>> b = ‘red’
>>> t.dot (a, b)
You should run this like 5 to 6 times in a row. You will notice that the size of
the red dot keeps on changing.
Next, we use the colormode function of the turtle module and apply the
random.randint () function to the color of our circle.
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(8)
>>> t.colormode (255)
>>> a = random.randint (5, 30)
>>> b = (random.randint (0,255),random.randint (0,255),random.randint
(0,255))
>>> t.dot (a, b)
Running this several times will show that the color and diameter of the circle
changes any time you run the code.
The next thing we do is create an infinite loop with the while loop.
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(8)
>>> t.colormode (255)
>>> a = random.randint (5, 30)
>>> b = (random.randint (0,255),random.randint (0,255),random.randint
(0,255))
>>> while a < 4 and a > 31:
t.dot (a, b)
When you run it at this point, you would notice that a circle of the same color
keeps forming on the same location.
The next thing to do is to give the turtle x and y coordinates to go to. Since
the screen is 800 points in width or on the x-axis and 500 points in height or
the y-axis, we assign values on the x and y-axis to the setx and sety
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(8)
>>> t.colormode (255)
>>> a = random.randint (5, 30)
>>> b = (random.randint (0,255),random.randint (0,255),random.randint
(0,255))
>>> while a < 4 and a > 31:
t.dot (a, b)
t.setx(random.randint(-390, 390))
t.sety(random.randint(-240, 240))
We set x and y to move randomly between -390 and 390 for x (390 + 390 =
780) and – 240 and 240 for y (240 + 240 = 480 ) so that the turtle stays within
the screen we created.
At this point, the turtle keeps forming circles of the same diameter all over
the screen. The rings are all connected with lines.
The next action is to remove the lines.
We will do that with the pen up and pen down functions
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(8)
>>> t.colormode (255)
>>> a = random.randint (5, 30)
>>> b = (random.randint (0,255),random.randint (0,255),random.randint
(0,255))
>>> while a < 4 and a > 31:
t.dot (a, b)
t.pu()
t.setx(random.randint(-390, 390))
t.sety(random.randint(-240, 240))
t.pd()
With the pen up and down functions, the lines are gone. The circles are
formed all over the screen, but they are still circles of the same size and color.
We need to make the circles change sizes and colors. To do this, we will copy
and paste into the loop the values of variables a and b. This will make the
circles change both color and width as they form around the screen.
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(8)
>>> t.colormode (255)
>>> a = random.randint (5, 30)
>>> b = (random.randint (0,255),random.randint (0,255),random.randint
(0,255))
>>> while a < 4 and a > 31:
t.dot (a, b)
t.pu()
t.setx(random.randint(-390, 390))
t.sety(random.randint(-240, 240))
t.pd()
a= random.randint (5, 30)
b= (random.randint (0,255),random.randint (0,255),random.randint (0,255))
Once this is done, we have circles of different colors and with forming
randomly across the screen. Your polka dots game is complete. You can vary
the parameters of the program and get something else.
The game runs on an infinite loop. You could use a for loop to make the
game run in a finite loop.
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(8)
>>> t.colormode (255)
>>> a = random.randint (5, 30)
>>> b = (random.randint (0,255),random.randint (0,255),random.randint
(0,255))
>>> for i in range (1, 400):
t.dot (a, b)
t.pu()
t.setx(random.randint(-390, 390))
t.sety(random.randint(-240, 240))
t.pd()
a= random.randint (5, 30)
b= (random.randint (0,255),random.randint (0,255),random.randint (0,255))
The code of the program can be changed to anything you wish. You could
increase the range to 1000 or 10000 if you want to.
There are still other functions of the turtle module.
You can control your turtle itself and do several beautiful things to it.
turtle.shape()
With this function, you can change the shape of the turtle. The turtle is
currently an arrow. You can change
turtle.shape (name)
name – a string that is a valid shape name.
Shape names = “arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”.
Example
>>> t= turtle
>>> t.shape ('turtle')
>>> t.fd (50)'
The most interesting of the shapes is the actual turtle shape. The others are
circle, arrow, square, triangle, and classic.
We can have more fun with the turtle if we apply the turtle to the polka dots
program.
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(3)
>>> t.colormode (255)
>>> t.shape (‘turtle’)
>>> a = random.randint (5, 30)
>>> b = (random.randint (0,255),random.randint (0,255),random.randint
(0,255))
>>> for i in range (1, 400):
t.fillcolor(random.randint (0,255),random.randint
(0,255),random.randint (0,255))
t.dot (a, b)
t.pu()
t.setx(random.randint(-390, 390))
t.sety(random.randint(-240, 240))
t.pd()
a= random.randint (5, 30)
b= (random.randint (0,255),random.randint (0,255),random.randint (0,255))
In this modification, we have made the speed of the turtle 3 (so you can see
the changes). We also made the fillcolor to be random. This makes the color
of the turtle to change randomly as the turtle moves around to spread the
multicolored circles.
turtle.stamp()
The stamp function makes the turtle leave an imprint on the screen. If the fill
color is set, the turtle and its color are stamped on the screen.
Let’s use this to upgrade our game.
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(8)
>>> t.colormode (255)
>>> t.shape (‘turtle’)
>>> a = random.randint (5, 30)
>>> b = (random.randint (0,255),random.randint (0,255),random.randint
(0,255))
>>> for i in range (1, 400):
t.stamp ()
t.fillcolor(random.randint (0,255),random.randint
(0,255),random.randint (0,255))
t.dot (a, b)
t.pu()
t.setx(random.randint(-390, 390))
t.sety(random.randint(-240, 240))
t.pd()
a= random.randint (5, 30)
b= (random.randint (0,255),random.randint (0,255),random.randint (0,255))
with this modification, the turtle outline and color is stamped on the screen
together with the turtle.
turtle.reset()
This function is used to clear all the code written for the turtle screen. Only
the code written after the rest will be honored.
>>> import turtle
>>> import random
>>> sr= turtle.Screen ()
>>> sr.bgcolor ('white')
>>> sr.title ('learning turtle')
>>> sr.setup (width= 800, height=500)
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(3)
>>> t.shape ('turtle')
When you run this code, the first polka dot typed on the screen will
disappear, leaving the screen blank for the stamps of the turtle. This is very
useful when you begin to design your games.
>>> t= turtle
>>> t.colormode (255)
>>> t.speed()
>>> t.shape ('turtle')
>>> t= turtle
>>> t.colormode (255)
>>> t.tracer (10)
>>> a= random.randint (5, 30)
>>> b= (random.randint (0,255),random.randint (0,255),random.randint
(0,255))
>>> for i in range(1, 100):
t.ht()
t.dot(a, b)
t.pu()
t.setx(random.randint(-390, 390))
t.sety(random.randint(-240, 240))
t.pd()
a= random.randint (5, 30)
b= (random.randint (0,255),random.randint
(0,255),random.randint (0,255))
the programs runs as fast as if you used t.speed (10)
Example
For this example, we will use the polka dots and turtle stamp program. We
will use a delay on the turtle stamp program. We use a delay of 50 seconds.
>>> import turtle
>>> import random
>>> sr= turtle.Screen ()
>>> sr.bgcolor ('white')
>>> sr.title ('learning turtle')
>>> sr.setup (width= 800, height=500)
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(8)
>>> t.shape ('turtle')
Key binding
This part is a very important part of game development. It shows how to
make your program to be controlled by your computer keyboard or mouse.
turtle.listen ()
This is the first function to type when you want the turtle to listen to your
keyboard or mouse.
When you use it, it will enable the other functions which allow a keyboard or
mouse binding to work.
turtle.onkeypress(fun, key)
turtle.onkeyrelease(fun, key)
· fun – a function with no arguments
· key – a string: key (e.g. “a”) or key-symbol (e.g., “space”)
Bind function to the key when the key is pressed or released.
Key bindings don’t work when there is no function.
Example
>>> import turtle
>>> import random
>>> sr= turtle.Screen ()
>>> sr.bgcolor ('white')
>>> sr.title ('learning turtle')
>>> sr.setup (width= 800, height=500)
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(8)
>>> t.shape ('turtle')
>>> def joe ():
for i in range(1, 50):
t.stamp()
t.fillcolor(random.randint (0,255),random.randint (0,255),random.randint
(0,255))
t.pu()
t.setx(random.randint(-390, 390))
t.sety(random.randint(-240, 240))
t.pd()
>>> t.listen()
>>> t.onkeypress (joe, 'e')
In this example, we converted the turtle stamp program into a function. Once
done, we used the listen to function and the onkeypress function to assign the
function, which we named joe to the key ‘e’ on the keyboard. When you run
the program, the turtle screen comes up, but nothing happens. When you
press ‘e’ on your keyboard, however, the program runs. You can press e a
1000 times, and the program runs a thousand times.
Click Binding
turtle.onclick(fun, btn)
turtle.onscreenclick(fun, btn)
· fun – a function with two arguments with the coordinates of the clicked
point on the canvas
· btn – number of the mouse-button, defaults to 1 (left mouse button)
the on-screen click works similar to the on keypress. It would help if you
tried to attach it to the polka dots program and see how it runs.
turtle.bye()
This shuts down the turtle module.
Shut the turtle graphics window.
Example
>>> import turtle
>>> import random
>>> sr= turtle.Screen ()
>>> sr.bgcolor ('white')
>>> sr.title ('learning turtle')
>>> sr.setup (width= 800, height=500)
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(8)
>>> t.shape ('turtle')
>>> def joe ():
for i in range(1, 50):
t.stamp()
t.fillcolor(random.randint (0,255),random.randint (0,255),random.randint
(0,255))
t.pu()
t.setx(random.randint(-390, 390))
t.sety(random.randint(-240, 240))
t.pd()
>>> t.listen()
>>> t.onkeypress (joe, 'e')
>>> t.bye
The turtle screen opens and runs briefly then closes because of the t.bye.
turtle.exitonclick()
This shuts down the turtle screen when the mouse clicks on the screen.
Bind bye() approach to mouse clicks on the Screen
Example
>>> import turtle
>>> import random
>>> sr= turtle.Screen ()
>>> sr.bgcolor ('white')
>>> sr.title ('learning turtle')
>>> sr.setup (width= 800, height=500)
>>> t= turtle
>>> t.colormode (255)
>>> t.speed(8)
>>> t.shape ('turtle')
>>> def joe ():
for i in range(1, 50):
t.stamp()
t.fillcolor(random.randint (0,255),random.randint (0,255),random.randint
(0,255))
t.pu()
t.setx(random.randint(-390, 390))
t.sety(random.randint(-240, 240))
t.pd()
>>> t.listen()
>>> t.onkeypress (joe, 'e')
>>> t.exitonclick()
This will allow the program to run when you press ‘e’ on your keyboard.
Once you click on the turtle screen the program stops running. It then gives a
very long error message especially when the program has started to run.
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32
bit (Intel)] on win32
Type "help", "copyright", "license()" for more information.
>>>
====================== RESTART: C:\Users\uf\Desktop\new.py
=====================
>>>
====================== RESTART: C:\Users\uf\Desktop\new.py
=====================
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\uf\AppData\Local\Programs\Python\Python38-
32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\uf\AppData\Local\Programs\Python\Python38-
32\lib\turtle.py", line 701, in eventfun
fun()
File "C:\Users\uf\Desktop\new.py", line 27, in joe
t.stamp()
File "<string>", line 5, in stamp
turtle.Terminator
>>>
With all we have discussed here, you should be a master of the turtle module.
Congrats!!
Level 6
Welcome brave programmer to the final level of this checkpoint. At this
level, you will learn the secrets of making a game. We will build a game
together and thus gain the basics of game making.
Here, you win your wizard’s badge.
Let’s go!!!!!!!!!!!!!!!!!!!
Ping Pong
In this project, we will code a version of the ping pong game. While Ping
pong is not particularly exciting compared to today's video games, ping pong
is simple to build and provides an excellent opportunity to work on most of
the skills that you will need to create a game.
import turtle
sr= turtle.Screen ()
sr.title('ping pong game')
sr.colormode (255)
sr.bgcolor(50,100,50)
sr.setup (width= 800, height= 500)
sr.tracer (8)
#GAME OBJECTS
#ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape('circle')
ball.color (105,0,0)
ball.penup()
ball.setpos (0,0)
ball.dx = 1
ball.dy = -1
#paddle_a
pa = turtle.Turtle()
pa.speed(0)
pa.shape('square')
pa.color ('black')
pa.shapesize(5,1)
pa.penup()
pa.setpos (-370,0)
#paddle_b
pb = turtle.Turtle()
pb.speed(0)
pb.shape('square')
pb.color ('black')
pb.shapesize(5,1)
pb.penup()
pb.setpos (370,0)
# keyboard binding
sr.listen()
sr.onkeypress(pa_up, 'w')
sr.onkeypress(pa_down, 's')
sr.onkeypress(pb_up, 'i')
sr.onkeypress(pb_down, 'k')
#score
score= turtle.Turtle()
score.speed(0)
score.color(255,123,20)
score.pu()
score.ht()
score.goto(0,210)
score.write('Paddle a: 0 Paddle b: 0', align= 'center', font = ('calibri', 25,
'bold'), )
score_a = 0
score_b = 0
#GAME LOOP
while True:
sr.update ()
# moving the ball
ball.setx (ball.xcor()+ ball.dx)
ball.sety (ball.ycor()+ ball.dy)
# border checking upper border
if ball.ycor()> 235:
ball.sety(235)
ball.dy*=-1
# border checking lower border
if ball.ycor()< -235:
ball.sety(-235)
ball.dy*=-1
# border checking left border
if ball.xcor()< -390:
ball.setx(-390)
ball.dx*=-1
ball.setpos(0,0)
score_b +=1
score.clear()
score.write('Paddle a: {} Paddle b: {}'.format(score_a, score_b), align=
'center', font = ('calibri', 25, 'bold'))
Game objects
The game objects are the thing we want to put on the screen, the objects we
want to see on the screen.
The objects we want to see on the screen include the ball, the paddles, and the
score of the game. We will address them one after the other.
#GAME OBJECTS
The Ball
The ball is one of the objects needed on the screen.
#ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape('circle')
ball.color (105,0,0)
ball.penup()
ball.setpos (0,0)
ball.dx = 1
ball.dy = -1
We make the ball a turtle object by assigning it to the variable turtle.Turtle.
We set the animation speed of the ball to 0, so it can move very fast when we
need to move it and set the shape to circle using the function ball.shape ().
We set the color of the ball to a slightly deep red (you can use any color ).
We set the pen to not show on lines on the screen using the penup function.
Also, we set the ball to the center of the screen with setpos. The code ball.dx
and ball.dy will be explained later.
Paddles
#paddle_a
pa = turtle.Turtle()
pa.speed(0)
pa.shape('square')
pa.color ('black')
pa.shapesize(5,1)
pa.penup()
pa.setpos (-370,0)
#paddle_b
pb = turtle.Turtle()
pb.speed(0)
pb.shape('square')
pb.color ('black')
pb.shapesize(5,1)
pb.penup()
pb.setpos (370,0)
The paddles are created just like the ball but with slightly different
parameters. We assign the first paddle to a variable called ‘pa’ and make it a
turtle object using turtle.Turtle. Unlike the ball, we made the turtle a square.
We also made the square to get longer using the function turtle.shapesize
(width= 1, height = 5). This made the square to become 5 times taller.
All the other things we did to the paddles, we did with the ball except that we
left the paddles black.
What we did for paddle a is the same thing we did for paddle b except that for
paddle b, we used the negative x coordinates to get it on the other side of the
screen.
For the score of the game, we assigned the score of the game to a paddle
object by using the function turtle.turtle.
We made the speed of the score up to date 0 so that when there is a score, the
score showing on the screen updates almost immediately.
We used the pen up function so that the lines of turtle movement of the turtle
do not show. We also hide the turtle so that the turtle does not show when the
turtle is moving. We also set the place where the score will show by
assigning the score to x = 0 and y = 210.
We made the turtle show paddle a and b and the scores of 0, 0 on the screen.
We also specified that the writing should be center-aligned and that the font
show is ‘calibri, 25 amd bold.’
We also created two other variables for the score. We will explain these
variables later.
Game loop
The game loop is where the action in the game is created.
A while loop was used so that the game can continue indefinitely.
GAME LOOP
while True:
sr.update ()
# moving the ball
ball.setx (ball.xcor()+ ball.dx)
ball.sety (ball.ycor()+ ball.dy)
First, we make the ball move. We specify in our loop that the ball should
move by 1 pixel on the x-axis and -1 pixel on the y-axis do that the ball can
move in a diagonal way.
Remember we earlier set ball.dx to 1 and baal.dy to -1.
This piece of code will cause the ball to begin to move.
We have created a problem, however. The ball begins to move off the turtle
screen.
That brings us to the border checking.
Border Checking
Border checking is activated so that the ball moves within the screen. We
use an if statement for the border checking.
# border checking upper border
if ball.ycor()> 235:
ball.sety(235)
ball.dy*=-1
We start with the upper border. We tell the turtle that once the ball gets past
235 on the y coordinate, the ball should be returned to position 235 on the
same y coordinate and begin to move in the opposite direction.
The opposite direction command is specified with the code
Ball.dy*= -1, which means that the ball by which moves the ball on the y-
axis by -1 pixel should begin to move the ball on the y-axis by +1 since -1 *
-1 = +1.
#GAME OBJECTS
#ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape('circle')
ball.color (105,0,0)
ball.penup()
ball.setpos (0,0)
ball.dx = 1
ball.dy = -1
#paddle_a
pa = turtle.Turtle()
pa.speed(0)
pa.shape('square')
pa.color ('black')
pa.shapesize(5,1)
pa.penup()
pa.setpos (-370,0)
#paddle_b
pb = turtle.Turtle()
pb.speed(0)
pb.shape('square')
pb.color ('black')
pb.shapesize(5,1)
pb.penup()
pb.setpos (370,0)
# keyboard binding
sr.listen()
sr.onkeypress(pa_up, 'w')
sr.onkeypress(pa_down, 's')
sr.onkeypress(pb_up, 'i')
sr.onkeypress(pb_down, 'k')
#score
score= turtle.Turtle()
score.speed(0)
score.color(255,123,20)
score.pu()
score.ht()
score.goto(0,210)
score.write('Paddle a: 0 Paddle b: 0', align= 'center', font = ('calibri', 25,
'bold'), )
score_a = 0
score_b = 0
#GAME LOOP
while True:
sr.update ()
# moving the ball
ball.setx (ball.xcor()+ ball.dx)
ball.sety (ball.ycor()+ ball.dy)
# border checking upper border
if ball.ycor()> 235:
ball.sety(235)
ball.dy*=-1
# border checking lower border
if ball.ycor()< -235:
ball.sety(-235)
ball.dy*=-1
# border checking left border
if ball.xcor()< -390:
ball.setx(-390)
ball.dx*=-1
ball.setpos(0,0)
score_b +=1
score.clear()
score.write('Paddle a: {} Paddle b: {}'.format(score_a, score_b), align=
'center', font = ('calibri', 25, 'bold'))
You should realize that the turtle module is drawing the whole thing, but the
drawing is happening really fast.
This game has several bugs. You should try to find them and try to reduce the
amount of code we used.
Congrats, you have created a game on turtle!!!!
You have earned it. You are now a full wizard of Adak.
__________________________________________________ the great,
wizard of the order of Growrher, Merlin and Python.