BDM's Definitive Guide Series
mec Peet
Pei ae be Ke eet
Perc Le , aie a
ee 1 Ciena
fupct. ~3 3
baa : F a
bs Cie o “
"par ameter", word:c[g]
4TH EDITION 100% INDEPENDENTDiscover more of our
Complete Manuals today...
Qrer
WhatsApp ihe Mal
Manual
Uosalss
eyed tet etree)
ea Manual,
Discover how to turn your ideas into code
Programmingis everywhere. From clicking anicon on your desktop
and opening a web browser to calculating the vast distances
between the stars or flying through them in the latest video game.
It's one of the most important digital skills you can have in the
modern world and it’s only going to get bigger as we move into a
new generation of interconnected devices and mediums.
Starting to learn to code isn't easy but we're here to help you get
going, In the pages of this book you can learn how to start coding
using Python, C++, Linux scripting, FUZE BASIC with the Raspberry
Pi, Windows batch files and Scratch. We also cover the common
pitfalls and mistakes every coder falls into and ways to avoid them
in the future; also where you can find help and howto experiment
with your code.
We've put together a great collection of tutorials and step-by-
step guides to help you understand how to start coding and what
you need to tum your ideas into ones and zeros that will help you
become a better coder.
Learning how to code is an on-going experience, where you learn
something new every day and every time you run your code.
Come with us and let's start coding!
i eves
BDM Publications €) www.bdmpublications.com¢ ->image_ td.
a
dio); $re¥
a one
BEN ier
ra KG
1
ZZ
p Fae aan O=
function Perel anak a kell
ors Pees na
: Cran Me Le)
errr
neta_day","day_id =
Bye siniace Ante a4
Prem) Nh Galle ened
faehaeey
WAN
Ly
Pree eee cost
Sees
How to Set Up C++ in Linux
Other C++ IDEs to Install
ET ec una
Er menetnaciions
ei ace Ten (9g eee STR
TD. her Telegu sa eee
44
46
ia OC
NNT ae
20 Equipment You will Need eta ed
Ce Moma}
Fr st at en Installing VirtualBox
CENT aU eed Aeon eran
Stee IS iene es ecard
EMSC UCase een Ene aR cid
Ci ee
Cerra
Ereierd
fe Te Eee Lae
See
Ee eee a)—
ee
array();
tere
I Pa ONE ea an
Ota hake yal
en coe
ee
B
LOMRer tne Cee a cat Uae) Cee ns
be Sea cage) SC MeCcUn ELC eee
LS cea)
seo ea iced
LCM canteen
Sete eS or a
peri ce ca)
Deca)
ee ates Sree nr
CMa aa Penne a ees
86 Getting Started with FUZE BASIC Sera eee ue Nga cd
Cen Raa Sle aT 134 Global Variables and a Dice Game
ET men R ena ee ae See ee Lolo ted
Py Mes ena a-7 lee ee)
Co MEL By: “stele Benen Me co
Rae Dell ead rene ene et
eae ee ea Pree S
RM cys aC ee Le Lcd
" Q - SCC eee cada
He NA essed ca mr YS Se oes
Nee SU ald Meo gee tena
108 Getting Started with Batch Files re renee acted
110. Getting an Output cents
Cm rah Uc EM cd
Creme) STs eect
comitirieice ——BED ~- ing and Program! 0)
So you want to start coding? It's not
going to be an easy road, and there are
many pitfalls along the way, but learning
to programs an amazing skill and one
that will stand you in good stead for
the future.
‘One of the hardest steps in learning to
code is the first: which programming
language to learn. Then, where do you
0 to find the tools you need and what
do all those terms mean? Don't worry,
we're here to help you on your way.
Inthis section we look at what you need
to take those first tentative steps into
the world of coding.
8 Choosing a Programming Language
10 Learning to Code - Study Tips
42 Coding Tools and Resources
14 Being a Programmer
BENE) scene aes ancsnnCoding and.
BEN ay :Language
mod Tru
It would be impossible to properly -— Cian = Fal
explain every programming language in Oe bd Tt tate
Price aeaaissrom cider ss ‘_Mod . u: [1
Pe Remnicihe arc y Br ee) a
Re Mees Ess ae ec OE Leet) ee ct
cue Ruesaeen en hance mod.use_z = Try
Ceeee Meni Rant
complex methods are being born. Here
is a list of the more common languages
along with their key features.
da
Selected” + str(mod
Weirror_ob.select = @
» bpy.context. selecte
) objects[one-.name
ease select e
SES“sql SQL stands for Structured Query Language. SQLs standard language
For accessing and manipulating databases. Although SQLs an ANSI
{American National Standards institute) standard, there ae different versions of
the SQL language. However, to be compliant, they all support at least the major
Ronee eee eet errr aa
PCa ae JavaScript (often shortened to J) isa lightweight,
interpreted, object oriented language with Firs class
functions. JavaScript runs on the client side ofthe web, that can be used to design
or program how the web pages behave on the occurrence of an event. JavaScript is
Pee ee teen teh eae)
Rees
Pa Java's the foundation for virtually every type of networked
See eo eek eee ie
Pe ee eS
‘of the Java platform are the Java Application Programming Interface (AP!) and the
Bt nc ete ee ec re
Cee ee eer a eet)
build a variety of secure and robust applications that run on the .NET
Framework. You can use Ct to create Windows client applications, XML Web
eee eee ne ea
curly-brace syntax of C# will be instantly recognisable to anyone Familiar with C,
oer
cae Python is a widely used high level programming language used
for general purpose programming, created by Guido van
Rossum and first released in 1991. An interpreted language, Python has a design
philosophy that emphasises code readability and a syntax that allows programmers
Sere eae a eee eee ta
Beenie
core ecm te ote ton er ete er aur)
language. thas imperative, object-oriented and generic programming
Features, twas designed with a bias toward system programming and embedded,
resource-constrained and large systems, with performance, efficiency and flexibility
eter eee
Deere eee tc em Seems
‘Matsumoto, blended parts of his Favourite languages (Pert,
Sree eee rere et oer
Ruby has drawn devoted coders worldwide. Ruby is seen as a flexible language;
eee ee cae cad
eres
S ca Pe roea aa eee
ee ee ae
Seer Meee ata Met aot ded
See ere aoe ro eae conrad
Peeing ec EL acy
cere ener
aa ‘Swift isa powerful and intuitive programming language for macOS,
eel . otra prea eer tt
eee ese eee tat ete a eet
developers love. Swift code is safe by design, yet also produces software that runs
ences ee cn a ae>) Coding and Programming )
Learning to Code -
Study Tips
Programming is one of the most valuable skills you can pick up these days,
PCM Ree ecco cstsackenaetssrient kare)
create something cool too. When you're new to coding, it can be hard to know where
to start and it’s easy to get sucked down paths that could waste a whole lot of your
time and money. If you're just getting started on your coding journey, here are some
ivecdcek ae am Natalee esc
CHOOSE YOUR LANGUAGE LEARN WHAT BEING A CODER MEANS
Itmay sound obvious but Take some time to look atthe things coding languages are used for sof you
choosing the are interested in web design, look at how JavaScript i being used on the sites
Fight coding or ‘you use every day; if youare in to mobile aps, look ita Java or Swift and see
programming language to how they make apps work. It can also be useful and encouraging to check aut
start learning is important ‘what qualified coders can expect to get paid by looking at local job sites. We
iF you want the creative are not saying that ifyou learn to code Python you are immediately going to
process tobe successful. IF
you need learn to code Fora specific reason,
Finding ajob For example, then you obviously
need to lear the language that’s relevant. IF
‘you simply want to learn coding, then picking
‘language lke Python, that is both powerful
‘and relatively easy to learn, can make success
more likely
be offered a £70,000 a year job but t can help spur you onto study harder.
TU m= San eda elle
IF you are completely new to coding leaming any programming
language can seem like a huge task. Getting completely bogged
‘down in pages and pages of code examples and explanations
isnot tkely to make the learning process much fun. n our
‘experience itis often better to learn through practice, or to
‘choose atask you want to perform with code, and then work
backwards to learn how to complete that task. By learning small
‘chunks and repeating what you have already learned at differing
intervalsis called Spaced Repettion.
BET) 00 eve cate sen attonSET UP YOUR ENVIRONMENT
‘Take some time to look atthe things coding
languages are used For; so if you are interested
in web design look at how JavaScript is being
used on the sites you use every day iF you are
in tomobile apps, lookinto Java or Swift and see
how they make apps work. Itcan also be useful
‘and encouraging to check out what qualified
coders can expect to get paid by looking at
local jb sites. We are nat saying that if you
learn to code Python you are immediately
‘going to be offered a £70,000 a year job but it
canhelp spur you on to study harder.
t+ WS]6+0-a+]4 eo
Pome st Bor vrs
Doen|aaaaeo nm
Dyas aa colt cae)
IFat ll possible, thatis. Deadlines, although a part ofa
professional programmers life, can definitely hurt your
progress when inthe process of learning to cade. Ths is
( Learning to Code study Tes GE
Sagas ACS
‘Sometimes, though admittedly not always, tsa good idea to get a more
rounded view of computer science before you dig down into more specific
‘programming language study. There are several ree “Introduction to
Computer Science” courses available online, including a great one from
Harvard Univesity (va the wwwedx.org website). Another study tool that can
bbe useful isto play coding games. Two ofthe best of these types of learning
‘games are CodeCombat and CodinGame. Search online to find them
LEARN FROM OTHER CODERS
The Fantastic Stack Overflow is one of the best places to find
answers to problems and to ask your own questions to other
coders around the world. There are many other language-
specific Forums online but whichever site you pick, dont be
afraid to ask questions. You might find that others are a bit
snappy iFyou don't Follow the questioning rules of that Forum
but just Figure out what you did wrong and learn to ask better
uestions. Don't worry though, ask your questions, listen to
the answers and remember to thank people for thelr help,
remembering to come back when you are more experienced
and answer a few questions yourself if you can.
‘especially tre of selFimposed deadlines, nd at this point
they almost certainly willbe, as they can damage your
progress when not reached. Trying to rush through any stage
‘of learning to code will not do you any good, and may make
laterstages harder if you do not fully understand the basics.
wor bmpublcationscom {20M Definitive Guide SeriesCoding Tools and
Resources
Peeks Ana ae Mes ee N cule tee ute RuS eas)
commands. If you don't have the tools and resources needed to test and express that
language, you won't be able to challenge and refine your skills.
GITHUB
You can use GitHub to create a personal project
r you want to experiment with anew
gramming language or host your life's work
‘Any kindof File can be uploaded to GitHub but t's
designed particula les and ishugely
3. It provides access control and several
tracking feature
‘making itt
code in the world
TEXT EDITORS.
La
Eee
Ponte aT
eng
eS at
errr
‘BOM's Definitive Gude Series | 4th Edition( Coding Tools and Resources
HEROKU =
I you are developing a web app, you willneed to host it before
people can accessit, GitHub can host your code but that doesn't
‘mean that end-users wil be able to se the working app. This, . =
Iswhere a service like Heroku comes into its own, Heroku is 2
cloud platform that lets you build, deliver, monitor and scale
‘apps, the Fastest way to go from idea to URL, bypassing all those
infrastructure headaches. t makes the processes of deploying, —=
configuring scaling tuning, and managing apps as simple and
straightforward as possible, so that you can focus on what's most :
Important: building great apps that delight and engage customers.
INTEGRATED DEVELOPMENT
ENVIRONMENT
Integrated Development Environments, uniike text
editors, offer a complete coding envionment. This
‘makes it easier For some programming beginners to get
tocarins with a new language. Integrated Development
Environments also known as Code Editors, ae software
applications that provides comprehensive Facilities to
Computer programmers For software development.
An DE normally consists ofa source code editor, bull
automation tools and a debuoger. Most modern IDEs
have inteligent code completion.
(ne of our favourite IDE'sis Aptana Studio 3. Aptana
allows you to develop and test your entre web
application using a single environment. There's
‘support forthe latest browser technology specs
suchas HTMLS, CSS3, JavaScript, Ruby, Rails,
PHP and Python,
STACK OVERFLOW SNIPPETS
7 pees | mes St8CK Overflow Snippets a programming term for a small region of reusable source
———— isa question ‘code, machine code or text. Snippets are often used to clarify the
and answersite meaning ofan otherwise “cluttered! function or to minimise the
For professional _use of repeated code thats common to other Functions. Snippets
and amateur isa powerful application for Mac and Windows that stores the most
programmers. valuable pieces of code that you can reuse indifferent projects
Itsbuileand mary times. The main idea isto make the process of reusing as easy
a runby usersas__as possible to avoid wasting your valuable time on writing the same
part ofthe Stack code again. You can download the Snippets manager free from
Exchange network ttpy//snippets.me/.
of QBAsites. With
its users help,
the site i building a library of detailed answers to every question
about programming. This site isall about getting answers; t's not a
discussion Forum so there's no chit-chat. Good answers are voted Up
‘and ise tothe top and the best answers show up First so that they
are always easy to find
The key to getting the most from Stack Overflow is to focus on
{uestions concerning actual problems you have faced. Include
details about what you have tried and exactly what you're trying to
do, Tags make it easy to find interesting questions. all questions are
tagged with thelr subject areas. Each can have upto S tags, since a
uestion might be related to several subjects.
wor bmpublcationscomEee ene mmc Used oma eer Reveal oOo
Mitekerrecere MY Idea T ated Cee ener eRe Nc
game to a critical element on-board the International Space Station. How do you
become a programmer though?‘Times have changed since programming inthe ‘80s,
but the core values still remain.
Being able to follow a logical pattern and see an end
resultis one ofthe most valued skills ofa programmer.
enone!
want to be takes time, patience
poner ietcas
“ Being a Programmer Em”
MORE THAN CODE
For those of you old enough to remember the 80s, the golden era of home
‘computing, the world of computing was avery different scene to how itis
today. -bit computers that you could purchase as a whole, as opposed to
being in kit Form and you having to solder the parts together, were the stuff
‘of dreams; and getting your hands on one was sheer bliss contained within
2 large plastic box. However, it wasn't so much the new technology that
‘computers then offered, moreover it was the act that forthe first time
‘ever, you could control what was being viewed on the ‘elevision
Instead of simply playing one of the thousands of games available at the
time, many users decided they wanted to create their own content, their
‘own games; or simply something that could help them with their homework
‘or home finances. The simplicity ofthe 8-bit home computer meant that
creating something from a few lines of BASIC code was achievable and so
the first generation of home-bred programmer was born,
From that point on, programming expanded exponentially. It wasn't long
before the bedroom coder was a thing ofthe past and huge teams of
designers, coders, artists and musicians were involved in making a single
‘game. This of course led to the programmer becoming more than simply
‘someone who could Fashion a sprite on the screen and make it move atthe
press of akey.
Naturally, time has moved on and with it the technology that we use.
However, the fundamentals of programming remain the same; but what
‘exactly does it take to be a programmer?
‘The single most common trait of any programmer, regardless of what
they're doing, isthe ability to see a logical pattern By this we mean
‘someone who can logically Follow something from start to finish and
envisage the intended outcome. While you may not feel you're such a
person, itis possible to train your brain into this way of thinking. Yes, it
takes time but once you start to thinkin this particular way you will be able
to construct and follow code.
‘Second to logic san understanding of mathematics. You don't have to be
at a genius level but you doneed to understand the rudiments of maths.
‘Mathsis all about being able to solve a problem and code mostly falls under
the umbrella of mathematics,
Being able to see the big picture is certainly beneficial for the modern
programmer. Undoubtedly, as a programmer, you will be part ofa team
cof other programmers, and more than likely part of an even bigger team
(of designers, all of whom are creating afinal product. While you may only
be expected to create a small element of that Final product, being able to
‘understand what everyone else is doing willhelp you create something
that's ultimately better than simply being locked in your own coding cubicle.
Finally there's also a level of creativity needed to be a good programmer.
‘Again though, you don't need to be a creative genius, just have the
imagination to be able to see the end product and how the user will interact
with it.
‘There is of course a lot more involved in being a programmer, including
learning the actual code itself. However, with time, patience and the
determination to learn, anyone can become a programmer. Whether
you want to be part ofa triple-A video game team or simply create an
‘automated routine to make your computing life easier, i's up to you how
far to take your coding adventure!
sos tenets son=> Say Hello to Python.)
Python is one of the most popular
modern programming languages
available today. Not only is it easy
to learn and understand but also
remarkably powerful; and with just
a few lines of code you can create
something spectacular.
This section covers what you need
to get up and running with Python,
which version to install and use and
how to set everything up in Windows,
macOS and Linux. There’s a lot you
can do with Python and this is just
the beginning.
18 Why Python?
20 Equipment You will Need
22 Getting to Know Python
24 Howto Set Up Python in Windows
26 Howto Set Up Python on a Mac
28 Howto Set Up Python in Linux
30 Installing a Text Editor
BEET) scene ates ancsnSay Hello
to PythonWhy Python?
Seen ics ae curl cue tce sr eee cial
computer, and some still available For older 8 and 16-bit computers too. Some of
(ena ee tle. ee Melee ecole e le ieee mele CP ccm Te)
trap Rees M Nuon toi Gna ed
PYTHON POWER
Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee
hours, slaving over an overheating heap of circuitry to create something akin to magic.
‘These pioneers of programming carved their way into anew
Frontier, Forging small routines that enabled the letter’ to scroll
‘across the screen It may not sound terribly exciting to a generation
{that’s used to ultra high-defintion graphics and open world, multi
player online gaming, However, Forty-something years ago it was
blindingly brillant.
"Naturally these bedroom coders helped form the foundations for,
every piece of digital technology we use today. Some went on to
become chief developers for top software companies, whereas
others pushed the available hardware tots limits and Founded the
billion pound gaming empire that continually amazes us.
Regardless of whether you use an Android device, iOS device, PC,
Mac, Linux, Smart TV, games console, MP3 player, GPS device builtin
to car, settop box ora thousand other connected and smart’
appliances, behind them als programming.
‘Allthose aforementioned distal devices need instructions to tell.
them what to do, and allow them to be interacted with, These
instructions form the programming core ofthe device and that core
‘canbe built using a variety of programming languages.
‘The languages in use today differ depending onthe situation, the
platform, the device's use and how the device wil interact with ts
ee acct >:
‘Setcursor(p.y)2
certsichitsentFocust?
itleurgor >= 0)
ofreshnow(cureor)
aoe
Ure er
break
d
Siramatay
i
iMlcn"= 0)
BET 20 eine cae see atton
oid Arraycert::childLostFocust)
whitets < catcount()) ¢
Getiinev (3)
LilePeop etze.ey) breaks
Fitop t oeteinecy (als
js < colum.catcount(); jst) (
reader eotisomdenty ef:
weregrad "Lys
colum, cetcount() = 2)) >= 0)
Color fe = Blend(scoleroissbled, ScolorPaper:
ob;
< column, cetcaunt();
int be header GetTabusdtnth)s
int em = columip) marginsenvironment or users. Operating systems, such as Windows, macOS
{and such are usually a combination of C++, C#, assembly and some
Form of visual-based language. Games generally use C++ whilst web
pages can use a plethora of available languages such as HTML, Java,
Python and so on,
‘More general-purpose programming is used to create programs,
apps, software or whatever else you want to call them. Theyre
widely used across all hardware platforms and sult virtually every
conceivable application. Some operate faster than others and some
are easier to lear and use than others. Python is one such genera
purpose language.
Python is what's known as a High-Level Language, in that it talks
to the hardware and operating system using a variety of arrays,
variables, objects arithmetic, subroutines, loops and countless
‘more interactions. Whilst it's not as streamlined as @ Low-Level,
Language, which can deal directly with memory addresses, call
stacks and registers, its benefits that it's universally accessible
and easy to learn,
TPT: aveke. ava
import java. lang.reflect.*;
class tnvoke {
public Statte void main¢ string () args > {
eikae c = class.fornama( argef0l 3:
satleg' = Caetnethode OPS, hon lass
Sbjeck hee = minyoke( mull, mull >;
systen.out printinc
‘Stqvokee, static method: * + args[1]
of class: * + args{ol
with no args\nkesults: * + ret);
} catch ( Classnotroundexception e ) {
77 Class. fornane(”). can't find the class
} cach € NosuchMethodexception 2") {
77 that method doesn't exist
2 each’ ¢ TTlepataccessexception e3 ),{
77 we don'tshave permission to invoke that
method.
2 Gatch mocarionrargetexcept fon e4 ) {
‘an exception ocurred while Invoking that
inechod ack
Systen.out. print
yeesNethod threw an: " + ef
gettargetenception( *)')}
Javais a powerful language
that’s used in web pages, set-
top boxes, TVs and even cars.
wn bdmpublcationscom
7
(why Python? el
Python was created over twenty six years ago and has evolved to
become an ideal beginner's language For learning how to programa
‘computer. Is perfect For the hobbyist, enthusiast, student, teacher
‘and those who simply need to create their own unique interaction
between either themselves ora piece of external hardware and the
‘computer itself
Python i free to download, install and use and i avallable or Linux,
‘windows, macOS, MS:DOS, 05/2, BeOS, IBM iseries machines, and
‘even RISCOS. Iehas been voted ane of the tap Five programming
languages in the world andis continually evolving ahead of the
hardware and Internet development curve.
‘So to answer the question: why Pythor? Simply put, it's Free, easy to
lear, exceptionally powerful, universally accepted, effective and a
superb learning and educational tool.
BASIC was once the starter language that early
‘eit home computer users learned.
so rarer Lon a eta eee aa
Python isa more modern take on BASIC, i's easy to learn
and makes for an ideal beginner's programming language.
20M = Define Gudeseries|ahestion QE]=> Say Hello to Python.)
Equipment You
Will Need
Dole Means ene LCA SB YA ee Mn Ike IK ROM LAMA Ce Leen a Cot]
een seen er cele VA Co i cee UMA MU ear cet Tel
Liss
WHAT WE'RE USING
Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linux, Raspberry Pi and more. If
you have one of those systems, then you can easily start using Python.
COMPUTER
Obviously you're going to need a computer in order to learn how to program in
Python and to test your code. You can use Windows (fram XP onward) on either a 32
‘or 64-bit pracessor, an Apple Mac or Linux installed PC.
AN IDE
AnIDE (Integrated Developer Environment is used to enter and execute Python
code, It enables you to inspect your program code and the values within the code, a5,
Wells offering advanced features. There are many different IDES avalible, so find
the one that works For you and gives the best results.
PYTHON SOFTWARE
‘macOS and Linux already come with Python preinstalled as part of the operating
system, as does the Raspberry Pi However, you need to ensure that you're running
the latest version of Python. Windows users need to download and instal Python,
which well cover shortly.
TEXT EDITOR
Whilst atext editor is an ideal environment to enter code into, it'snotan absolute
necessity. You can enter and execute code directly from the IDLE but atext editor,
such as Sublime Text or Notepad +, offers more advanced features and colour coding
= when entering code.
INTERNET ACCESS.
Python isan ever evolving environment and as such new versions often introduce
new concepts or change existing commands and code structure to make it a more
efficient language. Having access to the Internet will keep you up-to-date, help you
lout when you get stuck and give access to Python's immense number of modules.
|_| TIME AND PATIENCE
Despite what other books may lead you to believe, you won't become a programmer
in 24-nours. Learning to code in Python takes time, and patience. You may become
stuck t times and other times the code wil flow Uke water. Understand you're learning
something entirely new, and you wil get there
EID 200s DeFintve Guide Series sth EstonTHE RASPBERRY PI
Why use a Raspberry Pi? The Raspberry Pisa tiny computer that's very cheap to purchase but offers the user a fantastic learning
platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many Modules and extras.
PS ag)
The Raspberry Pi 3 isthe latest version, incorporating a more
powerful CPU, more memory, Wifi and Bluetooth suppor.
‘You can pick upa Pi for around €32 or asa part ofkitFor £504,
depending on the kityou'e interested in
FUZE PROJECT
The FUZE is learning environment built onthe latest model
of the Raspberry Pi. You can purchase the workstations that
come with an electronics kitand even a robot arm for you
to build and program. You can find mare information on the
FUZE at www. Fuze.co.uk.
ne eae reet apie cceaeelnnet se
baimpucationscom Our P books cover how tb ou
fest Raspberry P
ieee aerator
fystepelec wanoesaed eal
eee eater
the Raspberry Ptoo
[7
The Raspberry P's main operating system isa Debian-based
Linux distribution that comes with everything you need in
2a simple to use package. I's streamlined for the Piand is an
ideal platform for hardware and software projects, Python
programming and even asa desktop computer.
wor bmpublcationscom DMs Definitive GudeSeries |«tnecition QJay
=> SayHello to Python )
Getting to
Know Python
uN eer ecole rec ae | Cute ka enec eter
SoA MUMIA en ae Ree Reo TMs (Ure enlace]
one TRI
WHAT IS PROGRAMMING?
It helps to understand what a programming language is before you try to learn one, and Python is no different. Let's take 3
look at how Python came about and how it relates to other languages.
aro]
PROGRAMMING RECIPES
‘A programming language
Programs are lke recipes For computers. A
recipe to bake a cake could go like this:
isa listof instructions that
‘a computer follows. These
instructions can be as simple
‘as displaying yourname
or playing a music ile, or
‘ascomplex as building 2
‘whole virtual world Python
isa programming language
conceivedin the late 1980s
by Guido van Rossum
Put 100 grams of selFraising flourin a bow
‘Add 100 grams of butter tothe bowl,
‘Add 100 mliitres of milk.
Bake for half an hour,
CODE
Just lke a recipe, @ program consists of instructions that you follow
Jnorder. A program that describes acake might run tke this:
‘at Centrum Wiskunde &
Informatica (CW) in the bowl = 1
Netherlands asa successor to flour = 100
the ABClanguage. [butter = 50
milk = 100 TE Stttaceiartetarnsiny
Guido van Rossum, the
Father of Python.
bon .append([flour, butter mic]
I cake. cookCbon)
PROGRAM COMMANDS
You might not understand some of the Python commands, lke bowL append and cake.cook(bowl)
The firsts alist, the second an object; we'l look at both inthis book. The main thing to know is
that it’s easy to read commands in Python. Once you learn what the commands do, i's easy to
Figure out how a program works,
soso ite ees honHIGH-LEVEL LANGUAGES
Computer languages that are easy to read are known as high evel
Thisis because they fly high above the hardware (also referred to as
like Assembly,
ne metal’, Languages that “fly close to the metal
‘are known 35 “low-level”. Low-level languages commands read a bit
ike thisimsg db ,@xa len equ $ = msg
PYTHON 3 VS PYTHON 2
ou eae et
rE e!
Created
WORLD OF PYTHON
pees
ee age eas
CE pet ise
ieee
frequent upd
PC Roe eure uy
PYTHON 2.X J
rir
od
eee
Cetera
Se eee ged
ramming languages For beginners and experts to code.
ee gs
wr bdmpubleaions.com
ZEN OF PYTHON
Python lets you ace
that humans can u
Zen of Pythor
influences the design ofthe language. Principles include “Beautiful
isbetter than uoly” an
import: this int
all the power ofa computer ina language
ferstand, Behind all this isan ethos called "The
Thisisa collection oF 20 soPeware principles that
‘simple is better than complex.” Type
Python and Iwill dsplay al the principles,
istence of two active versions of the language:
peers
PYTHON 3.x
re at
eee
nse enna ge ets
ean pe ten as
rt seas Pe ttn
eee
eee
Ca ens
ets
eee
ee tes
3.X WINS palueneeen
Cae
iththe
rot
Python 3 For snippets oF important=> Say Hello to Python.)
How to Set Up
Python in Windows
WO teat ne aicea eed enna aaa
Pla eree eMC uenee enon ararake Caeser eea nA iret tar
platform of choice For building their code, it’s still an ideal starting point for beginners.
INSTALLING PYTHON 3.X
Microsoft Windows doesn’t come with Python preinstalled as standard, so you're going to have to install it yourself manually.
Thankfully, i's an easy process to follow.
Start by opening your web browser to www.python,
ora/downloads/. Look For the button detaling the
Bis
«download link or Python 3.xx (in our case thisis Python 3.6.2 but as
‘mentioned you may see later versions of 3).
Click the download button For version 3x and
save the file to your Downloads folder. When the
fle is downloaded, double-ick the executable and the Python
installation wizard wil launch, From here you have two choices
Install Now and Customise Installation. We recommend opting for
the Customise installation link.
—
@
PU cesar tenn nonnens
windows Gasman rn
Gis
Install Python 3.6.2 (32-bit)
EXD 200s DeFntve Guide Series sth Eston
BETERER Choosing the Customise option allows you to
specify certain parameters, and whilst you may
stay with the defaults, it's a good habit to adopt as sometimes (not
‘with Python, thankfully) installers can include unwanted addtional
Features. On the fist screen available, ensure all boxes are ticked
and click the Next button,
Optional Features
deemeaatn
ml
Bn eee emtbrie
wind
a)
Siar)
The next page of aptions include some interesting
additions to Python. Ensure the Associate file with
Python, Create Shortcuts, Add Python to Environment Variables,
Precompile Standard Library and Install for All Users options are
ticked. These make using Python later much easier. lick install when
you're ready to continue.
‘Advanced Options
(acme fn fie py ae)
easier mtr re
wl
as —
wind me Ora earHow to Set Up Python in Windows
BED (erretocointensitaionsthtne — EEEEEB cing nett hors 325k
Mindowsstherscation notation Sry ce inne eigen ed ahem yacan git
Yes and Python wil begin to instal, Once the installation is complete your Python programming journey. Don’t worryifyour version
the Final Python wizard page will alow you to view the latest release _isnewer, as long as it's Python 3.x our code will work inside you
aeons
*
ticate the p
Again, click Yes to aut
installation window.
cess; then you can Close the
© Disable path lenath limit
Close
Saar oo | ERD eccreeete enim rntonvarin
much the same way as the Sell you opened in
dows 1Duserswilnow gm“ Step 8; nate te three leftfacing arrows (>>). Whitt’ perf
find the installed Python eee Fine environment, i's not too user friendly, so leave the command
3.x within the Star button ar tne For now. Enter: exitO) to leave and close the Command
Recently Added section. The
frstlnk Python 3.6 (32-6)
wll launch the command
ine version of Python when
dlcked (more on that ina
moment). To openthe IDLE,
ype IDLE nto Windows statWHAT IS
BERG Laeen ee cd
providing you various content:
LC
Coe a a ae ee
ee ee CCS eM Co [ooo
Unlimited satisfaction one low price
Cheap constant access to piping hot media
Protect your downloadings from Big brother
Safer, than torrent-trackers
18 years of seamless operation and our users' satisfaction
PRE to
Brand new content
elt et)
AvaxHome - Your End Place
We have everything for all of your needs. Just open https://avxlive.icuSay Hello to Python
How to Set Up
Python on a Mac
(ann Eur Cnc TT ers Acconci)
Weiao eae em Cmte ir Cet etichtinints)
aka Re
INSTALLING PYTHON
Apple's operating system comes with Python installed, so you don't need to install it separately. However, Apple doesn't
update Python very often and you're probably running an older version. So it makes sense to check and update first:
(pena new Terminal ng co Cickon he ates version of ython 3 in or
Ena Utilities, then double-click the Terminal icon. Now Sus) case this is the download button For Python 3.6.2.
ester python’ =-version voushouldsee"Pytion?.5.‘ and Ths wil avtomaticaly downoad the test version o Python and
even later, i Apple has updated the OS and Python instalation. 1g on how you've got your Mac configured, it automatically
Either way, i's best ta check forthe latest version. installation wizard
Spenstaandheadovertowwstnonce/ ERE Winte yon station ward open ikon
Pe downloads. Just as with the Windows set up Sues) the Continue button to begin the installation. It’s.
procedure on the previous pages youcansee two yelow dounload worth aking amomentto read trough he Important infermaton
ns: ane For Python 3.6.2, and the other For Python 2.7.13, section, in case it references something that applies to your version
that version numbers may be different due to the frequentThe next section details the Software License
Agreement, and whilst not particularly interesting
to most folks it's probably worth a read, When you're ready, clck on
the Continue button once again
Final you're be presented withthe amount of
Suid ‘space Python will take up on your system and an
Install button, wbichyou need to clk to starthe actual nstalaton
af Python 3xonto your Mac. You may need to enter yout pasword
to authenticate the instalation process.
The instalation should take to ong te older
uP Mac Mini we used in this section isa little slower
than more modern Mac maine andi on tock round hit
seconds forthe neato Sucesful prompt tobe delayed
wor bmpublcationscom
Ter’ noting mich le etn dante Python
SH) installation wizard so you can click the Close button.
you now crop backinto Terminal session andreente the
commanc python3. =-verston you can eethe ne versions
now std. To enter the commantine version oF Python, you need
Center python3 Toate exitO
You need to searchin Finder forthe Python IDLE
ui) when you've Found it, click it to launch and it
shoul lok ila to that the Windows DLE version shown on
the previous page The onl difference being the Mac detected
hardware platform ts uneing on
ese Pitan Sho
Pyar 3.6.0 (3.6.0414F926I1, bee 22 206, 1723-0)
GC 42 Conte inc. build S866) Cant 3) on aren
Toe ami races Yo ry norman.
Older Mac versions may have trouble with the
newer versions of Python, in which case you will
need to revert toa previous Python 3.x build; as long as you're using
Python 3.x, the code in this book will work for you.
Python 3.1.2 (r312:79360M, Mar 24 2010, 01:33:18)
{6ce 4.021" (apple inc. build 5493] on’darvin
Type "copyright", “credits” or "license()" for mo
Ee ineornation.
eeHow to Set Up
Python in Linux
SNC aie ua eee sent ea ee aCe AT
Ree eed nec ia imac kana kas
Thankfully, it’s not too difficult.
PYTHON PENGUIN
Linux is such a versatile operating system that it's often difficult to nail down just one way of doing something. Different
distributions go about installing software in different ways, so we will stick to Linux Mint 18.1 for this particular tutorial
PEPER Fistyounced to ascertain which version of Python PEM some Linux distros will automatically update
iscurrently installed in your Linux system; as we the instalation of Python tothe latest versions
‘mentioned, we're going to be using Linux Mint 18.1 forthis section. whenever the system is updated. To check, First doa system update
‘Aswith macOS, drop into a Terminal by pressing Ctr, and upgrade with
sudo apt-get update && sudo apt-get upgrade
fle Eat View Search Terminal Help Enter your passward and let the system do any updates.
Netra yon =-verstonixote Teno! ERE orci nde snd.
sue screen. You should have the output relating to SUES may need to answer 'Y’ to authorise any upgrades,
version 2x of ythoninthedsply. Ousinthisease Python enter python3.=-version tose itPython 3xis updated or even
aria installed. inthe case of Lox Min the version we haves Python
3.5.2, whichis fine for or purposes
daidedavdmint
File Edit View Search Terminal Help aE
srrHowto St Up Python inti
Hower Fouwantteitetveron 62aepe EIREAEB wine tron eer
eae the Python website at the time of writing, you need Sues ‘Jeonfiguee
Lobuldyten romance Sry eer tee conan Fesonfoies stan
‘This could alittle while depending on the speed of your computer,
Once Finished, enter: python3.6 ==versivon to check the
installed latest version
sudo apt-get install build-essential checkinstalt
sudo apt-get install libreadLine-gplv2-dev
LibncursesnS-dev Libsst-dev Libsqlite3-dev tk-dev
Libgdbm-dev Libc6-dev Libbz2-dev
Open up your Lin eb browser and goto EEE 2 2212 soenestoenerneotonrs
Suid the Python download page: www.python.org/_ S12? 9 command into the Terminal:
downloads Cickon the Download Python 342 (or whichever
version it’s on when you look) to download the source Python- SeOpISTERINSHOLNNTALES
Sezione The LE can thenbe stated with the command: idl @3.Note, that
DDLErunsa diferent verso rom the one you installed from source
@ python
Inthe Terminal, go the Downloads folder by | sTEP 10 You also need FAP (Pip installs Packages) whichis a
Suzry entering: ed Downloads/. Then unzip the SHEP tool to help you install more modules and extras.
Contentsof the downloaded Python source code with: tar =xvF) Enter sudo apt-get install. python3-pip
Python-3.6.2. tar.xz, Now enter the newly uneiped folder . i:
EE PPPs then installed: checkfor the atest update with
pip3 install --upgrade pip
‘When complete, close the Terminal and Python 3 willbe available
via the Programming section in your distro’s menu.=> Say Hello to Python.)
Installing a
Text Editor
Tee ae Ces Ld esp te Tete ean Ne
Cuan AW NN ol RA Keele OOM Rem eT ke)
unique characters, paragraph settings and much more, so it’s not a good platform For
eye keels(
SUBLIME CODE
Sublime Text is an excellent, cross-platform text editor that's designed for entering code. It hasa slick interface, many
Features and performs magnificently. In short, it's an ideal starting point.
Lets begin by navigating tothe Sublime Tee
sa?) webpage, to download the latest version for
whatever operating sytem youre current runnin. Youcanfind
the website at wwwsublimetext.com, together with a download
button for the detected 0S that you're using
Sublime Text
‘However, iF you want to specify a particular
sure ‘operating system version, then click on the
Download Ink Foundinthe topmenu baron the ste, Tis wil open
{page with links For the latest version for OSX, Windows, Windows
{64-bit and Linux machines.
Sublime Text 3
Download
EDD eortsbetintive cute series sth tion
whichever version you choos, download the setup
SUa?e) files and double-click them to begin the set up
proces. youre usng Windows which we are inthis instance, then
you see the standard installation wizard, The defaults wil suffice, so
‘go ahead and install the program.
Welcome to the Sublime Text 3
Setup Wizard
arena oto om ear oe
cet ctr Cnal nent Sep
when stale Subime defaults tos Black
suaPs) ‘background and white text; whilst this is perfectly
Fine Formos user, snot aay he most comfortable Vewing
‘setup. Thankfully, there are countless themes you can apply by
Clcking Preferences» Colour Scheme, Weve optedForiDLEIn
thiscreenshotInstalling a Text Editor el
iG 19
Sublime Text offersome excellent estes over
eae that of the standard Python IDLE. For example,
enter the flowing
print (Hello everyone!)
‘Thisisan actual Python command, which will print the words
Hello everyone! on the screen, Notice how Sublime automatically
recognises this as code and places the quotes and parentheses.
suid that the standard IDLE isn’t quite up to the task
af keeping up wth your code alterations andinecton of code
tna through along progra However, Sublime wl keep you
Updated and you can evens indents ea
we're not going to getto heavily inthe
uP code right now but an indent is part of Python
programming, where astatementicatesthat the Falling
Indented commands mustbe rn nti a partcular even hs
appened after hich the nets top, Pressing Ce] wiindent a
Une oF codein Fehon,
wor bmpublcationscom
Soon, as you become more Python-savvy, youll find
However, we recommend you us the ILEto
sua begin with. Although the Python IDLE isn’t as.
chanced a Sublime fs a perfect aceon wien to buld your sls
‘Once you've mastered Python, andthe way it works, you can move
‘ontoa text editor forthe better Features
FEED svbiime isnt just for Python ether. wth t you can
build code for a number of programming languages.
Click on Tools > Build System to see which languages you're able to
build wth in Sublime.
FEE siincconcuanonmie eves
this point n ime but you wil ikely find them useful as your Python
skills increase.
‘AP Reference
eeMY SayHellotoC++ )
C++ is an amazing programming
language. Most of what you see in
Front of you when you power up your
computer, regardless of whether
you're using Windows, macOS or
Linux, is created using C++. Being able
to code in C++ opens up a whole new
world for you in terms of desirable
professional skills and the ability to
code amazing apps and games.
C++ is an efficient and powerful
language that's used to develop
operating systems, applications,
games and much more. It’s used
in science, engineering, banking,
education, the space industry etc.
We're here to help you take your first
steps into the world of C++ and get
your First Few lines of code up and
running.
Why C+?
Equipment You will Need
Getting to Know C++
How to Set Up C++ in Windows
How to Set Up C++ on a Mac
How to Set Up C++ in Linux
Other C++ IDEs to Install
RRESBRE
OM Definitive Guide Series sth Eston=> Say Hello to C+ +»)
Why C++?
eee gas Cr cc eateries let ACHE
Palko Kee ecoem acute Ie ere me eM eeu etcisrnogaty
rene enter ce ue ure tieke yeni nerl eo kn
C EVERYTHING
Due to how complex the language can be, and its power and performance, C++ is often used to develop games, programs,
device drivers and even entire operating systems.
Dating backto 1979, the start ofthe golden ere of home
‘computing, C++, or rather C with Classes, was the brainchild of
Danish computer scientist Bjame Stroustrup while working on his
PhO thesis. Stroustrup's plan was to Further the original C language,
which was widely used since the early seventies.
C++ proved to be popular among the developers ofthe 80s,
since it was a much easier environment to get to atps with and
‘more importantly, it was 99% compatible with the original ©
language. This meant that it could be used beyond the mainstream
‘computing labs and by regular people who didn't have access tothe
mainframes and large computing data centres.
‘C#4'simpactin the digital world is immense, Many ofthe programs,
applications, games and even operating systems are coded using
‘Cr For example, all of Adobe's major applications such as
Photoshop, InDesign and so on, are developed in C++. You will find
that the browser you surf the internet with is written in C++, as
‘well as Windaws 10, Microsoft Office and the backbone to Google's
search engine. Apple's macOS i written largely in C++ (with some
G cvs nerontattiton
1] #include
2 | using namespace std;
3 | void main()
4 |Dchar ch;
5 cout<<"Enter a charater to check it is vowel or not";
6 cin>>ch;
7 switch (ch)
8 10 (
9 case'a': case'A':
10 cout< Say Helloto C++ )
Equipment You
Will Need
Soiree Men eu ema aad eee hat
don't need an entire computing lab at your disposal either. Providing you have a fairly
modern computer, everything else is Freely available.
C++ SETUPS
Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linux, Raspberry Pi and more. If
you have one of those systems, then you can easily start using Python.
COMPUTER
Unless you fancy writing out your C++ code by hand on a sheet of paper (which is
something many older coders used to do), then a computer is an absolute must have
component. PC users can have any recent Linux distro or Windows OS, Mac users the
latest macos,
AN IDE
‘As with Python, an IDE is used to enter and execute your C++ code. Many IDEs come
oe
with extensions and plugins that help make t work better, or add an extra level of
[<=] Functionality. Often, an IDE will provide enhancements depending on the core OS
being used, such as being enhanced For Windows 10.
pe
_
COMPILER
Acomplersarogamthat ion the C+ ngs binary thatthe
Gnu cr unestona Whe soe scone who comoer atm thers
dort Cols sour notre tha come wv rs compl ae the
pase Moreonths ater
TEXT EDITOR
‘Some programmers much prefer to use atext editor to assemble their C++ code
before running it through a compiler. Essentialy you can any text editor to write
code, just sve it with a.cpp extension. However, Notepad++ is one of the best code
text editors available,
INTERNET ACCESS.
‘While it's entirely possible to learn how to code on a computer that’s not attached
tothe Internet, it's extraordinarily difficult. You will need to instal the relevant
software, keep it up to date install any extras or extensions, and look for help when
coding. Allof which require access to the Internet.
TIME AND PATIENCE
Yes, as with Python, you're going to need to set aside significant time to spend on
learning how to code in C++. Sadly, unless you're a genius, i's not going tohappen
‘overnight, or even a week. A good C++ coder has spent many years honing their
craft, sobe patient, start small and keep learning
ERD vorrsbetintive Gude series sth tion(“Equipment You will Need
OS SPECIFIC NEEDS
‘C++ will work in any operating system, however, getting all the necessary pieces together can be confusing to a newcomer. Here's
some OS specifics For C+.
DNL NEy
‘Aswe've mentioned previously, a oad IDE Is Microsoft's
Visual Studio. However, a better IDE and compilers
Code:Blocks, which is regularly kept up to date with a new
release twice a year, or so. Otherwise Windows users can
enter their code in Notepad++ then compile it with MinGW ~
which Code:Blacks uses,
ray)
Linux users ae lucky in that they already have a compiler and
text editor butt into their operating system. Any text editor
will alow you type out your C++ code, when it’s saved with a
_epp extension, use g¢+to compile it.
fl RASPBERRY PI
The Raspberry P's operating
system is Raspbian, which
isLinux based, Therefore,
you're able to write your code
‘out using a text editor, then
compile twith g++ as you
would in any other Linux distro
MAC
Mac owners will need to
download and install Xcode
tobe able to compile their
C++ code natively. Other
‘options For the macoS
include Netbeans, Eclipse o
Code:Blocks, Note: the latest
Code:locks isn't available for
Mac due toa lack oF
Mac developers
\s
|i
wor bmpublcationscom DMs Definitve Gudeseries|«hestion.
=> Say Helloto C++ )
Getting to Know C++
eee E LC cu CUM ACR eee Tce cee
or work at the cutting edge of science or engineering technology, then being able to
code in C++ is a must. Remember, you're never too old to learn how to code.
#INCLUDE
Learning the basics of programming, through Python for example, enables you to understand the structure of a program. The
‘commands may be different, but you can start to see how the code works.
#INCLUDE = *newcode.cpp (-/D
neduavectaceecoan eaten ene eee
ene ecyerene” (Ate se | yon | 3
‘<> The directive instructsthe "| *newcode.cpp
‘section of the standard C++ #include
input/output operations.
CH
C++ was invented by Danish
student Bjarne Stroustrup in
1979, asa part of his PhO
thesis. nitially C++ was called
with Classes, which added
Features tothe already popular
C programming language,
while making ita more
User-friendly environment.
Bjame Stroustrup, inventor
OF C++,
INT MAIN() . *newcode.cpp (~/D
int main) initiates the Fae eave cenretiarceenbecees een fiecs
declaration ofa Function, which
ieee
function, regardless of whereit "| *newcode.cpp |
#include
int main()
BRACES . *newcode.cpp (-/Documents) Z
The openbrace’s File Edit View Search Tools Documents Help
something that you may
nothave come across
evel Oe) >| xeelas
viedo Python The
opentraceindcatesthe ) fneweodecpp x
begining the man
fancon and contain al
the code that belongs to
that function, int main()
{
soso ite ees hon
#include COMMENTS
Lines that begin with a double slash are comments. This means they
won't be executed in the code and are ignored by the compiler, Why
are they there? Comments are designed to help you, or another
‘programmer looking at your code, explain what's going on, There
‘are two types of comment: * covers multiple line comments, // a
single ine,
ss snamcode pp -PDecuments
Fle Eat View Search Toots Docent: Help
Boa -~ xomjag
fe) revcodecap %
leinctude
‘int main()
1 My First Cos program!
Std:teout << (HELLO World!\n")
STD
while std stands for something quite different, in C+ it means
‘Standard. I's a part ofthe Standard Namespace in C+, which covers
‘a number of ifferent staterents and cornmands. You can leave
the std part out ofa code, but it must be declared atthe start with:
using namespace std
= sneweode.cpp -/Decuments)
File Edt View Search Tools Documents Help
Boaln~/yaonjag
snancode cpp ®
include
using nasespace std;
int main()
{17 rst Coe progrant
COUT
Inthis example we're using cout, which isa part of the Standard
"Namespace, hence why t's there, as you're asking C++ to use irom
that particular namespace. Cout means Character OUTput, which
displays, or prints, something to the screen. IFwe leave std: out we
have to declare it atthe start of the code, as mentioned previously.
. *newcode cpp -/Decuments)
File Eat View Search Tools Documents Help
Aoan~ yoo ag
(e) *newcodecpp x
#include
int main()
£
11 My first coe progeamt
Std: fcout
wor bmpublcationscom
OUTPUTS
Leading on, the ("Hello World!) part is what we want to appear on
the screen when the code is executed. You can enter whatever you
lke, as long asits inside the quotation marks. The brackets aren't
needed but some compiles insist on them, The \n partindicates a
new line is tobe inserted
11 My first C++ program!
Std: teout <¢ (°HeLLo World! \a")]
; AND}
Finally you can see that lines within a Function cade block (except
comments) end with a semicolon. This marks the end ofthe
statement and all statements in C++ must have one at the end or
the compiler wil fall to build the code, The very last line has the
closing brace to indicate the end of the main Function,
ee:
Getting to Know C++ ea.
=> Say Helloto C++ )
How to Set Up
C++ in Windows
Me ene Rea eee Or ec Reema
are loads of IDEs and compilers available, including Visual Studio From Microsoft.
However, in our opinion, the best C++ IDE to begin with is Code::Blocks.
CODE::BLOCKS
Code:Blocks is a free C++, C and Fortran IDE that is Feature rich and easily extendible with plugins. It’s easy to use, comes with
2 compiler and has vibrant community behind too
BARD Ser by istiatne code:stcsdounioadste at ATED) when youve oatedthe fleck onthe
wonw.codeblocks.org/downloads From there, Sourceforge.net ink atthe end ofthe line and a
onthe Dounicad tne bnay recess Inktobetlentthe atest ownondntfeton wow sopests ck on sove Fl fost
downloadable version for Windows. the download and save the executable to your PC. Locate the
downloaded Code:Blocks installer and double-click ta star. Follow
. << the on-screen instructions to begin the installation
Welcome to CodeBlocks Setup
Seng nl ge you trough eaten Cote
Rereommended tec sete ete
jueves psa uote
‘Seve ynon detest wre
ERE There you conse, there are several Windows COnceyouageetothe ening ters, ache of
Veron aalable The oneyou want to downoad instalation options becomes able Youn opt
hasmingwsetupere atthe end fhe cureneveion number at forasmarinstal, ising ut on some othe components bur we
thetime of wring this codeblcks1712mingwsetupexe The recommend that oop forthe ul option as efat
differences that the mingw-setup version includes a C++ compiler
{and debugger from TDM-GCC (a compiler suite).
a
—— =
nn ss Sapte mune organs yout nat 2
nent “seep chet RSA oi kg
name we! | qrecttewtel — pociat a
nenenaenae a=) | re | $lcmnrin
: ret (Pescara
a se nye tp Me agente lessccvet
Peet ate Snrenrd: 25488
ET evr beFnive Guide Series sth Eston(_ How to Set Up C++ in Windows em”
Next choos an instal acation fr te Codes Blocks
Susp files. t's your choice but the default is generally.
sufficient (unless you have any special requirements of course).
twhenyou cick Net the ntl begins when’ nshed 2
netifation ppsup ating youl you want start CodeBlocks now,
socks.
==
crate rt Ler i tc anny curso er rae
[eae
Banco *
Sere oit7
er
Sead ett ~ i
ur fe : vr
Seat nora C awa eas aco nda
ores
ESTEE The Fisttime CodeBlocks loadsitruns an auto:
detect For any Cr+ compilers you may already have
installed on your system. I you don't have any, click onthe
First detected option: GNU GCC Compiler and click the Default
button to setit as the systems C++ compiler. Click OK when you're
ready to continue.
iebitieeeceraensetccect
FEPISED) The program starts and another message appears
informing you that Code::locksis currently not
the default application for C+ files. You have two options to leave
{everything ast sor allow. Code:Blocks to associate all C++ fle
types. Again, we would recommend you opt forthe last choice, to
‘associate CodeBlocks with every supported file type.
wor bmpublcationscom
Inthe new window, enter the Following
#include
Int main)
{
7My frst C++ program
Std: scout << “Hello World!\n";
E
Notice how Code:locks auto-inserts the braces and speech quotes.
FETSETR ick File> Save as and save the code with a
Epp extension (hellowarld.cpp, For example).
Code:Blocks changes the view to colour code according to C++
standards. To execute the code, click on the Build and Run icon
‘along the top of the screen. l’sa green play icon together with 3
yellow cog..
=> Say Helloto C++ )
How to Set Up C++
ona Mac
neta eased PIMs ne Mee CN creel Mccain
(ected ere eee okt ene Ney ee ee rt ene eli
used to create C++ code relatively easily.
XCODE
Apple's Xcode is primarily designed for users to develop apps for macOS, iOS, tvOS and watchOS applications in Swift or
Objective-C, but you can use it For C++ too.
FETTER 2tby opening the App Store on your Mac, Apple
"Menu > App Store nthe Search box enter Xcode and
ress Return, There will be many suggestions Filing the App Store
‘window butts the Fist option, Xcode, that you need to click on
ERTeEED When you're ready, click on the Get button which
then turns into ‘install Ap’. Enter your Apple ID
‘and Xcode begins to download and install It may take some time
‘depending on the speed of your Internet connection.
FE es onexicvinsancuninews
EDD) eons DeFntive Guide Series sth Eston
ESTEEM When the installation is complete, click on the Open
button to launch Xcade. Click Agree tothe licence
terms and enter your password to allow Xcode to make changes
tothe system. When you've done that, Xcode begins to install
‘additional components,
Xcode a(How to Set Up C++ on a Mac ea
eeennngrouintstedincdesthe EEA tense stewheretocentesGtResestn
Susp additional components, Xcode launches, displaying Bue) for all your Future code. Choose a location on your
theverson number along wth tee chokesandary recent projets Maco anetworlocato, nck the Crete utton hen
thetyulveworked on athoughforaeshintal the showsblanke you've oneal that you cantar to code The efthan pane
‘details the files used in the C++ program you'e coding Click on the
main.cpp file inthe list
a
‘Welcome to Xcode
=
‘
i
FETED St2rtby clicking on Create New Xcode Project; this ENSIIEM Youcan see that xcode has automaticaly
‘opens a template window From which to choose the completed a basic Hello World program for you
platform you'te developing code for. Clickthe macOS tab, then the The differences here are thatthe int main (function now contains
‘Command Line Tool option and finaly, Next to continue. multiple Functions and the layout i slightly different. This s ust
oo Xcode utilising the content that’s available to your Mac.
FETE EE AD lin the various fields but ensure that the PEPE when you wantto run the code, click on Product >
Language option atthe bottom i set to C++. Simply un, You may be asked to enable Developer Mode
choose it from the drop-down list. When you'efiledinthe fields, on the Mac; thisis to authorise Xcode to perform functions without
‘and made sure that C++ isthe chosen language, clickon the Next’ _ needing your password every session, When the program executes,
button to continue, the output is displayed at the bottom of the Xcode window.
sete)
setingeszon ee:.
Say Helloto C++ )
How to Set Up C++
in Linux
tare Nexen Reel Teun ea ora eae ere CCN Ley
essential components preinstalled, such as a compiler and the text editors are
ea (na come Ree MoM ale Reol ol Reels Me MU Cee elcome er]
Sol iaW REVEL C CHM hotell at
LINUX++
We're going to be using a fresh installation of Linux Mint for this particular tutorial, More on Linux Mint can be found in the
next section of the book.
PEPE the fiststep with ensuring Linuxisready foryour — FEB Amazingly that'sit. Everything sall ready for you
Cr code is check the system and software are tostart coding. Here's how to get your First C++
Lup to date. Open a Terminal and enter: sudo apt-get update program up and running. In Linux Mint the main text editor is Xed
8& sudo apt-get upgrade. Press Return and enter your ‘ane launched by licking an the Menu and typing Xed into the
password. These commands updates the entire system and any _—_search ba. Click on the Text Editor button inthe right-hand pane to
installed software, ‘open Xed.
File Edit View Search Terminal Help
PEPER) ost Linux distros come preinstalled with allthe EEE |” X2d, or any other text editor you may be using,
necessary components to start coding in C++ enter the lines of code that make up your C++ Hello
However, is always worth checking to see iF everything s present, World program. To remind you its:
sostill within the Terminal enter: sudo apt-get install
build-essential and press Return. you have the right
components, nothingisinstalled but iF you're missing some then int. main)
they are installed by the command, i
#include
: My first G++ program
waa std::cout << “Hello World!\n”;
Ent maint
Upmy tat Coe program
Star cout << “welt wort \o"
>
eosin ttt onHow to Set Up C++ in Linux
The esthingyou can se that ied has
SUS automatically recognised this as a C++ file, since the
fle extension now set. cpp The colour coding i resent nthe
Cote andi you open up the le manager you canals see that the
Fes conhas Grr stamped on
PEPTIED) With your code now saved, drap into the Terminal
again. You need to navigate to the location of
the C++ file you've just saved. Our examples in the Documents
Folder, so we can navigate to it by entering: ed Documents.
Remember, the Linux Terminals case sensitive so any capitals must
be entered correctly.
FETS Before you can execute the C++ file you need to
compile. In Linux t's common to use g++, an open
source C++ compiler and as you're now inthe same folder as the
Ci file, go tothe Terminal, enter: g++ helloworld. cpp and
press return
. davidemit
File Edit View Search Terminal Help
rrr
roomates
Porras
‘There willbe a brief pause asthe code is compiled
bby g++ and providing there are no mistakes or
‘errors inthe code you are returned to the command prompt. The
‘compiling of the code has created a new file, you enter Us into the
Terminal you can see that alongside your C++ files aout.
: davide
Fle Edit View Search Terminal Help
rer
Documents § ts
emer
roy
FEET RD te acutfileisthe complied C++ code. Torun the
code enter: /a.out and press Return. The words
Hello World appears on the screen, However, a.cutisntvery friendly
‘To1name it something else post-compiling, you can recompile with:
gt+ helloworld.cpp -0 helLoworld. This creates an output
file called heloworld which can be run with: /heLLowor',
File Edit View Search Terminal
az
Help
Pesan
Documents $
wor bmpublcationscom
Fle Edt View Search Termin! Help
[8DMs Definitive Guide Seis | sth tionOther C++ IDEs to Install
ACM TS CCT clone R Neem Aer
plenty of options available to you. Windows is the most prolific platform for C++ IDEs
but there are plenty for Mac and Linux users too.
DEVELOPING C++
Here are ten great C++ IDEs that are worth looking into. You can install one or all of them if you like, but Find the one that
works best For you.
ren Ste Eclnseis a hugely popular C++ IDE that offers FRSTEMTTER odelite isa free and open source IDE that's
the programmer a wealth of Features, has a regularly updated and available for Windows,
‘great, clean interface, is easy to use and available For Windows, Linux and macOS. t's lightweight, uncomplicated and extremely
Linux and Mac. Head over to www.ecipse.org/downloads/ to powerful. You can find out more information as well as how to
download the latest version. If you're stuck, click the Need Help link download and istallit at www.codelite.ora/.
for more information,
FAA The GNAT Programming Studio (GPS) isapowerful — NPEESSRNNERS Another popular choice is NetBeans. This
‘and intuitive IDE that supports testing, debugging |s another excelent IDE that's packed with
and code analysis. The Community Edition is Free, whereas the Features and a pleasure to use. NetBeans IDE includes project based
ro version costs; however, the Community Editionis available for templates for C++ that give you the ability to build applications with
\windows, Mac, Linux and even the Raspberry PiYoucanfinditat dynamic and static libraries. Find aut more at www.netbeans.org/
wwrwaadacore.com/downtoad. Features/cpp/index.html.
ETD corr beFnve Guide Series sth Eston(Other C++ IDEs to install el
\
RTE OR) Microsoft's Visual studioisa
mammoth C++ IDE that allows you
to.create applications for Windows, Android, iOS and the web. The
Community version is Free to download and install but the other
versions allow 2 ree tral period, Go to www.visualstudio.com/ to
see what itcan do For you.
ESRD Ths ross platform DE s designed to
create C++ applications For desktop and
‘mobile environments. Itcomes with a code editor and integrated
tools For testing and debugging, as well as deploying to you chosen
platform, i's nat free but there sa trial period an offer before
‘requiring purchasing: www.at-io/at-Features-libraries-apis-tools-
andide/.
Bloodshed Dev C++, despite its colourful name,
isan older IDE that is for Windows systems only.
However, many users praise its clean interface and uncomplicated
\way of coding and compiling. Although there's not been much
updating for some time, i's certainly one to consider if you want
something cifferent: www.bloodshed.net/devcpp html
wor bmpublcationscom
The Anjuta Devstudio ia Uru ony DE that
NUTS Features some of the more advanced features you
would normally dina pad software development tudo, Theres
‘8 GUI designer, source ecitor, app wizard, interactive debugger and
much more, Go to wwwanjuta.ora/ For more information
a ane Ts excellent IDE allows developers
towrite C++ code For desktop and
‘web applications across all the major platforms. There's an advanced
text editor, integrated debugger and a configurable workbench to
help you create your code. I's available for Windows, Mac and Linux
ands ree to download and use: www.monodevelop.com/.
Ultimates isa cross:platform C+ IDE that boats @ rapid
development of code through the smart and aggressive
use of C++. Forthe novice, it'sa beast of an IDE but behind its
complexity is a beauty that would make a developer's knees go
‘wobbly. Find out more at www.ultimatepp.org/index.htmL
eeCoding on Linux
|
Linux is such a versatile operating
system and is both malleable
and powerful, while offering the
programmer a perfect Foundation
‘on which to build their skills. Linux
scripting in particular is a highly
prized skill with employers at the
moment and learning to master it and
the operating system will certainly
enhance your future job prospects.
Scripting is an amazing interface to
the Linux system, so we've crafted this
section to help you get to grips with
how everything fits together, and how
to make some amazing Linux scripts.
50 WhyLinux?
52 Equipment You will Need
54 Transfer Mint to DVD or USB
56 Installing VirtualBox
58 Testing Linux Mint’s Live Environment
60. Installing Linux Mint on a PC
62 Installing Linux Mint in VirtualBox
64 Getting Ready to Code in Linux
66 Creating Bash Scripts—Part 1
68 Creating Bash Scripts—Part 2
70 Creating Bash Scripts —Part 3
72__Creating Bash Scripts —Part 4
74 Creating Bash Scripts - Part $
76 Command Line Quick Reference
78 AZof Linux Commands
BEE) 20sec onCine
Coding
on
Linux
tCoding on
Why Linux?
Many developers, across all the available programming languages, use Linux as
EIR arlene ecu Mace me meee MOET nc eae Ua PARA TN
advantages over other systems and while it also has some quirks, it makes for a great
place to learn to code.
FREE AND OPEN
Linuxis a Fantastic fit For those who want to develop multi-platform code. The efficiency of the system, the availability of
applications and stability are just a Few good reasons.
‘The First thing we need to address is that there iso such operating
system called Linux. Linux in Fact the operating system kernel, the
core component of an OS. When talking about Linux what we, and
‘others, are referring to are one of the many distributions, or distros,
that use the Linux kemel No doubt you've heard of atleast one of
the current popular distros: Ubuntu, Linux Mint, Fedora, openSUSE,
Debian, the list goes on. Each one of these distros offers something
ait different forthe user. while each has the Linux kernel at
itscore, they provide the user with a different looking desktop
environment, different preloaded applications, different ways in
\which to update the system and get more apps installed and a slightly
different look and feel throughout the entre system. However, at
the centre lie Linux whichis why we collectively say, Linux
Linuxis a great operating system in
hich to start coding.
re ta oe arr tw ey POS Oe Kee ae
BD | o
er
BET) 20 eve cae see atton
Linux works considerably differently to Windows or macOS. I's
Free fora start, Free to download, install on as many computers as,
{yu lke and use For an unlimited amount of time. It's also free to
upgrade and extend using equally free programs and applications,
This Free to use element is one of the biggest draws for the
‘developer, While a Windows license can cost up to €100 and a Mac
‘one considerably more, a developer can quickly download a distro
{and get to work coding in a matter of minutes.
‘Alongside the free to use aspect comes a level of freedom to
‘customise and mould the system to your own use. Each of the
‘avaliable distros avallableon the Internet have a certain ‘spi’,
in that some offer increased security Fancy looking desktop, a
sama: || a‘gaming specific spin or something directed towards students. This
extensibility makes Linux a more desirable platform to learn coding
‘on, as you can quickly shape the system into a development base,
including many different kinds oF IDEs forthe likes of Python, web
development, C++, Java and soon,
‘Another remarkable advantage is that Linux comes with most of
the popular coding environments builtin, Both Python and C++ are
preinstalled in a high percentage of available Linux distros, which
‘means you can startto program almost as soon as you install the
system and boot it up for the first time.
Generally speaking, Linux doesn't take up as many system resources
‘as Windows or macOS. By system resources we mean memory, hard
drive space and CPU load; the Linux code has been streamlined and
is Free from third-party ‘bloatware’ which hogs those systems
resources. A more efficent system of course means more avaliable
resources forthe coding and testing environment, and the programs
you eventually create. Less use of resources also means you can use
Linux on older hardware that would normally struggle or even refuse
torun the atest versions of Windows or macOS, So rather than
‘rowing away an old computer, it can be reused with a Linux distro
‘There are thousands of free packages
available for programmers under Linux.
However t'snat all about C++, Python or any of the other more
popular programming languages. Using the command line of Linux,
‘also called the Terminal, you're able to create Shell scripts, which are
programs that are designed to run from the command line and are
made up of scripting languages. They are used mainly to automate
tasks or offer the user some Form of input and output For a certain
‘operation, They are surprisingly powerful and we look at how to
create them within this section,
Finally, although there are many more advantages to list, there
{are thousands and thousands of free programs and apps avaliable
that cover near every aspect of computing, Known as packages,
there are (atthe time of writing) over 8,700 specific programming
applications just for Linux Mint alone
Linux therefore, is a great resource and environment For
programming in. ts perfectly suited for developers and is
continually improving and evolving, IF you're serious about getting
into coding, then give Linux a try and see how it works For you
&. 8 = aan
Ql Mandriva slackware
s © @ 2
Each distro offers something unique to the
user but all have Linux atthe core
©éebian
Linux programming environment can be
as simple or as complex as you need it to be.
wor bmpublcationscom
DMs Definitive GudeSeries |«thezttion |Coin snte
Equipment You
Will Need
Out of all the many different distros available, Linux Mint is considered one of the
best For both the beginner and more advanced user alike. It's an excellent coding
platform, with many languages built-in. Here’s what you need to get up and running
OUTTA ae
FROM FREEDOM CAME ELEGANCE
With Mint's versatility, you have several choices available to install Mint. Take your time and see which method works best
for you.
SYSTEM REQUIREMENTS
The minimum system requirements For Linux Mint 18 are as
follows: Obviously the better the system you have, the better
the experience willbe, and quicker too.
cpu To0MHz
RAM 512MB
Hard Drive Space 9GB (20GB recommended)
Monitor 1024 x 768 resolution
USB INSTALLATION
You can install Linux Mint onto your computer via USB oF
VD. Well look into each alte later on but ifyou'e already
Familiar withthe process or you're thinking of USB and just
{gathering the hardware you need, then you're going toneed a
‘minimum 4GB USB Flash drive to contain the Linux Mint SO.
IE) 501s eve cesses onDVD INSTALLATION
YD installation of Linux Mint simply requires a blank DVD-R
disc, OF course, you also need a DVD Writer drive before you
can transferor burn the SO image to the disc
INTERNET CONNECTION
Tegoes without saying really, that an Internet connection is
vital For making sure that Linux Mint is up to date with the
latest updates and patches, as well as the installation of
Furthersoftware. Although you don't need an internet
‘connection to use Linux Mint, you'r sure to miss out on a
‘world of free software avalabe For this distro,
Xe UGS
although Linux Mint can be installed onto a Mac, there's
‘school of thought that recommends Mac owners use a
virtual environment, such as VirtualBox or Parallels; and why
‘ot, macOS is already a splendid operating system. Fyou're
wanting to breathe new life into an older Mac, make sure i's
an intel PU madel and nat the PowerPC models.
VIRTI
eh ans
Installation toa virtual environment isa Favourite method of
testing and using Linux distros. Linux Mint works exceedingly
well when used ina virtual environment. More on that later.
There are many different virtual environment apps available
however For this book we are using VirtualBox from Oracle.
You can get the latest version From www.virtualbox.orgEP Coding on Linux. )
Transfer Mint to
DVD or USB
You need the latest version of Linux Mint before you can transfer it to a DVD or USB. Go
to www.linuxmint.com/download.php and download the 64-bit version of Cinnamon to
start with. Other versions can be tested once you're accustomed to the system.
DVD BOOTABLE MEDIA
We're using a Windows 10 PC here to transfer the ISO to a DVD.
process is extremely easy.
First locate the ISO image of Mint you've already
downloaded, You can usually ind this in the
Downloads Folder of Windows 7, 8.1 and 10 computers; unless you
specified a different location when saving it.
what to do with the newly inserted dis; ignore this, as you're going
to use the built-in image burning Function,
DVD RW Drive (E:)
soso ite ees hon
you're using a version of Windows from 7 onward the
Righticlick the Mint ISO and from the menu select
‘Burn Disc image, Depending on the speed of the PC,
itmay take afew seconds before anything happens. Don't worry too
‘uch, unless it takes more than a minute in which case it might be
‘worth restarting your PC anditrying again, With Luck, the Windows
Disc image Burner should launch,
FETS Banecick the Mint iSO and from the menu select
‘Bum Disc Image. Depending on the speed ofthe PC,
itmay take a Few seconds before anything happens. Don't worry too
‘much, unless it takes more than a minute in which case it might be
‘worth restarting your PC and trying again, With luck, the Windows
Disc mage Burner should launch,
© Windows Disc Image Burner x
Discimageffle: linumint-18-cinnamon-64bit iso
Disc burner: BD-ROM Drive (0)
Status
Burning disc image to recordable dsc.USB BOOTABLE MEDIA
USB medias Faster than a DVD and it’s often more convenient as most modern PCs don't have an optical drive installed. The
process of transferring the image is easy but you need a third-party app first and a USB flash drive of 4GB or more.
FETE ERD Fi'stopen up a web browser and go to wwrw.rufus.
akeo.i, Scroll down the page alittle and you come to
‘a Download heading, under which you can see the latest version of
Rufus (2.12 in this instance. Left click the link to star the download,
Double-click the downloaded Rufus executable; you
can click 'Yes' to the Windows security question and
"Yes' to checking for updates. With Rufus launched it should have
already identified your inserted USB flash drive; If nat ust remove
and reinsert.
9 Rafer 211995 = x
ewes ee
(06 us6 Fae) 7968) Y
Partition scheme and target system type
MBR partion scheme for BIOS or UEFL 7
Fe sytem
(rar32 (Detaut »
cuter sae
hen youre ready, clckon the tart button atthe
Sue ‘bottom of the Rufus app. This will open up another
dialogue boxastngyouto dourioed an ee aren version o
Spinoc Sper isa selection of bot oadersvsedto alow 3
moder to scess and bot rom 3 USB ash ive tis necessary,
sodickon Yes tocontinve
‘The next step asks which image mode you want
the Mint ISO to be written tothe USB fash drive
in. Both methods work for different situations but generally, the
recommended ISO Image Mode is the more popular. Make sure this
mode is preselected and click OK to continue, followed by OK again
toccanfirm the action,
FETED *t fist clance the Rufus interface can look title
confusing, don’t worry though i's really uite
simple. To begin with, click on the disc and drive con next to the
“Create a bootable disk using.” section and the ‘FreeDOS’ pull-down
‘menu. This will launch a Windows Explorer window where you can
locate and selectthe Linux Mint SO.
wor bmpublcationscom
‘einige yeu arse ca SO age mane can be
‘sen shen Stee copy maser 00 rage ak me mace.
Tercera ng bene bas nos oh
ete fyonenenet ering bet ou cnt tg image
(2 vite nso mage made commended)
The Mint ISO is now being transferred to the USB
Sry
fash drive. The process shouldn't take too long,
‘again depending on the speed ofthe USB device and the PC. You
‘may find Rufus will auto-open the USB drive in Windows Explorer
during the process; don’t worry you can minimise o close tif you
‘want. When the process is complete, click on the Close button.
Create a bootable ask using (BBTRBBE 3
Create extended label and icon files
=
‘Copying ISO files.
Baw) [to
start Cancel
Transfer Mint to DVD or USB? Em”BY Coding on Linux
Installing VirtualBox
GOING VIRTUAL
Using a Virtual Machine (VM) will take resources from your computer: memory, hard drive space, processor usage and so on;
make sure you have enough of each before commencing,
PEPER The First taskis getting hold of VirtualBox. Fyou
haven't already, head over to www.virtualbox.org
{and lick on the large ‘Download VirtualBox 5.1" box. This wil take
you to the main download p:
system, Windows or Mag, th
system, and click to begin the download,
3e. Locate the correct host for your
7 .
WY VirtualBox
Download
VirtualBox
ESTEE DD ex, while stil at the vitvalBox download pase,
locate the VirtualBox Extension Pack ink The
Extension Pack supports USB devices, as well as numerous other
extras that can help make the VM environment a more accurate
emulation ofa ‘real’ computer.
S .
Gg VirtualBox
Download VirtualBox
OMS Definitive Guide Series | th tion
hostisthe current installed operating
PTTED) withthe correct packages downloaded, and before
we install anything, you need to make sure that the
computer youre using able to host a VM. To do this, reboot the
computer and enter the BIOS. As the computer starts up, press the
Del, F2 or whichever key is necessary to Enter Setup.
FETIP 5 cach 8105 is laid out citferently i's very dificult
to-assess where to look in each personal example
However, as a general rule of thumb, you're laoking for Intel
Virtualisation Technology or simply Virtualisation; i's usually within
the Advanced section ofthe BIOS. When you've located it, Enable
save the settings, exit the BIOS and
ot the computer.(installing VirtualBox el
th the computer back pandrnning locate
Susp the downloaded main VirtualBox application and
doubleciektobegin the instalation proces chckNext to continue,
when you're ready.
8 orci Vetoc51.10 Seip x
Welcome to the Oracle VM
VirtualBox 5.1.10 Setup
Wizard
‘Te Se and dra Wo 5.13008
omen
\heninstalingVituaBoxyour network connection
Sus will be disabled for a very brief period. This is due
LoVitulBox creating inked, vtul network connection that
any VM installed wl beable to aces the terme, rdyourhome
network resources va the computers aleady estab shed network
Connection, ck Yes then allo beginthe instalation,
/dev/eull )
UL 2m “soutput’ 15 then
fo ~Soutput
aise’
a a“ Creating Bash Scripts - Part 5
STEGER When executed the script wats for input fromthe JESSIE The output from colours sh can, of course, be
User, inthis case the file extension, such as pa,
mixed together, bringing different effects
‘mp4 and so on t's not very friendly though. Let'smakeit alittle depending on what you want to the output to say For example,
friendlier. Add an echo, with: echo =n “Please enter the white textinared background flashing (or blinking). Sadly the
extension of the file you’re looking for: just blinking effect doesn’t work on all Terminals, so you may need
before the read command, change toa different Terminal
‘speak, sh. As youcan seeit'sa rehash ofthe fist greeting script
\we ran, Only this time, it uses the variables in the espeak output
\We briefly looked at putting some colours in the -
BD ict torcurscrts whist k’stoolongtedga EBB whiswe'reon making fancy crits, how about
little deeper into the colour options, here's script that outputs sing Zenity to outputa graphical interface?
what's avallable, Create anew script called coLours.sh and enter Enter what you see below into a new script, menu sh Make it
the text (see below) intoit ‘executable and then runit You should have a couple of dialogue
com boxes appear, Followed by final message.
FERED Wile gaming in a Bash script isn't something
that's often touched upon, itis entirely possible,
albeit, little basic. Fyou Fancy playing @ game, enter nget
hetp://oruxy. regnet..cz/Linux/housenka/housenka. sh,
make the scrint executable and runit, sin Polish, written by
Martin Bruchanov but we're sure you can modify it Hint: the title
screen isin Base6s4Coding on
Command Line
Quick Reference
When you start using Linux Full time, you will quickly realise that the graphical
interfaces of Ubuntu, Mint, etc. are great for many tasks but not great for all tasks.
Understanding how to use the command line not only builds your understanding of
Linux but also improves your knowledge of coding and programming in general. Our
command line quick reference guide is designed to help you master Linux quicker.
TOP 10 COMMANDS
‘These may not be the most common commands used by everyone but they will certainly Feature Frequently for many users of
Linux and the command line.
‘The ed command is one of the commands you
will use the most at the command ine in Linux It
allows you to change your working directory. You
seit to move around within the hierarchy of your
file system. You can also use chair.
The Us command shows you the files in your
current directory, Used with certain options it lets
you see fil sizes, when Files where created and file
permissions. For example, 1s ~ shows you the files
Uthat are in your home directory,
‘The Ep command is used to make copies of files
and directories. For example, cp file sub makes
{an exact copy of the file whose name you entered
{and names the copy sub but the first ile wil tl
exist with ks original name.
‘The my command maves a file toa different
location or renames file. For example my file
sub renames the original fle to sub. mv sub
=/Desktop moves the file ‘sub to your desktop
directory but does not rename it. You must specify
‘anew filename to rename file.
‘The chown command changes the user and/
‘oF group ownership of each given fil. IFonly an
‘owner (a user name or numeric user ID) s given,
that users made the owner of each given file, and
the files’ group isnot changed.
‘The chmod command changes the permissions on
the files sted. Permissions are based on afairly
simple model. You can set permissions For user,
‘group and world and you can set whether each can
read, write and or execute theffe
The pd command prints the Full pathname of
the current working directory (pwd stands For
“print working directory’). Note thatthe GNOME
terminal also displays this information in the ttle
bar ofits window,
@ ‘The Lear command clears your screen if this
's possible. t looks in the environment forthe
terminal type and then in the terminfo database
to figure out how to clear the screen. This s
{equivalent to typing Control when using the
bash shell
soso ite ees hon
‘The Fm command removes (deletes files or
directories. The removal process unlink aflename
ina filesystem from data on the storage device
‘and marks that space as usable by Future writes. In
‘other words, removing fils increases the amount
(of available space on your disk
‘Short for ‘make directory", mkdir is used to
‘create directories ona ile system, ifthe specified
directory does not already exist. For example,
Inkdin work creates a work directory. More than
‘one directory may be specified when calling mir.Command Line Quick Reference Epes
USEFUL HELP/INFO COMMANDS
The Following commands are useful for when
eset
Linn eons
Cute a asta a
iia
Buttock Met saute sede ie eae
Cen errands CE ae iio
the system, For example, ISTEREET aives the ae tore ei ase
ees oe
Bic ore cutee
Cee rarest ry adduser
gst mires
ores)
‘The BERMEER command adds 3 new user tothe
untrue
Psp
DSO ee eae es The BENTEEG command removes a user from
EZ ee eg ee aes
CS ong test home divectory,you need to add the STONE
Cis [EE option.
crane et ese Foc are eed
allsytem information, including machine name, ARMY. th ster. You cannot removes group thats the
Dee UE EL tues primary group of any users.
Bsa ee eh ee
na
‘operating systems version of psis slightly
Cee eis
‘The EREELcommand brings up the manual
Cig ume tess
eset
‘The FIRE command allows you to search inside 3
Opie
mae eee ent te
‘The TERRIERS command is especialy useful
In displays the Intraduction to User Commands,
Serer emai
Beat eger eens
wor bmpublcationscom [8DMs Definitive Guide Seis | sth tionBUNT e ae] meal Lae ole Ne HORN Hana anole: Kee unl) cnr waaeol)
Cole M CIN AO a Kee Te ACOA TI Makes Programming with the FUZE )
The Raspberry Piis the powerhouse
For many excellent projects. However,
‘one project stands head and shoulders
above the rest, the FUZE Project.
FUZE isa learning environment for
the Raspberry Pi that’s amazingly
accessible and gets students,
teachers and enthusiasts coding and
‘experimenting with the Raspberry Pi
quickly and easily.
Used in hundreds of schools across
the UK, the FUZE is the perfect
combination of Pi potential,
imagination, engineering and
education, all presented ina cleverly
designed retro-themed keyboard
case. More importantly, the FUZE
also comes with its own programming
language, FUZE BASIC. With FUZE
BASIC you're able to create simple
routines, games, complex algorithms
and even interact with robots and
other electronics.
Introducing the FUZE Project,
Setting Up the FUZE
Getting Started with FUZE BASIC
Coding with FUZE BASIC Part 1
Coding with FUZE BASIC Part 2
Coding with FUZE BASIC - Part 3
Using a Breadboard
96 Using the FUZE 10 Board
98 Using a Robot Arm with FUZE BASIC
100 FUZE BASIC Examples — Part 1
102 FUZE BASIC Examples Part 2
S88eRe8
BE) 20's eve cesses onProgramming: -
VVieahepcaneyacce
=
baIntroducing the
FUZE Project
Baga ed Naina aried tienda a ce ua go
Pere ncdnumlacdeuctcl a cecek iso emt teat en cette ants
hardware side of the project, incorporating a Raspberry Pi inside a stunning retro-
themed case, complete with a full-sized keyboard, IO board and connectivity. The
software side is FUZE BASIC, available For both Windows and as a boot image for
Raspberry Pi models 2 and 3.
The FUZE Workstation itself, styled on
‘3 BBC Micro Model B from the 80s,
nstrycted with a metal body and
high quality keyboard complete with
programmable red coloured F-keys.
Note the holes atthe top edges: these
‘are compatible wth many popula
plastic building blocks and electronic
struction kts.
Inside the FUZ!
the beating heart of the project, a
Raspberry Pi3.lt's connected t
FUZE 0 board via the 40-pin GPIO pins
with a ribbon cable, wth the other
connections branching from it: HDM
power, SD Card and USB. The USB
ports have been rauted to a pawered
USB hub, attached tothe rear ofthe
workstation, providing the user with
Four USB ports accessible through the
rear lO back plate; there'san Ethernet
port too.
workstation is
‘The Rear back plate is where you
plug in your power, connection toa
monitor, mause, SD card, audio and
‘any USB devices you want to include,
Fromleftto right, acrossthe back pate,
there's an on/off switch, a power port,
bank of four USB ports the Ether
port, SD card slot and HOMI port. You
can remove the four corner screws oF
the back plate to gain access tothe
Raspberry, USB hub and cables inside
the workstation if needed.
slot at the top ofthe workstation, is
the connection to extended hardware
With ityou can connect, program and
se sensors, LEDs, rabatics and all
‘manner af amazing electronic proj(Introducing the FUZE Project Em”
You aso receive an electronics kitas part of
the FUZE workstation, to help you getstarted
con some ofthe projects the FUZE's designed
5 to support. within the kit you can Find 24
WI ZES Coloured LEDs, 1 sevensegment LED, 1 ight
aed dependant resistor, 8 mico switches, 30 mixed
Tiecront components it specication resistors, 20 jumper cables and 60
jumper wives.
Complementing the electronics project kit,
the FUZE team also bundles an 840-socket
solderless breadboard which you can use
towire up interesting projets and use
FUZE BASIC together withthe Raspberry
Pland the FUZE IO board to contro the
E components from the electronics kit. In
‘ase you're wondering why it'scalled a
breadboard its because inthe early days
of electronics users would use abread
board or the base oftheir projects,
‘Alongside the ather components with
the FUZE workstation, you also get ether
‘wired USB or wireless (batteries are
included if necessary) mouse and FUZE
(ogo mouse mat
‘The kit comes with two ring-bound books
Containing projectideas forthe electronics
kitand a programmer's reference guide
for FUZE BASIC. f you've purchased the
FUZE kt, then it's certainly worth your
‘while reading through this book and
familarising yourself with how
everything works.
Depending on which FUZE workstation
kit you've purchased, you could also
have a robot arm that requires building,
‘along with four Dsized batteries, a BBC
micrbit or even a Capacttive Touch kt.
Needless to say, there's plenty of project
potential with the FUZE.
entation covsoehtve citesees| «incon INSetting Up the FUZE
Rede. rel radeon ania RCo eke at En MOT eg
Monae Muar ur ancnece alan ecm iel
eI aces Monnet cette am at Mn orcas
Maeno oan
LIGHT THE FUZE
Getting the FUZE up and running is as simple as plugging ina standard desktop computer; but it’s always worth running
through the process For those who don't know what to do,
FERED Before you power up your FUZE, mak
provided SD cards inserted into the SD card slot
‘on the rear IO back plate ofthe FUZE workstation, The chances.
he SD card is already inserted but depending on how the FUZE was easier to establish a wired connection First f poss
packaged, it may bein the electronics kit box. Ethernet cable to rear 10 back plate ofthe FUZE
w, use the Ethernet port, LAN cable, fo
‘connection tothe home network and
BETSEDD ib spare monitor orif your existing monitor (or EREEZD tet o7en tne box contrng te rouse and
TY) can support more than one HOMI connection plug it into one of the USB ports on the rear 1 of
‘The FUZE comes with a quality HOM cable, emoveit the FUZE workstation back plate.
and connect one end to the HOMI port on the rear IOSetting Up the FUZE §
sTePs See BED roe oasis te tescentnor
othe FUZE workstation tele red [ae pring cp, teeter d-dh
{and start to boot tom the arrows and the current WiFi access points willbe displayed
Connect to yours as you would normally You can now unplug the
e° Ethernet cable iFyou wish,
BED You may need to change the source of the monitor BED Beyond the different desktop presentation, the
‘or TV's input to the HOM, or the numbered HOM! FUZE setup works exactly the same as any other
port that you've connected the FUZE to. Once the signal is found by Raspberry Pi Raspbian system, You can click the First F (the white
ne monitor it displays the FUZE desktop, Fon a black background) to open the systern menu detailing the
avalable apps and programs. The second F launches FUZE BASIC,
which well look tin the next tut
PPE the ist tingto notice that es sina BEER errr neat te tare a
afferent tht othe standard Rasphety | programs cckon the stat button, allowed
Raspbianinefae. The aunch panel and buttons are cated along by Accessores> Terminal nthe Terminal enter sudovapt=get
hebottomolthescieen aswthawindowstypesetup witha, update 8X sudo’ apt-get upgrade and accept ary changes
‘of icons on tt and updates the system has to offer, This will update al your
installed software and system files,
vow dmpubliationscom [8DMs Definitive Guide Seis | sth tionGetting Started with
FUZE BASIC
FUZE BASIC is a marvellous programming language to begin learning to code with. It
cele MU ae Mea M1095) WS) RESO MCO MONEE aU Len Lem ea Me Meany
the Commodore 64, ZX Spectrum and BBC Micro.
BACK TO BASICS
Let’s begin our programming journey with FUZE BASIC, an environment where you can create anything, from simple scripts to
‘complex games with graphics and sounds.
FERRER nthe bottom right panel the one that’scoloured — EEEMEMB the retro style interface of FUZE BASIChas several
white on ared und? Click t and you launch themes that you can cycle through, depending
the FUZE BASIC, complete with a C64-stye retro interface. You canon your taste. The default view i that of a Commodore 64 but if
also double-click the FUZE BASIC V3 icon on the desktop. you want a different view press the Insert key to cycle through the
available interfaces. You'll ne doubt recognise some of them, so find
one you like
PEPER Don't worryityoudon'thave a FUZE Workstation, AVR thescreen you're looking at naw is called
FUZE BASIC is availabe For Windows, the BBC immediate Mode; pressing the Enter key will reveal
microsbit and the Raspberry Pi (since i's already running on aRP). a cursor where you can start to enter code. Try this: press Enter,
a browser to www.Fuze.co.uk/download-fuze.html then type: Hello everyone and press Enter again. The output on the
download instructions for FUZE BASIC For Wi screen wil display whatever you've typed into the quotation marksGetting Started with FUZE BASIC
FER ou conaso int thetotal output of evra ED
numbers From within the nmetiate Mode. For
fore we get into variables and ather such
programming terms, let's havea little play around
example, try: print 10/4120 430, and press Enter. The sum of with a quick isting to ask For user input. Enter this:
the numbers you've entered will now be displayed on the screen,
intiscasetnenumberéO.Tymorenunbesanderendieent 30°68
Ee 20 input “What is your nane? “, nS
" shee 30 print
40 print “Hello “; nS
Enter Pun to execute the c
oon er
PEI i yourind the screen getting alitle Full, enter 1S
to lear the BASIC display. BASIC in Immediate Mode
is also capable of storing variables, something which well look at
in more depth inthe next tutorial. For now, try this and press Enter
aftereach line
ato
Print a
{ ster 9 ) Dissecting the previous code, we have the command
10 clear the screen [CLS], then the Input command
asking for user input and storing the input as the variable nS. The
Print tine 30 puts blank tine on the screen, whilst the Print
command at line 40 displays the message HeLL@ and the contents
ofthe variable n$.
Now enter RU. The word Hello should now cycle down the screen.
Pies the Bane De a ex BED There’sa lot doin immediate Mode:
however, to unleash the Full potential of FUZE
BASIC you're best working in the Program Ecltor. To enter the
Program Editor type in the command new to clear any progra
already stored in memory and press the F2 key. As you can see,
Program Editor looks significantly different to Immediate Mode.Programming with the FUZE
Coding with FUZE
BASIC — Part 1
Variables are used in programming to store and retrieve data from the computer's
memory. It's a specified location in memory that can be referenced by the
programmer at any point in the code, as long as it’s created and valid.
LET THERE BE VARIABLES
We've already looked at assigning some variables in the previous tutorial so let's extend that and see what else we can do
with them,
Ener Pesan toy prexingte ey, TRIBE or 2 toners on ew Now
uP ‘Within the Program Editor enter the Followi SUaPS let’s expand on the simple code. Enter the Following:
pressing Enter after each tne:
Let x=10
Let x=10 Let y=20
Print x Let 2=30
Now dick onthe Save button, along the top ofthe screenandsave PRIME # YZ
the program as Variables’. Clckthe OK button to returnto the Save as'Variables2' and Runt. Younow have the output of 60 on
Editor and the Run button to execute the code. the screen, as you've assigned X, Y and Z with numerical values, and
printed the total.
FPP wracif we wanted to change the value of a
variable? Enter this isting:
a - . Let xe10
break down this imple code, you've created the variable called X,
{and you've allocated the value 10 to it. The second line simply prints To begin with x equalled 10 but the next line subtracts 1 making it
the current value of X which is of course, 10. 9, then prints the current value oF X. Imagine ths as lives in a game,
starting with 10 lives, losing 1 and leaving 9 leftFETED) We can extend this Further with m
Try this:
Let
Gycte
Print x
Let x=x-1
Repeat until x-0
Print “Blast OFF!”
End
‘This creates a loop that willminus 1 from X untilit reaches 0, then,
prints last OFF!
PEPE variables can do more than store numbers
Input “Hello, what is your first name?
“8
Print
Input “Thanks, and what is your surnane? “, s$
as
Print “Hello “; #83“ “y s$;*
today?”
End
How are you
The varables § and s§ store input For
baackto them on the same lin,
user then printed it
FERED) concitional statements alow you to make you
program do aifferent things depending on the user
input. For example:
as
Input “Enter your name:
If name$="Dave” then
Print “I am sorry “; names
Print “I am afraid I can’t do that”
Else
Print “That is not a problem *; names
Endif
End
“5 names:
‘Save as'HAL’ and Run,
wor bmpublcationscom
Coding with FUZE BASIC - Part 1
‘The code from Step 7 introduced some new
commands, First we clear the screen, then ask
Foruser input and storeitn the variable name §. Line 3 starts the
ional statement, ifthe user enters the name ‘Dave’ then the
program will print HALs 2001 infamous lines. IFanother name is
inputted, then it wil print something else
[seo ) Programs store all manner of information, retrieving
i from memory indifferent ways:
as
Data “Monday”, “Tuesday”, “Wednesday”
Data “Thursday”, “Friday”, “Saturday”
Data Sunday”
Dim DaysofNeeks(7)
For DayNo = 1 0 7 loop
Read DaysOFleekS(DayNo)
Repeat
For DayNo'=/ 10 7 Loop
Print “Day of the week number“; DayNos
Print “ is “; DaysOfMeekS(DayNo)
Repeat
End
The code from Step 9s beginning to look quite
complex, using the Data command to store
lled DaysOfWeek using the Dim
command and assigning itan indexed dimension (7). The code then
Reads the stored Data, assigns ta variable dimension from 1 to7
and prints the resultCoding with FUZE
BASIC — Part 2
Moving on from the previous FUZE BASIC tutorial, let’s expand everything you've
Cera Rca cca ache maureen tos
asking For someone's name. In the grand tradition of BASIC programming, let's create
EN Geel ust
“PALE BULBOUS EYES STARE AT YOU.
A text adventure game is an ideal genre to explore your BASIC skills in. There are variables, events, user input, counting and if
you want, even a Few graphics here and there to inject and use.
FSTEGEDD Esterthe Program Editor and begin with asimple — ENEIEM Lev add a way whereby the users required to
clear screen, as t's always a good way to start. What press akey to continue, this way you can leave
Wwe need to dois set some basic parameters first, so start with the instructions onthe screen for an indefinite period:
ae a Printat (15,15); “Press the Spacebar to continue.”
While inkey > 32 cycle
Repeat
‘This prints the message whilst waiting For the specifickey tobe
pressed on the keyboard: the Spacebar.
Bare ow you canintroduce the game andlet the player ESSAI, Now we can start the story’part ofthe adventure:
know how mary lives they currently have. You can a
ois by addina the followin i tie ce Print “You awake to find yourself in an airlock
Printat (41,0); “You have “; lives; “ Lives left.” onboard a space station.”
Printat (0,0); “Welcome to Cosmic Adventure!” Input “There are two buttons in front of you:
Green and Red. Which do you press?”, button$
If button$="Red” then
Let lives=lives-1
Print “You just opened the airlock into space. You
‘are dead!”
Print “You now have
‘The printat command will specify a location on the screen to display
the text using xy.
slives; “ Lives left.”Coding with FUZE BASIC - Part 2
ESTED We con now continue the game from tine 29, adding
‘another press the Spacebar routine, followed bya
Now a
If Lives=0 then goto 25
print==Prese tha Sodeabar to" try agains ar screen ready for the next part ofthe adventure.
While inkey = 32 cycle Print “Press the Spacebar to continue..”
Repeat White inkey > 32 cycle
Goto 8 Repeat
Else as
Print “The door to the interior of the space
station opens, Lucky for you.”
‘The Goto command goes toa ine number and continues with the
code. Here you can use itto start an end of game routine
Youcan now ave the code calitadveture or
Sue) something), and Run it From the menu. Whilst it's not
themostelegant code you wil ee se, bigsin many ferent
elements ond shows you what on be done wth FUZEBAST:
PEPEED 2's Finish tis routine off with:
Endif
Endif
Goto 29
Print “Sorry, you are dead. End of game. Press
Spacebar to Start again.”
While inkey © 32 cycle
Repeat
Goto 1
This closes the ifstatements, then goes to line 29 (iF you pressed the
Green button) to continue the game, skipping the end of
game routi
Se RIT sefore vou continue wit the adventure, and map
BaD eee ee eee ae ae ees ED the fate of aur reluctant space hero, we're going
“ # ’, ue to improve our code with some graphics. FUZE BASIC has some
variable ives equals 0; the player's lives have run out. leprints 3 °
Ty youare dead’ message and asks to press the Spacebarto start 9T@2t graphical commands at its disposal, along with some other
Sorry you are dead! message and asis to press the Spacebar to start 5664 and interesting extra.
the game al over again from line 1, the goto 1 part.BED 21:20ina wtntneruze
Coding with FUZE
BASIC — Part 3
Poca ton her treet ier Tee eee aS e
While it works perfectly Fine, it would be nice to include some graphics and maybe a
Few other elements to have it stand out from the usual BASIC programs.
ADDING GRAPHICS
FUZE BASIC employs a variety of different commands to display graphics, either drawn on the screen or by displaying an
image file,
PEPER You're going to start by making the game full FETED ow create anew line 13,by getting the cursor to
screen, then adding an appropriate image that sets theend of line 12 and pressing Enter, For the new
ne theme ofthe adventure. From line 2 pressEnter,tocreatea new line, type in
ine 3, and type inthe following:
Hidesprite (spriteindex)
Fullscreen=1
Spriteindexenewsprite(1)
EarthS="pLanetEarth.png”
Loadsprite Cearth$, spriteindex, 0)
oes a
po
Beer vo sssoc nscnnomanson
bile rletrectr
‘and green buttons and copied to the /Desktop/fuze-basic/extras/
images folder. Now we need to add itto our code From line 15
This command will emove the image from the screen, allowing you
toinclude a new image for the next step in the game.
buttons$="buttons.png”
loadsprite (buttons$, spriteindex, 0)
BRED tre codefrom step willimport and displayan _-~PLOtSPrite: Cspriteindex,”300,/400,"0)
image of the Earth the image itself is already Make sure the image is called before the Input command!
available in the /Desktop/fuze-basicjextras/images Folder. t'snow
classed asa sprite and can be manipulated through the various
5 this means you're in the Documents
pt window isn’t much to laok at to begin with but ctory. Now, create a new directory call Batch Files. Enter
fows version number and copyright - =
wed by the promptitself The prompt detais the Md “Batch: Files?
current directory or Folder you're in, together with your username, _Youneed the quotations because without them, Windows creates
directories: Batch and Files, Now change directory into the
Batch Files
cd Batch Files
‘You won't need the quotes to change directories.Now that you have the directory setup, where you
store your batch files, here is how you can create
‘one. Leave the command prompt window open and click on the
Windows Start Button again. This ime enter Notepad and
the search result to open the Notepad program. Notepad isa simple
text editor but ideal For creating batch scripts with
To create your fist batch Fil
into Notepad
center the following
@echo off
echo Hello World!
8 default, abatch file displays allthe commands thatitruns
Uhrough, line byline. What the @echo off command does is turn
that Feature off for the whole scrip; with the (at) sign to apply
that command to itself
When saving anything in Notepad the default
SPT ‘extension is .txt, to denote a text file. However, you
want the extension to be bat. Clck on File > Save As and navigate
1 the newly created Batch Files directory in Documents Click the
drop-down menu Save as Type, and select Al Files from the menu. In
File Name, cll the fle Test.bat
wor bmpublcationscom
Getting Started with Batch Files
kat the command prompt window, eter:
SHEP) @iF/W again to list the newly created Test. bat file.
By the way, the Av part of dfw means the files are listed
the screen as opposed to straight down.
{although you need more files
Feadwith the jw Flag
‘ir iFyou want
view) but t's considered easier to
FETED To execute the batch file youve just created, simply
enter its name, Test, in the command prom
window. You don't need to add the bat part, as Windows recognises
itasan executable file, and the only one with that particular name in
the current directory. Press return and see how you're greeted with
Hello World in the command prompt
The echo comman
displays whatever after
STEP to the screen, Right-click the Test.bat file from
windows Export and selec Edt add more echo commands
youthe. this
echo off
echo Helo World!
echo This 1s ny first batch file
echo.
echo With @ blank Line between!
Remember to save ea
new change tothe bate
file.Coding with Windows 10 Batch Files)
Getting an Output
CS a a tccU au acint ks Se RU Tce
Elica een eRe Maen aerate (NUE nen eee
ere gare eecerad eke ueat Recent ce st
INPUT OUTPUT
Batch files are capable of taking a normal Windows command and executing them, while also adding extra options and flags in
to the equation,
FETTER 2t'skeep things simple to begin with. Createanew EIIEM Youhave no doubt noticed that there sno
View. Start with the @echo off command and under that add: rho meaningful output on the screen. However, iFyou now open
din “c:\users\YOURNAME\Docunents\Batch Files” > i Lele ee
——— substieute with your Windows username, and double
ae lick the dinvitew.txt file, you can see the batch fi’s output
Substitute YOURNAME with your Windows username
PEPPER the new line usesthe dircommand to listthe FPP D you want to automate the task of opening the
contents ofthe directory Batch Files, in your Home
text file that contains the output, add the following
directory, dumping the output to atextfile called dirviewstxtin line tothe batch file:
the root of your Home directory. Thisis done, so that the Windows — =
UAC doesnt require elevated permissions as everythings in your MOB@Padvexe'¥¢#\userss\YOURNAMENGieview txt
‘own Home area, Save and run the batch fi. ‘Save the fle and ance again run fram the command prompt. This
time, itcreates the output and automaticaly opens Notepad with
Ee the output contents.
BET 20s eve cate see tonOUTPUT WITH VARIABLES
Variables offer a more interesting way of outputting something to the screen and create a higher level of interaction between
the user and the batch file. Try this example below.
E>
Following tines:
Create a new batch file and call it name.bat, Sta
with the @echo: of Ficommand, then add the
set /p nane= What is your name?
echo Hello, name
Note: there's a space after the question mark. Thsis to make itlook
neater on the screen. Save it and run the batch fl.
The set /p name creates a variable called name, with
EUSAD the /p part indicating that an ‘=prompt string’ isto
follow. The Set command displays, sets or removes
system and environmental variables Far example, while in the
‘command prompt window enter:
set
Variables stored with Set can be called with the
S6VARIABLENAME% syntax. In the batch file, we
sed the newiy created %ename% syntax to call upon the contents oF
the variable called name. Your username, Fo
variable, Try thisina batch Fle:
echo Hello, RUSERNAMEX. What are you doing?
ample, is stored as 8
wor bmpublcationscom
Tis setremety seul you want to create a
Sus unique, personal batch file that automatically runs
when userlogsinto windows Using the default systems variables
that windows itself rates, you can make a bath le that greets
echo off
echo Hello, USERNAMEX.
echo.
echo Thanks for Logging in. Currently the network
is operating at 100%% efficiency.
echo.
echo Your Hone directory is located at: SHOMEPATH
echo The computer nane you're logged in to is:
‘COMPUTERNAMER
echo.
PPIIED seve and execute the batch file changes; you can
‘overwrite and stil use name.batif you want. The
batch file takes the current system variables and reports them
accordingly, depending on the user's lagin name and the name of
the computer. Note: the double percent symbol means
sign wil be displayed, and isnot a variable.
Alternatively, you can run the batch ile and display
iton the user's desktop asa text file
echo off
echo Hello, SUSERNAMEX. > c:XHOMEPATH\User. txt
echo. >> cSHOMEPATHR\user, txt
echo Thanks for Logging in. Currently the network
is operating at 100%% efficiency. >> c:#HOMEPATHI
user. txt
echo. >> ¢: SHOMEPATHR\User, txt
echo Your Hone directory is located at: SHOMEPATH:
>> C:BHOMEPATHE\user. txt
echo The computer nane you're Logged in to is:
XCOMPUTERNAMES >> c:HOMEPATH\user txt
echo. >> c:SHOMEPATHRuser. txt
notepad c:XHOMEPATH®\user. txt:
‘The > outputs to a new file called user, while the >> adds the
lines within the fie1
Coding with Windows 10 Batch Files)
Playing with Variables
There's a lot you can accomplish with both the system and environmental variables,
alongside your own. Mixing the two can make for a powerful and extremely useful
Pelee MMA Re MAC e Meco rl ETC oa
USING MORE VARIABLES.
Here's a good example of mixing system and environmental variables with some of your own creation, along with a number of
external Windows commands.
Create anew batch Fle called list. bat and start it ofF
with the @echo” off command. Begin by learing
the command prompt screen and displaying alist of the current
directories onthe computer
as
dir “c:\" > Listitxt
type List. txt
PEED Seve and execute the batch file. within the
‘command prompt you can see the contents ofall
the files and directories from the root ofthe C:\ drive; and as any
User under Windows has permission to see thi, there's no UAC
elevated privileges required
Rh Eston
FTTSED) ow, create a batch file that displays the contents
of any directory and post it as atext file to the user's
screen. Add the Following to the lst bat batch ile
‘echo Hello, USERNAMES.
‘echo From the List, which folder would you like to
view?
set /p view= Center as c:\folder)
dir “Kviews” > view. txt
notepad.exe view. txt
‘what's happening here is the batch file asks the user
to enter any ofthe directories displayed in the lis it
irectory’. Providing the user enters a
das atext file, We created
ED
generated, in the form of 'c\
valid directory, its contents are display
the view variable here along with sHOMEPATH®6, to store the input
and the text fleFETED: 2tvays 2 good idea, when creating text files FETED '2st22d of let clicking on the Command Prompt
forthe user to temporarily view, to clean up after sult, as you di the fist time you opened it,
yourself, There's nathing worse than having countiess, random Tight-clickit and from the menu choose Run as Administrator. There
text Files cluttering up the Filesystem, That being the case, let's isa rskthat you could damage system Files asthe Administrator
clear up with butas long as you're careful and don't do anything beyond viewing
directories, you willbe okay.
as
del /Q view.txt
del /Q List.txt
echo ALI files deleted. System clean. BD e awe
Best match
fH Corman Prompt
© _ Run as administrator
se
Open file location
£
“8 Pinto Start
FETED) The additions to the batch file simply clear the a
‘command prompt window (using the cls command)
d delete both the view.txt and lst.tt Files that were created by
the batch file. The /Q flag inthe del command means it deletes , wet z
the files without any user input or notification The final message
ce eee 7 FETED This action triggers the UAC warning message,
asking you if you're sure you want to run the
Windows command prompt with the elevated Administrator
nih privileges. Most ofthe time we wouldn't recommend this course
of action: the UAC is there to protect your system. in this case,
however, click Yes,
cS
moe ne
your system is configured,
you may not get any =
directory information Bm rmesrone
atalloramessage i
stating Access Denied. sexo nape —— soseeseen
Thisis because the UAC om PEER with the UAC active, the command prompt looks
is Blocking access to alittle different, For starters, i's now defaulting
protected areas ofthe tothe C\WINDOWS\system32 Folder and the top ofthe windows is
system, like c\Windows labelled Administrator, To run the batch File, you need to navigate to
(oF CAProgram Files, the Batch Files directory with: ed \Users\USERNAME\Documents\,
Therefore, you need to Batch Files. To help, press the Tab key to auto-complete the
vun the batch File as an
‘Administrator, Click the
\windows Start button and Ain on
enter CMD again.
directory names.=P Coding with Windows 10 Batch Files _)
Batch File Programming
It's the little additions we can make to a batch file that help it stand out and ultimately
[otto AU oie ARAN reo eKe Lr ec UCUceeesel cue Keele]
i KecUvel Seema Meee tea orem
SEARCHING FOR FILES
Here's an interesting little batch file that you can easily extend For your own use. It asks the user For a file type to search For
and displays the results.
ESTEE '¥2 are introducing a couple of new commands FRTTSED) ow let's extend the seek bat batch Fle:
ino the mix here but we think theyre really useful
Creates newbateh le caled see bt ndin echo off
als
secto off Stor 2
color 2 ‘echo Please enter the type of file you want to
echo Please enter the type of fle you want to Search for (WF3, DOC, JPG for example)
search for (MP3, DOC, JPG for example) a
= set /p ext=
a there /R ci\ *XextX > Found. txt
— notepad.exe Found. txt
ae cls
oe color
Jesioe 2 del /Q found. txt
PEPPED the new command inthis instance is color BSED nother new command, where, looks fora specific
(Americanised spelling). Color, as you already file or directory based on the user's requirements
‘assume, changes the colour of the command prompt display. The __In this case, we have created a blank variable called ext thatthe user
Calor attributes ae specified by two hex cals, the first corresponds can enter the filetype in, which then searches using Where and
to the background colour of the Command console and the second dumps the results ina text file called found.txt. Save and run the
to the foreground, and can be any of the following values: bateh fie.
O=Black 8=Grey
9 = Light Blue
2=Green A=Light Green
B= Light Aqua
4=Red C= Light Red
5=Purple D = Light Purple
6= Yellow E = Light Yellow
7=White F = Bright White
ERED 20%: bernie cuide Series sth EstonCHOICE MENUS
Batch Fle Programming
Creating a menu of choices isa classic batch file use and a good example to help expand your batch file programming skills
Here's some code to help you understand how it al works.
Rather than sng a variable to proces users
nar) response, batch files can instead use the Choice
‘command in conjunction with an ErrorLevel parameter to make a
menu. Create a new file called menu.bat and enter the following:
eecho off
als
choice /M “Do you want to continue? Y/N"
if errorlevel 2 goto N
if errorlevel 1 goto Y
goto End:
Running the code produces an error as we've called
ELISD a Goto command without any reference to it in the
File, Goto does exactly that, goes ta a specfic line in
the batch file. Finish the file with the Following and run it again:
echo:
‘echo You chose No. Goodbye,
goto End
echo:
‘echo You chose Yes. Hello
The output from your choices different depending on
SNEED inher you pk oN thee por simpy sonic
the end ofthe file (also known as EOF). without tthe batch ile runs
through each line and display the Y response even iFyou enter N;s0 it's
important to remember to Follow your Goto commands.
wor bmpublcationscom
FTIR érortevels are essentially variables and the /M
switch of Choice allows a descriptive message string
tobe displayed, Extend this menu with something new:
@echo off
cls
echo.
echo
‘echo.
echo
‘echo.
‘echo
‘echo.
‘echo
‘echo.
‘echo
‘echo.
‘echo.
‘echo.
echo)
choice /C 1234
if errorlevel 4 goto Videos
if errorlevel 3 goto Pictures
if errorlevel 2 goto Documents
if errorlevel 1 goto Music
FEPISED) Now add the Goto sections:
Videos
cls
CD RHOMEPATHRWVideos
‘echo You are now in the Videos directory.
‘goto End
Pictures
as
CD SHOMEPATHX\Pictures
echo You are now in the Pictures directory.
‘goto End
Documents
cls
CD XHOMEPATH\Document's
‘echo You are now in the Documents directory.
goto End
Music
as
CD RHOMEPATMusic
‘echo you are now in the Music directory.
‘goto End
nd
FEPITR wen executed the batch file dsplaysa menuand with
‘each choice the code changes directory tothe anethe
user entered, The SsHOMEPATH6 system variable wll enter the curently
logged in user's Music Pictures and so directories, and notarwone else's,
Please choose a directory.
Press 1 for c:\Music
Press 2 for ¢:\Docunents
Press 3 for c:\Pictures
Press 4 for c:\VideosCoding with Windows 10 Batch Files
Loops and Repetition
Looping and repeating commands are the staple diet of every programming
language, including batch file programming. For example, you can create a simple
colt cel RR MTU elit COLORS Cece STATES
COUNTERS
Creating code that counts in increasing or decreasing number sets is great for demonstrating loops. With that in mind, let's look
at the IF statement alittle more, alongside more variables, and introduce the Else, Timeout and eof (End of File) commands.
BED 2 eeisercrtocniectedconint EEIER) tecomenatsaron weet terest
@echo off Try this example instead:
as echo off
set /a counter=0 for /L nin (1,149) do echo
numbers
set /a counter-Xcounters+2
if Kcounter% ==100 (goto :eof) else (echo
counter)
‘timeout /T 1 /nobreak > nul
goto :nunbers
EED Breaking it
Zn, there's
For, then the /L switch, which
handles a range of numbers.
‘Then the parameter labelled
TEED The count. "i command romp count
bat code
starts at number one and
counts, sralling down the
screen, until it reaches 100.
The Timeout command
leaves aone second gap
tween numbers and the
anumber. Then
which tells
-atement how to count,
asin (start number), 1 (steps
99 (the end number)
ning DO
whatever command is after
Ise statement continues
inti the counter variable
‘equals 100 before going to
ne eof (End OF File), thus
closing the loop,You can inclu wumbers
easily enough within the far simpler For loop by
Jing multiple commands after the Do For loop. The brackets and
(8) separate the differ
ampersay
@echo off
for /L %in in (1,1,99) do Cecho Xn & timeout /T 1
Ynobreak > nul)
commands. Try this
hilesisto
BETTIE re oF the areat time saving uses of bat
create multiple, numbered files. Assume that you
want twenty five text files within a directory, all numbered from 1 to
25. AFor loop much lke the previous example does the trick
eecho off
for /L %8n in (1,21,25) do copy nul En. txt:
PEPIED you open windows Explorer, and navigate to the
Batch Files directory where you're working from,
can now see 25 text files all neatly numbered. OF course, you
end the fle name with something lke usert.txt and so on
altering the code to read
@echo off
for /L %8in in (11,25) do copy nul UsersK¥n.txt
wr bdmpubleaions.com
EED There are different ways of using the For loop. In
this example, the code creates 26 directories, one
foreach letter ofthe alphabet,» tory test which the
batch file makes using the MD.
echo off
FOR ¥KF IN Ca,b,c,d,e,F,0,h,1,5,k,1sm,9,0,P,4,0,
S,t,U,VsW,X,y,2) 00)
nd’ C:\test\aF)
oops can be powerful and extremely useful
elements ina batch file, While creating 26
ipful imagine having to create
1,000 users ona network and assign each one their own set of
Unique directories. This is where a batch fil saves an immense
amount of time.
directories may not sound too
BED Should you ever get stuck when using the various
commands within a batch fil, drop into the
command prampt and enter the command Followed by a question
switch, Far example, For or if. You get an on-screen help file
detaliing the commands use. For easier reading, pipe itto a text fle:
For /? > forhelp.txt
{OMS Definitive Guide Series | «th ition
taCoding with Windows 10 Batch Files
Creating a Batch File Game
Based on what we've looked at
so farwith batch files, you can:
Dice) VAS at ANB Melia)
simple text adventure or multiple-
fee ee Ma eee ella
créated, thatyou'fe Free to Fiddle
with and make your own.
“Make up your own questions but how about also
including an introductory or loading screen? Make your
loading screen ina separate batch file and save tas
screens.bat (for example). Then, fromthe main game
batch ile, you can loadit at the beginning ofthe Fle
with the cal command followed by colortoreset the
game's colours
echo oft
cis
Call screens.bat
color
tart
set /a scorend
set /a question=0
fet /p names What is your name?
UUM ee
DIGCLOCK.PY
Thisis a surprisingly handy little script and one that we've
used in the past instead of relying on a watch or even the
clock in the system tray of the operating system,
cls
echo.
ho tistieenerenennneneuasuastenannnennennenntnntents
‘echo.
fecho Welcome namet to the super-cool trivia gane.
echo.
fecho Press 1 to get started
echo.
fecho Press 2 for instructions
echo.
fecho Press Q to quit
echo.
8,
choice /c 129
Af errorlevel 3 goto :eof
Af errorlevel 2 goto Instructions
Af errorlevel 1 goto Gane
"Instructions
els
echo.
fecho *
echo.
fecho The instructions are simple, Answer the
‘questions correctly.
ho.
cho stistiatenssnnennnennenesnaatensente
pause
ele
goto menu
st /a question=tquestiont41
(goto end) else (echo you are on
‘timeout /T 5 /nobreak > nul
A€ tquestiont ==5 (goto end) else (goto tquestion®)1
cls
‘echo.
(echo. Semmernesaesavesnesnnenneseets,
‘echo.
‘echo Your current score is tacoret
‘echo.
cho sHtittenseaneanennstsntensenee
‘echo.
‘echo.
‘echo Question tquestiont
‘echo.
‘echo Which of the following version of Windows is the best?
‘echo.
‘echo A. Windows 10
sho.
‘echo B. Windows ME
‘echo.
‘echo C. Windows Vista
‘echo.
choice /C abe
Af errorlevel 3 goto wrong
Af errorlevel 2 goto wrong
Af errorlevel 1 goto correct
2
cls
‘echo.
cho setinteneeneesneuetantesente
‘echo.
‘echo Your current score is tscoret
‘echo.
Cacho. #ttsstensensnenennennanwanenss,
‘echo.
‘echo.
‘echo Question tquastiont.
‘echo.
‘echo Which of the following version of Windows is the
most stable?
‘echo.
‘echo A. Rindows 10
‘echo.
‘echo B. Windows 95
‘echo.
‘echo C. Windows ME
‘echo.
choice /C abe
Af errorlevel 3 goto wrong
Af errorlevel 2 goto wrong
Af errorlevel 1 goto corzect
3
els
‘echo.
(echo. sernernesaesavennranmerneneets
‘echo.
‘echo Your current score is tscoret
‘echo.
cho sHtitteeeneesnenetsnteseate
‘echo.
‘echo.
‘echo Question tquestiont
‘echo.
‘echo Which of the folowing Windows version is the latest?
‘echo.
‘echo A. Windows 10
‘echo.
‘echo B. Windows 98
‘echo.
wor bmpublcationscom
Creating a Batch File Game
‘echo C. Windows 7
echo,
choice /¢ abe
Af errorlevel 3 goto wrong
Af errorlevel 2 goto wrong
Af errorlevel 1 goto correct
4
cls
echo.
echo sttistenstatsesnesnstsstante
echo.
fecho Your current score is tscoret
echo,
echo thetestvastessensennenesvasten
echo.
‘echo.
fecho Question tquestiont.
echo.
‘echo Which of the following Windows uses Directx 127
echo.
fecho A. Windows 10
echo,
fecho B. Windows 3.12
‘echo.
fecho C, Windows xP
echo.
choice /C abe
Af ezrorlevel 3 goto wrong
Af errorlevel 2 goto wrong
if errorlevel 1 goto correct,
Wrong:
cls
echo thttastensestensee
echo.
fecho WRONG!!!
echo,
echo Shetvstvaneassnnee
t fa score=tscoret-1
pause
goto igame
cls
echo. sranverneseetanena
echo,
fecho CORRECT, YIPEE!!"
echo.
cho sittastessessensee
tt /a score=tscorettl
pause
(goto game
fend,
cls
fecho thstestvastessensennenasvesten
echo.
fecho Well done, names, you have answered all the questions
echo.
cho And your final score is.
echo.
fecho tacoret
echo.
fccho seteeiestantenessresneetneeeets
choice /M “play again? ¥/N"
Af errorlevel 2 goto :eof
A errorlevel 1 goto start
[8DMs Definitive Guide Seis | sth tion=> Programming with Scratch and Python )
Scratch is a Free programming
language and online community
that’s targeted primarily at young
people but also useful for older users
too. It’s a visual language created
by MIT (Massachusetts Institute of
Technology) and designed to help teach
the building blocks of programming.
It’s extremely versatile and as such can
be used in conjunction with Python
code to create interesting and useful
programs. With the pairing of Scratch
and Python you can make games,
system utilities and even control
external sensors, robots and motors.
122 Getting Started with Scratch
124 Creating Scripts in Scratch
126 Interaction in Scratch
128 _Using Sprites in Scratch
130 Sensing and Broadcast
132 Objects and Local Variables
134 Global Variables and a Dice Game
136 Classes and Objects
ED scene aes an cson(index
wor bmpublcationscom DMs Definitve Guide Series thin GHEP Programming with Scratch and Python)
Getting Started
with Scratch
INSTALLING SCRATCH
Scratch can be run inside your web browser at scratch.mit.edu. You need to have Flash installed in your browser; if isn't already,
it can be installed from get.adobe.com/flashplayer. Sign up For an account with Scratch so you can save your programs.
BETES Scratch runs from inside the web browser. lick PRTIIEDD 12%’ take alook at Scratch Cat. Use cick and drag
Create to open a new document. The Scratch with the mouse to position him on the Stage. At
InterFace opens in the web browser, click the maximise buttonon the top, just above Scripts, youl see two icons for Grow and Shrink.
your browser so you have plenty of space toview the window and Click one and click the cat to resize him, shift-click on Scratch Cat
allits contents, and choose info to access rotation controls. lick the blue back
button to get back to the Sprites pane.
BED ercrtesestinereewinatcarite ERI sectietatte ny enh
ems nthe lock Plt, an empty Sept rea sole’ gv im abaciground chick thestageicon
{and a Stage. On the Stage will bean orange cartoon cat, known tothe left of the Sprites Pane. The Script Area switches to Backdrop
{as “Scratch Cat’. This isthe default sprite that comeswith allnew Library displaying the available backgrounds. Click Music and Dance
projects; you will also see smaller versions ofthe sprite above the _and choose spotight-stage. Click OK.
Script Area and in the Sprites Panel
FB)
BETTI) wo ceive cae ee tonESTeGEERD The background appears on the Stage and Scratch
Cat looks a lot happier, Let's create a script that
‘moves him to the stage. Click Sprite! in the Sprites Pane to select
the cat and click the Scripts tab to return to the Script Area, Now
lick the blue Motion tab atthe top of the Block Palette
=
SAVING SCRATCH FILES
“ Getting Started with Scratch
Drag the turn [15] degrees block (with an
Sua anti-clockwise symbol) from the Block Palette
tothe Script Area, Now crag the move. [10] ‘steps bloc and
connect to the bottom othe Trn 15 Degrees lock They il
Snap together Change the 1Bin move [10] steps to 100, Ou
program snow ready. Clckthe scrip the two Bods) to see what R
Goes Scratch cat wl rotate and move towards the stage,
‘Take the time to learn how to open and save your files, and open other test programs, before you get stuck into programming
with Scratch. There are lots of Scratch programs available so it’s easy to learn alongside other users.
STEP 1 flick File> Save Now to save your project. Enter
‘anamein the New Filename box; we called ours
*Scsatch_Cat_On Stage”. As we mentioned in both Python and
Unix tutorials, i's important to avoid any special characters and
spaces in your filenames. Use underscores ”_” instead.
Lots of example Scratch files can be found on the
MIT website by clicking Explore. Here you can see
‘a huge range of projects built by ather users and youl also be
‘able to share your own projects. Choose a project From Explore to
‘openit.
STEP 3
hoor Fe» Goto My Suto exethe stage ne
area view the saved file. Click the Scratch_Cat_On_
Stage nko vew youre You ca add istructons Notes end
Credis here and Tags Ck See inside toheadback to viewing
Ss cea,
‘You can run the project directly inside the main
window by clicking the Green Flag icon. Click the
‘Star icon to Favourite or bookmark the project and the Heart icon
to lke i. More importantly, click the See Inside to see the code
used to create the projec. This is a good way to learn how Scratch
codes being used
STEP 4
wor bmpublcationscom
DMs Definitive Guide Series | «tection GaEP Programming with Scratch and Python)
Creating Scripts in Scratch
VISUAL CODING
The scripts in Scratch are created by snapping together blocks. These blocks are simi
programming languages, such as Python, but much easier to understand.
PEPE cick create to start anew Scratch project and
name it Dancing Cat. You're going to put your cat
‘and some other characters on a dance Floor and get them to bust
some moves. lick Stage, then Music and Dance and choose party
room, Drag the Scratch Cat graphic around the Stage to find a good
starting position,
1 to the code you Find in more complex
Click the Motion tab and drag themove [10]
S15 steps block and connect it beneath the when
flag clicked block. A quick word about that [10]. When you write
anumber or word inside those square rackets, that's He voy of
Saying youcan choose avalve Is the equa of aval’
because varies Wel tel ou which number osleton wee
using but youcan se ay ou want Pay around
Click on Spritet in the Sprites Panes and click the
Scripts tab above the Scripts area. Now click Events
inthe Blocks Pane and dragthe when flag clicked block into the
Scripts area. This block represents the stat of your program. Itells
Scratch to run through the blocks below it when we click the Green
Flag con above the Stage window.
[0.2] beats and connect it to the bottom of the stack of blacks.
Pa
(Creating Scripts in Scratch
Dancing ia bckand forth afar, so le’ get Scratch
1295 Cat moving back. Drag another move [10] steps
blokto the bottom othe stack Now ickthe 8 and change Rt
220 (ins 10, Eten mins Rares moves the cat bacvard
Orag another play. drumblock othe bottom the cp Paka
different rumsound, We chose 13,
—
f
EDITING SCRIPTS
Scratch Cat ony moves back and forth once, which
SSIES) isn't much of a party. Click Control and drag the
forever blockto the Sriot Aes Careful postion beneath the
when [flag] clicked block but above themove [10] steps
block The spt shoud nest hin the two prongs of the Forever
block Cte Green Flag onto stat the dco cckthe red top
lento end the program
Nothing is set in stone, and you can move your blocks in and out of scripts and even have several scripts or parts of scripts in
tthe Script Area. Scratch is Far more Forgiving than other programming languages for experimentation.
STEP 1) fes)pretty bad form to use the forever Block
‘or a forever loop in programming. Programs are
‘Supposed to run from start to a inish. Even programs like Scratch
have an end point when you quit the program. You want to replace
the forever block witha repeat one, Click the forever blockin
{yout script and drag t dowin to separate it From the other blocks.
Yourroveandp\ay_crunblcks re stilinested
area within the forever block though and you want
toe them, Cekthe topmost ~0ve lock and droga ofthe
Forever Blade e’snow goad get if the forever blocks0
dragitt the le andbacto the Blocks Ust to et do
=
wor bmpublcationscom
Nowéraga repeat [10] Block fromthe block ist
andeonnectietSEfginen [flag] clickedblock
inthe Script Area, Now drag the top play drunblockaf the stack
insidethe repect_ [10] block If you dragthe top block ll the
blocks underneath move witht and the whole lot willbe nested
insidetherepect [10] stack
STEP 3
‘You can position the stack anywhere on the Script
‘Area and even keep the unused blocks around,
although we thinkit’s good practice to keep only what you are
using in the Scriot Area and remove ary unused blocks, Click the
‘Green Flag icon above the Stage Window to view Scratch Cat doing
‘ashort dance.
a E-
25
STEP 4
[8DMs Definitive Guide Seis | sth tionEP Programming with Scratch and Python)
Interaction in Scratch
INTERACTIVE CONTROL
The only Control option we've really looked at so Faris the when [flag] clicked block, whi
is running it does its thing, right up until it Finishes. You're going to use the other Control blocks to do something more interesting,
(Open the Dancing Cat program from previous
tutorials Select Sprite1 and click on Events so you
cansee the when [fag] clicked script. Now click Controlin the
Block Palette and dragthe when [space] key pressed block to
‘antempty part ofthe Script re.
You can drag and rearrange the block scripts to any
pat ofthe Script area We ke to have our when
[fag] Licked scripts in the top left butt really doesn't matter
where they are. t's also worth potting that we now have more than
Cone scrit for Sprite; you can have multiple scripts For each sprite in
your program.
=a
EE
= fo
ao
=
=
=
=
=
wee goingto mate Scratch Ctjump up and down
SEP) when we press the space bar. Click Motion and drag
change y by [10] and cip tothe when space] key
pressed bloc What's wth they"? Thsisuhas owns
Pcoordnae
FI
aa
=
=
=
=
—
‘The position of each sprite on the stage is shown
Using two variables, xand y. These are referred
toas the "coordinates". The xis the sprites horizontal postion
‘on the stage whilst the y coordinate isthe vertical position. Click
and drag the sprite araund the Stage and youll see the x and
rhumbers change.
starts the program. Once the programInteraction in Scratch
The centre of the tage x0 andy.0. As youve
1275 the sprite up and to the right the numbers increase
andasyourove lef and down the decrease (Gong into negative
numbers) Sowhenwe use the chonge y by. [10] block says
take the current value of y (the vertical position) and increase it by
10. That mates ow et jump up.
hat goes up must come back down, So crag
S16 another change y by [10] block and attach it
tothebottom othewhen [space] Key pressed cpt Now
change [18] to [-10] Clk the GreenFlag and run he program,
Now pres the space ar nd. cho, ating heppers Weve js
encountered ourfrst "bug
FIXING YOUR SCRIPT
‘We know that there's something wrong with our script and we want to see Scratch Cat jump when the space bar is pressed. So
let's quickly squash this bug and see it working.
STEP 1. ) theproblemis that programs are superfast and
highly visual programs like Scratch can move in
the blink ofan eye and that's what is happening here. Ifyou tap
the space bar repeatedly while the pragram is running you'llsee
‘Scratch Cat Flickering as it jumps up and down.
*
oo
eo
The chalenge that our mation conto move the
area cat instantly from one place to another, so fast that
ie cart see Sometimests ine, Ike our back and Forth dance,
but obviously we need to slow downthe ump. Helps than.
Click the Mion ab fo vew the Maton Blocks
wor bmpublcationscom
Braganait [1] secs block from the Blocks
Palette and isertieunderneath the change Ly]
by 10 block Now press the space bar on the keyboard to see
‘Scratch cat jump up, and then back down, Notice that you don't
need to press the Green Flag con to run the program; the Green
Flag starts our other scrip.
STEP 3
We think Seat Cat stays in the aa ito tng
see ‘We want a jump, not a levitation effect. Change
thewait [1] secsMarableto [0.25 | Thisisa quarter ofa
second and il sve usamore fn hop. Press the Gren Flag to
Sat the script and tap the space br whenever you want Scratch
Catto jump.
DMs Definitive Gude Series | «tection GBRUsing Sprites in Scratch
LOOK SPRITE
Sprites are 2D (flat) graphics drawn on top of a background. They are commonly used to display information in games such as.
health bars, scores or lives. Older games are composed entirely of sprites, just like our Scratch project.
PEPER We're a0ing to add another sprteto our project and JESIEIEM ali the blocks on the Script Area have vanished. The
‘second character to the scene, Click the Choose scripts we built For Scratch Cat relate to that object,
Sprite From Library button, just above the Sprites pane. Thisopens not to our newprite. Click on Spritet in the Sprites pane to view
the Sprite Library that displaysall the different characters available. the Scratch Cat scripts again, Then click Giga to return to your
Giga character.
7
7
i UATE
wy
PEPIIPDD click on the Fantasy linkin the sidebar and choose © RAB now that we have more than one sprite, i's a
Giga, Click OK to add the character to the stage. ‘good idea to name them. Click the "icon next to
Click and drag the sprite to reposition Gigato the right of Scratch Sprite Change Spritet in the text box to Scratch Cat. Take a look at
CCat-Notice that a Gigaicon hasjoined Spritet inthe Sprites pane. _the other options here. You can remove a sprite from the stage by
Lnticking the Show checkbox, without deleting it from the project.
Wy
BNET) won etn cae ee ton(_ Using Sprites in Scratch
Select ig and choose Evens Drag aie
1275 [space] key pressed and change [space] to
[right arrow]. Adda change x by [10] block beneath,
Shife-click the script and choose duplicate to create another. For the
second script change the when [right arrow] key pressed to
[left arrow] and change x by [10] to [-10}.
CHANGING COSTUMES
(We're quite sure you can see where this is going
Press the Green Flag icon and our Scratch Cat object
willstart to dance and stil jumps with space, whilst our other
‘object, Giga, can be moved left and right using the arrow keys on
cour keyboard
‘Our two objects, Giga and Scratch Cat don't have to look like the original characters. That's ust the name we've given to each
sprite. The visual appearance is a costume and our objects can change their costume and look completely different,
STEP 1 ) Select Gigain the Sprite Pane and click the
Costumes tab. The Scripts Area now displays the
‘costumes being used by Giga, including the current look. Choose
) Programming with Scratch and Pytho! )
Global Variables
and a Dice Game
DOUBLE TROUBLE
We're going to start with the dice game from the previous tutorial, but create a second character. The Fancy OOP word For this
is “instantiation”: creating an instance of something ~ in this case another instance of Scratch Cat.
FETTER . This sits between
two numbers, i.e. 3> 2 and lets you know ifthe number on the left is bigger than the one on the right.
STEP 1
Both sprites are going to announce thelr score and
the one with the highest score wil say, twin!
CRETE drag say [hello] for 2 secs: Naw dick Data
land drag_vic_total Rofeplaes [hel Lo PRRs part of the
‘game is réady, we're going to use an iF block with an > operator,
For the next part of the game.
STEP 3
‘Bob needs to run the same script, only with bob_
total in place of cat_total. We could write Bob with
the same code but the point of objects that you can stamp out
‘copies. Shft-ck Bob and choose Delete, Now shift-click Vic and
‘choose Duplicate. Click the Info con and rename Vic2 as Bob.
{lick Controtand drag an «block to the script
ag I
Slot in the «block. Click Variables and drag vic. total tothe left
‘ofthe block and bob total to the righ: Finally click Looks and,
dreqa|say [hel Lo!) BIGeRinside the «F block and change the
Roxio win'
wor bmpublcationscom
‘ou need to cange Bobs variables Change
sree iset_vic_totalfgset bob_totaljandsay
frTetotatllsay bobo li spiaahe vc
Totaljandbob total | blak Now eke Gree
Flag conto play the me, Vic and Bob role the de andthe
inners announced
DMs Definitive Gude Series | «tection (GBBClasses and Objects
SCRATCH THAT
©0P can be hard to explain, but makes sense when you start using it
looks like a sprite. This is why we detoured into Scratch. It’s great for learning OOP.
what an object look
IF you've used Scratch then you already have an idea of
PEPER | thistutorial we're going to open the dice game
program that we created earlier in Scratch. Resize
the window and place Scratch on the letthand side ofthe screen,
[Next we're going to recreate this game in Python using objects, so
you can see how objects are similar to Scratch sprites
‘Open Python 2 and choose File> New Window.
Resize the Editor window tothe righthand size of
the screen. Choose File» Save As and nameit dice_game. Now let's
hhave a look atthe objects in Scratch. We have two: Vic and Bob.
ach has three variables (two dice and a total); both pick random
‘numbers between 1 and 6 and check ta see if their totals bigger
than the other
BETS) wos ete cae ee ton
in OOP we on design objects. steed we desion
STE a blueprint For our object, called a "Class". Think of
ikea bern or stamp. Vic and Bob ae bat erolng cts 50
wwe crete a buepinfora dceroling animal We then stamp out
two identical objects rm tha blueprint One cle "Vc theater
Galed"B0b, We're goingtoneedthe random number made so
eer thse
from random import randint
EERE Now let's derine our class, which we're going to call
Diceanimal. Enter:
class DiceAninal(:
dicel = 0
dice2 = 0
total = 0
Notice the funny capitalisation of DiceAnimal. This isknown as
‘CamelCase and class definitions should be named inthis Fashion,(Classes and Objects
Now we'e gong to define a function that os both
ona dice, and adds the two together to create the total.
inde the class indented our ines tone up wth ce, dle? and
talent ths
def rotlaice(set®):
self.dicel = randon.randint Ct, 6)
Self dicee = random: randintCl, 6)
Self total = self-dicel + self.dice2
CREATING OBJECTS
‘Now that our classis ready, we need to create two characters from it. One ‘vic’ and one ‘bot
Looks Scat, ndyou'see th the sre as
S16 the set dice? to pick random 1 to 6 block. But what
arethose sel bits about Remember that ic and Bob have the
din dee. ies ke re going beacesed sevice ane
diced and Bos using bob det andbobiced but the dass doesnt
Know what we'e gong to calleach object stead uses"sel 953
placeholder This works matter what name ech objet hs
"These are known as objects, and
‘also sometimes as instances (or ‘object instance’). Because each one is an instance of the DiceAnimal class.
STEP 1 £feating an object in OOP has abig fancy name:
"instantiation’. Don't be impressed by the
{fanquage, allt meansis creating an instance of your class. And this
{s exactly the same as creating a variable, ony instead of passing in
‘a number, orstring, you make it equalto your class, Enter this.
Wvic = DiceAnimal()
b= DiceAnimalc)
‘There, that wasn't hard a all.
You now have two objects, a vic and a bob. You
area access the variables and functions inside the object.
using the objects name followed by a dot. To access Vic's dice, you
“usevic.dice1 and vic.dice2. We're going to get both objects to roll
thei die and store the total inthe own seltoal. Enter
Wic.rolldicec)
bob. rolldiceC)
‘Now we're going to use dot notation to access
the values inside both the cat and lobster. Enter
STEP 3
this code:
print “Vic rolled a™, vic.dicel, “and a”
ivic. diced)
print “Bob rotted a™, bob.dicel, “and a”
bob. dice7]
Finally, vee going to use if elif and else statements to create
the game.
STEP 4 | Enterthiseade:
RF vic.total > bob. total:
print "Vic wins
[elif bob. total > vic. total:
print "Bob wins”
jelser
print “It's a draw”
ress FS to run the game,
wor bmpublcationscom
DMs Definitive GudeSeries | «tection GBRWorking with Code
At this point, you can see that there's
more to coding than simply entering
a Few lines into an IDE and expecting
a result. Working with code means
conforming to proper layout, adhering
to strict operations and making
the code as easy to understand and
efficient as possible.
In this section we take a look at the
‘common coding mistakes with Python,
C++ and Linux scripting and how to
avoid them. You can learn how to
check your code with checklists, Find
sources of help when you're stuck and
test your code online in a safe and
secure environment.
Learning to code is an on-going
‘occupation, where you discover new
techniques and ways of managing
code from other developers. Being
able to recognise mistakes, Fix them
and then help others is all part of
becoming a better coder.
140 Common Coding Mistakes
142 _ Beginner Python Mistakes
144 Beginner C++ Mistakes
146 Beginner Linux Scripting Mistakes
148 Code Checklist
150 Where to Find Help with Code
152 _Test Your Code Online
154 Python OS Module Error Codes
156 Python Errors
158 Where Next?
160 Glossary of Terms
OM Definitive Guide Series sth EstonWorking
with CodeCommon Coding Mistakes
NUR eee hae NR Mu Aue cme ey Tag
down to inexperience and those mistakes are great teachers in themselves. However,
even experts make the occasional mishap. Thing is, to learn from them as best you car
X=MISTAKE, PRINT Y
‘There are many pitfalls For the programmer to be aware of, Far too many to be listed here. Being able
to recognise a mistake and fix tis when you st
Ie would be wonderful to be able to
‘work lke Neo from The Matrix movies.
Simply ask, your operator toads it into
your memory and you instantly know
everything about the subject. Sadly
though, we cant do that. The First
‘major pitfallis someone trying to learn
too much, too quickly. So take coding in
small pieces and take your time.
Use comments. I's a simple concept but commenting on
your code saves so many problems when you next come to
look over it Inserting comment lines helps you quickly sift
through the sections of code that are causing problems;
also useful if you need to review an older piece of code.
t to move into more advanced territory.
"Meaningful naming for variables is @ must to eliminate
common coding mistakes. Having letters ofthe alphabet
isfine but what happens when the code states there's.
a problem with x variable. It’s not too dificult to name
variables tives, money, playert and soon.
points
points);
write("Lives: "s1ives);
write + "totaltimes" secs’
write( Y
‘totalscore = 07
urite( "Your total Score is: ~stotalscore) 4
PLAN AHEAD
While it’s great to wake up one morning and decide to code
a classic text adventure, it's not always practical without a
‘good plan. Small snippets of code can be written without,
too much thought and planning but longer and more in
depth cade requires a good working plan to stickto and
help iron out the bugs.USER ERROR
BACKUPS
RE-INVENTING WHEELS
SECURE DATA=P Working with Code
Beginner Python Mistakes
Se eo CUtee erences MMe sos
Recomm en acie ec an eee TU
programming language, it can be easy to make common mistakes that'll stop your
code From running.
DEF BEGINNER(MISTAKES=10)
Here are ten common Python programming mistakes most beginners Find themselves making. Being able to identify these
mistakes will save you headaches in the Future.
Python has two live versions of ts language available to download
{and use, There is Python version 2.7.xand Python 3.63. The 3.6.
version isthe most recent, and the one we'd recommend stating,
ut, version 2.7.x code doesnt always work with 3.6.x code and
To add to the confusion that most beginners
already Face when coming into programming,
python
very programmer has and does at some
THE INTERNET
point go on the internet and copy some
cade to insert into their own routines. There's nathing wrong with
Using others’ code, but you need to know how the code works and
what it does before you go blindly running iton your own computer.
Creatldlete a tt fen a python program
FEED cor: oernve cuide Series sth Eston
Python uses precise
(RTECS URES Ri DfES indentations when
displaying its code. The indents mean thatthe code in that section
isa part ofthe previous statement, and not something inked with
‘another part ofthe code. Use four spaces to create an indent, not
the Tab key,
‘Again we mention commenting
Ita hugely important factor in
programming, even ifyou'e the only one who is ever going to view
the code, you need to add comments as to what's going on. Is this
Function where you lose a life? Write a comment and help you, or
anyone else, see what's going on,