Coding For Kids Python A Playful Way For - Mark B Bennet
Coding For Kids Python A Playful Way For - Mark B Bennet
A Playful Way Of Programming, Coding, And Doing Projects With Your Kids.
Learn Computer Science Quickly While Stimulating Your Kids’ Creativity.
Mark B. Bennet
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.
Table of Contents
NOTE TO PARENTS
INTRODUCTION
WELCOME TO PYTHON
WHY LEARN TO CODE?
WHY PYTHON?
WHAT IS IN THIS BOOK?
CHAPTER 1: LEARNING TO PROGRAM
WHAT YOU WILL LEARN
PYTHON BASIC (GET TO KNOW YOUR ENVIRONMENT)
INSTALLING PYTHON (WINDOWS - MAC - UBUNTU)
ONCE YOU HAVE INSTALLED PYTHON
SAVING YOUR PROGRAM
USING IDLE (GUIDE A TO Z)
ACTIVITY 1: ROCK PAPER SCISSORS
ACTIVITY 2: GUESS!
ACTIVITY 3: CHOOSE A CARD
ACTIVITY 4: RANDOM NUMBER GENERATORS: MIMIC A COIN FLIP
ACTIVITY 5: COIN FLIP GAME ALGORITHM
CHAPTER 2: MAKING CHOICES AND DECISIONS
WHAT YOU WILL LEARN
IF-ELSE STATEMENT
INDENTATION
IF-ELIF STATEMENT
FOR-IN LOOPS
WHILE LOOPS
CONTINUE
BREAK STATEMENT
INPUT TEXTS (1)
INPUT TEXTS (2)
PASS STATEMENT
EXERCISE: TRAFFIC LIGHT
SUMMARY
QUIZ
ACTIVITY 6: THERE ’ S A LOOP FOR THAT!
ACTIVITY 7: LOOP DE LOOP, WHICH HULA HOOP LOOP?
ACTIVITY 8: IFFY LEGS
ACTIVITY 9: PASSWORD-PROTECTED SECRET MESSAGE
ACTIVITY 10: GUESS-THE-NUMBER GAME
CHAPTER 3: TURTLE GRAPHICS
WHAT YOU WILL LEARN
BRINGING UP THE SCREEN
TURTLE SETUP
DRAWING A RECTANGLE
CIRCLE
STARS
ACTIVITY 11: LET ’ S DRAW A STAR!
ACTIVITY 12: FORTUNE-TELLER
ACTIVITY 13: RAINBOW TURTLES!
ACTIVITY 14: CIRCLECEPTION
ACTIVITY 15: TOOGA ’ S HOUSE
CHAPTER 4: VARIABLES IN PYTHON
WHAT YOU WILL LEARN
DATA TYPES AND VARIABLES
ACTIVITY 16: INTRODUCE YOURSELF
ACTIVITY 17: TO QUOTE A QUOTE
ACTIVITY 18: THESE ARE A FEW OF MY FAVORITE THINGS
ACTIVITY 19: SHAPESHIFTERS
ACTIVITY 20: RANDOM FACTORY
CHAPTER 5: LEARNING GAMES IN PYTHON
WHAT YOU WILL LEARN
ACTIVITY 21: ROCK PAPER SCISSORS
ACTIVITY 22: GUESSING GAME
ACTIVITY 23: DRAWING GAME BOARDS
ACTIVITY 24: IF THIS, THEN THAT
ACTIVITY 25: SLICING AND DICING
ACTIVITY 26: TO CHANGE OR NOT TO CHANGE
ACTIVITY 27: CHOOSE YOUR ADVENTURE
CHAPTER 6: WORKING WITH PYTHON FUNCTIONS
WHAT YOU WILL LEARN
HOW TO DEFINE AND CALL FUNCTION?
UNDERSTANDING FUNCTIONS BETTER
QUIZ
ACTIVITY 28: SUPER FUNCTION!
ACTIVITY 29: FUNNY FUNCTIONS
ACTIVITY 30: WHAT TIME IS IT OVER THERE?
ACTIVITY 31: FACTORIAL FUNCTION
ACTIVITY 32: MATH CODES
ACTIVITY 33: CUPCAKECOOKIE
CONCLUSION
GLOSSARY
ANSWER KEY
CHAPTER 3: MAKING CHOICES AND DECISIONS
CHAPTER 7: WORKING WITH PYTHON FUNCTIONS
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 Python?
Just like humans can understand many different languages, a computer can
understand the ideas and concepts that we put in through several different
programming languages. In this book, we will focus on the Python
programming language, because Python is easy to understand, can be used
in many different ways, and can be learnt quickly. Also, it is a popular
language that runs on almost every machine and is used at many influential,
important organizations like Google, Instagram, NASA, and Spotify.
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.
3. Through the magic of coding, 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. In our case, we
wanted Python 3.7.0 which was the latest version as at the time this
book was written. Do not worry if it tells you to download a newer
version. Go ahead and click the Download button.
8. Click Install Now . Python should start installing. You should see a
window like this one:
9. Wait for the installation to finish and the green bar to be complete.
Once it is done, the final screen should appear, saying that your
installation was successful.
10. You are done! Click the Close button and you are ready to go. You
have installed Python on Windows!
O N 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.
12. Congratulate yourself! You have just installed Python on your Mac!
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.
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.
2. Click New File .
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.
ON A PC
1. Click the Windows Start menu.
- The above images are being used in another book named [1]
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:
O N 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.”)
while player != “ quit ”:
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
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.
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.
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.
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.
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:
>>> 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.”
You can ’ t use the choice( ) function without importing the random module
first. That is why you start with an import statement first and then use the
choice( ) function.
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
- The above graphics are too basic. We’d like to have something more
elaborate. [2]
a = 200
b = 100
if a > 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:
If-elif Statement
if test-expression:
statements # run when this text-expression is
true
elif test-expression:
statements # run when this text-expression is
true
else:
statements # run when all text-expressions are
false
Example
Num = 200
else:
Output:
Explanation
For-In Loops
The for-in loop repeats a given block of code a specified number of times.
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.
(1)
Example
print (var)
Output: 0,1,2,3,4,5.
(2)
print (num)
Output: 3,4,5,6,7,8,9.
Explanation
While Loops
While loops are used repeatedly to execute blocks of code.
while <test-expression> :
<statement>
<test-expression> looks like a < 100, b! = 200. c==d [4] , etc.
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.
Continue
continue
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).
variable = input(“prompt”)
Note : Please use double quotation marks to enclose your input (in some
Python versions).
Example
Output:
Please input your name: “Jack”
Jack
16
Explanation
The input( ) function can accept the data from the user ’ s keyboard input.
variable = raw_input(“prompt”)
Example
Output:
Jack
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:
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, break, is used to stop the running of a loop according to the
condition.
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
3. Is the following statement true? A while loop will iterate until told
otherwise.
True
False
!=
==
Yes
No
Indentation
For-loop
While-loop
Integer
Boolean
Float
;
:
True
False
>>
=>
>=
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.")
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.
Expected Result
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.
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!
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.
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
You can change the color by typing in any color you want.
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
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
>>>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().
“ fastest ”: 0
“ 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.
Speeds ranging from 1 to 10 makes the pen become increasingly fast, with
10 being the fastest.
A speed of 0 means the turtle will instantly do what you ask; thus, you will
not see the turtle drawing a square; you will just see the square on your
turtle screen. [9]
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)
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.
Circle
To draw a circle, you use the function turtle.circle (). In the parenthesis, you
input the radius of the circle you want to draw.
Example
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
>>> t.circle(50)
Stars
Remember the loop we used for drawing 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)
t.forward(100)
t.left(125)
>>> t= turtle
>>> t.speed(8)
>>> t.width(3)
>>> for i in range(1, 9):
t.forward(100)
t.left(145)
You can just keep changing the size of the angles and the distance the turtle
will travel each time.
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?
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()
pen.ht()
Finally, pass your spin_amount variable to your pointer ’ s left() or right()
function to make it spin a certain direction.
Save your file. Now, every time you run your fortune-teller program, you
will get a random answer to your questions!
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.
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
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
example = 657.3432445423
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
A common practice while programming is to check two strings to see if
they are equal. We check for string equality using two equals signs, which
will return a Boolean value depending on if the compared strings are
exactly the same. The comparison is case-sensitive, and spaces count.
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 encapsulate [11] 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].'
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]
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
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!")
elif player == "rock":
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()
First, we import the random package, which allows us to use some
functions that we are going to take advantage of when 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. When that happens the game is over. Our loop
makes sure that if the player does not select the quit option, the game will
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 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. [12]
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:
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. [13]
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():
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():
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!
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:
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.
3. The code found within all functions we are working with needs to
start with a colon, and needs to be indented as well.
4. The return statement that we get, or the expression, will need to exit
a function at this time. We can then have the option of passing back
a value to the caller. A return statement, that does not have an
argument with it, is going to give us the same return as none.
Before we get too familiar with some of the work that can be done with
these Python functions, we need to take some time to understand the rules
of indentation, when we are declaring these functions in Python. The same
kinds of rules will be applicable to some of the other elements of Python as
well, such as declaring conditions, variables, and loops, so learning how
this works can be important here.
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.
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
print
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:
red
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
None
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
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!
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!
>>> factorial(4)
24
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.
An example of I LOVE YOU would be
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:
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
Now, create two variables that will store the names of each player
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
CHALLENGE 1: HANGMAN GAME
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 called secret_word to store the word to be guessed
# Create a variable to store the maximum number of turns the game will
allow
# 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!
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
# Turn your first turtle to the right by a number of degrees 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.
Programming also enhances logical reasoning skills, because, for even the
simplest programming task, the use of logic is essential. Furthermore, this
logical way of thinking is good for developing children ’ s math and science
skills. Programming and the use of computers is also a science in itself.
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
Passing a value to a function. Sometimes called a parameter.
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
Loop
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
A character sequence that can form words or sentences. They include
letters, symbols, numbers, as well as spaces.
Syntax
Variable
A value with a name, which can always change inside the program.
While loop
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'>
4. 6
5. Orange
6. True
7. Type Error
8. Error/Name Error
9. False
10. 0
[1]
I removed those that can be removed.
-- The latest Python version is 3.8.5. I only found 3.7 as the latest version
from the Amazon books.
I made a few adjustments on the images so it won’t look too ‘copied’ from
another book
[2]
I couldn’t find better images like the client wants ☹
[3]
Review.
[4]
Review if correct.
[5]
Incomplete. Review.
[6]
Incomplete, review.
[7]
See if this is meant to be double with a . & space in between.
[8]
Review and see if this needs to mimiced whereever ‘Turtle’ is mentioned.
[9]
These seem like contradictory statements.
[10]
Review.
[11]
Review if choice of word is correct.
[12]
This is the repeated Activity 1. not removed in the clean version.
[13]
Save for the final paragraph in Activity 2, the rest is all copied. Not omitted
in clean version.
[14]
Review and capitalize as appropriate.