Beginners Stepbystep Coding Course Learn Computer Programming The Easy Way Dk pdf download
Beginners Stepbystep Coding Course Learn Computer Programming The Easy Way Dk pdf download
https://ebookbell.com/product/beginners-stepbystep-coding-course-
learn-computer-programming-the-easy-way-dk-56023114
https://ebookbell.com/product/beginners-stepbystep-coding-course-
learn-computer-programming-the-easy-way-dk-publishing-46708562
https://ebookbell.com/product/beginners-stepbystep-coding-course-
learn-computer-programming-the-easy-way-suefa-lee-10792118
https://ebookbell.com/product/sql-coding-for-beginners-stepbystep-
beginners-guide-to-mastering-sql-programming-and-coding-2022-crash-
course-for-newbies-fawn-watson-51284574
https://ebookbell.com/product/absolute-beginners-guide-to-python-
programming-master-coding-quickly-with-handson-realworld-projects-
stepbystep-guidance-and-comprehensive-learning-for-all-ages-stirling-
hale-58084436
Python Pythons Companion A Step By Step Guide For Beginners To Start
Coding Today Joe Thompson
https://ebookbell.com/product/python-pythons-companion-a-step-by-step-
guide-for-beginners-to-start-coding-today-joe-thompson-5597956
The Python Bible For Beginners The Stepbystep Roadmap For Aspiring
Programmers To Achieve Coding Mastery And Unlock Rewarding Tech
Careers Pacey Islas
https://ebookbell.com/product/the-python-bible-for-beginners-the-
stepbystep-roadmap-for-aspiring-programmers-to-achieve-coding-mastery-
and-unlock-rewarding-tech-careers-pacey-islas-56502436
https://ebookbell.com/product/computer-programming-allinonecoding-for-
beginners-a-stepbystep-guide-to-learn-python-java-sql-c-c-c-html-and-
css-from-scratch-michail-klling-55885230
https://ebookbell.com/product/python-programming-for-beginners-basic-
language-from-absolute-beginners-to-intermediate-learn-easily-and-
fast-data-science-and-web-development-in-a-simple-and-practical-way-
stepbystep-mark-coding-11157304
https://ebookbell.com/product/coding-for-beginners-blockchain-
development-a-stepbystep-guide-to-create-your-own-blockchains-
cryptocurrencies-and-nfts-learn-to-code-davis-42483362
BEGINNER’S
STEP-BY-STEP
CODING
COURSE
LEARN COMPUTER PROGRAMMING THE EASY WAY
DK DELHI
Senior editor Suefa Lee
Project art editor Sanjay Chauhan
Project editor Tina Jindal
Art editors Rabia Ahmad, Simar Dhamija,
Sonakshi Singh
Assistant editor Sonali Jindal
Jacket designer Tanya Mehrotra
DTP designer Jaypal Chauhan
Pre-production manager Balwant Singh
Senior managing editor Rohan Sinha
Managing art editor Sudakshina Basu
DK LONDON
Project editor Miezan van Zyl
Project art editor Francis Wong
Managing editor Angeles Gavira Guerrero
Managing art editor Michael Duffy
Associate publishing director Liz Wheeler
Publishing director Jonathan Metcalf
Art director Karen Self
Jacket design development manager Sophia MTT
Producer (pre-production) Gillian Reid
Senior producer Meskerem Berhane
ISBN: 978–0–2413–5873–3
Printed in China
A WORLD OF IDEAS:
SEE ALL THERE IS TO KNOW
www.dk.com
CONTRIBUTORS
Clif Kussmaul is Principal Consultant at Green Mango Dr Tammy Pirmann is a computer science professor
Associates, LLC, where he designs and implements at the College of Computing and Informatics at Drexel
research projects, faculty development workshops, and University in Philadelphia, Pennsylvania. She is an
classroom activities. Formerly, he taught for 20 years at award-winning educator, recognized for her focus on
college level and worked full and part time in software equity in computer science education and for promoting
development and consulting. Craig was a Fulbright guided inquiry in secondary computing education. She
Specialist at Ashesi University and a Fulbright-Nehru was the co-chair of the Computer Science Teachers
Scholar at the University of Kerala. He has received Association’s Standards Committee and an advisor on
multiple grants from the US National Science Foundation, the K12 CS Framework.
Google, and other sources to support his work with
Process Oriented Guided Inquiry Learning (POGIL), Dr Martin Goodfellow is a Lecturer in the
Free and Open Source Software (FOSS), and other topics Computer and Information Sciences department
in computer science education. at the University of Strathclyde. He has also developed
educational computer science content and workshops
Sean McManus writes and co-writes inspiring coding for other organizations worldwide, including Google,
books, including Mission Python, Scratch Programming Oracle, CoderDojo Scotland, Glasgow Life, Makeblock,
in Easy Steps, Cool Scratch Projects in Easy Steps, and the BBC.
and Raspberry Pi For Dummies.
Jonathan Hogg is an audiovisual artist who has
Craig Steele is a specialist in computer science spent the last decade constructing works out of
education who helps people develop digital skills in combinations of software, electronics, sound,
a fun and creative environment. He runs Digital Skills light, wood, plastic, and metal. He often works
Education, and is a founder of CoderDojo in Scotland, with young people, running creative and technical
which runs free coding clubs for young people. Craig workshops. Prior to art, Jonathan designed and
has run digital workshops with the Raspberry Pi developed software in the London finance industry.
Foundation, Glasgow Science Centre, Glasgow School He began his career researching and teaching
of Art, and the BBC micro:bit project. Computing at the University of Glasgow. The
only constant in all of this has been Python.
Dr Claire Quigley studied Computing Science at
Glasgow University, where she obtained a BSc and David Krowitz learnt to program in the early
PhD. She has worked in the Computer Laboratory at 1980’s on a Commodore VIC-20 plugged into a
Cambridge University and at Glasgow Science Centre. portable black-and-white TV set. He has been studying
She is currently STEM Co-ordinator with Glasgow Life, and practising computer programming ever since.
and lectures part-time at the Royal Conservatoire of Nowadays, Dave spends his time building microservice
Scotland, working with BEd Music students. Claire architecture for businesses, whilst expounding his love
has been involved in running CoderDojo Scotland since for object-oriented design patterns and software
its initial session in 2012. architecture. See dotpusher.com for more info.
CONTENTS FOREWORD
INTRODUCTION
10
12
What is programming? 16
Programming languages 22
SCRATCH
What is Scratch? 28 Logic and decisions 44
Manipulating data 42
PYTHON
What is Python? 94 Libraries 116
Functions 112
WEB TECHNOLOGIES
How the Web works 206 JavaScript debugging 280
Build a better website 214 PROJECT: Animating the web page 288
Foreword
If you’ve ever asked a teenager for help with your Starting at the absolute beginning, this guide will
computer, you’ll probably have felt the crushing introduce the jargon and tools you’ll need to get
weight of self-doubt as you realize you understood programming in the most popular and versatile
less than half of what they just said. That same software languages. The pages are also peppered
“helpful teen” would most likely scoff at the idea of a with interesting facts about coding and careers,
book – made out of honest-to-goodness old-fashioned together with step-by-step projects to get you going.
paper – on the subject of learning to code. “Just Even if you decide not to become the next Mark
Google it, there are loads of tutorials on Youtube!” Zuckerberg, the skills you’ll learn will be a great
they might say. asset when talking to technology professionals
But not everyone is high-bandwidth, multi-screen and will also help develop your own logic and
ready. Plus, when you are carefully stepping through problem-solving abilities.
the creation of your first lines of code, a physical page It was an ancient Greek philosopher who first noted
with your fingertip planted firmly on the next step can the irony “the only constant in life is change”, and
act as a valuable lifeline to the tangible world. this has never been more true than in the world of
If you’re reading this as a teenager yourself, computing. Maybe you’re looking for a different career
congratulations on discovering life beyond YouTube! or want to learn a new skill to support a hobby or
You’re about to find out that the creators of this guide passion project? Or perhaps you just want to be able
are exactly the kind of industry-defining professionals to talk to your tech-obsessed teenager in a language
whose content channels, blogs, and social media posts that will impress them!
you’d end up on if you did decide to Google “learning For those curious about coding, this guide is full of
to code”. straightforward information, in easily digestible bites,
As a life-long gamer and computing enthusiast written by some of the leading educators and experts
I’ve been reporting on technology for almost a quarter in their field. There is jargon, but it’s jargon you’ll
of a century. In that time, I’ve witnessed seismic understand as you get to it. Is learning about coding
changes in the way we interact with the world. A.I., essential? No. Will it help you understand and feel
big data, automation, e-commerce – all now intrinsic more comfortable in the world we now live? I think so.
parts of our daily routines even if we aren’t always Could it lead to a new and amazing career direction?
aware of them. Definitely, if that’s what you want.
Technology is no longer a niche topic. In fact, There is still a desperate shortage of technology
today, every industry could be considered a tech professionals in the workforce. Opportunities exist,
industry, which leads to a simple choice: get with but they are not going to come looking for you unless
it or get left behind. you speak at least a bit of their language.
Kate Russell
Technology reporter,
author, and gamer
About this book
How this book works grouped under Web Technologies. The book defines
Divided into three chapters, this book teaches the the basic concepts of each programming language and
fundamentals of five programming languages: Scratch, builds on them with the help of detailed projects that
Python, HTML, CSS, and JavaScript; the last three are you can try on your own.
Concepts
Each chapter contains the basic
programming concepts of the language.
These are explained with the help of
practical code examples that you can try
out to understand the concept better.
Illustrations help
you understand
and learn concepts
Projects
The projects in this book teach you how to YOU WILL LEARN
create games, planners, apps, and websites. Indicates the estimated
Each project starts with a brief overview of Time: time it will take to create
what you will learn in the project, how to 1 hour a project
plan the project, and what you will need to
create it. Simple step-by-step instructions Lines of code: 58 Indicates the estimated lines
guide you through the project and explain of code in a project. This
Difficulty level may vary depending on the
every aspect of the code, with the help of
detailed annotations. code editor being used
1.2
Projects are broken down into 1.1
smaller sections with clear steps
to make learning easier
available = 2500.00
budgets = {}
STEP-BY-STEP
These chevrons appear only in Every indent (spaces at the start of a line)
the shell window. Type in the equals four empty grid blocks. All subsequent
code at the >>> prompt indents will be in multiples of four
In this book, ellipses are used at the Grey code indicates an CODE WINDOW FOR The placement of the arrow
start of a line of code to indicate an existing line of code in WEB LANGUAGES indicates if a space needs to
extended indent, usually more than the program. It is used be added before it. In instances
eight grid blocks to identify the line below where there will be no space,
or above which the new no empty grid blocks are left
code must be added between the arrow and the code
Data centre
A data centre is similar to an
industrial-scale computing facility.
Its many servers may be accessed
over the Internet to store data or
run software “in the cloud”. The
“cloud” is a global network of Desktop computer
remote servers that can provide Computers are widely used in
services through the Internet. offices and homes for managing
administrative and creative activities,
such as music, design, writing,
Car banking, and many more.
Software can be used to Washing machine
monitor a car’s systems and Many household appliances run
performance, including its embedded programs to perform
speed, temperature, and a function. Inside the casing of a
fuel. The global positioning washing machine, software runs
system (GPS) used to manage its wash cycles, water
for navigation also temperature, and timings.
requires programs.
INTRODUCTION
What is programming? 16 17
What is a computer program? Thinking like a computer
A program is a set of instructions that a computer To write a program it is necessary to
follows to perform a task. Programs can be extremely understand how a computer processes
complex, and there can be several different layers of instructions. This means that tasks need to
programs working together. Microsoft Windows, for be broken down into smaller chunks so that
example, is made up of millions of lines of instructions. the computer can understand the instructions.
For example, a robot cannot simply be asked to
Applications software, “make some toast”. It is necessary to program
such as word processors,
run on top of the
precise and detailed instructions for each step.
operating system
Instead of repeating
Operating systems, such 1. Open breadbin the same instruction
as Microsoft Windows 2. Remove loaf twice, it will be
and macOS manage the 3. Open bag shorter and clearer
hardware and software to say “Do this twice:
4. Remove slice
remove slice, insert in
5. Insert in toaster toaster” in a program
Firmware is software that
6. Remove slice
is coded into the hardware,
including the Basic Input/ 7. Insert in toaster
Output System (BIOS) 8. Push down plunger
9. Wait until toast
Hardware includes the physical pops up
elements of a computer, such
as the monitor
Games console
Consoles such as the Sony
PlayStation, Microsoft Xbox,
and Nintendo Switch are Camera
computers designed to offer Modern cameras use
a great gaming experience. software to change settings,
capture images digitally,
and enable users to review
and delete photographs.
Factory equipment
Factories can be highly automated. Assembly
line robots, planning and control systems,
and quality-control cameras all require
programs to operate.
Managers and office workers
Many businesses create and use specialized software.
Software engineers develop complex software systems,
but managers and office workers often write short
programs to solve problems or automate tasks that
might take hours or days by hand. For example,
they might write code to query databases,
format information, analyse data, control
equipment, customize websites, or add features
to word processors and spreadsheets. Some
programming languages are specifically
designed for these purposes (see pp.344–47).
Coding in
the real world
Coding is used in nearly every aspect of modern life
and work. Basic knowledge of coding helps people to
use software more effectively, create simple programs,
and communicate with other software developers.
INTRODUCTION
Coding in the real world 18 19
Software engineers and web developers
Software developers work for many different businesses
and organizations. Businesses require software to
track inventory and place orders with suppliers,
to schedule employees and track work hours,
and to send mailings to customers. Insurance
companies use software to set pricing based
on the number and cost of events, and to
review and approve policies. Websites
often combine existing programs with
custom coding for special features.
Software engineers play key roles
in developing systems that suit
a client’s needs.
25,000,000
WORKERS ACROSS
THE WORLD ARE
SOFTWARE DEVELOPERS
Working as a
software developer
Writing a simple program might seem straightforward, but it can be
surprisingly difficult. Developing large, reliable software systems is
even more complex, and requires teams of software developers with
a variety of specialized skills and roles.
Analyse
In this phase, developers decide what the
software must do. They might study existing
systems, design new processes, or interview
people to understand how they will use the
system. This also defines other constraints
or requirements. For example, how much
data must the system handle, how quickly
must it respond, and what should it do when
problems occur? The resulting documents could
range from a few pages to hundreds or more.
Test
Developers check whether the
software works correctly, and fix
any problems they find during
the testing phase. This is often the
longest and least predictable phase,
and a common reason for delays
and extra costs. There are many
types of tests – unit tests check if
individual functions are correct,
functional tests check individual
components, integration tests
check if components work together,
and system tests check the
entire system.
INTRODUCTION
Working as a software developer 20 21
Overview
Software development involves four phases: analyse, design and
plan, build, and test. These phases, however, can be structured in
a variety of ways. A waterfall model steps through each phase once,
which seems simple, but often leads to problems. An iterative model
cycles through the phases several times, building part of the system
in each cycle. An agile model cycles through each phase many times,
adding different features in each cycle.
Design and plan pieces, and specifying the files and even the individual
In this phase, developers decide how the software functions to be created. Developers also need to
will work and how it will be created. This can include estimate the time, effort, materials, and cost to create
deciding on which language to use, sketching user the system, and a schedule for who will do which tasks
interfaces, designing databases, subdividing it into at what time.
Build
In the build phase developers
create the software, including
user interfaces, databases, code,
and documentation for users and
programmers. This means that
coding is just one part of one
phase of software development,
and in some ways the easiest and
most predictable. As each piece is
built, developers might inspect or
review the code to see how well
it is written, and then integrate it
into the larger system.
Programming
languages
A programming language is a set of words and symbols that
allows people to write instructions for a computer. There is
sometimes a compromise between how easy the language
is to use and how powerful it is.
High- and low-level languages program can run on different hardware if it is written
High-level programming languages are designed to be in a high-level language. By contrast, low-level
easy to use without needing a detailed understanding languages give programmers granular control over
of the computer hardware. They often use words that the computer, but also require a deeper understanding
are similar to human language, and manage some of how it works. Programs written in a low-level
aspects of the computer automatically. Often, the same language might not work on other hardware.
Instruction to
HIGH-LEVEL LANGUAGES display some text
• Relatively fast to write
• Relatively easy to understand
• Usually fast enough in execution print("Hello!")
• Programs can be used on different
hardware Python
• No need to understand hardware A popular high-level language,
Python is easy to read and write.
This instruction puts the message
“Hello!” on the screen.
This is hexadecimal,
a common counting
system in computing
LOW-LEVEL LANGUAGES
• Direct control of hardware features
• Can increase speed of highly MOV AX, 66H
performance-sensitive code
• Requires an understanding of Assembly language
the hardware Assembly language more
• Program only works on the closely reflects the processor's
same or similar processor machine code. This example
takes a number and places it
into the part of the processor
called the accumulator.
INTRODUCTION
Programming languages 22 23
Machine code How the computer understands
Low-level code that represents how the computer a programming language
hardware and processor understand instructions Ultimately, all programs end up as machine
is called machine code. It is a collection of binary code. Most programs are written in more
digits – 1s and 0s – that the processor reads and human-friendly languages and need to be
interprets. Machine code instructions are comprised translated into raw bits so that they can
of an opcode and one or more operands. The opcode be executed by a processor. An interpreter
tells the computer what to do and the operand tells translates and executes the instructions as
the computer what data to use. the program is running, while compilers
translate the program in one go before it runs.
Microprocessor
The microprocessor is the “brain”
of a computer and controls most
of the machine’s operations. It
carries out commands and runs
01101000
the machine code instructions. 01101001
00001101
00001010
HUMAN- CONVERT TO RUN
FRIENDLY COMPUTER INSTRUCTIONS
CODE INSTRUCTIONS
EVENT-DRIVEN PROGRAMMING
The event-driven programming concept is
Creates a
one where the program listens for certain
web page button
things to happen, and then starts the
appropriate program sequence when they
do. For example, a program might react <input type="button" value="Click me!"
to user actions, sensor input, or messages
from other computer systems. JavaScript
(see pp.264–65) and Scratch (see pp.28–29),
onClick="showMessage();">
among others, can be used to write
event-driven programs.
Runs the showMessage() This icon has been used in
JavaScript instructions when the book to indicate code
the button is clicked being split into two lines
INTRODUCTION
Programming languages 24 25
CHOOSING A LANGUAGE
Sometimes, programmers’ choice PYTHON SCRATCH
of language may be dictated by the
A flexible language, it emphasizes A great first programming language,
hardware they are using, the team ease of understanding in the code. Scratch is perfect for simple games.
they are programming with, or the
kind of application they want to
JAVA JAVASCRIPT
create. Often, they will have a choice.
Here are some popular languages Widely used in financial services, The language used by web
that can be considered. small devices, and Android phones. pages for interactivity.
MAIN PROGRAM
Data for this object
FUNCTION 1
FUNCTION 3
Features
Scratch has a number of features that
make it an ideal programming language
for beginners. The use of ready-made
blocks of code sets it apart from most
Com
other programming languages. Scra munity
t
othe ch allow
com rs throu s users t
m g o
prog unit y. h a buil conne
U t c
mod rams for sers ca -in Scrat t with
n
learn if y, and others t share t ch
by st remix o pla
y
heir
ud y i .
ng o They can with,
t h er
s’ pr also
ojec
t s.
drop
Drag and cks can be
h b lo
Scratc ped in
and drop
dragged rea to build
A
the Code here is very
T
programs. , so users are
g
little typin make errors.
to
less likely
uage
Power ful lang use,
h is ea sy to
Scratc
core concepts
but includes
sional
used in profes s. It
ng la ng ua ge
codi
ides a good
therefore prov uction
in trod
all-round
ing.
to programm
Jigsaw de
sig
Instruction n
b
like jigsaw locks snap together
pie
cannot con ces, so users
nect them
ways. Non in wrong
sensical co
are typical mbination
ly s
errors in lo impossible, so
gic are min
imized.
SCRATCH
What is Scratch? 28 29
Learning to program with Scratch used in education. Scratch has a highly
Scratch was created by the Lifelong Kindergarten visual interface with coloured blocks of
group at the Massachusetts Institute of Technology code that join together to form scripts,
(MIT) in the US. It was first launched in 2007. which can include images and sounds
Scratch was designed to be fun and easy to use to create action on screen. Scratch provides
for beginners, and to help them understand basic a powerful platform (see pp.30–31) for
concepts and avoid errors. It is therefore widely exploring programming.
Hardware support
The latest version of Scratch works on computers
with Windows, macOS, and Linux. It can even
Built-in assets be used on tablets. Scratch projects can use
th a pre-installed
Scratch comes wi d extensions to interact with hardware devices.
so un ds and images (calle
librar y of 3) th at ma kes it
.32–3
sprites – see pp r
g right away. Othe
easy to start codin es lac k in this
guag Raspberry Pi
programming lan d
need to be create . Scratch can use a Raspberry Pi to connect
regard as images itin g a program
be for e wr to other sensors or motors.
or uploaded
micro:bit
Scratch can be used with a BBC micro:bit,
which has a built-in LED display, buttons,
and tilt sensors.
Lego®
Scratch can connect to Lego® WeDo and
Lego® Mindstorms™ to work with motors,
sensors, and robots.
Webcam
Scratch can access a webcam to layer images on
a live video feed to create simple augmented
reality applications.
GETTING SCRATCH
The Scratch developer environment is required
Colou
Instru r coding
for using Scratch. It can be accessed both online
c
move tion blocks and offline.
m
and se ent, sound for
are co nsing (amo , control, In your browser
lo n
be ea ur coded, g others) Visit the Scratch website at
s s
when ily identifie o they can https://scratch.mit.edu/ and click
creatin da
g a p r nd re ad Join Scratch to create an account.
og r a m
.
Offline
Scratch can be downloaded and used
without an Internet connection at
https://scratch.mit.edu/download.
Scratch interface
The screen layout, or interface, in Scratch can be used to build
programs, edit them, and view the output in the same screen. The
interface is divided into several sections, each serving a particular
purpose. This book uses Scratch 3.0 – the latest version of Scratch.
Create new projects, Use the Sounds tab to
Understanding the screen layout Change upload or save work Edit existing add music and sound
The Scratch interface is divided into the language to the computer projects effects to sprites
following sections:
• Blocks Palette: This contains the instructions,
SCRATCH File Edit Tutorials
or code blocks, required to build a program
• Code Area: The instruction blocks are Code Costumes Sounds
assembled here to create a script
• Stage: Allows the user to interact with Use the Costumes
Motion tab to change
the program Motion the appearance of
• Sprite List: Displays and manages all the move 10 steps a sprite
images, or sprites, used in a program
• Stage Info: Manages the background images Looks
turn 15 degrees
Events
go to random position
STAGE
BLOCKS CODE
Control go to x: 0 y: 0
PALETTE AREA
glide 1 secs to random position
SPRITE Sensing
LIST
glide 1 secs to x: 0 y: 0
Operators
STAGE INFO
point in direction 90
Variables
VERSIONS OF SCRATCH
point towards mouse-pointer
My Blocks
There have been three versions of Scratch so far,
Select instruction blocks and
each with a different screen layout. New features drag them into the Code Area
and instruction blocks were added at each update to build a program
of the interface. These features may not work on
earlier versions. Contains the instruction
• Scratch 1.4: The interface was similar to Scratch blocks that can be used
3.0, but the Code Area was called Scripts Area.
• Scratch 2.0: The Stage was on the left of the
screen. Introduced sprite cloning and reorganized
some blocks into the Events category. Backpack
• Scratch 3.0: Introduced Blocks Palette
extensions, and moved the Pen blocks into them. Use the “Add Extension” Store useful code, sprites, costumes,
button to add new categories and sounds in the Backpack so that
of blocks to the Blocks Palette they can be used in other projects
SCRATCH
Scratch interface 30 31
when clicked
forever
glide 3 secs to x: 0 y: –150
glide 3 secs to x: 200 y: 100
glide 3 secs to x: –200 y: 100
Stage
Sprite Sprite1 x -90 y -10
Sprite 1 Cactus
Drag instruction blocks into the A blue box This panel shows the sprites used Add new sprites Change the
Code Area and join them together highlights the in a program. Select one to see to the project backdrop
to build a script for a sprite selected sprite its code in the Code Area
Sprites
Sprites are the basic components of Scratch. Similar to characters
in a video game, they can move around the Stage, change their
appearance, and interact with other sprites. Each sprite uses one
or more images and is controlled by scripts.
Creating a sprite
Scratch allows its users to add or create their own images. The Choose
a Sprite button on the bottom right of the Sprite List reveals options to
add, create, or upload sprites in a project.
Upload Surprise
Users can include their own Scratch also has an option
images and upload them to the to add a random sprite from
Scratch interface to be used as the Sprite library. It can be a
sprites. This includes images, such quick way to add sprites to
as photographs, which may be experiment with, or to generate
required to create or new game ideas.
personalize games.
1 Costume Costume1
Group Ungroup Forward Backward Front Back
Fill Outline 2
costume1 Copy Paste Delete Flip horizontal Flip vertical
239 x 315
Choose which
costume to edit Select an Line thickness Flip selected
Select a
outline colour elements
fill colour
horizontally
2 or vertically
Select tool
Convert to Bitmap
wait until
Control blocks
Control blocks are used to make decisions
about what to do next. They also dictate how
often a set of blocks should repeat, and when
the script should pause.
Events blocks
These blocks detect when the green
flag is clicked, a key is pressed, or a
sprite is clicked.
SCRATCH
Coloured blocks and scripts 34 35
Using the Blocks Palette Select this tab to begin
Output blocks
+ move 10 steps
Sound blocks
Sound blocks are used to add sound
effects to a program. They provide audio
output by replaying recorded sounds.
Output using
movement
Scratch is an ideal language for programming simple games and
applications that move images around the screen. It has a set of
blue Motion blocks that can be used to control a sprite’s movement.
x axis
–240 0 240
Coordinates 180 x and y grid
The Stage here has
In Scratch, any position on the Stage can be been marked with grid
(x=180, y=120)
pinpointed using the x and y coordinates. The x lines every 60 steps. Try
axis runs from -240 on the left to 240 on the right, (x=–120, y=60) these positions in the
y axis
0 Motion blocks (below)
and the y axis runs from -180 at the bottom to 180 for moving a
at the top. When writing a program, coordinates sprite using
(x=–180, y=60) coordinates.
can be used to place a sprite in a particular position.
(x=60 y=-120)
–180
go to x: 0 y: 0 set x to 0 x position
MUSIC BLOCKS
The Music blocks in Scratch are an extension,
set tempo to 120
and need to be added using the Add
Extension button on the bottom left of the set instrument to (20) Synth Lead
Blocks Palette. They make it possible for
programmers to use blocks to play musical play note 60 for 0.25 beats
notes. It is not necessary to know the number
for each note, since clicking the hole for the play note 62 for 0.25 beats
note number will display a piano keyboard to
help enter the required music. play note 64 for 0.25 beats
Playing sounds play sound Meow until done change pitch effect by 10
Sounds are a great way to
provide feedback in a game Pause script to play sound Alter pitch
Sets a sound to play, and then pauses Changes the pitch of a sound effect. Positive
or as an alert in a program. the script until it is finished. The menu numbers make the pitch higher and negative
Before a sound can be used, in the block can be used to choose a ones make it lower. The stereo setting can
it has to be added to the different sound. be adjusted as well.
sprite from the Choose
a Sound button under the start sound Meow set pitch effect to 100
Sounds tab. Programmers
Play sound in background Reset pitch
can either use a sound from Starts playing a sound, but does not Resets the pitch or changes it to a value
the Scratch Sound library, pause the script. The sound plays in specified by the programmer. It can also be
the background while the script runs. used to adjust the stereo left/right setting.
or can record or upload a
sound of their own.
stop all sounds clear sound effects
Event-driven programming
In event-driven programming, the program’s actions are started by events,
such as user input, sensor input (see pp.46–47), or messages sent by other when clicked
programs or parts of the program. The Events section of the Blocks Palette
contains blocks that can start scripts when something happens. Also Use green flag to start
Provides an easy way for users to start the
called hat blocks due to their shape, these Events blocks provide many program. Copies of this block can be used to
more ways to start scripts than simply clicking on them. start multiple scripts simultaneously.
when this sprite clicked when loudness > 10 when I receive message1
Use mouse click to start Use sounds to start Use message to start
This block starts the attached script when When the microphone detects a volume Scripts can send messages to each other
the sprite is clicked. It is ideal for creating more than 10 (on a scale of 0 to 100), the (see pp.48–49). This block starts a script
on-screen buttons for users to click on. script can be activated. when a particular message is received.
This costume
The blue highlight indicates indicates that the
this is the selected sprite Drum Kit is playing
when this sprite clicked
INTRODUCING DELAY
It is not always desirable to have
a program run as fast as possible.
In many cases, a program may when clicked
need to be slowed down so that
when clicked move 10 steps
users can easily see what is going
on and have time to respond. move 10 steps wait 1 seconds
Games are often artificially
slowed down in order to ensure move –10 steps move –10 steps
that players can keep up.
Normal movement Delayed movement
In this example, the program runs so Introducing a wait block makes
fast that the sprite’s movements are it possible to see the sprite move
not visible. Nothing seems to happen. from right to left and back again.
Manipulating data
Programs are often used to manage and process data. This data
is either provided by the user or collected from other computer
systems. In Scratch, the Operator blocks are used to manipulate
numbers and text stored in variables.
Variables
Many programming languages use variables Strings
to store information. A variable can store one Programmers often call a piece of text in a
piece of information, either text or a number. program a “string”. For example, a string can
In a game, for example, two variables might be a name, an answer to a question, or an entire
be used to store the player’s name and score. sentence. In Scratch, any variable can store a
number or a string, and it can store different
Make a variable
1 To create a variable in Scratch, select Variables in the Blocks values at different times.
Palette and click on the Make a Variable button. Give the new
variable a meaningful name, such as score, so that the code is easy banana
join apple
to understand. Usually, variables need to be created for all sprites,
which means that all sprites can see and change the variable. Join strings
This block can be used to join two strings. The strings are
joined without a space, so the result for this example will be
“applebanana”. Variable blocks can also be used in place of
Make a Variable words typed into the block.
Check strings
This block checks whether the second string input is in the first
one, and gives the answer as true or false. It is also possible to
check for more than one letter: apple contains app?
SCRATCH
Manipulating data 42 43
LISTS
A list is used to store similar pieces of information,
such as a list of names. In Scratch, a list can be created
from the Variables section of the Blocks Palette. List
positions are used for inserting and deleting items. For
example, the delete 2 of [list name] block can be used
to remove the second item from a list.
say You didn’t beat the high score this time! for 2 seconds
Logic and
decisions
Programs can be made more flexible and useful
if they are coded to make decisions about what to
do next. They can use variables to control which
instruction to run, and when to run them.
SCRATCH
Logic and decisions 44 45
Combining expressions
Boolean expressions can be combined to make decisions
based on more than one factor. Here are some examples
using the current year Sensing block. It has a menu in it
to change the year to other time periods.
USING BOOLEANS
Boolean expressions can Using Booleans with loops
be used in other ways as The repeat until block repeats repeat until lives left = 0
well. Clicking on them in one or more instructions until
the Code Area allows users an expression is true. In this case,
the loop will keep going until the
to see their results while player has no lives left.
programming. They can also
be combined with repeat
Waiting using a Boolean
and wait blocks to make a Using a wait until block will pause wait until score = 50
program repeat or pause a script until an expression is true.
until something changes. However, it is often better to use a The program takes no
broadcast (see pp.48–49). action till the score is 50
Input
Sometimes programs need to receive information in order
to deliver a result, or output. Scratch has several ways
of getting input, including through key presses,
by sensing on-screen interactions, and by
asking users to type in information.
User interactions
Users can type information into
the computer, or use the keyboard
Types of input or mouse to provide movement or
There are a lot of different ways in which positioning instructions.
information can be entered into a computer
system for processing. In Scratch, input to a script
External information
is usually in the shape of a rounded block that Scratch can detect the username of the
contains some information, or a pointed block logged-in user, the current date and time,
that contains a Boolean expression (see p.44). and can get translations from Google
Translate using an extension.
change x by -10
Movement script
This script illustrates
how to move a sprite if key right arrow pressed ? then
under keyboard control,
using the arrow keys. It change x by 10
uses the pen to draw a
line as it goes, so it can
also be used as a simple
art program.
SCRATCH
Input 46 47
Collision detection
touching mouse-pointer ?
Video games often need to detect when two
objects touch each other, which can require tricky This block can be
calculations. However, Scratch has this capability mouse-pointer found under Sensing
in the Blocks Palette
built in. The touching mouse-pointer block has a
edge
drop-down menu that can be used to detect if a
sprite is touching the mouse-pointer, the edge of Sprite1 The drop-down menu lists
the screen, or another sprite. the available options
broadcast ouch
Adds a random delay
when clicked before moving
forever
Moves the
when I receive music on Butterfly
Ballerina Butterfly 2 Speaker sprite to the
glide 3 secs to Speaker Speaker
SCRATCH
Sending messages 48 49
2. When one sprite sends a
broadcast, it is picked up by
any sprite that may be
listening for that message
SENSIBLE MESSAGES
The default name for a broadcast message
in Scratch is message1, but this can be
renamed by the user. To make a program
easier to understand, it is advisable to change
the message to something relevant. The menu
in the broadcast blocks can be used to choose
a new message name.
MAIN SCRIPT
RUNS
OTHER SCRIPTS
CAN ALSO USE
THE FUNCTION
AT ANY TIME
SCRIPT
CALLS THE
FUNCTION
THE
FUNCTION
BLOCKS RUN
WHEN THE
FUNCTION ENDS,
THE MAIN SCRIPT
PICKS UP AT ITS
NEXT BLOCK
Random documents with unrelated
content Scribd suggests to you:
III.
ebookbell.com