Coding For Kids An Unmissable Introductio - Mark B Bennet
Coding For Kids An Unmissable Introductio - Mark B Bennet
Coding For Kids An Unmissable Introductio - Mark B Bennet
Mark B. Bennet
Table of Contents
Mark B. Bennet
© Copyright 2020 - All rights reserved.
The content contained within this book may not be reproduced, duplicated or transmitted without
direct written permission from the author or the publisher. Under no circumstances will any blame or
legal responsibility be held against the publisher, or author, for any damages, reparation, or monetary
loss due to the information contained within this book. Either directly or indirectly.
Legal Notice:
This book is copyright protected. This book is only for personal use. You cannot amend, distribute,
sell, use, quote or paraphrase any part, or the content within this book, without the consent of the
author or publisher.
Disclaimer Notice:
Please note the information contained within this document is for educational and entertainment
purposes only. All effort has been executed to present accurate, up to date, and reliable, complete
information. No warranties of any kind are declared or implied. Readers acknowledge that the author
is not engaging in the rendering of legal, financial, medical or professional advice. The content
within this book has been derived from various sources. Please consult a licensed professional before
attempting any techniques outlined in this book.
By reading this document, the reader agrees that under no circumstances is the author responsible for
any losses, direct or indirect, which are incurred as a result of the use of information contained within
this document, including, but not limited to, errors, omissions, or inaccuracies.
Note to Parents
C
oding with Scratch is an easy-to-understand introduction to both
programming and video game development using Scratch, a
popular online coding environment for kids. This book will teach
your child just how fun, useful, creative, and empowering
computer coding can be.
Coding is a blast to learn, especially when you are building video games.
For younger children (ages 6–8 years), I recommend that parents sit with
their children and help them navigate the beginning concepts until they are
confident enough to use Scratch all by themselves.
Coding is not only a valuable ability for kids to have but also an engaging
activity that helps promote creativity, develop problem-solving skills, and
give them a head start in a respected career. Parents can provide guidance
and support throughout this process, which will not only aid in the child’s
growth but also establish a connection that bonds them emotionally and
intellectually. Critical thinking skills and learning how to solve problems
are important skills that are highly needed in the 21st century. There are
many career paths that are going to be open to those that have these kinds of
skills, and coding is a great way to help build them. Even if a child does not
take up coding as a career choice, the experience of learning to code will
help them in whatever endeavors they become involved with.
Scratch, a children-oriented coding website provides users with the basic
building blocks they need to be properly introduced into the domain of
coding without overwhelming them. The simplicity of this website allows
children to build a necessary knowledge and understanding that permits
growth later in life in regard to coding.
When guiding your children with Scratch, it is important not to force them
to do it. Not everyone is going to be inclined to do computer programming.
If some children find it uninteresting, let them try something else. It is not
going to be the end of the world if your child does not grow up to be a
coder.
This book is going to teach you exactly how to code in Scratch. It will teach
you about all the different blocks and extensions, so you will be a master in
no time! Whether you are creating a Scratch project for the first time or
have played around with it before, this book is meant for you. It will teach
you a whole bunch of tips and tricks that you will need to take your project
to the next level. Think of this book as a jumping-off point, so you can take
off and soar into the world of Scratch!
Introduction
Welcome to Scratch
H
ey, kids! Are you ready to build your own video games? It is
really fun and easy to build video games using Scratch. What is
Scratch? It is a website that allows you to build and launch video
games on the web for the world to play. Yes, all of your friends
and family members will be able to play the video games you
make! And, to make it even better, you do not even need typing skills!
Scratch uses drag-and-drop coding—just clicks and drags with your
computer mouse—to build your games.
Are you wondering what you will need to begin this journey? Well, if you
have this book, then you are already halfway there. All you need now is a
computer or tablet with Internet access.
You may wonder, what is programming? Programming, also known as
coding, is putting ideas into a form that the computer can understand.
Scratch lets you express your ideas using pictures. Other ways for people to
program usually involve typing words on a keyboard. But Scratch does the
work for you by turning the pictures you create into those words!
Yes, we are going to build actual video games. But do not worry, we will
start with steps as simple as one line of code, then slowly progress towards
coding complete games.
All of the lessons include easy-to-follow, step-by-step instructions for
programming. Each lesson is illustrated with clear screenshots. My goal is
not only to teach you but to also challenge you and help you show off your
creativity and game-building skills.
If you have trouble remembering any of the words or concepts, just check
the back of the book for a glossary of coding terms.
By reading Coding With Scratch and trying the games, you will embark on
a fun adventure that will teach you not only amazing skills for building
video games today but also skills that will serve you well into your future—
maybe even as a career!
Why Scratch?
Do you remember your first word as a child? Probably not. Perhaps you can
ask your parents what your first word was. Was it Mommy? Or Daddy? Or
hello?
If you were a computer, your first words would likely be ‘Hello, World.’
Huh? Why ‘Hello, World? ’It may sound silly, but it is a tradition for new
coders to make the computer say ‘Hello, world. ’Telling the computer to do
this, is the first program most computer programmers ever run.
So, how do you make a computer say ‘Hello, World? ’First, you need to
talk to the computer in its own language. But what language does a
computer speak? Computers speak in a language called binary, which only
has two symbols: 0 and 1. For example, a computer might understand
something written like this: 01101000 01101001. (This is the word ‘hi ’in
binary.)
Of course, writing 0s and 1s for humans is pretty confusing, so computer
engineers and computer scientists created languages that both humans and
computers could understand. We call those languages ‘programming’
languages.
Scratch is a computer programming language, and it is cool because it looks
and reads very much like how you would speak to a friend. With a little
practice, you might even start thinking in Scratch code!
When someone is writing a computer program, we say they are coding.
When you create a video game using Scratch, you are writing a computer
program. A program is simply a set of instructions for a computer to follow.
Computer programs can be short or very long in length, depending on the
video game or application. You might consider the word coding to be very
similar to writing. Try using the word ‘coding ’in conversation. Here is an
example: “Sorry, Madam President, I will have to meet with you later. I am
busy coding a video game.”
Scratch is just one of many computer coding languages in the world, and
new languages are invented all the time. But Scratch has a lot of advantages
as a first programming language to learn:
1. It is designed for kids.
2. It uses drag-and-drop coding (no typing required!).
4. You can see inside the code of other games (see Running a
Program).
Scratch is also super-fast for prototyping games. Do you know the word
‘prototype’? A prototype is a quick rough draft of an idea. For example, if
you want to build a game about hippos that fart rainbows, you can quickly
build a prototype of the game using Scratch. When I say quickly, I mean in
about 30 minutes. If you were to code a similar game prototype in a
different computer language, like JavaScript, it might take many hours to
complete.
Even professional coders love how easily and quickly you can code games
with Scratch. It is a language that appeals to all types of coders and game
makers, regardless of their age. Are you excited yet? I hope so because it is
time for you to launch the Scratch website and start coding!
3. Making an animal
4. Adding a background
5. Fun activities
The More Complex The App, The More Planning You Need
If you are going to design a complicated game, using the same procedure
can be of immense help. If you are building a script that is going to be
really complicated, then it is even more important to first plan out how you
are going to do it. The worst thing that you could do is jump on the
computer, and just start trying to build a game or large application, without
having any idea about how it is going to work and progress.
Let us say you want to build a maze game. A good way to approach this is
to draw out all of your mazes on paper before you even open up Scratch.
You might find that some mazes that look good on paper are too hard to get
through when you actually put them up on the computer screen. But one
thing for sure is that your building the game is going to be accomplished in
a much shorter time once you get on the computer in Scratch than if you
had not planned it out ahead of time.
S
igning up for Scratch is very simple to do, and after you sign up,
you will get to use the tools on the site to bring all of your dreams
to life! Before you sign up, it is really important that you ask for
your parents ’permission. The internet is a big place, and it is
really easy to get lost or get into trouble.
Step 1: First, go to https://Scratch.mit.edu. There should be two options at
the top that reads, Join Scratch or Sign In. Because this is your first time on
Scratch, you should click Join Scratch to register. Whenever you want to
come back to work on a project on Scratch, click on Sign In, then input the
username and password that you chose when joining Scratch.
Step 2: After clicking Join Scratch , you will be asked to create your own
username and password. Do not make your username your real name!
Choose something special that shows other people on Scratch what you are
all about. For example, if you absolutely love cupcakes, it could be
something like ‘CupcakeLover3000’ or ‘CoolCupcakeCat.’ It can be
anything that you want, as long as it is not unkind, horrible, or
inappropriate. When choosing a password, make sure it is easy for you to
remember, but hard for others to guess. If you need help remembering, ask
any of your parents to write it down for you, and keep it somewhere safe.
Step 3: Next, you will be asked questions about your birthday, gender, and
the country you live in. The answers that you provide here will help make
your experience on Scratch be customized to your exact needs and wants.
Step 4: You will need your parents ’help with this step. Ask them to enter
their email address to confirm your account. That way; you can begin
commenting and sharing your projects with other members of Scratch.
Step 5: The next page will confirm your new Scratch account. An email
will be sent to your parents that will help you activate all the features to
begin making friends, and creating your own content using tools in Scratch.
Community Guidelines
Everyone who contributes to Scratch needs to:
Be respectful. This means when you share your projects or post comments
on other people’s projects, remember that kids of many different ages –
some may even be younger than you - can see what you have shared.
Be constructive. When making comments on other people’s projects, say
something you like about it, and tell them what you think they could do
better next time.
Share. It is okay to remix projects, images, ideas, or anything you find on
Scratch – and anyone can do the same with anything that you create. Be
sure to give the other person credit when you remix.
Keep personal info private. To keep everyone on Scratch safe, do not use
your real names, anyone else’s name. Do not post contact information like
phone numbers, addresses, or anything that could put you or someone else
in danger.
Be honest. Do not pretend to be other Scratchers, tell stories that are not
true, or try to fool the community into thinking that you are someone that
you are not.
Help keep the site friendly. If you think a project that someone made, or a
comment that someone posted is mean, rude, or causing harm to someone
else or yourself, you should tell the Scratch team about it. By clicking
Report, you can let the Scratch team know about it and solve the problem.
No bullies are allowed on Scratch!
Add A Background
The backdrop is the background of your stage. It is rather boring to have a
plain background, so let us add some a Colorful City background.
Adding a backdrop
To add a backdrop, find the (+) icon on the right of the Stage panel, and
click the Search button.
A screen will show with plenty of backdrop in the gallery. This game needs
a night and a day backdrop.
Search for a night image and find the Night City backdrop; add it, then
search again and find/add Colorful City:
The stage will show the last drop you added. So, it should look like this:
Note: The backdrops can be found on the left side, just beside the Blocks
panel, there is a Backdrop tab.
Click on it and see that there is a list of backdrops, one for the night city,
and one for the day city.
You can click on the backdrop you want by default; we want the Colorful
City by default.
CHAPTER 3:
· Backdrops
· Size
Costumes
Now we are going to learn how to use the blocks to change costumes while
the script is running.
Costume
The costume is the picture or image that a sprite displays. Set a sprite to a
specific costume, to have it display that image on the stage.
Each sprite has one or more costumes. Each costume is a different image. If
you click on a sprite and then click on the Costumes tab near the top of the
screen, you will see all of the costumes for that sprite.
Each costume has a number and a name. These are two of a sprite’s Looks
variables. Each sprite has its own separate costume number and name
variables since each sprite might have a different costume.
You might be asking “when do I get to use these variables”? Good question.
Here is an example. Does your sprite have special powers in your game?
Perhaps it can power up and get stronger with a different costume. You can
have the game check the costume name or number, to see if it can defeat
certain enemies.
You can click on the first, second, or third costume here to change which
costume the toucan will show on the stage. But what if you want to change
the costume in the middle of a game? You cannot have the player stop the
game, choose a different costume, and then start the game again!
One way you can change the costume using blocks is with the ‘switch
costume to’ block. This lets you switch the costume to whichever one you
want. You can go from the second costume to the third costume, and back
again (skipping the first one), so it looks like the toucan is flying! If you do
not want the costumes to switch in a specific order, you can use the ‘next
costume’ block. This will simply change the costume to the next one in line,
instead of going to the one you choose.
Backdrops
Just like with your sprites ’costumes, you can have quite a few backdrops
too! You can even change them the same way you change your sprites’
costumes. If you go to the Costumes tab after clicking on the stage
workspace, you will see all of the backdrops you have chosen for your
project so far, and you can switch to which one you want. Just like you can
switch your sprites ’costumes with the ‘ switch costume to’ block or ‘next
costume’ block, you can choose your backdrop with the ‘switch costume to’
block, or switch to the next one with the ‘next backdrop’ block. You can
also use the ‘switch backdrop to ’ block to go back to the last backdrop or
use a random backdrop.
There is one more block that switches the backdrop that is a little different
from the rest: the ‘switch backdrop to _______ and wait ’ block. This block
works with a block in the yellow Events blocks section, called ‘when
backdrop switches to _______.’ The ‘switch backdrop to _______ and wait’
block will change the backdrop, and then wait for all of the codes that start
with the ‘when backdrop switches to _______’ block, before it moves on to
the next block.
There is one Looks variable you can use with backdrops: the ‘ backdrop
_______’ block. Just like the ‘costumes _______’ block, there are two
options you can choose: number or name. When you click on this block, it
will tell you either how many backdrops you have chosen (number), or
what the name of the backdrop you have chosen is (name).
Take a look at this picture. If I used the ‘backdrop number ’block, what
would come up? What about if I changed it to ‘ backdrop name’ instead? If
you said ‘two’ for the first question and ‘Party’ for the second, you are
right!
Size
All of the sprites you can choose from Scratch are usually about the same
size. But that does not make sense, does it? An elephant and a doughnut are
not of the same size! Their sprites should not be either!
Well luckily, you can change the size of your sprites with both the ‘change
size by _______’ block, and the ‘set size to _______ %’ block. These
blocks either make the sprite grow by the number you put in the white oval
or set the size to that number.
Be careful though. You can make a sprite only so large or small. You cannot
make the sprite’s size zero, otherwise, it will disappear! And you cannot
make the sprite’s size too big, otherwise you will not even be able to tell
what it is! How large can you go? Once the size of the sprite is about twice
the size of the stage, you cannot make it any bigger. Can you work out what
size that would be? Usually, it is several thousand percent for most sprites.
Do not worry though. Setting it to the maximum still makes the sprite look
enormous! If you want to get the sprite back to its normal size, change the
size to 100 (100 percent). That is considered the normal size for every
sprite.
Every sprite remembers its current size, and the last size of each sprite is
also saved with your project. This means when you come back to work on it
next time, each sprite will still be the same size as when you left it. You can
tell what size it is by looking at the sprite area and checking the number in
the Size field. You can also show the size of the sprite in the top left corner
of the stage, by checking the box next to the size Looks variable.
Control when your sprites show up with these blocks. Maybe you do not
want a character in your game anymore, but it might come back. Maybe
there is an obstacle that your character needs to get by, and once you get
past it, it should disappear.
The Show and Hide blocks are great for that! Be careful though. Any other
effects that you have going on with the sprite also disappears when you hide
it. For example, if a sprite tries to say something, it will immediately
disappear once it is hidden.
Sometimes you might have a sprite that does not need to show up right
away when your project starts. You can hide these sprites right after the
green flag is clicked, and show them when you want them to appear.
· Layers
· Activity—tell a story!
Graphic Effects
Graphic effects change how the entire sprite looks, even if you change its
costume.
There are a whole bunch of really cool effects that you can put on your
sprite. You do this with the ‘change _______ effect by _______ ’ and ‘set
_______ effect to _______’ blocks. If you want to get rid of all of the
changes you have made, use the clear graphic effects block.
If your script changes a sprite’s graphic effects, it is good practice to clear
your graphic effects at the very start after a green flag block. This sets
everything back to normal, so your game always looks the same when it
starts.
Let us take a look at all of the affects you can create with these blocks.
Color
The first effect you can play with is changing the color of your sprite! You
can change it to pink, green, blue, purple, or any color in between, using
this effect. If you want the color to change a lot, like going from yellow to
dark blue; you should set the number in the block to be really high, up to
200. If you want it to only change a really tiny amount, like going from a
light blue to a dark blue, use a really low number. Let us take a look at
Scratch Cat with its color effect set to 100.
Fisheye
This effect makes the middle of a sprite look really big, and the outer part of
the sprite look really small. The larger the number of the effect, the more of
a Bubble effect you will see from the sprite. Here is what Scratch Cat looks
like with the Fisheye effect at 150.
Whirl
This effect makes it look like your sprite is all twisted up! It twists your
sprite around a center point to make it look like it is spinning around. This
is what Scratch Cat looks like with the Whirl effect set at 200, but you can
use numbers much higher for even more Whirl effect.
Pixelate
Pixelating your sprite makes it look fuzzier, like a 1980s video game. You
can use this one if you do not want people, playing the game, to know
which sprite you are using. Here is the Pixelate effect on Scratch Cat set to
20. Higher numbers will make it even fuzzier, and harder to know who it is.
Mosaic
This effect lets you create many smaller copies of your sprite in the same
space. Set the number higher for more copies to appear! Here is what
happens when you set the Mosaic effect to 9.
Brightness
Just like you change the brightness of your phone screen, you can also
change the brightness of your sprite. The more you raise the brightness, the
lighter your sprite will become until everything is bright white! Let us see
what Scratch Cat looks like with a Brightness effect of 50.
Ghost
This effect makes your sprite more transparent, which means you can see
through it more easily, like a ghost! The higher the number you use, the
easier it is to see through it, though it will still have the same colors. This is
what a Ghost effect of 50 looks like on Scratch Cat.
Combining Effects
You do not have to have just one effect going at a time. You can use a
couple of these blocks in a row to create some really cool effects. For
example, if you want four blue Scratch Cats in a square to look fuzzy, you
could use the Color effect combined with the Mosaic and Pixelate effects.
The Ghost effect can also be used to hide your sprite, without using the
Hide block. Why would you want to do this? Well, it can be useful if you
want the ‘say ’or ‘think ’bubbles to show up, but not your sprite.
They will not show if your sprite is hidden, but they will show if your
sprite’s Ghost effect is set to 100 (which makes it invisible).
Animating Effects
By changing an effect rapidly, you can create animation-style effects. You
can create an animated effect by repeating the ‘change _______ effect by
_______ ’ block. In the following example, if you hold down the space bar,
it will change the sprite’s Pixelate effect together with a Ghost effect. This
results in a slow pixelation and fade out of the sprite (see some of the
different frames in the following diagram of what happens over time). Then
you can click the green flag to reset it back to normal.
The blocks here animate the sprite to change its effect to Pixelate, combined
with a disappearing effect using G host.
Layers
Sometimes you might be looking for your sprite and not be able to find it. It
might be hiding behind something else! You can bring it in front of
everything else with the ‘go to _______ layer ’block. That lets it cut in front
of all the other sprites on the screen, so you can get to see it.
If you want a sprite in front of some sprites but behind others, you can use
the ‘go _______ _______ layers ’block. This lets you move a sprite behind
or in front of other sprites, without sending it all the way to the front or
back. Think of this as cutting in front of your friend in line for lunch. You
would be going forward one layer in the line, and your friend would be
going back one layer.
Let us do an example with the Lion, Beachball, and Crab sprites. Can you
tell which sprite is in the front layer, and which is in the back?
Layer
When sprites are positioned on top of each other, they are arranged in
layers. The layer for the sprite decides if that sprite is in front of or behind
other sprites.
If you said the Lion is in the front layer and the Crab is in the back, you are
right!
Now, if you tell the Beachball sprite to ‘go to the front layer, ’it will move
the ball up. If you tell the Beachball sprite to ‘ go backward 1 layer,’ it will
move the ball down. This is really useful if you want to hide a sprite behind
another one.
You always want the balloon to start with its first costume, so add a ‘switch
costume to _______ ’block. You are going to add more balloons, so you
will be changing the other balloons to a different costume.
The balloons should show up after the monkey finishes talking. That means
you need to add a ‘wait _______ seconds ’after the ‘ switch costume to
_______’ block. How much time do you think you should set it for? Well,
the cat spoke for two seconds, and then the monkey spoke for two seconds,
so the balloons should show up after four seconds.
A party with just one balloon is no fun. Let us get some more! Right-click
on the balloon sprite and select Duplicate twice. You should now have
three balloons. Drag them around on the stage where you want them to be;
then click on each balloon in the sprite area, and change the blocks of code
to have a different costume. This way each balloon will look different.
· Space invaders
· Moon landing
Space Invaders
Space Invaders is another simple program that many beginner programmers
complete.
In this program, you simply shoot the on-coming aliens while you avoid
their lasers. You will have three lives, and each time you get struck by an
alien laser, you lose a life.
In contrast to the original Space Invaders games, the alien ships do not
approach you. Instead, they simply sweep from right to left, and it is your
job to destroy them.
This program will require you to set up the following variables:
· Characters
There are two essential characters here: the player and the opponents. Now,
both sides are represented by differing ships
· Movements
The movements of the ships are simple, for the ships simply shift left to
right.
· Lasers
Like the players, the lasers are representative of the opposing sides. Now,
these lasers can be of any color, but I suggest picking totally opposing ones
as this creates a better graphical user interface and a better gaming
experience for the user.
· Lives
A player is given three lives in this game. A counter should be visible, and
each time a player gets struck by a laser, then the counter goes down by
one.
Moon Landing
This program is certainly more difficult than preceding projects.
In this program, we have to simulate landing a moon lander on the surface
of the moon. If you land on anywhere but the landing pad, then your moon
lander gets destroyed.
To make it easier, here are the things that you will need to have in your
program:
1. Movement
Obviously, the movement will be an essential component of the whole
project. In this game, you will have to be able to move your spacecraft left
and right, as well as up and down, taking into account that there is no air
resistance in space. Once your character starts moving in one direction, then
it should keep gliding in that direction.
2. Crashing
This is one of the simpler things that you will be programming. You will
essentially need two costumes: the lunar lander sprite and the explosion
costume. Since all of the rocks will be grey, you simply have to create the
program such that when the lunar lander sprite touches something grey, it
switches to the explosion costume before ending the program, essentially
meaning you lost.
3. Gravity
Like all planets, the moon has gravity, and this gravity pulls things towards
the ground. Try to incorporate that into your code.
4. Landing
The goal of this program is such that when the lander touches the landing
pad, the game ends. However, you could make it such that if the lander
lands too fast on the landing pads, the ship falls apart.
Solutions
Now, this is the part of this chapter where you will find the solutions, but
please remember that these are not the only correct solutions. If you have
come up with your own solutions (as many of you should have), then I
congratulate you on your grit and determination! However, regardless of
whether or not you had completed the projects by yourself, I still urge you
to read the solutions here, for you might find better and more efficient
solutions than the ones you made.
Tron
Here is a possible solution to the game:
· Player Starting Position and Trails
These blocks of code set the starting position of the characters. The sprites
labeled bike are set to the position of (-175,0) while facing the 90-degree
direction. From here, the following lines of code make it so that when the
character is moved, it would leave a pen trail of the specified color.
· Crash Checker
This is, as the name suggests, checks whether or not the sprite has crashed.
The blocks of code do so by checking the pen trail that the characters have
left behind. If the character ends up touching its own pen trail or its
opponent’s, the sprite turns into the ‘explosion ’character. If the character
touches the other sprite, then they both transform into ‘explosion’
characters.
· Player Movement
These lines of code control the movement of the characters. They control
the direction in which the character is moving. Because of the pen up and
pen down blocks, the characters will continuously move unless told
otherwise. As such, these blocks are meant to more of direct the sprites
rather than actually move them.
Space Invaders
· Player
This is the main body of the program that basically describes the
functionality of the player. Here, you will find that once you start the
program, you will be given two variables: Health and Points. The code will
then continue to set the position of the sprite, choose a sprite, and show the
variables.
The second half of the blocks of code is essentially the win-checker. Once
either the player has obtained five points or the player has lost all his lives,
the game ends. Until then, the player will continue to move around, by
either pressing the right arrow key or the left.
· Your Laser
These lines of code explain how your laser works. Basically, if you press
the space bar, it will release a sprite in the form of the laser. If this sprite
makes contact with the edge, it simply vanishes. If the laser makes contact
with a yellow color, which is the color of the aliens, then it destroys them.
Although it is not explicitly stated in this block of code, it will be stated in a
different block.
· Opponent
This is the block of code wherein you will find the functionality of the
opponent aliens. It sets the starting position of the alien and creates its
functionality wherein the sprite would continue drifting left to right in a
single direction until it hits the edges of the game. If the sprite gets struck
by one of your lasers, then your point tally goes up, the sprite is replaced by
an explosion sprite before vanishing.
· Bad Laser
This is the portion of the program that controls the functionality of the ‘bad’
lasers, or more appropriately, the lasers shot by the alien sprites. Essentially,
the aliens shoot lasers at random intervals, and if they hit the player, the
player loses a life; otherwise, the laser simply disappears.
Moon Landing
· Movement
This block of code simply moves the character around using the left, right,
up, and down arrow keys. The logic behind this code is very similar to the
logic behind the blocks for movement for Tron and Space Invaders. After
all, movement is movement, and in most games, movement mainly pertains
to the change in position of the sprite in relation to the background of the
program.
· Crash
This additional block of code is responsible for checking whether or not the
lander has crashed. It simply says that if the sprite touches the color gray,
then it should switch to an ‘explosion ’costume.
· Movement
The change in these blocks of code simply shows that instead of changing
the position of the sprite in relation to the background, we change the speed
to simulate the presence of gravity in the program.
· Up and Down
Similar to the change that you had input in the previous section, you replace
the code that is used for up and down movement so that instead of simply
changing the position of the sprite in the program, we also try to simulate
the presence of gravity in our program.
· Landing
Finally, this separate block of code is used as a landing checker. It simply
states that if the moon lander sprite touches a yellow color (the landing
pad), but is moving slower than a speed of -2, then your sprite implodes on
impact.
Looking at the solutions to the projects above, you will find that the
projects increase in difficulty. As you continue programming, you will find
that the projects that you create will require you to add more and more
variables to your projects. The sheer complexity of the projects, that you
will soon be creating, might seem daunting at first, but perseverance and
determination will get you anywhere. Note, however, that the solutions
above are not the only solutions out there. It is best to try and come up with
your own solutions! The library of programming solutions and concepts is
so wide, and the variety of solutions that you can come up with are
plentiful.
Now this part of the book has given you some increasingly difficult
challenges. You do not need to accomplish the projects, but in doing so, you
would have shown general mastery in the use of Scratch.
CHAPTER 6:
Repetition
Keep your code as concise as you can, meaning that if you notice that you
are doing the exact same thing everywhere in your code, then it might be
time to create your own block, or use a Repeat block. Just don’t use the
repeat block too many times, as anyone who may be looking at your code
could get confused.
Record = Infinity??
Creating a game and want to have the highest record?
When you create your Record variable, off to the side, set your record
variable to 1
followed by as many zeroes as you can (or copy and paste this:
1000000000000000000000000000000000000000000000000000000000000
000
0000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000).
Then, place a for-loop around a ‘change record by __’ block (with the long
number in it).
These two blocks combined will change the variable to display its value as
infinity.
If you do a simple comparison of the player’s score to the record, the record
should always be greater.
Record NaN?!
In the ‘set __ to _ ’block, instead of typing a numerical value, type in any
letter you want! Then, use the ‘change __ by _ ’block for the particular
variable and use the number ‘1 ’in the number space. After you have done
this, the variable will be displayed as having a value of NaN, meaning
‘nonexistent.’
Size it up
Have you ever had the experience of trying to make your sprite really large,
but it is just not getting big enough? Make two costumes in the sprite. In the
first costume, make the character super small. Then, use your grow code
until the sprite (in the smaller costume) seems like it is not growing
anymore.
Then, switch the costume of your sprite to the regular-sized costume. This
can be useful in multiple instances. (One example is if you want a piece of
art to be shown closer than it is normally shown on Scratch.) See if you can
figure out a practical use of this Scratch secret!
Varying Variables
You may already know this one by now but regardless, we are going to talk
about it anyways. Are you tired of having the same type of display for your
variables on the screen? If you are, you can right-click on the variable
display on the screen and you should get the following options: Normal
readout, Large readout, and Slider. The last option, Hide is another way to
hide your variable display. The other three options are different ways that
your variable display can appear on your screen! With this knowledge, you
can either make the score of a player be in the Large readout option, or you
could use the Slider option for pen size in a pen game!
Rotation Styling
Have you ever been in a situation where you need to change the rotation
style from one type to another, mid-project?! It is actually rather easy to do
(it can be done with a not-so-prominent block). If you observe the Motion
section, there is a block called ‘set rotation style __ ’with a drop-down
menu.
WeDo
Have you ever wondered if you could use Scratch to program something
else? A LEGO robotics set called WeDo is compatible with Scratch! A cord
that is part of the set can be connected to the computer. Turning on Scratch
after connecting the cord to the computer shows you a few more blocks
based on motor movement!
The sets can be used alone or combined to make even larger things. They
do have simple examples you could make from the set, but see what you
can make and program, without instructions!
Password Please?
When you are creating a project for other users to see, and you want to test
if a user has already been on your project before, you can use the username
block, which is located in the Sensing tab. It is a round block that is useful
when making a project that you are sharing publicly. You can use this block
to display messages to a specific user. The only problem is anyone can see
the message if they open up your code and read it.
Timer
For the entire course of this book we have been telling you to make your
own variable for a timer, when in reality, there is already a block for a timer.
The two blocks related to timer can be found underneath the Sensing tab,
and are the Timer block (which is a round block with a check-box next to it)
and the Reset Timer block (a regularly shaped block). These blocks work
well, but the only issue is that this timer starts at 0 and will continue to
increase nonstop until you use the Reset Timer block (after which it will
continue to increase… also nonstop). This is not entirely useful, you could
say. However, there are multiple places where you could use this variable. If
you are making a game where the objective is to last the longest, you can
save the user’s best time using the timer, a variable, and the Username
block.
And Action!
Have you ever wanted to see yourself in your own project? Under the
Sensing tab, there are blocks related to video, however, you would need a
video camera on your computer to achieve this.
· Math operators
Operators
Think about math class, what do you learn? Addition, subtraction, maybe
even multiplication and division! These are called operations, and you can
do this math with codes too! You need to learn to use operators in Scratch,
so you too can perform just the right action to get what you need to be done.
You might have to make something twice as big, half as loud, or increase a
score in your game. With operator blocks, you will be able to do this and so
much more.
Math Operators
When you need to do some math in Scratch, the math Operators blocks
have your back. Starting from the simpler ones, there are the (+), (-), (*),
and (/) blocks. These are the blocks for addition, subtraction, multiplication,
and division respectively.
These operator blocks are also called Reporter blocks. Just like a report
card from school, they tell you (or whatever block they are in) the number
they calculate. If you click on one of these math Operators blocks when
they are by themselves, they do not have any other block to report the
number to, and so they will just show it in a little bubble.
If you want to see the answer without having to click on it each time, you
can put the operator inside a ‘say _____’ block to have your sprite say the
answer instead.
Essential
Clicking on the blocks is a great way to test what your block actually does,
and figure out any problems with your script. Often, you can work out
problems in your blocks by disconnecting them, clicking on each of them
separately, and slowly building them back together. This will help track
down any problems you have.
You do not have to use just one Operators block. The blocks can be
combined together or stacked to create longer operations. For example, if
you want to find out what ‘2*3*4 ’is, you can put an Operators block
inside of another Operators block like this.
You might have learned in school that there is a certain order you have to do
math operations in. If you do them out of order, it might give different
answers!
Alert
If you have not learnt about parentheses and exponents in school yet, do not
worry. You will learn about them in a few years, and you do not need to
know about them to be able to code with Scratch.
For example, let us look at a simple equation like 2+3*4. What do you think
the answer is? Did you guess 20? Sorry, it is 14, but good try! If you do this
operation by adding 2 and 3 together first, you would get 5. Then if you
multiply by 4, you would get 20.
But math has rules about what order to do everything in. First, you do
everything in parentheses. Then you do any exponents. Then, you do all of
the multiplication and division. Finally, you add or subtract whatever is left.
So, let us look at that math problem again. The rules tell you to multiply
before adding, so multiply 3 by 4. You should get 12. Now it is time to add
the 2, and you end up with 14. That is not the same as 20!
Scratch helps you with this order when you stack blocks together. The way
you stack them will determine which order it does these operations in. Let
us take a look at that math equation again, this time using Scratch. If you
put the ‘2 +3’ block inside of the ‘___*4’ block, it will add the numbers
first and then multiply. If you put the ‘3 *4’ block inside of the ‘2
+_______’ block, it will multiply the numbers first.
Essential
Think of it like the highest or topmost Operators block always go first, then
the next block under it would go, and so on until the end of the script.
Besides the four normal math Operators blocks, there are a few others. The
‘round _______ ’Operator block rounds whatever number you put in, to the
nearest whole number. That means it gets rid of any decimal part of a
number.
Any number that has a decimal between 0.0 and 0.49 will be rounded down,
so you do not see the decimal point. For example, 10.25 would be rounded
down to 10. Any number that has a decimal between 0.5 and 0.99 will be
rounded up to the next closest number. So, for example, the number 10.75
would be rounded up to 11.
The ‘round _______ ’Operators block can be very helpful when used with a
Sensing block, or other math operations that have a lot of decimals, that you
do not want to show. For example, if you put the timer block inside the
‘round _______’ block, it will count by the number of seconds, instead of
showing all those annoying parts after the decimal point changing like
crazy!
When you play games, you might have noticed that some mobs of monsters
have a lot of randomness to them. They seem to find their way to attack, but
they do not go right to you. They kind of just wander in different directions.
The ‘pick random _______ to _______’ block can make your sprite do the
same thing.
You can put things into random places, make them appear at random times,
and much more. This is one of the most useful blocks in Scratch, to make
your projects more challenging and fun.
What if you needed a random number to include decimals? To get the ‘pick
random _______ to _______ ’block to also pick decimals, all you have to
do is put a decimal in the block! For example, if you want to get a decimal
between 0 and 1, all you have to do is use ‘0.0 ’or ‘1.0 ’in your block.
Essential
Coding often requires you to look up how to do things on the Internet.
These blocks are there, in case someone with a little more experience tells
you to use it. Once you learn about these functions, you can come back and
use them in Scratch!
CHAPTER 8:
2. Logical operators
3. Word tricks
4. Activity
Conditional Operators
That is enough numbers for now. There are other types of operators that you
can use from this section as well. Another type is conditional operators. Let
us learn about them!
This is also useful for checking to see if things are close to the bottom of
the screen. Why would you want to see if your sprite is close to the bottom
of the screen? Well, maybe you created a game where your sprite is falling.
While it might seem like these blocks are good only for numbers, you can
also compare words. This can be useful when you want to know if a
variable is the right value. In this example, it checks if the dragon sprite’s
costume is currently the ‘dragon-c ’costume before it runs the if/then block.
The if/then block here uses the operator to decide whether to do the ‘think
_______ for _______ seconds’ block that is inside the if/then block.
When you are putting words into these blocks, you do not have to worry
about capitalizing letters. Scratch ignores uppercase and lowercase letters
and keeps them all the same. More advanced programming languages do
not do this, so be careful if you start programming in Python or JavaScript.
You can also use the comparison conditional operators to sort strings
alphabetically. In this case, cats are not greater than dogs! The word ‘cat’
starts with a ‘c, ’so it would come before (or is less than) the word ‘dog.’
Logical Operators
The conditional operators reviewed so far can work with numbers and
words. There are three other conditional operators that work only with other
conditional operators. They are called logical operators: the ‘___ and
___’block, the ‘___ or ___’ block, and the ‘not ___’ block.
These first two blocks do exactly what you might expect. If someone tells
you to clean your room and vacuum the stairs, you would understand that it
is different from someone saying, ‘clean your room or vacuum the stairs.’
Scratch ‘____ and ____’ and ‘____ or ____’ blocks work the same way.
Word Tricks
Often you will want to combine different words together for a sprite. It
might be that you want it to say something that uses one of its variables,
like its costume name here.
This block just connects two sets of words together. Anytime you have text
or words instead of numbers, it is usually referred to as a string. There are
two strings that join blocks. The first is the string ‘ My costume is,’ and the
second is the variable c ostume name. Make sure to add a space at the end
of the first string. If you do not, the two words will smooch together!
Fact
String
A string is a set of text or words used in coding.
There are three other blocks that also work with strings. The ‘letter _______
of _______’ block finds the letter that is at a specific count in a string. So,
for example, ‘letter 1 of world’ would be the letter ‘w’ and ‘letter 5 of
world’ would be ‘d’ .
Sometimes you will want to know how long your string is. The ‘length of
_______’ block tells you how many letters are in the string. In this
example, the ‘length of world’ is five.
The final block that works with strings is the ‘_______ contains _______?’
block. This can be helpful if you need to know if a string is part of a
different string. For example, let us say you have a sprite that has five
costumes: ‘Charlie- 1,‘ ’Charlie-2-bouncing-ball,‘ ’Charlie-3-dunking,’
‘Charlie-4-holding-ball, ’and ‘Charlie-5-sitting. ’If you want to know if
Charlie is currently wearing a costume with a ball, then you can use the
‘_______ contains _______’ block to tell you.
Activity
In this activity, you will get to create a math game to challenge your
friends! Just like in Jeopardy! Ripley will give the answer and ask you a
question. You can put in a lot of distracting answers to make it harder, and
each one that the player clicks on will show if it is right or wrong!
Alert
You can either use one of the space backgrounds found in Scratch or you
can use a picture from the Internet like the one in this example.
1. Add the Sprites
First, add a sprite to give the player the question. Then, add a backdrop to
make it more fun. You can pull one from the internet or use a background
from Scratch. Let us use Ripley for this example. You want to make sure
the player knows what to do, so have Ripley give some directions, and then
ask the question.
Click the Paint icon to draw your own sprite. Draw the costume with some
text, by clicking the Text icon and adding your own math equation, such as
32*3 in the example. Do this a few times, making sure that only one
equation is right.
Do the same thing for each of the wrong answers. The more wrong answers
you make, the more difficult it will be. But now you need to add the correct
question. It would be pretty frustrating to play with no correct question!
Alert
Later on, try to have each sprite’s question check if its answer matches the
answer that Ripley asks for, so that Ripley can ask more questions. You can
even have more than one right question!
Description
Let us start with an overview of the game we want to build. It is a maze
game. Scratchy, the cat, wandered too far away from home, one night. Now
he is lost, and cannot find his way back home. Help Scratchy find his way
through the maze and return home.
What We Need
As I have mentioned, we will be using most of the blocks we have learned
about so far, and some simple cool tricks.
Adding a sprite: First, we will add a Sprite. I am using Scratchy, the cat, for
mine. You can use any of the human or animal sprites for this game. We
will also work on positioning a Sprite as well.
Drawing a backdrop: We will be drawing a maze for our context. This game
will make use of some simple shapes for drawing. We will also learn to
color, duplicate, and resize shapes.
Event blocks: We will be using Events blocks when the green flag is
clicked to start our game, and position Scratchy.
Motion blocks: To get Scratchy home, he will have to move through the
maze. We will be using some Motion blocks to make this happen.
Button control: You will learn to use button control as well. The player of
the game will be able to move Scratchy through the maze, using the up,
down, and right keys of your keyboard.
Conditional commands: Remember when I said we would be using
conditional commands a lot when we build games? This game will have a
number of them. We will use if/then controls, to tell Scratchy to return to
its starting position when he touches any part of the maze or the edge of the
stage.
Sensing blocks: We have not learned about Sensing blocks yet. They are
used to make your game character sense when something happens in the
game and respond accordingly based on the script you have written.
Sound blocks: Finally, when Scratchy finds his way home, we want the
game to play an exciting sound. We will be using Sound blocks to get that
done.
We will be using all of these blocks to make a simple but fantastic game. I
will guide you through the basics, but you are free to play around with some
of the blocks and add some exciting features to your game if you want.
Ready! Steady! Let’s go.
Phase 1: Setting Things Up
Step 1: Open a new project: you should start your game by creating an
entirely new plan. You can give it any name of your choice, and save it.
Step 2: Let us set the stage for our game. We will not be choosing one of the
fancy backdrops for our game. Instead, we want to use a blank backdrop on
which we can draw our maze. You still remember how to choose a blank
backdrop for bringing, right? Do not worry; I will remind you. Go to the
backdrop area below the stage, and hover over the Backdrop icon. Select
the Brush icon from the list of options. A blank white canvas should be
displayed on the left-hand side of the page. This is your blank backdrop
page.
Step 2: Make Scratchy move up when you press the Up arrow button on
your keyboard. For this, you will need the ‘when _ key is pressed’ block
under the event palette. Also, go to the motions palette and choose the
‘change y by _’ block. Set this number to 10 (you can use a lower amount if
you want you Sprite to take shorter steps)
Helpful tip: Do you remember what y represents? It is the vertical position
of your object. Changing it can be used to make your objective go up or
down on the same line.
Step 3: Make Scratchy move down, when the Down arrow key of your
keyboard is pressed. For this, you do not need to pick a new block from the
palette. Duplicate the blocks from Phase 2 above. Change the Up arrow key
to the Down arrow key. You should also change the number of steps to -10
since this button will make Scratchy go down and not up.
Step 4: Make Scratchy move right, when the Right arrow key is pressed on
your keyboard. Drag in the ‘when _ key is pressed’ block, and edit to the
Right arrow key. Since you want this key to move Scratchy from left to
right on the x-axis, you will have to select the ‘change x by _’ block. Set the
number of steps for this as well.
At this stage, when you click on the green flag, your Sprite should
automatically appear in the starting position, and you can move it through
the maze quite easily using the arrow keys.
Getting Started
You will have to find the Scratch Jr application on your device. Tap on the
Home button. Press on the plus ( + ) sign to start a new project.
3. Add an Object
The cat needs a ball to play basketball. Add a basketball from the library to
Page 1.
4. Add a Background
Tap the background button at the top of the screen, to go to the background
library.
Find the gym background and tap it twice. Add the same background to a
second page.
Drag the basketball player and the ball, and position them in the middle of
the court. Drag the player, and place its right hand in front of the ball to
make it look like they are bouncing it.
Did you know?
Sheryl Swoopes became the first-ever player to be signed by the WNBA
(Women’s National Basketball Association) in their first season in 1997.
She played for the Houston Comets.
You now have the background and characters to start programming your
basketball animation.
5. Resize Character
Let us make the basketball smaller, to make it fit better with the cat’s size.
Tap on the ball and copy the following code:
This block will make the ball smaller. The bigger the number, the smaller
the ball will become.
This code will make the animation start when you tap on the basketball.
The orange envelope at the end will send a message to the cat to shoot at
the hoop. This is called a trigger message. Tap on the basketball on Page 1
to test your animation.
You might have noticed that this program starts with an orange envelope in
the ball’s program, which triggers an action on the cat.
Tap on the ball again and add the following blocks to the program you
created in Step 6.
The red block at the end will move the animation to Page 2:
Tap on Page 2, and add the basketball player character and the basketball.
Place the ball under the hoop, and the basketball player in the middle of the
court.
Troubleshooting
Sometimes the trigger message might make the animation look slow. To
solve this, add speed blocks (medium or fast) after the trigger message, to
make the action faster.
Challenge
Use the purple looks blocks to add a speech bubble to the player saying
“Yes!” after they score.
Can you make the player dribble the ball?
Using the blue motion blocks, try to make the player dribble the ball.
Conclusion
I
want to thank you for taking out time to read this book! I certainly
hope that you have found it informative and useful. The goal in this
book was to keep things simple so that beginners can understand
Scratch and get started with using it. Hopefully, we have kept it
interesting and fun as well.
In this guide, we have had the opportunity to discuss the most important
features in Scratch. Since this guide is dedicated to those who are not that
knowledgeable but still interested in programming, we tried to keep it as
simple as possible. However, we wanted to give you as many entertaining
projects that you can try to create on your own, as we could. It was
important to become familiar with Scratch and the environment in which
you are supposed to work. Furthermore, we explained all of the basic
commands that Scratch offers and walked you through the different kinds of
games and animations, so you can use that material for practicing.
In the end, we dedicated a lot of time to variables which are one of the key
concepts of programming. Once it happens that this guide becomes less
advanced for you, feel free to use all of the additional files and resources
that we mentioned, at least when it comes to the version of Scratch that we
used in this guide.
The best approach is not only to find simple tasks on the site but also tasks
that are interesting. One task that is good to try is the one we touched on in
the book. That is the animated letters. This is a fun task that children enjoy,
and it lets them directly connect the commands they are giving to the action
that they see on the screen. The animation process can also involve several
different methods, and so it also gives the children a chance to learn a lot
about Scratch, in a simple context.
Glossary
Animation
Something that moves around on the screen and looks like it has come to
life.
Character
A person or animal in a story.
Code
A language for expressing information and instructions that can be
understood by a computer.
Coder
A coder is someone who writes code. A coder creates computer games.
Coordinate
A set of numbers used to locate a point on a line, map, or grid.
Crash
To crash means to stop working. When computer games crash, people
cannot keep playing them.
Data
Data is saved information that can be used later. The Scratch program can
save data.
Detect
To detect is to discover or learn something. Sensing blocks in Scratch help
the program save data.
Ellipse
A shape that looks like a flattened circle.
Equations
Equations are mathematical statements that include an equals (=) sign.
Operators blocks in Scratch involve equations.
Felix
Felix is the name of the orange cat that you see at the start of every project.
You can use Felix in your project, or delete him and add a new character.
Grid
Turn the x-y coordinate grid on and off.
Interact
To communicate or spend time with something.
Interface
It is the way a computer program looks on-screen; for example, the layout
of the screen and the menus.
Library
A collection of characters and backgrounds.
Motion
Used for moving sprites around the stage.
Orbit
A repeated movement around an object, such as the moon orbiting Earth.
Palette
The range of colors used in a painting or design.
Random
Showing no clear pattern or plan.
Selections
Selections are a type of code that computers use to choose between different
options. A coder uses selections to tell the computer which messages to
display in the game.
Sequence
The order in which instructions are given to the computer.
Simulate
To mimic or act like something else.
Sound
Used for playing recordings or musical notes.
Variables
Variables are things that have values and that can be measured. Data blocks
save variables in a Scratch program.
Visual
Something that can be seen. Scratch is a visual programming language
because the user can see it.
CODING WITH PYTHON
A Playful Way Of Programming, Coding, And Doing Projects With Your Kids.
Learn Computer Science Quickly While Stimulating Your Kids’ Creativity.
Mark B. Bennet
© Copyright 2020 - All rights reserved.
The content contained within this book may not be reproduced, duplicated or transmitted without
direct written permission from the author or the publisher. Under no circumstances will any blame or
legal responsibility be held against the publisher, or author, for any damages, reparation, or monetary
loss due to the information contained within this book. Either directly or indirectly.
Legal Notice:
This book is copyright protected. This book is only for personal use. You cannot amend, distribute,
sell, use, quote or paraphrase any part, or the content within this book, without the consent of the
author or publisher.
Disclaimer Notice:
Please note the information contained within this document is for educational and entertainment
purposes only. All effort has been executed to present accurate, up to date, and reliable, complete
information. No warranties of any kind are declared or implied. Readers acknowledge that the author
is not engaging in the rendering of legal, financial, medical or professional advice. The content
within this book has been derived from various sources. Please consult a licensed professional before
attempting any techniques outlined in this book.
By reading this document, the reader agrees that under no circumstances is the author responsible for
any losses, direct or indirect, which are incurred as a result of the use of information contained within
this document, including, but not limited to, errors, omissions, or inaccuracies.
Note to Parents
T
his book is intended for children who wish to learn to
programming, especially in Python language.
Imagine you have coded a calendar. It is a basic one, in which you have 12
months/365 days with just a small space next to each day, where you can
note your appointments and tasks for that day. This is good for today, but as
soon as tomorrow comes, a program with more advanced functions will
appear on the market. Someone else may have found a way to put, for
example, more space for editing besides each day, or may have coded a
clock into the calendar. In this new, advanced calendar, besides the date,
you may be able to keep track of time during each day, or perhaps holidays
or the ability to set audible reminders in the calendar are now included. This
is the kind of innovation we are talking about in this book.
The reasons mentioned here make programming one of the most useful and
beneficial skills to possess, for both children and adults alike. As with most
other science-based disciplines, it is best to start learning early in childhood
- the sooner, the better. Therefore, this book is written to motivate children
to start learning to code in order to enhance their imagination and logical
reasoning skills, and to prepare them for their future adult lives. Today,
computer literacy is mandatory. This book can help you give the children in
your life the tools they need to be successful when they grow up.
Introduction
Welcome to Python
Hey there!
I
f asked what a core subject in school is, English, Mathematics and
Science are most likely the subjects that jump to mind. However, in
recent years, we have seen coding appearing as a new ‘must teach’
subject, although there is an air of controversy over whether it should
or shouldn’t be taught. Wherever you stand on this debate, there is no
denying that learning to code will provide children with valuable skills that
can be used in all areas of their life.
Even if you are learning to code as an adult, this book is the perfect starting
point for a much-needed foundation. This book is most definitely not just
for kids.
This book contains proven steps and strategies on how to start teaching
children (or adults) to code. It includes hands-on activities that can be used
both in the classroom and at home to consolidate coding concepts, as well
as useful resources for working with code on a computer or tablet.
What is Coding?
Coding sounds daunting if you aren’t technologically minded. We imagine
it to be complicated jargon, which of course it is until you understand it. In
reality, anyone can learn to code, just like anyone can learn a new language,
or how to play a musical instrument. It just takes perseverance.
You see, while we think that they are smart, computers are, in fact, useless
unless somebody methodically tells them what to do. A person who writes
this code is known as a computer programmer. These instructions are then
used to tell a computer how to run a specific program, follow a command,
or open an application (app). For example, when you click the button on
your mouse, pre-existing code written to tell the computer what to do is
activated when the button is clicked.
Why Learn to Code?
According to Code.org, there are more than 500,000 unfilled computing
jobs, and programming jobs are the number one source of new wages.
Coding truly has evolved into the new literacy of the Augmented Age. Even
if you do not become a software engineer or work a computing job, you will
still be impacted by its prominence in the industry. Developing at least a
fundamental understanding of programming is a valuable skill-set for future
employment opportunities and understanding the implications of
technology use. Technology is such an integral part of this generation, that
it is rather naive to not have some understanding of software that controls
billions of devices and how they work.
Learning to Program
ON A PC
If you are on a Windows computer, you probably do not have Python
installed already. This is because Windows operating systems do not usually
come with the Python language. That is okay though! We can get it
ourselves.
10. You are done! Click the Close button and you are ready
to go. You have installed Python on Windows!
ON A MAC
1. On your computer, open an Internet browser like Google
Chrome or Mozilla Firefox.
The website will probably know what type of computer you are using, and
the Download button will show you the correct version of Python to install.
You can also find the installer for the specific computer you are using in the
Files section.
4. When you start the installer, you should see a window like the
one below.
5. Click the Continue button. You will then be presented with
some important information that you can choose to read or not.
6. Click the Continue button. Next, you will see the license
information.
7. Keep going! Click the Continue button. You will be asked to
agree to the terms of the software license agreement.
8. Click the Agree button. You will reach the final window, as
shown below.
9. Click the Install button. If you need to, enter your personal
username and password for your account on your computer.
Mac OS sometimes asks for this to make sure you want to
install something. If you do not see this pop-up window, you
can continue to the next step.
print("Hi Python!")
Now, hit the Enter key. Do you see something like this?
Great job! You have written your first line of Python code! Give yourself a
pat on the back or high-five the person closest to you. You are about to
learn some awesome things next.
Saving Your Program
Even though it is a short program, Let us save our Python greeting to a
separate file, so you can see how easy it is to save your work.
1. On the Menu bar in your Shell, click the File tab to open its
context menu, which is a list of actions that you can perform.
We have to put our greeting into this piece of Python code so that the
computer knows to write this message for us on the screen (you will learn
more about this later).
Great! Now you have your code in a file that we can save. This is important
because the first code we wrote was in the Shell, which means it will not be
saved once you close the window. Writing code directly in the Shell is just a
quicker way to run Python code and see the results right away. Always
create a new file and save it, to keep track of your work and save your
progress!
Now that we have created a file with our greeting code, let us save it.
You can save your program in IDLE by following these next steps.
5. On the Menu bar of your Shell, click the File tab to open its
context menu.
6. Click Save.
7. The next window will ask you to name your file. Go ahead and
give it a name. I will call mine ‘greeting.’
8. Make sure to save your Python program in a place that you will
not forget! If you do not choose another place, new files are
usually saved in the same folder where Python was
downloaded, so go ahead and change the Save In folder to a
better one. I created a folder called Cool Python in my
Documents directory, so that is where I will save my programs.
9. Click Save. That is it!
Using IDLE (Guide A to Z)
When you download and install Python, it will also install an application
called IDLE. IDLE is short for Integrated Development and Learning
Environment (that is a mouthful!), and it is an integrated development
environment (IDE), that helps us in writing Python programs. Think of it as
an electronic notepad with some additional tools to help us write, debug,
and run our Python code. To work in Python, you will need to open IDLE;
opening Python files directly will not work!
ON A PC
1. Click the Windows Start menu.
2. Start typing ‘idle, ’then select the search result ‘IDLE (Python
3.7 64-bit).’
Note: Yours might say IDLE (Python 3.7 32-bit) if that is the kind of
computer you have.
3. A window should pop up that looks like this:
ON A MAC
· Navigate to Go > Applications.
The first game will be Rock, Paper, Scissors, which is normally played by
two people, but in this case, it’s going to be you against the computer. The
first thing we need to do when creating a game is brainstorming. Using a
pen and paper, map out how the game should be designed. Start by first
considering the rules of the game, and only then worry about the
programming side.
This classic game involves choosing one of three objects, as the name
suggests. Once both selections are made, the items are revealed to see who
wins. The player who wins is determined by three simple rules: Rock will
crush Scissors, Scissors will cut Paper, and Paper covers Rock.
To handle these rules we are going to create a list of choices, similar to the
list of colors we created before in some of our drawing programs. Then, we
will add a random selection function that will represent the choice the
computer makes. Next, the human player will have to make his or her
choice. Finally, the winner is decided with the help of several if statements.
Before we continue with the code, you should start performing these steps
on your own. You already have the plan and you know which steps you
need to take. So, simply break down the game into easy sections, and work
on each section one at a time. If you don’t remember how to write an if
statement correctly, go back to the chapter about if statements and refresh
your memory. The point of this chapter is to help you apply what you
already know. So give it a try before you read the following code.
Have you tried to create your version of the game yet? If so, good job! Even
if you didn’t finish it or you wrote the game and are still getting some
errors, you should still reward yourself for trying. Now, let’s go through the
code and see how this game should turn out:
import random
print (“Rock beats scissors. Scissors cut paper. Paper covers rock.”)
player = player.lower ()
computer = random.choice(selectionChoices)
if computer == "scissors":
print ("Victory!")
else:
print("You lose!")
elif player == "paper":
if computer == "rock":
print("Victory!") else:
print("You lose!")
elif player == "scissors":
if computer == "paper":
print ("Victory!") else:
print("You lose!")
else:
print("Something went wrong…")
print()
First, we import the random package which allows us to use a number of
functions that we are going to take advantage of, giving the computer the
ability to make random choices. Then, we create a list for the three game
objects and print the game rules so that the human player knows them. The
computer will already know what to do because it is programmed, after all.
Next, we ask the player to type his or her choice, and then a loop is
executed to check the choice of the player. The player also has the option of
quitting the Prompt window, and when that happens the game is over. Our
loop makes sure that if the player doesn’t select the quit option, the game
will continue to run.
The next step is to ask the computer to select one of the three game objects.
This choice is done randomly, and the selected item is stored inside a
variable called “computer.” After the choice is memorized, the testing phase
begins to see which player will win. First, a check is performed to see
whether the two players have chosen the same item. If they did, then the
result is a draw, and nobody wins. Next, the program verifies whether the
player chose rock, and then it looks at the computer to see if it chose
scissors. If this is the case, then the rule says Rock beats Scissors, so the
player wins. If the computer neither selected Rock nor Scissors, then it
certainly chose Paper. In this case, the computer will win. Next, we have
two elif statements, where we perform two more tests that check whether
the player selected Paper or Scissors. Here, we also have a statement that
checks to see if the player chose something that isn’t one of the three
possible items. If that is the case, an error message is sent that tells the
player he either chose something that is not allowed, or he mistyped the
command.
Lastly, the user is prompted to type the next selection. This is where the
main loop goes back to the beginning. In other words, the game starts
another round of Rock, Paper, Scissors.
This game is simple, but it is fun because anyone can win. The computer
has a chance of beating you and there’s also a real chance of the game
ending up in a draw. Now that you understand how to create a random
chance type of game, let’s look at other examples to add to our game library
while also learning Python programming.
Activity 2: Guess!
This project will be another fun chance-based game that will make use of
the random module. The purpose of the game will be choosing a number
between a minimum and a maximum limit, and then the opponent tries to
guess that number. If the player guesses a higher number, he will have to try
a smaller one, and vice versa. Only a perfect match will turn into a win.
import random
Python will now automatically generate a random figure between 1 and 20.
Keep in mind that the minimum and maximum values are included in the
number generation; therefore, Python can also generate numbers 1 or 20.
You can test this command as many times as you want to make sure that
you are truly getting random values. If you execute it often enough, you
will see that some values will repeat themselves, and if the range is large
enough you might not even encounter certain numbers, no matter how
many times you run the code. What’s interesting about this function though,
is that it isn’t truly random. This is just a side note that won’t affect your
program, but it is intriguing nonetheless. The randint function actually
follows a specific pattern; the chosen numbers only appear to be random,
but they aren’t. Python follows a complex algorithm for this pattern instead,
and therefore, we experience the illusion of randomness. With that being
said, let’s get back to the fun and games. Let’s create our game with the
following code:
import random
myGuess = int (input (“Try to guess the number. It can be anywhere from 1
to 100:”))
That’s it! Hopefully, you tried to create this game on your own because you
already have the tools for the job. Remember that programming is only easy
as long as you practice it enough on your own. Just take it one step at a
time. With that being said, let’s discuss the code in case you need some help
figuring the game out. Just like before, we first need to import the random
module so that we can use the random number generating function. Next,
we use the randint function with two parameters. As mentioned before,
these parameters are the lowest number we can guess, which is 1, and the
highest number we can guess, which is 100. The random number generator
will generate a number within this range. Once the number is generated, it
is stored inside the “randomNumbers” variable which we declared. This
number will not be known by the player because he or she needs to guess it.
That’s the point of the game.
Next up, the player needs to guess the hidden number. This guess will then
be stored inside a new variable called “myGuess.” In order to check
whether the guess is equal to the number, we are using a while loop with the
“not equal to” operator. We do this because if the player gets lucky and
guesses the number correctly on the first attempt, the loop simply doesn’t
finish executing because there’s no need.
Next, if the player guesses the wrong number, we have two if statements
that check whether the guess is a higher value than the hidden number or a
lower one. An appropriate message is then printed for the player in each
case. In either scenario, the player receives another chance to make the right
guess. Finally, in the end, if the user guessed the number correctly, the
program declares victory by printing a message and then the program stops
running.
To make the game more interesting, you can challenge yourself to modify
the random number generator to include different values. You can also add
a statement that enables the game to print the score to see how many times
the player tried to guess the number. Also, since the game ends when the
player guesses correctly, you could write the main loop so that the player
can choose to restart the game instead of automatically quitting. Have fun,
and don’t be afraid to try anything.
Activity 3: Choose a Card
Card games are always fun, and they also rely on random elements to some
degree. No matter what the card game is, chances of having multiple
identical games are quite small. This means you won’t get bored any time
soon. With what we discussed so far about Python programming, we can
create a card game. It might not look good unless you have an artistic friend
to draw everything for you, but you could still create the graphics with the
help of the Turtle module, as we did for other projects. This will require
some patience though. In any case, we can create a card game even without
graphics by simply generating the name of each card. Instead of seeing a
virtual card, we will see the name “four of spades,” or “queen of hearts.”
Before we continue, you should take note that this project is your challenge.
You have learned everything you need to write such a game, and we already
created two other fairly similar projects. So, this time, you are almost
entirely on your own. As usual, start with a pen and paper and figure
everything out in logical order. Worry about the code afterward. However,
to help you out a little, we are going to brainstorm together just to give you
some ideas.
One of the simplest card games we can create involves a game with two
players that battle each other to see who draws the card with the highest
value. Each player will randomly pull a card from the deck, and the one
who has the higher card will win. It is a simple yet fun game due to the
element of randomness.
Since we won’t be using any graphics, we will have to create our deck of
cards some other way. We are going to set them all up as a list of strings as
we will be using their names instead. Next, we need to give the players the
ability to randomly pull a card from the deck. This means that we are going
to use the random module once again, and we will add a choice function
that randomly distributes cards to the players. Finally, we need a way to
compare the two cards that are drawn by the two players. As you probably
guessed, this is a case for comparison operators.
That is pretty much all it takes to create a card game. You can add more
features, or remove some, if you aren’t interested in them. Whatever you
do, design the game on paper so that you know your goals beforehand.
Then, work on those goals by writing one line of code at a time. This way
you will write your game in no time and you will be able to fix whatever
problems you encounter fairly quickly.
Activity 4: Random Number Generators: Mimic a Coin Flip
Now, before we can write a coin flip/toss program, we need a way to
produce random numbers. That may sound like something difficult if not
impossible. After all, how in the world do you make something random?
Well, the good news is that there is a way for you to generate random
numbers with the help of Python programming. As you might have guessed,
it requires some serious math. But don’t worry. Someone else has done the
math for you.
You don’t have to come up with the mathematical formula or the algorithm
that will create random numbers. It has all been done for you. In fact, there
are several ways to produce random numbers in Python.
Not only do these functions produce random numbers, but they can also
manipulate the randomness of the numbers being created. In a way, they
give you some degree of control, so you can decide which set of numbers
can be produced.
Note that these functions are used in many games, apps, lottery programs,
and many other applications where an element of randomness is needed.
They are pretty useful actually.
We can use the choice( ) function to randomly generate either the number 1
or 0—well, we can also choose 1 or 2, too. It’s all up to you which two
numbers you will choose. The next question is how does this function
work?
Here is an example of how the choice( ) function will look like in a Python
program:
You are already familiar with the print( ) function. Next, as you can see
from the sample above, you use the choice( ) function by using the
following line of code:
random.choice( )
From the said example above, you will also notice a set of numbers
enclosed within a pair of square brackets, which are the following:
[5, 4, 3, 2, 1]
This function will choose any of the numbers inside the set contained
within the square brackets. Note that only the numbers in this container will
be used. That is the control that will be given to you when using this
random number generator.
What we have below is called the syntax of a statement. In programming
terms, the syntax is the proper arrangement of terms in a programming
language so that it can be interpreted correctly (or translated correctly into a
language that can be understood by a computer).
random.choice([sequence])
Here are the parts of this function:
Writing all those numbers in your Python code will become way too long if
you do it that way. Don’t worry. Other functions can handle such a task. For
now, let’s just concentrate on using the choice( ) function since we want a
limited set of numbers to choose from.
Open your Python console and enter the following lines code:
>>> import random
>>> print(random.choice(["heads","tails"]))
Import Statement
You remember that it was explained earlier that other people have written
the algorithms and the Python code for a lot of tasks that you will need in
programming. In this case, when you need a program that will generate
random numbers, other programmers have already done the job for you.
All you need to do is to use their code. That means someone else already
wrote the code for the choice( ) function that we were discussing earlier.
Now, for you to use that function, you need to import it from the code that
they wrote into your own code.
That eliminates the need to write what they already wrote. All you need to
do is to import it. In this case, you will import something called “random.”
Moving forward, notice that when you press enter after this line of code:
>>> print(random.choice(["heads","tails"]))
The system will display either heads or tails. Press the Up arrow key to
display that command again. Pressing the Up arrow key on the command
console of Python will display the last command that you entered. That way
you don’t have to retype everything over and over again. This only works
on the command-line console.
Now we are ready to create the algorithm for the coin flip game. Here it is:
2. Explain the rules of this game: a virtual coin will be tossed. There will be
no graphics involved. Just an imaginary or virtual coin toss for now.
3. The player will guess whether the coin will show heads or tails.
5. The player that guesses the side of the coin correctly gets 1 point, the
player who doesn’t guess correctly has 1 point deducted. The player who
gets 3 points first, wins.
CHAPTER 2:
· Indentation
· If-else statements
· For-in loops
· While loops
· Input texts
If Statement
if test-expression:
statements
Example
a = 200
b = 100
if a > b:
print ("a is greater than b.")
Output:
a is greater than b.
Explanation
a > b is a test expression; it tests whether 200 > 100. If it returns true, it will
execute the code print( ), if it returns false, it will not execute the code
print( ).
If-else Statement
if test-expression:
statements # run when text-expression is true
else:
statements # run when text-expression is
false
Example
a = 100
b = 200
if a > b:
else:
Output:
a is less than b.
Explanation
a > b is a test expression; it tests whether 100 > 200. If it returns true, it will
execute the code print(‘a is greater than b’). If it returns false, it will
execute the code print(‘a is less than b’).
Indentation
In Python, indentation is used to mark a block of code. To indicate a block
of code, you should indent each line of the block of code by four spaces,
which is the typical amount of indentation in Python.
Example
a = 100
b = 200
if a > b:
else:
Note:
if a > b:
else:
Example
Num = 200
else:
Output:
Example
Output:
Current Character: G
Current Character: o
Current Character: o
Current Character: d
Explanation
for str in 'Good' loops four times because ‘Good ’has 4 characters. str stores
the value of each character.
For Variable In Range( )
A for variable in range( ) can generate a sequence number.
(1)
Example
print (var)
Output: 0,1,2,3,4,5.
(2)
print (num)
Output: 3,4,5,6,7,8,9.
Explanation
while <test-expression> :
<statement>
Example
n=0
while n < 9:
print (n)
n=n+1
Output:
012345678
Explanation
n < 9 tests the n value. If n is less than 9, while-loops will execute the print
(n) and will continue to run the next loop. Until n is greater than or equal to
9, while-loops will terminate the loop.
The continue keyword can skip the next command and continue the next
iteration of the loop.
Example
num=0
while num<10:
num = num + 1
if num==5:
continue
print (num)
Output:
1234678910
Explanation
The statement, if num==5: continue, skips the next command, print (num),
when num is 5, and then continues the next while loop.
Break Statement
break
The keyword break is used to stop the running of a loop according to the
condition.
Example
num=0
while num<10:
if num==5:
break
num=num+1
print (num)
Output:
Explanation
The statement, if num==5: break, will run the break command if num is 5;
the break statement will exit from the while loop, and will run print (num).
Input Texts (1)
Sometimes users need to input some text via the keyboard.
variable = input(“prompt”)
Note: Please use double quotation marks to enclose your input (in some
Python versions).
Example
Output:
Jack
16
Explanation
The input( ) function can accept the data from the user’s keyboard input.
Input Texts (2)
Sometimes users need to input some text by keyboard.
variable = raw_input(“prompt”)
Example
Output:
Jack
16
Explanation
The statement raw_input( ) can accept the data from the user’s keyboard
input.
Note: The statement raw_input() is no longer used nowadays, but you need
to know a little bit about Python history.
Pass Statement
The pass statement is a null operation; it means ‘does nothing.’
It is also very useful as a temporary placeholder for future code that needs
to be inserted later.
Example
condition = True
if condition:
elif True:
else:
Output:
Explanation
Please go to Start > Programs > Python3.5 > IDLE (Python GUI).
if trafficLight == "red":
else:
Output:
if test-expression:
elif test-expression:
else:
Note: Please use double quotation marks to enclose your input (in some
Python versions).The statement raw_input() is no longer used nowadays,
but you need to know a little bit about Python history.
Summary
The if statement executes only if a specified condition is true; it does not
execute any statement if the condition is false.
The for-in loop repeats a given block of code a specified number of times.
The keyword, continue, can skip the next command and continue to the
next iteration of the loop.
The keyword, break, is used to stop the running of a loop according to the
condition.
variable = input(“prompt”)
If/Then Games
These games are based on conditional statements.
Quiz
1. What is an iteration?
A program test
A decision
if and while
if and else
True
False
!=
==
Yes
No
6. Which loop is used to repeat a statement a specific number of
times?
Indentation
For-loop
While-loop
Integer
Boolean
Float
True
False
>>
=>
>=
Activity 6: There’s A Loop For That!
Let’s say we want to output a greeting to our friends and tell them what our
favorite dessert is: print("Hi! My name is Adrienne. My favorite dessert is
ice cream.")
This works if your name happens to be Adrienne. Oh, and if your favorite
dessert also happens to be ice cream. What if it was chocolate? Or cookies?
Or cake? What if you had a different name? How would you change the
print() function to output your name and favorite dessert?
You could write a print() function for each combination. It would look like
this: print("Hi! My name is Adrienne. My favorite dessert is ice cream.")
That’s a lot of work, though. If you look at the three print() functions, do
you notice any kind of pattern? All of them are exactly the same, except for
the name and the dessert! This would be a great case to use an f-string and
some loops!
What to Do
Write a loop that outputs the name of a person and their favorite dessert
using the two lists below. The order of favorite desserts matches the order
of the people who like them, so don’t worry about that. Use an f-string to
print out the message.
Nacho, the cat, is walking through the neighborhood when he sees some
hula hoops by a playground. He notices that there are a few placed together
by the swings and another few propped up by the basketball court. Nacho
gets the idea to invite his friends to come and play.
What to Do
Nacho has requested that his more athletic or younger friends be sent to the
hula hoops by the swings, since those hula hoops are more difficult to jump
through while the swings are in motion. If the cat friends are older or less
athletic, they should go to the hula hoops propped up by the basketball
court, as they are easier to jump through.
hula_hoops_by_swings = 0
hula_hoops_by_basketball_court = 0
As you cycle through Nacho’s friends, determine which group they belong
to. Then, add another count to that group to keep track of how many cats
are in each. Finally, print how many cats are at the hula hoops by the swings
and how many cats are at the hula hoops by the basketball court.
Let’s try writing a small program to help us sort our animals instead. Sound
good?
What to Do
To start, let’s create some variables for the different groups of animal legs
and assign a starting count of 0 (since we haven’t sorted any yet!):
has_zero_legs = 0
has_two_legs = 0
has_four_legs = 0
Cool! For now, we know that these are the three types of groups that an
animal from our zoo can be placed into: a group for animals with no legs,
another group for animals with two legs, and a third group for animals that
have four legs. Here’s some information about the various animals and their
number of legs:
moose = 4
snake = 0
penguin = 2
lion = 4
monkey = 2
dolphin = 0
bear = 2
elephant = 4
giraffe = 4
koala = 2
shark = 0
kangaroo = 2
komodo_dragon = 4
Create a list with the animal leg information, use a loop to iterate through
them all, and keep count of which group we add each animal to. Print out
the total number of animals in each group.
There are times when we need to share secrets with our friends. Wouldn’t it
be cool to write a small program that only allows users to see the contents if
they provide the right password? Well, we can do that using while loops!
What to Do
Create a new Python file called ‘secret-message’ and save it. In your
program, create three variables: one for a password, one for a user’s guess,
and another for your secret message. I started some below for some
inspiration:
password = 'cupcakes'
guess = ''
share at lunch!'
Now, create a while loop. Our while loop will be checking the password a
person tries through the guess variable. Our program should continue to ask
for a password if the person’s guess is incorrect!
To make sure that only those with the right password can view your
message, have your while loop check to see that your password variable is
not equal to the guess variable. If it isn’t, that means the person using your
program has not entered either the right password or any input at all. In that
case, continue the while loop and use a print() function to ask the user for a
password. Also, within the while loop, keep re-assigning your guess
variable to whatever the user types into your program like this: guess =
input()
You should only stop your while loop once the user enters the correct
password. Once that happens, use another print() function to show your
secret message!
Save your program, then run it. You should see it continue to ask you for
the right password and only show you the secret message once you provide
it!
Using Python’s built-in random module (see here) and while loops, build a
simple number guessing game! The computer will pick a random number
and assign it to a variable, while you take turns trying to guess that number.
Let’s code!
What to Do
import random
number = random.randint(1,100)
number_of_guesses = 0
Remember, you can change the range of the random number picked. This is
your game!
If it is, that means you still have guesses remaining. In that case, continue
the while loop and write a print() function to ask for a number between the
range you have selected.
Also, within the while loop, assign a new guess variable to whatever you
type into your program, like this: guess = input()
By default, anything you enter into your shell is a string type. To make sure
you can check your number of guesses correctly, transform your guess
variable into an int type by using Python’s built-in int() function: guess =
int(guess)
Now that you’ve taken another guess, you should increase your
number_of_guesses variable as well.
Finally, you need to check that the guess you’ve input is equal to the
number the computer chose at the beginning of your game. Use an if
statement for this, and break out of (stop) the loop if it is. To do this, simply
type the reserved code keyword, break.
You should only stop your while loop once you either guess the correct
number or when you’ve run out of chances to guess. In either case, feel free
to write a print() function that tells you it’s game over or that you’ve
correctly guessed the right number!
Save your program, then run it. You should be able to play your secret
number guessing game!
CHAPTER 3:
Turtle Graphics
· Turtle setup
Turtle graphics is a popular module for programming for kids (and adults).
You already know that to use turtle, you need to ‘import ’it. When you
import turtle and 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 the way you want it to. To do this, we would discuss a few
functions of the turtle module.
Bringing up the Screen
You need to assign turTle () to a variable to make editing the screen easy.
Here we are assigning it to the variable sr.
Example
You can also use the turtle Screen () function. (note that the S in ‘Screen ’is
in capital letters)
Example
Example
This will cause the turtle screen to be named ‘turtle screen. ’You could
name your turtle screen anything.
Turtle Setup
For the turtle setup, we will specify the size of the turtle. To do this, we use
the .setup function.
Example
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.
turtle.forward (distance)
turtle.backward (distance)
turtle.left (angle)
turtle.right (angle)
turtle.forward
This is used to move the turtle forward by a specific number of points or
pixels.
Example
R: This will move the turtle forward by 150 points to the direction the
arrow is facing.
turtle.backward (distance)
This moves the turtle in the opposite direction.
Example
turtle.left ()
This moves the turtle to the left, across the angle specified.
Example
>>>turtle.left (60)
turtle.right ()
The turtle.right function moves the turtle in the direction opposite to that
which the turtle.left function moved it.
Example
>>> import turtle
>>>turtle.right (60)
Pen up means that no line will show as the turtle moves, while pen down
means the lines will show.
The codes for pen up are turtle.penup(), turtle.pu(), and turtle.up(). You may
use any one of them.
The codes for pen down are turtle.pendown(), turtle.pd(), and turtle.down().
Example
>>>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 created earlier. 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 Speed
You may have noticed that the pen moves a little slower whenever it is
drawing the square. You can make it move faster.
The function for that is the pen speed function, which is applied by using
the code turtle.speed().
“fast”: 10
“normal”: 6
“slow”: 3
“slowest”: 1
If you type in a number greater than 10 or smaller than 0.5, the speed is
returned to 0.
Pen Width
The pen width controls the thickness of the lines drawn by the turtle. The
bigger the turtle pen is, the bigger the lines are.
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 the variable, t.
Example
>>> t= turtle
Drawing a Rectangle
Drawing a rectangle is comparable to drawing a square.
Example
>>> sr = turtle.Screen ()
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
This block of code tells the turtle to move backwards 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
distance. This gives us a rectangle.
You can play with the code, thereby 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.
Example
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
>>> t.circle(50)
Stars
Remember the loop we used for drawing a square simply? We can modify
the loop to give a star!
Example
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
t.forward(100)
t.left(225)
Unlike with the square where we looped 4 times with range (1,5), we loop
this eight times with range(1, 9).
Also, we tell the turtle to move forward 100 points after each loop. We also
make the turtle turn 225 degrees to the left, instead of 90 degrees to the left.
Examples
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
>>> for i in range(1, 9):
t.forward(100)
t.left(125)
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
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.
Activity 11: Let’s Draw A Star!
Now that we’ve learned about the turtle module and what it can do, let’s
draw a star! We’ll create a small program that can do this for us.
What to Do
import turtle
4. Create a pen variable and assign a turtle object to it. This makes it easier
to understand that we’re drawing something, instead of dealing with a
turtle!
pen = turtle.Turtle()
5. Choose some RGB values for a shade of yellow you like, or choose a
different color. For this activity, I’m using a bright yellow: pen.color(255,
215, 0)
6. Let’s also change the pen size so our star is nice and visible! You can
choose whatever size you want: pen.pensize(5)
7. Now let’s hide the shape so we can see our star a bit better: pen.ht()
8. Let’s draw! We’ll move our pen forward by 100 points, then turn our pen
144 degrees to the right. We’ll do this five times to create a five-pointed
star. The code will look like this:
pen.forward(100)
pen.right(144)
pen.forward(100)
pen.right(144)
pen.forward(100)
pen.right(144)
pen.forward(100)
pen.right(144)
pen.right(144)
9. Finished! Save your code by pressing the CTRL and S keys together.
Then press the F5 key to see your star drawn in front of you! Bonus: Can
you optimize the code above to use a for-loop instead?
Activity 12: Fortune-teller
What to Do
Create a new file called ‘fortune-teller ’and save it. Within it, import the
turtle module and the random module: import turtle
import random
Create a new copy of the turtle object and call it ‘pointer’; you can leave it
as the default arrow shape because that’s what we’ll need! Also, set its size:
pointer = turtle.Turtle()
pointer.turtlesize(3, 3, 2)
Create another copy of the turtle object and call it a ‘pen. ’We’ll use this to
create our fortune-teller board: pen = turtle.Turtle()
Finally, create a variable to hold your spinner amount, and use the random
module to pick a random number: spin_amount = random.randint(1,360)
Now, lift your pen so that it doesn’t start drawing. We only want it to draw
on the spots we tell it to: pen.penup()
Use the goto() function to move your pen to the four sides of your screen.
On each side, write some answers that your fortune-teller pointer can land
on. These can be simple “Yes” or “No” answers or silly ones like “Never in
a million years!” To help you out, I’ve provided the coordinates for the four
sides of the screen:
# right side
pen.goto(200, 0)
pen.pendown()
pen.penup()
# left side
pen.goto(-400, 0)
pen.pendown()
pen.penup()
# top side
pen.goto(-100, 300)
pen.pendown()
pen.penup()
# bottom side
pen.goto(0, -200)
pen.pendown()
Save your file. Now, every time you run your fortune-teller program, you
will get a random answer to your questions!
Activity 13: Rainbow Turtles!
What to Do
Helpful Hints
Use a for-loop to iterate through the steps you need to repeat. This includes
changing the color of the turtle, and stamping and moving the turtle a
certain amount.
What to Do
Using the circle() function and your knowledge of filling in shapes with
colors, draw one big circle, and fill it with a color. Then, draw a medium-
sized circle and fill it with a different color. At this point, make sure that
you can still see the medium-sized circle and that it’s contained within the
big circle. Finally, draw one smaller circle, fill it with a different color, and
make sure it is contained within the two larger circles.
Helpful Hints
Again, for-loops will be your best friend in creating this drawing, as a lot of
steps are repeated! First, keep track of each step you take to draw a circle
and fill it with color. Once you have found the repeated steps, try moving it
into a for-loop. Then, figure out which parts you need to change to create
different-sized circles and change colors.
Activity 15: Tooga’s House
Now that we know how to use the turtle module’s built-in functions, let’s
create a proper home for Tooga!
What to Do
Create a new turtle named Tooga and a new pen to build Tooga’s home:
tooga = turtle.Turtle()
pen = turtle.Turtle()
Using the penup() and pendown() functions, and the changing colors and
pen sizes, draw some shapes to create a house for Tooga. Make sure Tooga
is actually inside the house you created for him!
This can be a simple square around Tooga with a triangle above the square
to represent the roof. Get creative with the colors and pen sizes. Tooga
would surely appreciate a non-boring, colorful home!
Helpful Hints
Use the penup() and pendown() functions to lift and drop the pen when you
need to draw and not draw, respectively. This will make sure you don’t
draw on Tooga!
Variables in Python
· Declaring variables
· String operations
· Casting
Data Types and Variables
A variable is a programming construct that represents data, such as a
number or a word, that can be modified or used later. In math, you have
encountered variables in courses such as Algebra I, where x represents a
value and can be plugged into an algebraic equation. There are different
forms of data we encounter in the world, such as sentences composed of
multiple words; decimal numbers that represent temperature; whole
numbers that represent shirt sizes; and binary conditions, such as whether it
is day or night. All these scenarios contain different data types or
classifications of data.
Run the program (Run > Run Module), and notice how it prompts you to
enter input. Enter your name and press Return. Notice how the welcome
message is printed in the console.
This code uses the built-in Python input function to prompt the user to enter
a value. After they enter their name, this value is assumed in place of the
variable in the print statement on the following line. Without the use of
variables, we would not be able to take user input, because we would either
have to hard code a name in the print statement, or we would need to call
the input function inside the print statement, which would be messy.
Data Types
To represent the various types of data, it is important you fully understand
data types, which is the way data is classified in programming. Not all
objects are created equal. The classification of data types is like the
different states of matter: each has its own qualities and properties; e.g. a
liquid can change shape to fit the container it is in, but a solid retains the
same shape. Here are the main data types you should be aware of:
percentage_complete = 89.53
temperature = 72.0 # still considered a float since it is written with a
decimal
example = 657.3432445423
Variables in Python are dynamic, meaning they can change data types.
While this can be advantageous, some drawbacks could cause your
programs to perform an unintended action. For example, you may make a
variable an integer, but then try to print it to the screen as a string, thus
causing your program to crash. Dynamic typing in Python is very different
from other languages, such as Java, where you must set the type when
declaring the variable, in what is known as static typing, after which it
cannot be changed. For example, if you create an integer in Java called
‘score, ’and decide you want to make it into a float point value, you cannot
simply assign your old variable a decimal value. Instead, you must create an
entirely new variable to store this value.
Declaring Variables
Initializing a variable in Python is very simple; you choose the name of
your variable and assign it a value with an equal sign (=). Unlike other
languages, you do not need to declare the variable data type before the
name. See the structure below for the syntax.
You can give your variable any name, except you cannot use Python
reserved words such as in, as, and assert. It is important to name your
variable something relevant to the data it will contain so that your code is
more readable in the future. For multiword variable names, camel casing is
the standard naming convention in languages such as Java. However, in
Python, the convention is to separate words with an underscore. To be
aware of it for other programming languages, camel casing is a naming
convention for compound names, in which the first letter of the first word is
not capitalized, but the first letter of subsequent words are. For example,
userData or eventStartTime would both follow proper camel casing
conventions. For the variable naming convention in Python, see the
structure below:
String Operations
Strings can be manipulated using several Python functions available to us.
An important operation in programming is concatenation – the action of
combining strings. The plus sign (+) is used for concatenation, and you can
combine two or more strings. For example, the code below combines a
string and a string variable type, to print out a full statement.
The code above would output the following after concatenating the strings:
>>> The plane landed in Orange County after flying from New York
For example:
“Mikey” == “Mikey” # returns true since they #are exactly the same
company1 = “Acorns”
company2 = “SouthWEST”
print(company2.upper())# output - SOUTHWESTs
Casting
The subsequent table contains function calls to cast from one data type to
another. Each function takes a variable or data as input, what we call an
argument in Python (sometimes called parameters in other languages). Note
that the argument you would like to cast must contain the appropriate value
or you will receive a value error. For example, the string (73) can be cast to
an integer (73) or a float (73.0), but the string ($) cannot be cast to either of
these types, due to the value of the string. The ($) symbol cannot be
quantified as an integer or float.
Function Description
The code below is an example of how values would change when casted:
What to Do
“These are the words you are repeating a.k.a. quoting.”—Person Who Said
This
What to Do
Find a quote online or use one of your own. It can be about something that
inspires you, a funny line from a movie, or even something a family
member said. Use the print() function to write a proper quote (as shown) in
the console window. Remember to print out characters like double quotes;
you need to properly them with the backslash (\) character (see here for the
lesson that will help you do this).
What to Do
Create a list named ‘my_favorite_things ’and add five things to it. Print out
a message that says “These are {your name}’s favorite things: [‘your’,
‘favorite’, ‘things’]. Use an f-string to print out this message with your
name and your list of favorite things!
'Running', 33.3].'
Activity 19: Shapeshifters
One day, you and your friend decide to go to the park and watch the clouds.
You want to keep track of the different clouds you see and what shapes they
look like to both of you, so you each create empty lists (in brackets [])
before you begin: your_cloud_shapes = []
friend_cloud_shapes = []
While watching, you continue to add the shapes of clouds you see to your
lists. Once you go home, you take a look at each other’s lists:
your_cloud_shapes = ['circle', 'turtle', 'dolphin', 'truck', 'apple', 'spoon']
Interesting! Both of you mostly have the same shapes, but probably saw
them at different times!
What to Do
Using if statements, the == operator, and indices, write some code to check
if your cloud shape matches your friend’s cloud shape at the same position
in each of your lists. You can do this by comparing your object with your
friend’s object at each index. If your shapes match at the same position,
print out “We saw the same shape!” If they don’t match, print out “We saw
different shapes this time.” Go one by one, and compare each item on your
lists.
Helpful Hints
Remember, you can access specific items in lists by using the indices!
Example: your_list[2]
Activity 20: Random Factory
What to Do
Example
Marie is playing ping-pong with her friends. Another friend, Pierre, says
that ping-pong is called something different in his country. Can you form
the other name for ping-pong using the random_items list?
print(f"{random_items[3]} {random_items[1]}")
Example Output
table tennis
Scenario 1
Andre is about to play tennis with some friends. He has his tennis racket,
but he needs one more thing. Write a code to print out what he needs!
Scenario 2
Jean just baked some fresh bread. He wants to bring a few loaves home to
share. What can you make from the random_items list that can help him
carry his bread home?
Scenario 3
Scenario 4
Leslie is writing a story about her favorite sport. It involves a hoop, five
players on each team, and a recognizable orange ball with black stripes.
Which sport is it?
Scenario 5
Julia just received one of the fresh loaves of bread from Jean. Thanking
him, she quickly puts the loaf she received in this item to keep it warm.
Scenario 6
Mario has a lot of board games and video games. Luckily, he can store most
of them in this item to keep his room nice and clean!
CHAPTER 5:
· Guessing games
Activity 21: Rock Paper Scissors
The first game will be ‘Rock, Paper, Scissors, ’which is normally played by
two people. But in this case, it is going to be you against the computer. The
first thing we need to do when creating a game is to brainstorm. Using a
pen and paper, think about how the game should be designed. Start by first
considering the rules of the game, and only then worry about the
programming side.
This classic game involves choosing one of three objects, as the name
suggests. Once both selections are made, the items are revealed to see who
wins. The player who wins is determined by three simple rules: the rock
will crush the scissors, while the scissors cut the paper, and the paper covers
the rock.
To handle these rules, we are going to create a list of choices, similar to the
list of colors we created before in some of our drawing programs. Then, we
will add a random selection function that will represent the choice the
computer makes. Next, the human player will have to make his or her
choice. Finally, the winner is decided with the help of several if statements.
Have you tried to create your version of the game yet? If so, good job! Even
if you did not finish it, or you wrote the game and are getting some errors,
you should still reward yourself for trying. Now, let us go through the code
and see how this game should turn out:
import random
player = player.lower ()
computer = random.choice(selectionChoices)
if player == computer:
print("Draw!")
if computer == "scissors":
print ("Victory!")
else:
print("You lose!")
if computer == "rock":
print("Victory!")
else:
print("You lose!")
if computer == "paper":
print
("Victory!")
else:
print("You lose!")
else:
print()
The next step is to ask the computer to select one of the three game objects.
This choice is done randomly, and the selected item is stored inside a
variable called the computer. After the choice is memorized, the testing
phase begins to see which player will win. First, a check is performed to see
whether the two players have chosen the same item. If they did, then the
result is a draw, and nobody wins. Next, the program verifies whether the
player chose ‘rock, ’and then it looks at the computer to see if it chose
‘scissors. ’If this is the case, then the rule is ‘rock beats scissors, ’so the
player wins. If the computer neither selected a ‘rock ’nor ‘scissors, ’then it
certainly chose ‘paper. ’In this case, the computer will win. Next, we have
two elif statements, by which we perform two more tests that check whether
the player selected ‘paper ’or ‘scissors. ’Here we also have a statement that
checks to see if the player chose something that is not one of the three
possible items. If that is the case, an error message is sent, that tells the
player he either chose something that he is not allowed to, or he mistyped
the command.
Lastly, the user is prompted to type the next selection. This is where the
main loop goes back to the beginning. In other words, the game starts
another round of Rock, Paper, Scissors.
This game is simple, but it is fun because anyone can win. The computer
has a chance of beating you, and there is also a real chance of ending up in
a draw. Now that you understand how to create a random chance game, let
us look at other examples to add to our game library while also learning
Python programming
Activity 22: Guessing Game
import random
Python will now automatically generate a random figure between 1 and 20.
Keep in mind that the minimum and maximum values are included in the
number generation. Therefore, Python can also generate numbers 1 or 20.
You can test this command as many times as you want, to make sure that
you are truly getting random values. If you execute it often enough, you
will see that some values will repeat themselves. If the range is large
enough you might not even encounter certain numbers, no matter how
many times you run the code.
What is interesting about this function though, is that it is not truly random.
This is just a side note that will not affect your program, but it is intriguing,
nonetheless. The randint function follows a specific pattern and the chosen
numbers only appear to be random, but they are not. Python follows a
complex algorithm for this pattern instead, and therefore we experience the
illusion of randomness. With that being said, let us get back to fun and
games. Let us create our game with the following code:
import random
if myGuess>randomNumbers:
if myGuess<randomNumbers:
That is it! Hopefully, you tried to create this game on your own because you
already have the tools for the job. Remember that programming is only easy
as long as you practice it enough on your own. Just take it one step at a
time. With that being said, let us discuss the code, in case you need some
help figuring the game out.
Just like before, we first need to import the random module so that we can
use the random number generating function. Next, we use the randint
function with two parameters. As mentioned before, these parameters are
the lowest number we can guess, which is 1, and the highest number we can
guess, which is 100. The random number generator will generate a number
within this range. Once the number is generated, it is stored inside the
randomNumbers variable we declared. This number will not be known by
the player, because he or she needs to guess it. That is the point of the game.
Next up, the player needs to guess the hidden number. This guess will then
be stored inside a new variable called myGuess. To check whether the guess
is equal to the number, we are using a while-loop with the not equal to
operator. We do this because if the player gets lucky and guesses the
number correctly on the first attempt, the loop simply does not finish
executing because there is no need.
Next, if the player guesses the wrong number, we have two if statements
that check whether the guess is a higher value than the hidden number, or a
lower one. An appropriate message is then printed for the player in each
case. In either scenario, the player receives another chance to make the right
guess. Finally, in the end, if the user guessed the number correctly, the
program declares victory for the user by printing a message, and then the
program stops running
Activity 23: Drawing Game Boards
What to do
Create a file called ‘game-board ’and save it. Then, define two functions:
one to print some horizontal lines and one to print some vertical lines: def
print_horizontal_line():
Def print_vertical_line():
Next, use the print() function to print out the lines: def
print_horizontal_line():
Def print_vertical_line():
Print("| _ ")
Next, we need to ask the player what size game board they need. We should
capture their input in a variable: board_size = int(input("what size game
board do you need?"))
Finally, create a for-loop that iterates as many times as the board size
requested by the player, and print the lines using your defined print line
functions!
Now, to correctly print the game board, we need to change our print line
functions a bit. For the print_horizontal_line() function, how would you
change it to print as many lines as the requested game board size? (hint:
remember that weird operator that we can use to “multiply” strings?
Hmm...) Def print_horizontal_line():
For the print_vertical_line() function, you’ll need to print out as many lines
as the requested board size, plus one.
Def print_vertical_line():
Finally, print one last horizontal line to finish your board after your for
loop: print(" --- " * board_size)
That’s it! When you save and run your file, it will ask you what size board
you need. Give it a number, and it will print out a board for you, making the
board the number of squares in height and width. As you can see here, the
number 3 gave us a board three squares wide and three squares high!
Activity 24: If This, Then That
As we grow older, who we are, what we look like, and what we are
interested in will probably change. Let’s capture that in an if statement and
print out what we think we will be like in the next 5, 10, 15, and 20 years.
What to Do
Write an if statement that checks for the year, and then output the different
predictions you have about yourself for that year! As you can see, I’ve
helped you get started. Write the remaining elif statements, and make sure
to update your variables properly for each year.
Let’s capture three things to output with some variables. Create age,
favorite_outfit, and favorite_hobby variables, and assign each of them to
what they are today.
year == 2019
age = 10
favorite_hobby = "coding"
Next, start your if statement and check for the current year: if year == 2019:
if year == 2019:
Now, create four more elif statements for 5, 10, 15, and 20 years from now.
Adjust your variables, too!
Activity 25: Slicing And Dicing
This activity is about a boy named Tony. He has crates of fruits and
vegetables coming in and needs someone to sort them. If the crate has
vegetables, they need to be taken out and moved to the “dicing” area, so his
helpers can begin dicing them for the restaurant. If you find fruits though,
they need to be brought to the “slicing” area, so his bakers can prepare the
fruits for their desserts.
What to Do
Using slice ranges and the different methods we’ve learned to add items to
a list, write some code for each crate to properly separate the fruits and
vegetables, and add them to the right area.
slicing_area = []
dicing_area = []
Once you’ve gone through all of the crates, print out all of the separated
fruits and vegetables.
For each collection of items, create either a tuple or list, and store those
items within it. Then, print out the contents of the list and which type it is
stored in.
Collection 1:
# Adventure begins.
print("You find yourself in a dark room with 2 doors. The first door is red,
the second is white!")
if door_choice == "red":
print("Great, you walk through the red door and are now in the future! You
meet a scientist who gives you the mission of helping him save the world!")
if choice_one=="1":
print("""___________SUCCESS____________
You helped the scientist save the world! In gratitude, the scientist builds a
time machine and sends you home!""")
else:
print("""___________GAME OVER_______________
Too bad! You declined the scientist's offer and now you are stuck in the
future!""")
else:
print("Great, you walked through the white door and now you are in the
past! You meet a princess who asks you to go on a quest.")
quest_choice = input("Do you want to accept her offer and go on the quest,
or do you want to stay where you are? 1=Accept and go on quest or
2=Stay")
if quest_choice=="1":
print("The princess thanks you for accepting her offer. You begin the
quest.")
else:
print("""___________GAME OVER____________
Use what you’ve learnt about if statements, along with your knowledge of
variables, the print() function, and several data types to continue this story.
Change the outcomes, have more than one decision to make or set your
story in a different setting. It’s up to you! Once you are finished, save your
game and then run it. You or a friend can now choose your adventure, and it
will be the game you created!
CHAPTER 6:
· Return statement
· Multiple parameters
· Lambada function
We began with almost no prior knowledge about Python, except for the fact
that it was a programming language that is in great demand these days.
Now, look at you: creating simple programs, executing codes, and fixing
small-scale problems on your own. Not bad at all! However, learning
always comes to a point where things can get rather tricky.
In quite a similar fashion, functions are docile-looking things; you call them
when you need to get something done. But did you know that these
functions have so much going on at the back? Imagine every function as a
mini-program. It is also written by programmers like us to carry out specific
things, without having us write lines and lines of codes. You only do it
once, save it as a function, and then just call the function where it is
applicable or needed.
The time has come for us to dive into a complex world of functions, where
we do not just learn how to use them effectively, but we also look into what
goes on behind these functions, and how we can come up with our very
own personalized function. This will be slightly challenging, but I promise
you, there are more references that you will enjoy, to keep the momentum
going.
How To Define And Call Function?
To start, we need to take a look at how we can define our own functions in
this language. The function in Python is going to be defined when we use
the def statement, and then follow it up with a function name and
parentheses in place as well. This lets the compiler know that you are
defining a function, and the specific function you would like to define at
this time as well. There are going to be a few rules in place when it comes
to defining one of these functions though, and it is important to do these
properly, to ensure your code acts in the way that you would like. Some of
the Python rules that we need to follow for defining these functions will
include the below rules:
3. The code found within all functions we are working with needs
to start with a colon, and needs to be indented as well.
You will find that Python is going to follow a particular style when it comes
to indentation, to help define the code, because the functions in this
language are not going to have any explicit beginning or end, like the curly
braces in other languages that help indicate the start and the stop for that
function. This is why we are going to rely on indentation instead. When we
work with proper indentation here, we can really see some good results and
ensure that the compiler is going to know when the function is being used.
Understanding Functions Better
Functions are like containers that store lines and lines of codes within
themselves, just like a variable that contains one specific value. There are
two types of functions we get to deal with in Python. The first ones are
built-in or predefined, while the others are custom-made or user-created
functions.
Either way, each function has a specific task that it can perform. The code
that is written before creating any function is what gives that function an
identity and a task. Now, the function knows what it needs to do whenever
it is called in.
When we began our journey, we wrote ‘I made it! ’on the console as our
first program, right? We used our first function there as well: the print()
function. Functions are generally identified by parentheses that follow the
name of the function. Within these parentheses, we pass arguments called
parameters. Some functions accept a certain kind of parenthesis while
others accept different ones.
Let us look a little deeper and see how functions greatly help us reduce our
work, and help better organize our codes. Imagine we have a program that
runs during the live streaming of an event. The purpose of the program is to
provide our users with a customized greeting. Imagine just how many times
you would need to write the same code if there were quite a few users who
decided to join your stream. Using functions, you can cut down on your
work easily.
def say_hi():
Here, say_hi is the name I have decided to go with; you can choose any that
you prefer. Remember, keep your name descriptive, so that it is
understandable and easy to read for anyone. After you have named your
function, follow it up with parentheses. Lastly, add a colon to let Python
know we are about to add a block of code. Press Enter to start a new
indented line.
Now, we shall print out two statements for every user who will join the
stream.
print("Hello there!")
After this, give two lines of space to take away those wiggly lines that
appear the minute you start typing something else. Now, to have this printed
out easily, just call the function by typing its name, and then run the
program. In our case, it would be:
· say_hi()
· Hello there!
See how easy this can make our work in the future? We do not have to
repeat our codes over and over again. Let us make this function a little more
interesting by giving it a parameter. Right at the top line, where it says def
say_hi(), let us add a parameter. Type in the word name as a parameter
within the parenthesis. Now, the word should be greyed out to confirm that
Python has understood the same as a parameter.
Now, you can use this to your advantage and further personalize the
greetings to something like this:
If you are doing it on Shell, you need to delete the previously defined
function with
Del sayhi
def say_hi(user):
say_hi(user)
The output would now ask the user their name. This will then be stored in a
variable called ‘user. ’Since this is a string value, say_hi() should be able to
accept this easily. Bypassing the user as an argument, we get it as an output:
Now that is more like it! Personalized to perfection. We can add as many
lines as we want, the function will continue to update itself, and provide
greetings to various users with different names.
There may be times where you may need more than just the user’s first
name. You might want to inquire about the last name of the user as well. To
add that, add it to the first line and follow the same process accordingly:
say_hi(first_name, last_name)
Now, the program will begin by asking the user for their first name,
followed by the last name. Once that is sorted, the program will provide a
personalized greeting with both the first and last names.
However, these are positional arguments, meaning that each value you input
is in order. If you were to change the positions of the first and surnames in
‘John Doe,‘ ’Doe ’will become the first name and ‘John ’will become the
last name. You might want to be a little careful about that.
Hopefully, now you have a good idea of what functions are, and how you
can access and create them. Now, we will jump towards a more complex
front of return statements.
Wait! There is more! Well, I could have explained it; however, you may not
have understood it completely. Since we have covered all the bases, it is
appropriate enough for us to see exactly what these are, and how these gel
along with functions.
Quiz
1. Which function will print an output to the screen?
echo
eval
def x:
pass
def a (b, c, d)
pass
a = [1,2,3,None,(),[],]
print len(a)
5. State the value of the item with index 1 from the following list:
orange
violet
6. Is the statement “There are only two value types in Python, strings,
and numbers” correct?
True
False
333
Type Error
“abc”
abc
Error
True
False
0.6
0
None
Activity 28: Super Function!
What to Do
What to Do
When you have friends around the world, keeping track of the right times to
call them can get a little tricky. Depending on where they are, they can be
hours ahead of or behind you! To help coordinate, let’s write a function that
helps us figure out what time it is in our friends ’cities.
What to Do
Using the datetime() and timedelta() functions from the Datetime module
(see here) and some math, write a function that prints out the current time in
your home city and the following three cities:
Berlin, Germany
Tokyo, Japan
First, be sure to import the following functions so you can use them: from
datetime, import datetime; from datetime, import timedelta
Next, create a function called world_times(). I’ve already started the
function for you, so just fill in the blanks to calculate the other cities ’times
and then print out the final string!
def world_times():
my_city = datetime.now()
To calculate the other cities ’times, you’ll probably need to add some hours
to the my_city variable. You can add hours to a variable by using the
timedelta() function. The timedelta() function gives us an easy way to
properly add units of time (like days, months, hours, minutes, etc.) to a date
or time.
In this activity, you’ll only need to add hours. You do this by adding a
datetime object to a specific amount of hours. So as an example, if you
wanted to add 9 hours to the current time and then assign this result to a
variable called nine_hours_from_now, you’d do the following:
nine_hours_from_now = datetime.now() + timedelta(hours=9)
>>> Helpful Hint: You can use the Internet to find the time differences
between your home city and the three cities mentioned. Once you figure out
those numbers, use them in your function’s calculations!
>>> Helpful Hint: Don’t change the f-string I’ve provided! The resulting
times you calculate should print out to a nice, readable format.
>>> world_times()
That means it's 04:37 in Berlin, 10:37 in Baguio City, and 11:37 in Tokyo!
Activity 31: Factorial Function
One of the most common functions every coder has to write is called a
factorial function. It’s a function that calculates the factorial of the number
you pass into it. And yes, it sounds like something to do with
multiplication, because it is! In math, a factorial is the product of a number
and all the numbers that come before it. So, if I asked you to calculate the
factorial of the number 4, you would have to multiply 4 by, 3, 2, and 1. The
factorial of 4 is 24.
What to Do
Write a function called factorial() that takes one parameter. This parameter
will be a number. Then, write the code to calculate the factorial of the
number that is passed in as a parameter. Have your factorial() function
return the answer!
24
Activity 32: Math Codes
You can get in a bit of mathematics practice while playing these coding
games, as well. This can be either as part of a treasure hunt or can just be
written down on paper for the fun of solving them. You can add in an extra
challenge by saying, “How many can you solve in three/five/ten minutes?”,
and setting a timer.
For example, using the numbers instead of letters code, where A = 1 and B
= 2, etc., you can leave spaces or draw a line for each letter, and underneath
it, write a math’s sum. The child works out the sum, which gives them a
number, which they then have to translate into a letter.
Dolores and Maeve are having a party together and are setting up the
dessert tables. Dolores likes cupcakes and Maeve loves cookies!
Unfortunately, when they go to the kitchen, all of their boxes have been
mixed up! Each dessert is in a special box, but all the boxes look the same!
Dolores and Maeve don’t fret, though. They know that they can tell which
dessert is which, because the cookies are in a box with a 3 on them, and the
cupcakes are in a box with a 5. Let’s write a function to help them organize
their desserts!
What to do
Write a function called dessert_sorter() that takes one parameter. Call the
parameter total_desserts. Then, write some code that will help Dolores and
Maeve separate the cupcakes from the cookies. This should be a for-loop
that goes through the total_desserts and checks for these things:
•If it’s a number that’s divisible by 3, print out the word “cupcake.”
•If it’s a number that’s divisible by 5, print out the word “cookie.”
•If it’s a number that’s divisible by both 3 and 5, print out “it’s a
cupcakecookie!”
When you’re done creating your dessert_sorter() function, pass 200 as the
total_desserts parameter, because that’s how many boxes Dolores and
Maeve have to sort!
>>> dessert_sorter(15)
Cupcake
Cookie
Cupcake
Cupcake
Cookie
Cupcake
It's a cupcakecookie!
Rock, paper, scissors, go! This game is a very popular game to play with
friends. For as many turns as you like. You and a friend can choose between
Rock, Paper, or Scissors and see who wins between the two of you. Let’s
create this game in Python, where you can battle friends on the computer!
What to Do
Next, define a function called compare() and have it accept two parameters.
This function will compare the players ’choices (which are the two
parameters it accepts) and will tell us who won, based on the rules of Rock,
Paper, Scissors: def compare(item_1, item_2):
Be sure to add one last elif statement to deal with any choice that is not
Rock, Paper, or Scissors. It would be a good idea to also tell the players that
they have entered a choice that is not possible if they do this.
Now that we have a compare() function that can check the combinations for
us, the last part is to capture the choices our players make! Create two
variables to store the player’s choices: player_1_choice = <Write some code
here>
Lastly, use a print() function to print the results of the compare() function
when you pass the players ’choices into it!
print(compare(player_1_choice, player_2_choice))
That’s it! Save your file, then press F5 to run it so you can play Rock,
Paper, Scissors with a friend! Take turns entering your choices, and see
who’s won!
CHAPTER 7 ✮ CHALLENGES
Using everything you have learnt, try finishing this Hangman game. I have
provided the structure for a Hangman game below for you to use. However,
it’s up to you to fill in the blanks! Once you have filled in all of the missing
code, noted by the <Write some code here> placeholders, save your file. At
this point, you should be able to play hangman when you press F5 and run
your game!
What to Do
Create a new file called ‘hangman, ’and save it. Using the template below,
start writing the code into your hangman.py file. When you come to a
placeholder that says <Write some code here>, remove the placeholder
and replace it with the proper code. Use the comments to help you figure
out what kind of code to write.
import time
time.sleep(1)
print("Start guessing...")
time.sleep(0.5)
# Create a variable to store the maximum number of turns the game will
allow
<Write some code here>
# guesses we make
else:
print("_")
break
guesses += guess
# Create an if statement
# Also tell the player how many turns they have left
Let’s race some Toogas! We’ll create a race track and some colorful turtles,
and then send them off! Play with your friends by choosing a turtle at the
beginning of the race and seeing if it finishes first!
What to Do
Create a new file called ‘turtle-race-game, ’and save it. Then, begin coding
your turtle race game!
First, import the turtle and random modules like this: from turtle import *
speed()
penup()
goto(-140, 140)
# Use the write() function to write the number of your for loop iterator.
# Set the align parameter to 'center'. These will be your steps or distances
# in the race!
<Write some code here>
right(90)
# Now, begin creating turtles! I'll create four, but feel free to create more
# Create a turtle
# Create a for loop that iterates from zero to a number you choose
# Create three (or more!) turtles with different names and colors
# Make sure each turtle repeats all of the steps and code we wrote
That’s it! Save your game, pick a turtle, and press F5 to run your game.
You’ll get to watch your race track be drawn, and all of your turtles race!
Conclusion
T
his brings us to the end of this guide. I hope that you enjoyed
learning more about the world of programming, and how
powerful and versatile it can be. Programming has become one of
the most valuable skills you can acquire today, not only in your
professional life but in your personal life as well. I cannot count how many
times I have written a small script to help me with my daily tasks. It is
something you can use for the rest of your life.
I hope that you were able to grasp the core gaming concepts, as well as the
fundamental programming techniques. Note that the lessons you learnt do
not only apply while programming games. They can also be used for
creating apps and other types of programs as well.
Thus far, you have only gone through most of the basics—yes most of
them. There are a few more ideas that we could have covered like file
processing, dictionaries, tuples, but they are for another time.
There is still a ton of stuff to know about programming in Python. But you
have at least completed all the fun stuff. From here you can learn more
advanced topics of Python programming, such as graphics and sound,
which should be fun as well.
You might ask what is next. By now you probably have an idea of which
programming language you prefer. You really cannot go wrong with any of
these languages. However, if you are still undecided, I suggest just trying
one out. If you do not like it, you can simply move on to the next one.
Here are countless reasons you might want to learn Python programming.
The age we are in is evolving at a breath-taking pace. In the near future,
there will be a high demand for programmers. Now is the best time to brace
yourself.
Although there are other popular computing tools used for data analysis,
Python is the only reliable programming language intended for general use.
Learning the actions of various Python libraries mentioned in this e-book
will help aspirants to specialize in data manipulation.
I hope that the lessons that you learned here have inspired you to learn more
about Python programming.
Glossary
W
hen learning a programming language, or just programming
in general, you cannot help but come across many terms that
you do not understand. A lot of these terms are not used in
our daily vocabulary, or they have a completely different
meaning in the world of programming. Therefore, in this glossary, you will
find the most important terms that are used throughout this book.
Algorithm
Append
Argument
Boolean
Concatenate
Conditional expression
A statement that gives the program its ability to check a certain value, and
then perform a set of actions based on it.
Expression
For-loop
Function
Import
Index
Initialize
Assigning the first value to a variable, or any other item, in other words,
giving it its initial value.
Input
It is the act of entering data into a program or a system. An input can come
from a keyboard, mouse, or any other device that can record information.
These devices are also called input devices.
List
Module
A type of file that contains various functions, classes, and variables that can
be used in any program once imported.
Parameter
Range
Shell
String
Syntax
Variable
A value with a name, which can always change inside the program.
While loop
A statement that repeats a collection of instructions while a certain
condition is true.
Answer Key
Chapter 3: Making Choices and Decisions
1. Repetition of certain steps.
3. True
4. ==
5. Yes
6. For-loop
7. Boolean
8. :
9. False
10. >=
Chapter 7: Working with Python Functions
1. print
2. <type 'NoneType'>
5. Orange
6. True
7. Type Error
8. Error/Name Error
9. False
10. 0
[1]
Review if correct.