Coding For Parents Frazer Wilson download
Coding For Parents Frazer Wilson download
https://ebookbell.com/product/coding-for-parents-frazer-
wilson-30097868
https://ebookbell.com/product/courage-after-fire-for-parents-of-
service-members-strategies-for-coping-when-your-son-or-daughter-
returns-from-deployment-paula-domenici-46312988
https://ebookbell.com/product/getting-through-my-parents-divorce-a-
workbook-for-children-coping-with-divorce-parental-alienation-and-
loyalty-conflicts-andre-11336362
https://ebookbell.com/product/a-parents-guide-to-managing-childhood-
grief-100-activities-for-coping-comforting-overcoming-sadness-fear-
loss-katie-lear-46417396
https://ebookbell.com/product/a-parents-guide-to-managing-childhood-
grief-100-activities-for-coping-comforting-overcoming-sadness-fear-
loss-katie-lear-43764488
Dr Paulas Good Nutrition Guide For Babies Toddlers And Preschoolers
Answers To Parents Most Common Questions Plus Help For Coping With
Fussy Eaters Paula Elbirt
https://ebookbell.com/product/dr-paulas-good-nutrition-guide-for-
babies-toddlers-and-preschoolers-answers-to-parents-most-common-
questions-plus-help-for-coping-with-fussy-eaters-paula-elbirt-1382204
Coping With Parental Death Insights And Tips For Teenagers Michelle
Shreeve
https://ebookbell.com/product/coping-with-parental-death-insights-and-
tips-for-teenagers-michelle-shreeve-46360036
Coding For Beginners In Easy Steps Basic Programming For All Ages Mike
Mcgrath
https://ebookbell.com/product/coding-for-beginners-in-easy-steps-
basic-programming-for-all-ages-mike-mcgrath-46474102
https://ebookbell.com/product/coding-for-beginners-13th-papercut-
limited-47505760
https://ebookbell.com/product/coding-for-pediatrics-2022-a-manual-for-
pediatric-documentation-and-payment-twentyseventh-american-academy-of-
pediatrics-committee-on-coding-and-nomenclature-48844096
STERLING
N ew Y o rk
An Imprint of Sterling Publishing Co., Inc.
1166 Avenue of the Americas
New York, NY 10036
ISBN: 978-1-4549-2567-5
www.sterlingpublishing.com
CODING
FOR PARENTS
FRAZER W IL S O N
JuV-
v v #
S T E R L IN G
N e w Yo r k
FOREWORD
4 // F O R E W O R D
weren't afraid?" You would find the resources and guidance that you need
in order to provide your children the help that they need. And that’s where
Coding for Parents comes in handy!
Recognizing that you are playing two roles—a learner who may be new
to coding, and a guide who is seeking to assist your children—this book
presents you with clear examples, easy-to-understand images, and just the
right quantity of text to clarify each concept. You’ll find helpful guidance
that introduces you to coding in the same manner your children are
being introduced to it: building gently and progressively, from simple tile
languages like Scratch to web basics (including HTML and CSS), and finally
to web interactivity (JavaScript).
As with many activities in which we coach our children, we learn and
improve as we go. You are not expected to be an instant expert in coding,
and Coding for Parents understands and values your concerns. There
will be occasions when you'll need to work through a section, put the
book down and reflect on the ideas, then return to the material later.
That's OK! It won't happen too often, but know that this is normal when
working to develop a completely new skill set. I encounter this situation
often, and when I do, I share my concerns with my own children. The soft
skills of remaining optimistic, pushing through challenges, and consulting
resources (people, books, and other tools) are equally important messages
to your kids as elevating coding skills. Ultimately, you and your kids will
benefit from Coding for Parents, setting the stage for success in future
technological forays we have yet to dream up!
F O R E W O R D // 5
CONTENTS
IN T R O D U C T IO N / / 8
The introductory section explains what coding is, as well as common uses,
common misconceptions, what you will need to get started, and a simple
guide to this book.
CHAPTER 1: C O D IN G CONCEPTS / / 18
Key concepts of coding are based on logic and common sense. This
chapter will teach you how to think in a new way—and you won't even need
a computer!
CHAPTER 2: W H A T IS SCRATCH? / / 56
Scratch is a great program for beginner coders. Learn to use it to write
simple code blocks in a visual format and create dynamic animations.
Includes several sample projects.
6 // C O N T E N T S
#
CHAPTER 4: W H A T IS JAVASCRIPT? / / 136
JavaScript is a programming language used to make web pages interactive.
Learn the key elements of JavaScript, and work on sample projects for
coding interactive web pages.
FURTHER LE A R N IN G / / 188
A closing section discusses areas of further study, from programming
languages not covered in this book to advanced coding skills. Resources
for online learning are explained, and finally some tips to encourage your
coding practice—a great note to end on!
GLOSSARY / / 196
IN D E X / / 2 0 6
ACKNOWLEDGMENTS / / 208
C O N T E N T S // 7
INTR O D UCTIO N
SYMBOL KEY
f -c ? v'
Tips and Activities and Key points Concepts
inspiration mini-tasks and tricks to
remember
8 // I N T R O D U C T I O N
One of the best ways to learn is by doing, so this guide encourages
practical application of the topics covered. Throughout the book, notes,
tips, and activities are included to help you add another level to your
learning. Enjoy the process of developing a new skill and keep on track by
referring to the glossary (terms are bolded throughout). Once you have
mastered the basics, there is advice for further learning in the last chapter
of the book. Children learn incredibly quickly and are used to the fast-
paced nature of technology, but there is no need to be left behind—work
together with your kids to develop a skill that is certain to be of use to you
both in the future!
In this book, we will introduce some examples of key coding concepts to
highlight the way in which a machine organizes and processes information.
We will look at how mistakes can occur, how to create organized, beautiful
code examples, and even build some cool animations, games, and
applications using a range of coding programs. This book will provide
you with a helpful introduction to coding, setting you up with a solid
understanding of its key concepts and a clear starting point for further
learning. In an increasingly digitized world, a grasp of coding can offer
many exciting opportunities.
Children are being taught the basics of programming in schools to prepare
them for today’s digital culture, and it's important for the rest of us to do
our best to keep up! As well as being especially helpful for imparting a base
level of knowledge to inspire continued study, this book will prepare you to
help young beginner coders with their homework!
I N T R O D U C T I O N // 9
WHAT IS C O D I N G ?
Y
,_________________________ J
Coding is a language, and also a logic-based way of thinking.
At its simplest, learning to code is simply learning to tell machines what to
do. Code is the language used to give instructions to a computer for every
task it performs from displaying words on a screen, to running elaborate
animations. Send a text, take money from an ATM, play a video game, and
you are relying on people having written the code that makes it possible.
Unlike the languages used by people to communicate with each other,
which can be vague, emotional, or even irrational, coding languages are
fixed, logical, and precise. They have to be, because computers take
everything literally!
Imagine this scenario: you're about to ask a friend to buy you some
snacks. You need to provide money, directions to the store, and a list of
your favorite foods. It sounds simple, but your friend would still need to
make decisions in order to succeed, considering the information you have
provided. They would need to follow directions, (deciding what to do if
they got lost on the way): at the store, they would have to consider each
item to see if it met your criteria. They would also have to check each
snack's cost against the current total of the purchase and the total amount
of money they have; then they would have to complete the purchase,
collect any change, and return to you.
The process would be simple enough for your friend, as these decisions can
be made intuitively, but a machine has no intuition to fall back on. A coder
would need to find a specific way to instruct a machine. There are values to
remember (directions, money total), repeatable actions (considering snack
options), and comparisons (checking price against total), making this a
very tricky task indeed for a machine.
This book will introduce you to computational thinking, and give you the
tools to program code for just this sort of task.
10 // I N T R O D U C T I O N
H O W DID W E GET HERE?
Here are some of the key milestones in the creation and development of
modern coded machines.
■r-
I N T R O D U C T I O N // 11
U S E S OF C O D I N G
KIDS W H O CODE
Like everything, coding is actually easier to learn for children than for
adults—the key is to understand computational thinking, and to grasp what
is possible within its frameworks. It really is like learning a new language!
All that's required to learn coding is a grasp of logic. The program Scratch,
covered in Chapter 2, was originally designed for kids eight and up, but
can be used by younger children (basic reading is required, and adult
supervision or parental controls are recommended for young children
using the Internet). The later chapters of this book focus on HTML, CSS,
and JavaScript, which are very detail-oriented and can be frustrating for
younger children (and adult beginners!), but certainly not impossible.
Coding is a fantastic skill, well worth learning at any age!
12 // I N T R O D U C T I O N
GET KIDS EXCITED A B O U T CAREER O P TIO N S
Skills in coding are increasingly valuable as advances in technology and
computing produce greater demand. If kids find coding an exciting and
challenging hobby then it could be worth encouraging them to think about
careers that involve coding tasks—and there are all kindsf
Gam ing
The gaming industry is huge and varied with many careers for people to
write, build, and test new projects. Modern games are usually complex with
detailed graphics, but just like the simple projects we will learn to build in
this book, they need to follow logical steps and avoid errors.
Software
Browsers are used to run our web code, but the browsers themselves
are built with code! Beyond the web, computer software and operating
systems are always in need of coders to keep them updated.
AI
Data science
Using large amounts of input data, statistical analysis can provide insight
into trends and behaviors. Using supercomputers, which are large-capacity
and fast processing machines, many records can be processed so that data
scientists can predict otherwise unpredictable outcomes, for example the
financial market.
n I N T R O D U C T I O N // 13
M ISCO N CEPTIO N S
ABOUT CO D IN G
______________ ___ ___________________________________________ j
Y
Here are some common myths that m ight put you off
encouraging your kids to code—let’s dispel them!
14 // I N T R O D U C T I O N
0 Myth: You need expensive com puters and software
Truth: Nope. Fast, modern computers are necessary for some art and video
software and that need high processing power and memory, but code itself
is just text. A PC or laptop with a text editor program and a browser is
sufficient to get started—you don't even need an Internet connection!
Truth: Like most subjects, coding does become more complicated as you
progress and learn more, but this shouldn't be a block to getting started.
A glance at a page of complex code may appear daunting to a beginner,
but don't worry, we will start small. This book begins at the ground level to
introduce concepts, then gradually builds toward simple code blocks and
eventually some more involved code, giving every new addition a context
and explanation. By the time you get to the end, that page of code might
not seem so complicated after all!
I N T R O D U C T I O N // 15
G E T T I N G STARTED
____________________________________________ J
y"
As with any new skill, it’s im portant to start at the beginning and
build your knowledge.
There are many ways that you could approach learning to code. A large
percentage of professional developers are entirely or partly self-taught,
as the field is so new and these skills have only recently been deemed
teachable. Learning through necessity is effective, but it will give you
the skills to perform only specific tasks and could leave gaps in your
understanding, so we will begin with the basics.
By beginning with the concepts that coding is built upon, you
can focus on what the code does, rather than worrying about the
format. Once we have covered the logic, we will look at Scratch
software, which is designed to easily introduce computational
thinking. From there we will begin to look at hand-typed code
with HTML and CSS web pages, then finally, we will explore the
use of JavaScript to alter the inputs and behavior of web pages.
With this progression from thought to tools and software, you
will hopefully appreciate the fundamentals and gain a solid
SETTING UP
Our opening chapter does not require any software, though you may want
to take notes or draw out your own algorithms on paper. For the later
chapters you will need a computer to complete the exercises. You will need
an Internet connection to access Scratch for Chapter 2, as well as an email
address to sign up, but the software is free. You will also need a simple
HTML text editor program to complete Chapters 3 and 4. These are also
free to download, and we have suggested several options.
TABLET OR COMPUTER?
You could use a tablet to follow along with this book, but you may find it
more difficult in the later coding chapters, which require heavy amounts
of typing and symbols (such as </"|>) that could be difficult on a tablet.
The process of saving and refreshing web pages requires frequent jumping
between applications, which can also be harder on a tablet. A laptop or PC
will be the best tool for coding.
G O O D C O D IN G BEHAVIORS
As we will discover in this book, there are some behaviors, general policies,
and attributes of writing effective code. Some of these will involve the
formatting and simplification of the code itself, but also attention to detail
and commitment to making things work correctly. Try to avoid directly
copying examples from the book without first examining what is happening
and why. This will keep you thinking creatively and actively learning, which
are both key to becoming a great coder!
I N T R O D U C T I O N // 17
CO DING CO NCEPTS
COMPUTER-FREE CODING
You will not need a computer or any software for this chapter, as we are
looking at ideas rather than direct code. You may need a pencil and paper to
follow mini-challenges and try drawing your own functions.
18 // C O D I N G C O N C E P T S
P R OG R A M M I N G LANGUAGES
There are many different programming languages (such as HTML,
JavaScript, etc.). Once you've learned one, it will be easier to pick up a
second programming language, as they are based on similar concepts.
Learning the core basics independently of a particular language or
software should make it easier to take on any programming language you
choose. It may also be helpful to refer back to this chapter when we begin
coding in later chapters.
^ Building blocks
The core concepts, or building blocks of coding (such as loops, functions,
conditions, and variables) are used similarly by different programming
languages and software.
C O D I N G C O N C E P T S // 19
UNDERSTANDING
ALGORITHM S
20 // C O D I N G C O N C E P T S
RULES OF THE ALG ORI THM
Define start and end points
One at a time
Each step must be completed before you can start the next.
Algorithms don’t allow for multitasking, although you can
write a single step that includes multiple actions.
Values needed
Conditional flow
W HO IS IT FOR? M IN I TASK
C O D I N G C O N C E P T S // 21
MORE ALG O RITH M S
,________________________ J
V
To create more complex algorithms capable of performing
complicated tasks, we will need to add options for customization.
Another reason the algorithm is ideal for telling computers what to do,
is that it can offer options, allowing the computer to make decisions and
calculate information. This means that the same algorithm can work in lots
of situations with different inputs (information provided by users) and
solve different problems. Clever algorithms that can do repeatable tasks,
but not always the exact same way, are a vital reason why computers are
so efficient and powerful.
22 // C O D I N G C O N C E P T S
MORE RULES OF A L GO R I TH MS
The "Making Coffee" algorithm uses some
additional rules to vary the final output.
Loops
Flow
Conditionals
End
C O D I N G C O N C E P T S // 23
CO ND ITIONS
IF/ELS E
An if/else statement is a type of conditional that instructs a program what
to do if it passes a requirement, or alternatively what to do if it fails. In the
diagram on the opposite page, we use a series of questions and if/else
branching to guess what type of pet you might have. At every decision
making point, there is an option given if the statement is accepted, and
another option in case it is not.
A N D /O R
If you are checking for multiple things, you may check a combination using
and/or values. Using "and" will do something if both conditions are met.
Using "or” will do something if one of the conditions is met. Using these
together will allow for a more powerful ability to query information.
24 // C O D I N G C O N C E P T S
What pet do you have?
0
Follow the questions and the flow diagram will guess your answer!
Remember: there should always be a Using the flow chart, work out
plan for what to do in every scenario. which animals will be found for
If the algorithm doesn't know what to the following queries:
do (for example, if the person guessing • Has 2 legs, can fly OR
doesn't actually have a pet) there is no cannot fly
route to proceed, it cannot finish and • Has 4 legs AND eats meat
the flow will be broken. • Does not have 4 legs AND
can fly OR has gills
C O D I N G C O N C E P T S // 25
LOOPS
26 // C O D I N G C O N C E P T S
USING LOOPS FOR O UTPUT
Using dynamic values (which can be edited) we can write an algorithm
to reduce a list of instructions to one instruction that contains loops. For
example, to instruct a program to complete a repetitive numerical task, you
could create an algorithm that loops for every number in a set range.
r -------
fo r 1-5
w ri te number x 7
S__________
C O D I N G C O N C E P T S // 27
FUNCTIONS
28 // C O D I N G C O N C E P T S
^ Function: Make a Drink
r-
KEY
fu n c tio n s
"--------------------------------
v a ria b le s p a ra m e te rs ""] end
□ j
. “
make a d r i n k typ e o p tio n sugar
©
b o il w a te r ©
wai t 1 mi nute
if “ is i t h o t enough” eq u als f a ls e
e ls e pour in t o cup
d r in k equals typ e ©
©
add ite m sugar
s t i r d r in k
r e tu r n d r i nk ©
C O D I N G C O N C E P T S // 29
V A R IA B L E S
Value variables
The variable "dogs" is a saved list of dogs that is updated when we apply
functions to it, as below. The function "add dog (name)" will add another
dog to the information stored in the original variable "dogs."
e q u a ls : s p ik e , b u s te r
e q u a ls : 2
x n
e q u a ls : 3
;-'Y
i i
number o f dogs e q u a ls : 4
30 // C O D I N G C O N C E P T S
VARIABLE TYPES
Variables can be inputs (values added by users) or even combinations of
other variables. Many types of function can be carried out on variables
based on their type. The next pages will look at four types of variable.
Input variables
"First" and "second" are input variables, and "full name" is a combination of
two variables. Editing either of the input variables will update "full name."
e q u a ls “ lo h n ”
e q u a ls " S m it h ”
e q u a ls first p lu s second
Reusing a variable
Another benefit of variables is the fact that they can be reused. By making
a variable for a character's name in a story, for example, we can edit the
variable to change the name throughout the story, rather than manually
changing each instance. This is an example of a config value.
C O D I N G C O N C E P T S / / 31
INTEGERS AND
BOOLEANS
INTEGERS
Simply put, integers are variables for whole numbers. Setting a variable
integer is obviously helpful for tracking a number in your code (such as the
quantity of something or how many times an action should be performed)
and integers allow you to make mathematical changes through functions
(such as addition/subtraction).
Numbers can also be used for checking if something has reached a
maximum or minimum value, or if it is equal to a certain numerical
requirement. Setting integer variables is also a key component of algebra,
where the character x is most commonly used to represent the variable.
Variables in algebra
The equations below show how variables are used in simple algebra, but
they can be used for much more complex math, and more.
32 // C O D I N G C O N C E P T S
BO O LEANS
Booleans are the simplest variable type as there are only two possible
values: true or false. A Boolean value will always be either true or false,
making it ideal for something you need to set as on or off, done or not
done. While this may seem limiting compared to numbers or text, it’s
sometimes very helpful to make a simple switch variable with a clear status
(such as adding milk or not in our coffee-making algorithm on page 22).
Functions can use Boolean variables to identify all the true statements
from a list, or to return a list of tasks that still need to be done. They
are a useful tool for sorting data. In the diagram on page 32, you could use
a function to query whether ”x” is greater than 4, or divisible by 5, and the
return would be either true or false; a Boolean value.
B o o le a n v a lu e
tru e
tru e
f a l se
f a l se
C o m p le te d ta s k s e q u a ls : 2
C O D I N G C O N C E P T S // 33
S T R I N G S A N D L IS T S
J
V
Variables can be text, or even combinations of other variables,
allowing you to set up even more complex types of function.
STRINGS
Strings are variables made up of text values. You may use a text variable
for a name or label, and you could perform functions on a string to check
its length (how many text characters it has), change the text (such as
convert to all capitals), or combine with other strings. If you refer back to
our "Make a Drink" function (page 29), the variable “drink" has to be set
to a parameter, "type," which could be a value like coffee, tea, cocoa, etc.
These are all examples of string variables.
LISTS
The final variable type we will look at is lists (sometimes called arrays).
Lists can be combinations of string, integer, and Boolean values, and
are helpful for storing a sequence of information. Functions can use list
variables to check their length and add and remove things from them, as
well as checking for specific items using a loop, or requesting an index
from the list. This is all very helpful for organizing and presenting data.
Parents, this is a good topic to practice until kids can identify variable types
automatically. Try identifying examples of each type in a newspaper page,
highlighting each in a different color. Once you start noticing them, you'll see
variable types everywhere!
34 // C O D I N G C O N C E P T S
yt Identifying variable types
Different variable types allow functions to use their information to check
different things. Take a look at the variables below, which include all the
types we have discussed. With all these variables, you could build a detailed
function. You can check if the name is too long because it is a string, you
can check the age is not too old as it is an integer. You can check if the
person owns a pet because it is a Boolean, and you can check how many
pets because the value is a list. You could also query the list variable to find
out how many pets there are, and check there aren't too many, or find a
specific entry (for example, the third pet is "Spots").
name Susan s t r in g
age 43 — in te g e r
has a p e t tr u e Boolean
p e ts
C O D I N G C O N C E P T S // 35
USER INPUTS
Input values are provided by the user, which present their own
unique challenges.
The user is whoever your code is built for, and user input means any
information or interaction that the user provides. For example, in a game
the user might press a button or select an option, or on a website the user
might fill in a form —these are all types of user input. Earlier we looked at
parameters, such as how a user can specify options when calling a function
(i.e. coffee with milk and two sugars). This is an example of user input as
the user is specifying inputs to determine how the function will work.
One of the challenges of user inputs is that you cannot predict what a user
might do or what inputs a user might provide, and will need to prepare
responses for all possible outcomes.
Even a question that's simple to ask aloud becomes much more
complicated when you realize that you have to write a function that can
process all kinds of possible answers!
36 // C O D I N G C O N C E P T S
^ Function: How Many Pets?
how many p e t s ? f| in p u t
if in p u t | ty p e = number
e ls e i f | i nput ty p e = t e x t
if in p u t
I if
[
i nput
= 1 ©
I = 2
e l se answer = “ n o t g iv e n ” ©
r e tu r n answer ©
C O D I N G C O N C E P T S // 37
CORE CO N CE PTS
I
D O N ' T REPEAT
Y O U R S E L F (DRY)
38 // C O D I N G C O N C E P T S
N O W LET’S SIMPLIFY!
To simplify a repetitive function, ask yourself what its key components
are—what is accomplished? Then identify the pattern and which steps are
consistently being repeated.
In the example of a snack function, we are clearly looking to create a
function for buying food, and the steps in the process—such as going to
the store and looking for each item—apply equally to each separate food
item. Therefore the unique steps in the list can be reduced to the actual
snack items you want, for example:
1. Get a drink
2. Get a pizza
3. Get an ice cream
come home
The process of refining code by breaking it into smaller functions like this
is called code refactoring. Parents, it's a great idea to keep track of the new
vocabulary terms were learning and make a set of flashcards.
C O D I N G C O N C E P T S // 39
CORE C O N CE P T S
s e t age number
age
eq u als
number
age
40 // C O D I N G C O N C E P T S
0 The simplest "Find My Pet" function
We want to create a function to find my dog, "Spike." The first attempt
focuses on various details, and requires three parameters to be confirmed
to com e to a conclusion. The reduced option uses the quickest and easiest
function to solve the problem, based on the information we have available.
Since we know his name, let's just search for that. This function has been
simplified based on logic rather than tidying code.
fin d my p e t name
f o r each pet
if p e t: name = l name
answer
=L _.p e t 1
r e tu rn answer
C O D I N G C O N C E P T S // 41
CORE CONCEPTS
I
DEBUGGING
Once you have checked for basic typos and errors in structure, if the code
still isn't behaving as expected, try asking yourself these questions:
1. What makes you think your code isn't working?
2. What did you expect your code to do and why?
3. What did your code do instead, and how do you know?
42 // C O D I N G C O N C E P T S
DEBUG G ING A SAMPLE F U N C T IO N
This function lets you input your age to see if you are old enough to watch
an R-rated movie, but it has wrongly allowed someone who is too young to
see the film. We need to debug the function!
L_ 7_ l
some part of the function
© am I o ld enough? is working. If no response
was returned we would
suspect the problem to be
retu rn s true
a broken function flow.
© Test a different input. By
© am I o ld enough?
□ 20HI changing the input value
we can see if the response
changes. (If we test with
r e t u r n s TRUE an older age and receive
a no, we would know the
function is giving opposite
© am I o ld enough? age answers.)
(3) Read through the function
step-by-step to see what
© if L age J > 2 could be happening each
time—you might spot
what is going wrong.
answer = TRUE
( 4 ) Aha! It seems we have
Else entered the wrong
number to check against
I our age input. Let's change
it to 17
| return answer
C O D I N G C O N C E P T S // 43
CODE MANAGEMENT
J
V
W e have all the tools to begin coding, but need to bear in mind
how to maintain and manage this code.
When working on a project it's easy to get carried away and end up writing
a large amount of code. While this is not necessarily a problem, if you don't
keep it easy to read and understand, it can create problems later on, such
as incorporating errors. You may find it easier to break your code into
sections, making it more transparent and easier to check. You may also
want to write notes for yourself to help remind you what is happening in
your code.
0 Best practices
Take a look at the opposite page. This is our "Make a Drink" function from
page 29, but reduced and organized to its simplest form.
(T) Add comments: Most software will allow you to add comments to
functions so you can label different elements. This will not be read by
the computer or change the code, but will help you and other readers
to understand the code better.
(2) Give descriptive names: Another way to make it easy for you to
remember what the code does is with clear descriptive names for
your functions and variables. It is obvious the function "add milk" will
probably add the milk.
(3) Clean display: Another way to make code cleaner is with visual
spacing and indentation. This way we can see which functions
belong together This will not make the code any better in
functionality, but will make it easier for humans to use.
(4) Arrange by type: By putting similar sections together, we can easily
find the relevant part to work on. Here all the function calls are
grouped together, so we don't need to find where each call is being
made throughout the code.
44 // C O D I N G C O N C E P T S
0 W ell-m anaged code: "Make a Drink" function
//Function definition
b o il w a te r
I w a it 1 m in ute
if “ is i t h o t enough” eq u als f a ls e
make a d r i n k typ
ty p e □ c o p tio n sugar
e ls e pour in t o cup
c d r i nk
[ ty p e
© if o p tio n
add o p tio n
f | sugar
add sugar
s tir d r in k
r e tu rn d rin k
V ___ )
//Sample function calls
make a d r i n k te a m ilk
□
make d r i nk te a
° n
C O D I N G C O N C E P T S // 4S
C O M M O N C O D IN G ISSUES
J
v ------------------------------------------------------------------------------------
You may find an issue with your code not working, but not know where
it’s happening. This might be a sign that your functions are too large and
complicated, and could use some simplification and refactoring. See page
40 for tips on keeping code simple.
You may have used the same variable more than once. Variables need to
be kept unique or your code could become confused. Keep them distinctly
named and descriptive as to what information they hold. If your variable
isn't showing any information at all, you may have spelled it differently or
used spaces or capital letters, so your variables do not match throughout
the function.
46 // C O D I N G C O N C E P T S
© My function is not doing what I expected
You might find the outputs or results of your code are not working in the
way you wanted, meaning you have a bug in your code. Not to worry,
debugging is an essential skill to coding and is an opportunity to learn.
Looking at the result of your code may provide a clue as to what's wrong
with the code, see page 42 for more debugging advice.
Perhaps your code isn’t doing anything at all and there is no response when
you test it. This could be a number of things, but maybe it's simply because
it's coded to not do anything in some circumstances. It is important that
your functions are able to handle all outcomes as otherwise it will confuse
you by returning nothing. You must also be careful that your code doesn't
get trapped in never-ending loops and flows.
You may become frustrated that you don't know how to solve a problem
or do something with code, and the problem may be you are limiting
yourself by what you know. If you feel you are devising overly elaborate or
complicated ways to do something, there may be a simpler way that you
are not aware of. It's important to keep learning and to challenge yourself
to find ways to simplify your code by researching other solutions.
C O D I N G C O N C E P T S // 47
TEST YOUR KNOWLEDGE
I
P R O J E C T 1:
FASHIONBOT
FashionBot
Help find the ideal outfit with our new FashionBot function (opposite). This
function allows you to enter two parameters: the weather outside and your
destination, and returns the list variable "clothing," telling you what to wear
today. The function works so far, but requires some adjustments:
F a s h io n B o t[ra in , pa rk]
R eturns “ r a i n c o a t , rubber b o o ts "
F a s h io n B o t[d ry , s c h o o l]
R eturns “ school u n ifo rm , shoes”
48 // C O D I N G C O N C E P T S
IMPROVE OUR FUNCTION
Draw out a copy of this function, but add these changes to make it better:
• Add new conditions for if weather is equal to "sunny" and add
sunglasses to the "clothes" list variable.
• Add a new third parameter for hat, if hat is equal to true and
destination is not equal to school then add hat to the list variable
"clothes."
• Add an option that if destination is equal to "stay home" then return
only "pajamas" as the variable "clothes."
C O D I N G C O N C E P T S // 49
TEST YOUR KNOWLEDGE
P R O J E C T 2:
FIN D THE W IZ A R D
Again, draw a copy of this function with these changes to make it better:
• Create a new wizard to be included in our list. Give them a name and
power and set their dark magic to true or false. What function would
you need to call to retrieve your wizard?
• Imagine there were two wizards with the same power—can you find
a way to search for the wizard by name instead?
• We don't want our function to allow wizards with dark magic
anymore, so if the wizard found has dark magic set to true, then
instead set your "answer" variable to "not allowed."
50 // C O D I N G C O N C E P T S
name: G l i n d o r name: N o i r i n
power: Ic e power: Earth
dark magic: f a l s e da rk magic: t r u e
C O D I N G C O N C E P T S // 51
L
Other documents randomly have
different content
from what has been the case with any of the previously considered
mechanisms. The tangible manifestation of energy which we term
heat is not merely a condition of action and a by-product, as it was
in the case of the animal machine; it is the essential factor upon
which all the efficiency of the mechanism depends.
It should perhaps be stated that this explanation of the action of
the steam engine is a comparatively modern scientific interpretation.
The earlier experimenters brought the steam engine to a high state
of efficiency, without having any such conception as this of the
nature of steam itself. For practical purposes it suffices to note that
water when heated takes the form of steam; that this steam has the
property of powerful and indefinite expansion; and thirdly, that when
allowed to escape from a state of pressure, sudden expansion of the
steam cools it sufficiently to cause the recondensation of part of its
substance, thus creating a vacuum.
Stated in few words, the entire action of the steam depends upon
these simple mechanical principles. The principles are practically
applied by permitting the steam to enter the cylinder where it can
act on a piston, to which it gives the thrust that is transmitted to an
external mechanism by means of a rod attached to the piston. When
the piston has been driven to the end of the desired thrust, the valve
is opened automatically, permitting the steam to escape, thus
producing a vacuum, and insuring the return thrust of the piston,
which is further facilitated, ordinarily, by the admission of steam to
the other side of the piston. Practical operation of this mechanism is
familiar to everyone, though the marvel of its power and efficiency
seems none the less because of its familiarity.
It is not too much to say that this relatively simple device, in its
first general application, marked one of the most important turning
points in the history of civilization. To its influence, more than to any
other single cause, must be ascribed the revolutionary change that
came over the character of practical life in the nineteenth century.
From prehistoric times till well toward the close of the eighteenth
century, there was scarcely any important change in carrying out the
world's work. And in the few generations that have since elapsed,
the entire aspect of the mechanical world has been changed, the
working efficiency of the individual has been largely increased;
mechanical tasks have become easy which hitherto were scarcely
within the range of human capacity.
Before we go on to the detailed study of the machine which has
produced these remarkable results, it is desirable to make inquiry as
to the historical development of so important an invention.
The practical steam engine in its modern form dates, as just
mentioned, from the latter part of the eighteenth century, and was
perfected by James Watt, who is commonly thought of as being its
inventor. In point of fact, however, the history of most inventions is
duplicated here, as on examination it appears that various
forerunners of Watt had been on the track of the steam engine, and
some of them, indeed, had produced a workable machine of no
small degree of efficiency.
The very earliest experiments were made away back in the
Alexandrian days in the second century before the Christian era, the
experimenter being the famous Hero, whose work in an allied field
was referred to in the preceding chapter. Hero produced—or at least
described and so is credited with producing, though the actual
inventor may have been Ctesibius—a little toy mechanism, in which
a hollow ball was made to revolve on an axis through the agency of
steam, which escaped from two bent tubes placed on opposite sides
of the ball, their orifices pointing in opposite directions. The
apparatus had no practical utility, but it sufficed to establish the
principle that heat, acting through the agency of steam, could be
made to do mechanical work. Had not the age of Hero been a time
of mental stasis, it is highly probable that the principle he had thus
demonstrated would have been applied to some more practical
mechanism in succeeding generations. As it was, however, nothing
practical came of his experiment, and the steam turbine engine was
remembered only as a scientific toy.
No other worker continued the experiments, so far as is known,
until the time of the great Italian, Leonardo da Vinci, who, late in the
fifteenth century, gave a new impulse to mechanical invention.
Leonardo experimented with steam, and succeeded in producing
what was virtually an explosion engine, by the agency of which a
ball was propelled along the earth. But this experiment also failed to
have practical result.
ROTARY MOTION
ebookbell.com