100% found this document useful (1 vote)
191 views164 pages

BDM's Coding For Beginners - 2018 UK

Uploaded by

Jaydeep Pawar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
191 views164 pages

BDM's Coding For Beginners - 2018 UK

Uploaded by

Jaydeep Pawar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 164

Coding

New! | Python 3 | Linux


Scripting | C++ BDM’s

for Beginners Helping You with Your First Steps in Coding

Learn
Python,
100% Independent

Scratch and
BASIC!

. ..
i de un
eed tok
ns Packed with top Featuring C++, Become the
All yo

I
no

tips, tricks and Python 3, Linux scripting, coder you


w

tutorials Scratch and more want to be re


ng
fo

a s y c o di
BDM’s Definitive Guide Series

Coding
for Beginners
Discover how to turn your ideas into code
Programming is everywhere. From clicking an icon 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
how to 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 turn 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!

BDM’s BDM’s Coding for Beginners Editorial and design are the copyright © Papercut Limited. No part of this publication BDM’s BDM’s Coding for Beginners is an independent publication and as such does
ISBN: 978-1-907306-18-1 may be reproduced in any form, stored in a retrieval system or integrated into any not necessarily reflect the views or opinions of the producers contained within. This
Published by: . . . . . . . . . . . . . . . . Papercut Limited other publication, database or commercial program without the express written publication is not endorsed by or associated in any way with Microsoft, The Linux
Managing Editor: . . . . . . . . . . . . James Gale permission of the publisher. Under no circumstances should this publication and Foundation, The Raspberry Pi Foundation, ARM Holding, Canonical Ltd, Python,
Art Director & Production: . . . Mark Ayshford its contents be resold, loaned out or used in any form by way of trade without Debian Project, Linux Mint, Lenovo, Dell, Hewlett-Packard, Apple and Samsung
the publisher’s written permission. While we pride ourselves on the quality of or any associate or affiliate company. All copyrights, trademarks and registered
Production Manager: . . . . . . . . Karl Linstead
the information we provide, Papercut Limited reserves the right not to be held trademarks for the respective companies are acknowledged. Relevant graphic
Design: . . . . . . . . . . . . . . . . . . . . . . Robin Drew, Lena Whitaker
responsible for any mistakes or inaccuracies found within the text of this publication. imagery reproduced with courtesy of Lenovo, Hewlett- Packard, Dell, Samsung, FUZE
Editorial: . . . . . . . . . . . . . . . . . . . . David Hayward Due to the nature of the software industry, the publisher cannot guarantee that all Technologies Ltd., Linux Mint and Apple.
Sub Editor: . . . . . . . . . . . . . . . . . . Paul Beard tutorials will work on every version of Raspbian OS. It remains the purchaser’s sole
Additional images contained within this publication are reproduced under licence
responsibility to determine the suitability of this book and its content for whatever
Digital distribution: Pocketmags.com, Zinio.com, Apple App from Shutterstock.com.
purpose. Images reproduced on the front and back cover are solely for design
Store & Google Play purposes and are not representative of content. We advise all potential buyers to Prices, international availability, ratings, titles and content are subject to change. All
check listing prior to purchase for confirmation of actual content. All editorial opinion information was correct at time of print. Some content may have been previously
Copyright © 2018 Papercut Limited. All rights reserved. herein is that of the reviewer as an individual and is not representative of the publisher published in other volumes or BDM titles. We advise potential buyers to check the
or any of its affiliates. Therefore the publisher holds no responsibility in regard to suitability of contents prior to purchase.
INTERNATIONAL LICENSING – Papercut Limited has many editorial opinion and content.
great publications and all are available for licensing worldwide. Papercut Limited
For more information go to: www.brucesawfordlicensing.com; Registered in England & Wales No: 4308513
email: [email protected];
telephone: 0044 7831 567372

@bdmpubs BDM Publications www.bdmpublications.com


BDM’s Coding for Beginners

Contents
6 Coding and Programming 36 Equipment You Will Need
38 Getting to Know C++
8 Choosing a Programming Language
40 How to Set Up C++ in Windows
10 Learning to Code – Study Tips
42 How to Set Up C++ on a Mac
12 Coding Tools and Resources
44 How to Set Up C++ in Linux
14 Being a Programmer
46 Other C++ IDEs to Install

16 Say Hello to Python 48 Coding on Linux


18 Why Python?
50 Why Linux?
20 Equipment You Will Need
52 Equipment You Will Need
22 Getting to Know Python
54 Transfer Mint to DVD or USB
24 How to Set Up Python in Windows
56 Installing VirtualBox
26 How to Set Up Python on a Mac
58 Testing Linux Mint’s Live Environment
28 How to Set Up Python in Linux
60 Installing Linux Mint on a PC
30 Installing a Text Editor
62 Installing Linux Mint in VirtualBox
64 Getting Ready to Code in Linux
32 Say Hello to C++ 66 Creating Bash Scripts– Part 1
34 Why C++? 68 Creating Bash Scripts– Part 2

4 BDM’s Coding for Beginners


Contents

70 Creating Bash Scripts– Part 3 116 Loops and Repetition


72 Creating Bash Scripts– Part 4 118 Creating a Batch File Game
74 Creating Bash Scripts– Part 5
76 Command Line Quick Reference 120 Programming with Scratch and Python
78 A-Z of Linux Commands
122 Getting Started with Scratch
124 Creating Scripts in Scratch
80 Programming with the FUZE 126 Interaction in Scratch
82 Introducing the FUZE Project 128 Using Sprites in Scratch
84 Setting Up the FUZE 130 Sensing and Broadcast
86 Getting Started with FUZE BASIC 132 Objects and Local Variables
88 Coding with FUZE BASIC – Part 1 134 Global Variables and a Dice Game
90 Coding with FUZE BASIC – Part 2 136 Classes and Objects
92 Coding with FUZE BASIC – Part 3
94 Using a Breadboard 138 Working with Code
96 Using the FUZE IO Board
140 Common Coding Mistakes
98 Using a Robot Arm with FUZE BASIC
142 Beginner Python Mistakes
100 FUZE BASIC Examples – Part 1
144 Beginner C++ Mistakes
102 FUZE BASIC Examples – Part 2
146 Beginner Linux Scripting Mistakes
148 Code Checklist
104 Coding with Windows 10 Batch Files 150 Where to Find Help with Code
106 What is a Batch File? 152 Test Your Code Online
108 Getting Started with Batch Files 154 Python OS Module Error Codes
110 Getting an Output 156 Python Errors
112 Playing with Variables 158 Where Next?
114 Batch File Programming 160 Glossary of Terms

www.bdmpublications.com BDM’s Coding for Beginners 5


Coding and Programming

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 program is 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
go 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.
In this 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
12 Coding Tools and Resources
14 Being a Programmer

6 BDM’s Coding for Beginners


Index

Coding and
Programming

www.bdmpublications.com BDM’s Coding for Beginners 7


Coding and Programming

Choosing a
Programming
Language
It would be impossible to properly
explain every programming language in
a single book of this size. New languages
and ways in which to ‘talk’ to a computer
or device and set it instructions are being
invented almost daily; and with the
onset of quantum computing, even more
complex methods are being born. Here
is a list of the more common languages
along with their key features.

8 BDM’s Coding for Beginners


Choosing a Programming Language

SQL SQL stands for Structured Query Language. SQL is a standard language
for accessing and manipulating databases. Although SQL is an ANSI
(American National Standards Institute) standard, there are different versions of
the SQL language. However, to be compliant, they all support at least the major
commands such as Select, Update and Delete in a similar manner.

JAVASCRIPT JavaScript (often shortened to JS) is a lightweight,


interpreted, object-oriented language with first class
functions. JavaScript runs on the client side of the web, that can be used to design
or program how the web pages behave on the occurrence of an event. JavaScript is
an easy to learn and also powerful scripting language, widely used for controlling
web page behaviour.

JAVA Java is the foundation for virtually every type of networked


application and is the global standard for developing enterprise
software, web-based content, games and mobile apps. The two main components
of the Java platform are the Java Application Programming Interface (API) and the
Java Virtual Machine (JVM) that translates Java code into machine language.

C# C# is an elegant object-oriented language that enables developers to


build a variety of secure and robust applications that run on the .NET
Framework. You can use C# to create Windows client applications, XML Web
services, client server applications, database applications and much more. The
curly-brace syntax of C# will be instantly recognisable to anyone familiar with C,
C++ or Java.

PYTHON 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
to express concepts in fewer lines of code. This can make it easier for new
programmers to learn.

C++ C++ (pronounced cee plus plus) is a general purpose programming


language. It has imperative, object-oriented and generic programming
features. It was designed with a bias toward system programming and embedded,
resource-constrained and large systems, with performance, efficiency and flexibility
of use as its design highlights.

RUBY Ruby is a language of careful balance. Its creator, Yukihiro “Matz”


Matsumoto, blended parts of his favourite languages (Perl,
Smalltalk, Eiffel, Ada and Lisp) to form a new language. From its release in 1995,
Ruby has drawn devoted coders worldwide. Ruby is seen as a flexible language;
essential parts of Ruby can be removed or redefined, at will. Existing parts can be
added to.

PERL Perl is a general purpose programming language, used for a wide


range of tasks including system administration, web development,
network programming, GUI development and more. Its major features are that it’s
easy to use, supports both procedural and object-oriented (OO) programming, has
powerful built-in support for text processing and has one of the most impressive
collections of third-party modules.

SWIFT Swift is a powerful and intuitive programming language for macOS,


iOS, watchOS and tvOS. Writing Swift code is interactive and fun;
the syntax is concise yet expressive and Swift includes modern features that
developers love. Swift code is safe by design, yet also produces software that runs
lightning fast. A coding tutorial app, Swift Playgrounds, is available on iPad.

www.bdmpublications.com BDM’s Coding for Beginners 9


Coding and Programming

Learning to Code –
Study Tips
Programming is one of the most valuable skills you can pick up these days,
particularly for your career prospects; and great just to test your brain and get to
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
tips to set you off in the right direction.

CHOOSE YOUR LANGUAGE LEARN WHAT BEING A CODER MEANS


It may sound obvious but Take some time to look at the things coding languages are used for; so if you
choosing the are interested in web design, look at how JavaScript is being used on the sites
right coding or you use every day; if you are in to mobile apps, look into Java or Swift and see
programming language to how they make apps work. It can also be useful and encouraging to check out
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 if you learn to code Python you are immediately going to
process to be successful. If be offered a £70,000 a year job but it can help spur you on to study harder.
you need learn to code for a specific reason,
finding a job for example, then you obviously
need to learn the language that’s relevant. If
you simply want to learn coding, then picking
a language like Python, that is both powerful
and relatively easy to learn, can make success
more likely.

PUT THEORY INTO PRACTICE


If you are completely new to coding, learning any programming
language can seem like a huge task. Getting completely bogged
down in pages and pages of code examples and explanations
is not likely to make the learning process much fun. In our
experience it is often better to learn through practice, or to
choose a task 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
intervals is called Spaced Repetition.

10 BDM’s Coding for Beginners


Learning to Code – Study Tips

SET UP YOUR ENVIRONMENT STUDY IN DIFFERENT WAYS


Take some time to look at the things coding Sometimes, though admittedly not always, it’s a good idea to get a more
languages are used for; so if you are interested rounded view of computer science before you dig down into more specific
in web design, look at how JavaScript is being programming language study. There are several free “Introduction to
used on the sites you use every day; if you are Computer Science” courses available online, including a great one from
in to mobile apps, look into Java or Swift and see Harvard University (via the www.edx.org website). Another study tool that can
how they make apps work. It can also be useful be useful is to play coding games. Two of the best of these types of learning
and encouraging to check out what qualified games are CodeCombat and CodinGame. Search online to find them.
coders can expect to get paid by looking at
local job sites. We are not saying that if you
learn to code Python you are immediately
going to be offered a £70,000 a year job but it
can help spur you on to study harder.

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, don’t be
afraid to ask questions. You might find that others are a bit
snappy if you don’t follow the questioning rules of that forum
but just figure out what you did wrong and learn to ask better
questions. Don’t worry though, ask your questions, listen to
the answers and remember to thank people for their help,
remembering to come back when you are more experienced
and answer a few questions yourself if you can.

DON’T SET YOURSELF DEADLINES

If at all possible, that is. Deadlines, although a part of a


professional programmers life, can definitely hurt your
progress when in the process of learning to code. This is
especially true of self-imposed deadlines, and at this point
they almost certainly will be, 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
later stages harder if you do not fully understand the basics.

www.bdmpublications.com BDM’s Coding for Beginners 11


Coding and Programming

Coding Tools and


Resources
Learning to code isn’t just about studying the syntax of a language and memorising
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,
whether you want to experiment with a new
programming language or host your life’s work.
Any kind of file can be uploaded to GitHub but it’s
designed particularly for code files and is hugely
popular. It provides access control and several
collaboration features such as bug tracking, feature
requests, task management and wikis for every
possible project. GitHub reports having more
than 14 million users and more than 35 million
repositories, making it the largest host of source
code in the world.

TEXT EDITORS
If you are serious about learning to code, you
will spend much of your time working in a
simple text editor. Finding the right one for
you, and for the language you are working
with, may take a bit of experimentation
but this process is completely worth the
effort. All personal computers come with
text editors built in. If you’re on a PC, then
your built-in text editor is Notepad. If you’re
on a Mac, there isn’t a program exclusively
designed for writing code. However, you
can set up TextEdit to work as a text editor
by going into Preferences and selecting the
Plain Text radio button.

Popular text editors for coders and


programmers include: Sublime Text,
Notepad++ and Vim.

12 BDM’s Coding for Beginners


Coding Tools and Resources

HEROKU
If you are developing a web app, you will need to host it before
people can access it. GitHub can host your code but that doesn’t
mean that end-users will be able to use the working app. This
is where a service like Heroku comes into its own. Heroku is a
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. It 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, unlike text
editors, offer a complete coding environment. This
makes it easier for some programming beginners to get
to grips with a new language. Integrated Development
Environments, also known as Code Editors, are software
applications that provides comprehensive facilities to
computer programmers for software development.
An IDE normally consists of a source code editor, build
automation tools and a debugger. Most modern IDEs
have intelligent code completion.

One of our favourite IDE’s is Aptana Studio 3. Aptana


allows you to develop and test your entire web
application using a single environment. There’s
support for the latest browser technology specs
such as HTML5, CSS3, JavaScript, Ruby, Rails,
PHP and Python.

STACK OVERFLOW SNIPPETS


Stack Overflow Snippet is a programming term for a small region of reusable source
is a question code, machine code or text. Snippets are often used to clarify the
and answer site meaning of an otherwise “cluttered” function or to minimise the
for professional use of repeated code that is common to other functions. Snippets
and amateur is a powerful application for Mac and Windows that stores the most
programmers. valuable pieces of code that you can reuse in different projects
It’s built and many times. The main idea is to make the process of reusing as easy
run by users as as possible to avoid wasting your valuable time on writing the same
part of the Stack code again. You can download the Snippets manager free from
Exchange network http://snippets.me/.
of Q&A sites. With
its users help,
the site is building a library of detailed answers to every question
about programming. This site is all about getting answers; it’s not a
discussion forum so there’s no chit-chat. Good answers are voted up
and rise to the 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


questions 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 their subject areas. Each can have up to 5 tags, since a
question might be related to several subjects.

www.bdmpublications.com 13
Coding and Programming

Being a Programmer
Programmer, developer, coder, they’re all titles for the same occupation, someone
who creates code. What they’re creating the code for can be anything from a video
game to a critical element on-board the International Space Station. How do you
become a programmer though?

14 BDM’s Coding for Beginners


Being a Programmer

MORE THAN CODE


For those of you old enough to remember the ‘80s, the golden era of home
computing, the world of computing was a very different scene to how it is
today. 8-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
a large plastic box. However, it wasn’t so much the new technology that
computers then offered, moreover it was the fact that for the first time
ever, you could control what was being viewed on the ‘television’.

Instead of simply playing one of the thousands of games available at the


Times have changed since programming in the ‘80s, time, many users decided they wanted to create their own content, their
but the core values still remain. own games; or simply something that could help them with their homework
or home finances. The simplicity of the 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 of the 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 at the
press of a key.

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, is the 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, it is possible to train your brain into this way of thinking. Yes, it
takes time but once you start to think in this particular way you will be able
to construct and follow code.

Second to logic is an understanding of mathematics. You don’t have to be


at a genius level but you do need to understand the rudiments of maths.
Maths is 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 of a team
of other programmers, and more than likely part of an even bigger team
of designers, all of whom are creating a final product. While you may only
be expected to create a small element of that final product, being able to
Being able to follow a logical pattern and see an end
understand what everyone else is doing will help you create something
result is one of the most valued skills of a programmer.
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
Whatever kind of programmer you you want to be part of a triple-A video game team or simply create an
want to be takes time, patience automated routine to make your computing life easier, it’s up to you how
and the will to learn. far to take your coding adventure!

www.bdmpublications.com BDM’s Coding for Beginners 15


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 How to Set Up Python in Windows
26 How to Set Up Python on a Mac
28 How to Set Up Python in Linux
30 Installing a Text Editor

16 BDM’s Coding for Beginners


Index

Say Hello
to Python

www.bdmpublications.com BDM’s Coding for Beginners 17


Say Hello to Python

Why Python?
There are many different programming languages available for the modern
computer, and some still available for older 8 and 16-bit computers too. Some of
these languages are designed for scientific work, others for mobile platforms and
such. So why choose Python out of all the rest?

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 a new Regardless of whether you use an Android device, iOS device, PC,
frontier, forging small routines that enabled the letter ‘A’ to scroll Mac, Linux, Smart TV, games console, MP3 player, GPS device built-in
across the screen. It may not sound terribly exciting to a generation to a car, set-top box or a thousand other connected and ‘smart’
that’s used to ultra high-definition graphics and open world, multi- appliances, behind them all is programming.
player online gaming. However, forty-something years ago it was
blindingly brilliant. All those aforementioned digital devices need instructions to tell
them what to do, and allow them to be interacted with. These
Naturally these bedroom coders helped form the foundations for instructions form the programming core of the device and that core
every piece of digital technology we use today. Some went on to can be built using a variety of programming languages.
become chief developers for top software companies, whereas
others pushed the available hardware to its limits and founded the The languages in use today differ depending on the situation, the
billion pound gaming empire that continually amazes us. platform, the device’s use and how the device will interact with its

18 BDM’s Coding for Beginners


Why Python?

environment or users. Operating systems, such as Windows, macOS Python was created over twenty six years ago and has evolved to
and such are usually a combination of C++, C#, assembly and some become an ideal beginner’s language for learning how to program a
form of visual-based language. Games generally use C++ whilst web computer. It’s perfect for the hobbyist, enthusiast, student, teacher
pages can use a plethora of available languages such as HTML, Java, and those who simply need to create their own unique interaction
Python and so on. between either themselves or a piece of external hardware and the
computer itself.
More general-purpose programming is used to create programs,
apps, software or whatever else you want to call them. They’re Python is free to download, install and use and is available for Linux,
widely used across all hardware platforms and suit virtually every Windows, macOS, MS-DOS, OS/2, BeOS, IBM i-series machines, and
conceivable application. Some operate faster than others and some even RISC OS. It has been voted one of the top five programming
are easier to learn and use than others. Python is one such general- languages in the world and is continually evolving ahead of the
purpose language. hardware and Internet development curve.

Python is what’s known as a High-Level Language, in that it ‘talks’ So to answer the question: why Python? Simply put, it’s free, easy to
to the hardware and operating system using a variety of arrays, learn, exceptionally powerful, universally accepted, effective and a
variables, objects, arithmetic, subroutines, loops and countless more superb learning and educational tool.
interactions. Whilst it’s not as streamlined as a Low-Level Language,
which can deal directly with memory addresses, call stacks and
registers, its benefit is that it’s universally accessible and easy to
learn.

BASIC was once the starter language that early


8-bit home computer users learned.

Java is a powerful
language that’s used in
web pages, set-top boxes,
TVs and even cars.

Python is a more modern take on BASIC, it’s easy to learn


and makes for an ideal beginner’s programming language.

www.bdmpublications.com BDM’s Coding for Beginners 19


Say Hello to Python

Equipment You
Will Need
You can learn Python with very little hardware or initial financial investment. You
don’t need an incredibly powerful computer and any software that’s required is
freely available.

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 (from XP onward) on either a 32
or 64-bit processor, an Apple Mac or Linux installed PC.

AN IDE
An IDE (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, as
well as offering advanced features. There are many different IDEs available, 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 install Python,
which we’ll cover shortly.

TEXT EDITOR
Whilst a text editor is an ideal environment to enter code into, it’s not an absolute
necessity. You can enter and execute code directly from the IDLE but a text editor,
such as Sublime Text or Notepad++, offers more advanced features and colour coding
when entering code.

INTERNET ACCESS
Python is an 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
out 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-hours. Learning to code in Python takes time, and patience. You may become
stuck at times and other times the code will flow like water. Understand you’re learning
something entirely new, and you will get there.

20 BDM’s Coding for Beginners


Equipment You Will Need

THE RASPBERRY PI
Why use a Raspberry Pi? The Raspberry Pi is a 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.

RASPBERRY PI
The Raspberry Pi 3 is the latest version, incorporating a more
powerful CPU, more memory, Wi-Fi and Bluetooth support.
You can pick up a Pi for around £32 or as a part of kit for £50+,
depending on the kit you’re interested in.

FUZE PROJECT
The FUZE is a learning environment built on the latest model
of the Raspberry Pi. You can purchase the workstations that
come with an electronics kit and even a robot arm for you
to build and program. You can find more information on the
FUZE at www.fuze.co.uk.

BOOKS
We have several great Raspberry Pi titles available via www.
bdmpublications.com. Our Pi books cover how to buy your
RASPBIAN first Raspberry Pi,
set it up and use
it; there are some great step-
The Raspberry Pi’s main operating system is a Debian-based
by-step project examples and
Linux distribution that comes with everything you need in
guides to get the most from
a simple to use package. It’s streamlined for the Pi and is an
the Raspberry Pi too.
ideal platform for hardware and software projects, Python
programming and even as a desktop computer.

www.bdmpublications.com BDM’s Coding for Beginners 21


Say Hello to Python

Getting to
Know Python
Python is the greatest computer programming language ever created. It enables
you to fully harness the power of a computer, in a language that’s clean and easy
to understand.

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 a
look at how Python came about and how it relates to other languages.

PYTHON PROGRAMMING RECIPES


Programs are like recipes for computers. A
A programming language recipe to bake a cake could go like this:
is a list of instructions that
a computer follows. These Put 100 grams of self-raising flour in a bowl.
instructions can be as simple Add 100 grams of butter to the bowl.
as displaying your name Add 100 millilitres of milk.
or playing a music file, or Bake for half an hour.
as complex as building a
whole virtual world. Python
is a programming language CODE
conceived in the late 1980s
Just like a recipe, a program consists of instructions that you follow
by Guido van Rossum
in order. A program that describes a cake might run like this:
at Centrum Wiskunde &
Informatica (CWI) in the bowl = []
Netherlands as a successor to flour = 100
the ABC language. butter = 50
milk = 100
Guido van Rossum, the bowl.append([flour,butter,milk])
father of Python. cake.cook(bowl)

PROGRAM COMMANDS
You might not understand some of the Python commands, like bowl.append and cake.cook(bowl).
The first is a list, the second an object; we’ll look at both in this book. The main thing to know is
that it’s easy to read commands in Python. Once you learn what the commands do, it’s easy to
figure out how a program works.

22 BDM’s Coding for Beginners


Getting to Know Python

HIGH-LEVEL LANGUAGES ZEN OF PYTHON


Computer languages that are easy to read are known as “high-level”. Python lets you access all the power of a computer in a language
This is because they fly high above the hardware (also referred to as that humans can understand. Behind all this is an ethos called “The
“the metal”). Languages that “fly close to the metal,” like Assembly, Zen of Python.” This is a collection of 20 software principles that
are known as “low-level”. Low-level languages commands read a bit influences the design of the language. Principles include “Beautiful
like this: msg db ,0xa len equ $ - msg. is better than ugly” and “Simple is better than complex.” Type
import this into Python and it will display all the principles.

PYTHON 3 VS PYTHON 2
In a typical computing scenario, Python is complicated somewhat by the existence of two active versions of the language:
Python 2 and Python 3.

WORLD OF PYTHON When you visit the Python PYTHON 3.X In 2008 Python 3 arrived with several new
Download page you’ll notice that and enhanced features. These features
there are two buttons available: one for Python 3.6.2 and the other provide a more stable, effective and efficient programming
for Python 2.7.13; correct at the time of writing (remember Python is environment but sadly, most (if not all) of these new features are
frequently updated so you may see different version numbers). not compatible with Python 2 scripts, modules and tutorials. Whilst
not popular at first, Python 3 has since become the cutting edge of
Python programming.

PYTHON 2.X So why two? Well, Python 2 was originally 3.X WINS Python 3’s growing popularity has meant that
launched in 2000 and has since then it’s now prudent to start learning to develop
adopted quite a large collection of modules, scripts, users, tutorials with the new features and begin to phase out the previous version.
and so on. Over the years Python 2 has fast become one of the first Many development companies, such as SpaceX and NASA use
go to programming languages for beginners and experts to code Python 3 for snippets of important code.
in, which makes it an extremely valuable resource.

www.bdmpublications.com BDM’s Coding for Beginners 23


Say Hello to Python

How to Set Up
Python in Windows
Windows users can easily install the latest version of Python via the main Python
Downloads page. Whilst most seasoned Python developers may shun Windows as the
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, it’s an easy process to follow.

STEP 1 Start by opening your web browser to www.python. STEP 3 Choosing the Customise option allows you to
org/downloads/. Look for the button detailing the specify certain parameters, and whilst you may
download link for Python 3.x.x (in our case this is Python 3.6.2 but as stay with the defaults, it’s a good habit to adopt as sometimes (not
mentioned you may see later versions of 3). with Python, thankfully) installers can include unwanted additional
features. On the first screen available, ensure all boxes are ticked
and click the Next button.

STEP 2 Click the download button for version 3.x, and STEP 4 The next page of options include some interesting
save the file to your Downloads folder. When the additions to Python. Ensure the Associate file with
file is downloaded, double-click the executable and the Python Python, Create Shortcuts, Add Python to Environment Variables,
installation wizard will launch. From here you have two choices: Precompile Standard Library and Install for All Users options are
Install Now and Customise Installation. We recommend opting for ticked. These make using Python later much easier. Click Install when
the Customise Installation link. you’re ready to continue.

24 BDM’s Coding for Beginners


How to Set Up Python in Windows

STEP 5 You may need to confirm the installation with the STEP 8 Clicking on the IDLE (Python 3.6 32-bit) link will
Windows authentication notification. Simply click launch the Python Shell, where you can begin
Yes and Python will begin to install. Once the installation is complete your Python programming journey. Don’t worry if your version
the final Python wizard page will allow you to view the latest release is newer, as long as it’s Python 3.x our code will work inside your
notes, and follow some online tutorials. Python 3 interface.

STEP 6 Before you close the install wizard window, STEP 9 If you now click on the Windows Start button again,
however, it’s best to click on the link next to the and this time type: CMD, you’ll be presented with the
shield detailed Disable Path Length Limit. This will allow Python Command Prompt link. Click it to get to the Windows command line
to bypass the Windows 260 character limitation, enabling you to environment. To enter Python within the command line, you need
execute Python programs stored in deep folders arrangements. to type: python and press Enter.
Again, click Yes to authenticate the process; then you can Close the
installation window.

STEP 7 STEP 10 The command line version of Python works in


much the same way as the Shell you opened in
Windows 10 users will now Step 8; note the three left-facing arrows (>>>). Whilst it’s a perfectly
find the installed Python fine environment, it’s not too user-friendly, so leave the command
3.x within the Start button line for now. Enter: exit() to leave and close the Command
Recently Added section. The Prompt window.
first link, Python 3.6 (32-bit)
will launch the command
line version of Python when
clicked (more on that in a
moment). To open the IDLE,
type IDLE into Windows start.

www.bdmpublications.com BDM’s Coding for Beginners 25


Say Hello to Python

How to Set Up
Python on a Mac
If you’re running an Apple Mac, then setting up Python is incredibly easy. In fact a
version of Python is already installed. However, you should make sure you’re running
the latest version.

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.

Open a new Terminal window by clicking Go > Click on the latest version of Python 3.x, in our
STEP 1 STEP 3
Utilities, then double-click the Terminal icon. Now case this is the download button for Python 3.6.2.
enter: python --version. You should see “Python 2.5.1” and This will automatically download the latest version of Python and
even later, if Apple has updated the OS and Python installation. depending on how you’ve got your Mac configured, it automatically
Either way, it’s best to check for the latest version. starts the installation wizard.

Open Safari and head over to www.python.org/ With the Python installation wizard open, click on
STEP 2 STEP 4
downloads. Just as with the Windows set up the Continue button to begin the installation. It’s
procedure on the previous pages, you can see two yellow download worth taking a moment to read through the Important Information
buttons: one for Python 3.6.2, and the other for Python 2.7.13. section, in case it references something that applies to your version
Note, that version numbers may be different due to the frequent of macOS. When ready, click Continue again.
releases of Python.

26 BDM’s Coding for Beginners


How to Set Up Python on a Mac

The next section details the Software License There’s nothing much else left to do in the Python
STEP 5 STEP 8
Agreement, and whilst not particularly interesting installation wizard so you can click the Close button.
to most folks, it’s probably worth a read. When you’re ready, click on If you now drop back into a Terminal session and re-enter the
the Continue button once again. command: python3 --version, you can see the new version is
now listed. To enter the command line version of Python, you need
to enter: python3. To exit, it’s: exit().

Finally you’re be presented with the amount of You need to search in Finder for the Python IDLE;
STEP 6 STEP 9
space Python will take up on your system and an when you’ve found it, click it to launch and it
Install button, which you need to click to start the actual installation should look similar to that of the Windows IDLE version shown on
of Python 3.x on to your Mac. You may need to enter your password the previous page. The only difference being the Mac detected
to authenticate the installation process. hardware platform it’s running on.

The installation shouldn’t take too long; the older Older Mac versions may have trouble with the
STEP 7 STEP 10
Mac Mini we used in this section is a little slower newer versions of Python, in which case you will
than more modern Mac machines and it only took around thirty need to revert to a previous Python 3.x build; as long as you’re using
seconds for the Installation Successful prompt to be displayed. Python 3.x, the code in this book will work for you.

www.bdmpublications.com BDM’s Coding for Beginners 27


Say Hello to Python

How to Set Up
Python in Linux
Python version 2.x is already installed in most Linux distributions but as we’re going
to be using Python 3.x, there’s a little work we need to do first to get hold of it.
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.

First you need to ascertain which version of Python Some Linux distros will automatically update
STEP 1 STEP 3
is currently installed in your Linux system; as we the installation of Python to the latest versions
mentioned, we’re going to be using Linux Mint 18.1 for this section. whenever the system is updated. To check, first do a system update
As with macOS, drop into a Terminal by pressing Ctrl+Atl+T. and upgrade with:
sudo apt-get update && sudo apt-get upgrade
Enter your password and let the system do any updates.

Next enter: python --version into the Terminal Once the update and upgrade is complete, you
STEP 2 STEP 4
screen. You should have the output relating to may need to answer ‘Y’ to authorise any upgrades,
version 2.x of Python in the display. Ours in this case if Python enter: python3 --version to see if Python 3.x is updated or even
2.7.12. installed. In the case of Linux Mint, the version we have is Python
3.5.2, which is fine for our purposes.

28 BDM’s Coding for Beginners


How to Set Up Python in Linux

However, if you want the latest version, 3.6.2 as per Within the Python folder, enter:
STEP 5 STEP 8
the Python website at the time of writing, you need
./configure
to build Python from source. Start by entering these commands into
sudo make altinstall
the Terminal:
This could a little while depending on the speed of your computer.
sudo apt-get install build-essential checkinstall
Once finished, enter: python3.6 --version to check the
sudo apt-get install libreadline-gplv2-dev
installed latest version.
libncursesw5-dev libssl-dev libsqlite3-dev tk-dev
libgdbm-dev libc6-dev libbz2-dev

Open up your Linux web browser and go to For the GUI IDLE, you need to enter the following
STEP 6 STEP 9
the Python download page: www.python.org/ command into the Terminal:
downloads. Click on the Download Python 3.6.2 (or whichever
sudo apt-get install idle3
version it’s on when you look) to download the source Python-
3.6.2.tar.xz file. The IDLE can then be started with the command: idle3. Note, that
IDLE runs a different version from the one you installed from source.

In the Terminal, go the Downloads folder by You also need PIP (Pip Installs Packages) which is a
STEP 7 STEP 10
entering: cd Downloads/. Then unzip the tool to help you install more modules and extras.
contents of 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 unzipped folder
PIP is then installed; check for the latest update with:
with cd Python-3.6.2/.
pip3 install --upgrade pip
When complete, close the Terminal and Python 3.x will be available
via the Programming section in your distro’s menu.

www.bdmpublications.com BDM’s Coding for Beginners 29


Say Hello to Python

Installing a
Text Editor
It’s not entirely necessary (as you can use the IDLE) but a text editor will help you
immensely when you’re entering code. A normal word processor inserts its own
unique characters, paragraph settings and much more, so it’s not a good platform for
Python code.

SUBLIME CODE
Sublime Text is an excellent, cross-platform text editor that’s designed for entering code. It has a slick interface, many
features and performs magnificently. In short, it’s an ideal starting point.

Let’s begin by navigating to the Sublime Text Whichever version you choose, download the setup
STEP 1 STEP 3
webpage, to download the latest version for files and double-click them to begin the set up
whatever operating system you’re currently running. You can find process. If you’re using Windows, which we are in this instance, then
the website at www.sublimetext.com, together with a download you see the standard installation wizard. The defaults will suffice, so
button for the detected OS that you’re using. go ahead and install the program.

However, if you want to specify a particular When installed, Sublime defaults to a black
STEP 2 STEP 4
operating system version, then click on the background and white text; whilst this is perfectly
Download link found in the top menu bar on the site. This will open fine for most users, it’s not always the most comfortable viewing
a page with links for the latest version for OS X, Windows, Windows setup. Thankfully, there are countless themes you can apply by
64-bit and Linux machines. clicking Preferences > Colour Scheme. We’ve opted for IDLE in
this screenshot.

30 BDM’s Coding for Beginners


Installing a Text Editor

Sublime Text offers some excellent features over Sublime isn’t just for Python either. With it you can
STEP 5 STEP 8
that of the standard Python IDLE. For example, build code for a number of programming languages.
enter the following: Click on Tools > Build System to see which languages you’re able to
build with in Sublime.
print (“Hello everyone!”)
This is an 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.

Soon, as you become more Python-savvy, you’ll find Sublime comes with a number of preinstalled
STEP 6 STEP 9
that the standard IDLE isn’t quite up to the task plugins for Python code, allowing you to experiment
of keeping up with your code, alterations and injections of code with your code in real-time. They’re probably a little bewildering at
mid-way through a long program. However, Sublime will keep you this point in time but you will likely find them useful as your Python
updated and you can even utilise indents easily. skills increase.

We’re not going to get too heavily into the However, we recommend you use the IDLE to
STEP 7 STEP 10
code right now but an indent is part of Python begin with. Although the Python IDLE isn’t as
programming, where a statement indicates that the following advanced as Sublime, it’s a perfect base on which to build your skills.
indented commands must be run until a particular event has Once you’ve mastered Python, and the way it works, you can move
happened; after which the indents stop. Pressing Ctrl+] will indent a on to a text editor for the better features.
line of code in Python.

www.bdmpublications.com BDM’s Coding for Beginners 31


Say Hello to C++

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.

34 Why C++?
36 Equipment You Will Need
38 Getting to Know C++
40 How to Set Up C++ in Windows
42 How to Set Up C++ on a Mac
44 How to Set Up C++ in Linux
46 Other C++ IDEs to Install

32 BDM’s Coding for Beginners


Index

Say Hello
to C++

www.bdmpublications.com BDM’s Coding for Beginners 33


Say Hello to C++

Why C++?
C++ is one of the most popular programming languages available today. Originally
called C with Classes, the language was renamed C++ in 1983. It’s an extension of the
original C language and is a general purpose object-oriented (OOP) environment.

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 back to 1979, the start of the golden era of home computing labs and by regular people who didn’t have access to the
computing, C++, or rather C with Classes, was the brainchild of mainframes and large computing data centres.
Danish computer scientist Bjarne Stroustrup while working on his
PhD thesis. Stroustrup’s plan was to further the original C language, C++’s impact in the digital world is immense. Many of the programs,
which was widely used since the early seventies. applications, games and even operating systems are coded using
C++. For example, all of Adobe’s major applications, such as
C++ proved to be popular among the developers of the ‘80s, Photoshop, InDesign and so on, are developed in C++. You will find
since it was a much easier environment to get to grips with and that the browser you surf the Internet with is written in C++, as
more importantly, it was 99% compatible with the original C well as Windows 10, Microsoft Office and the backbone to Google’s
language. This meant that it could be used beyond the mainstream search engine. Apple’s macOS is written largely in C++ (with some

C++ code is much faster than that of Python.

34 BDM’s Coding for Beginners


Why C++?

Microsoft’s Visual Studio is a great,


free environment to learn C++ in.

other languages mixed in depending on the function) and the likes


of NASA, SpaceX and even CERN use C++ for various applications,
programs, controls and umpteen other computing tasks.

C++ is also extremely efficient and performs well across the board
as well as being an easier addition to the core C language. This
higher level of performance over other languages, such as Python,
BASIC and such, makes it an ideal development environment for
modern computing, hence the aforementioned companies using it
so widely.

While Python is a great programming language to learn, C++ puts


the developer in a much wider world of coding. By mastering C++,
you can find yourself developing code for the likes of Microsoft,
Apple and so on. Generally, C++ developers enjoy a higher salary
than programmers of some other languages and due to its Indeed, the operating system
versatility, the C++ programmer can move between jobs and you’re using is written in C++.
companies without the need to relearn anything specific.
However, Python is an easier language to begin with. If you’re
completely new to programming then we would recommend you
begin with Python and spend some time getting to grips with
programming structure and the many ways and means in which you
find a solution to a problem through programming. Once you can
happily power up your computer and whip out a Python program
with one hand tied behind your back, then move on to C++. Of
course, there’s nothing stopping you from jumping straight into
C++; if you feel up to the task, go for it.

Getting to use C++ is as easy as Python, all you need is the right set
of tools in which to communicate with the computer in C++ and
you can start your journey. A C++ IDE is free of charge, even the
immensely powerful Visual Studio from Microsoft is freely available
to download and use. You can get into C++ from any operating
system, be it macOS, Linux, Windows or even mobile platforms.

Just like Python, to answer the question of Why C++ is the answer
is because it’s fast, efficient and developed by most of the
applications you regularly use. It’s cutting edge and a fantastic
language to master.

www.bdmpublications.com BDM’s Coding for Beginners 35


Say Hello to C++

Equipment You
Will Need
You don’t need to invest a huge amount of money in order to learn C++, and you
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
with extensions and plugins that help make it 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.

COMPILER
A compiler is a program that will convert the C++ language into binary that the
computer can understand. While some IDEs come with a compiler built in, others
don’t. Code::Blocks is our favourite IDE that comes with a C++ compiler as part of the
package. More on this later.

TEXT EDITOR
Some programmers much prefer to use a text editor to assemble their C++ code
before running it through a compiler. Essentially you can any text editor to write
code, just save 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
to the Internet, it’s extraordinarily difficult. You will need to install the relevant
software, keep it up to date, install any extras or extensions, and look for help when
coding. All of 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, it’s not going to happen
overnight, or even a week. A good C++ coder has spent many years honing their
craft, so be patient, start small and keep learning.

36 BDM’s Coding for Beginners


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++.

LINUX WINDOWS
Linux users are lucky in that they already have a compiler and As we’ve mentioned previously, a good IDE is Microsoft’s
text editor built into their operating system. Any text editor Visual Studio. However, a better IDE and compiler is
will allow you type out your C++ code, when it’s saved with a Code::Blocks, which is regularly kept up to date with a new
.cpp extension, use g++ to compile it. release twice a year, or so. Otherwise Windows users can
enter their code in Notepad++ then compile it with MinGW –
which Code::Blocks uses.

RASPBERRY PI MAC
The Raspberry Pi’s operating Mac owners will need to
system is Raspbian, which download and install Xcode
is Linux based. Therefore, to be able to compile their
you’re able to write your code C++ code natively. Other
out using a text editor, then options for the macOS
compile it with g++ as you include Netbeans, Eclipse or
would in any other Linux distro. Code::Blocks. Note: the latest
Code::Blocks isn’t available for
Mac due to a lack of
Mac developers.

www.bdmpublications.com BDM’s Coding for Beginners 37


Say Hello to C++

Getting to Know C++


C++ is an amazing programming to learn. If your dream is to become a games designer
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 <C++ IS ACE!>


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.

C++ #INCLUDE
The structure of a C++ program
C++ was invented by Danish is slightly different to that of
student Bjarne Stroustrup in Python and radically different
1979, as a part of his PhD to BASIC. Every C++ code
thesis. Initially C++ was called begins with a directive, #include
C with Classes, which added <>. The directive instructs the
features to the already popular pre-processor to include a
C programming language, section of the standard C++
while making it a more code. For example: #include
user-friendly environment. <iostream> includes the
iostream header to support
Bjarne Stroustrup, inventor input/output operations.
of C++.

INT MAIN()
int main() initiates the
declaration of a function, which
is a group of code statements
under the name ‘main’. All
C++ code begins at the main
function, regardless of where it
actually lies within the code.

BRACES
The open brace is
something that you may
not have come across
before, especially if you’re
used to Python. The
open brace indicates the
beginning of the main
function and contains all
the code that belongs to
that function.

38 BDM’s Coding for Beginners


Getting to Know C++

COMMENTS <<
Lines that begin with a double slash are comments. This means they The two chevrons used here are insertion operators. This means
won’t be executed in the code and are ignored by the compiler. Why that whatever follows the chevrons is to be inserted into the
are they there? Comments are designed to help you, or another std::cout statement. In this case the words are ‘Hello World’, which
programmer looking at your code, explain what’s going on. There are to be displayed on the screen when you compile and execute
are two types of comment: /* covers multiple line comments, // a the code.
single line.

STD OUTPUTS
While std stands for something quite different, in C++ it means Leading on, the (“Hello World!”) part is what we want to appear on
Standard. It’s a part of the Standard Namespace in C++, which covers the screen when the code is executed. You can enter whatever you
a number of different statements and commands. You can leave like, as long as it’s inside the quotation marks. The brackets aren’t
the std part out of a code, but it must be declared at the start with: needed but some compilers insist on them. The \n part indicates a
using namespace std. new line is to be inserted.

COUT ; AND }
In this example we’re using cout, which is a part of the Standard Finally you can see that lines within a function code block (except
Namespace, hence why it’s there, as you’re asking C++ to use it from comments) end with a semicolon. This marks the end of the
that particular namespace. Cout means Character OUTput, which statement and all statements in C++ must have one at the end or
displays, or prints, something to the screen. If we leave std:: out we the compiler will fail to build the code. The very last line has the
have to declare it at the start of the code, as mentioned previously. closing brace to indicate the end of the main function.

www.bdmpublications.com BDM’s Coding for Beginners 39


Say Hello to C++

How to Set Up
C++ in Windows
Windows users have a wealth of choice when it comes to programming in C++. There
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
a compiler and has a vibrant community behind it too.

STEP 1 Start by visiting the Code::Blocks download site, at STEP 3 When you’ve located the file, click on the
www.codeblocks.org/downloads. From there, click Sourceforge.net link at the end of the line and a
on the ‘Download the binary releases’ link to be taken to the latest download notification window appears; click on Save File to start
downloadable version for Windows. the download and save the executable to your PC. Locate the
downloaded Code::Blocks installer and double-click to start. Follow
the on-screen instructions to begin the installation.

STEP 2 There you can see, there are several Windows STEP 4 Once you agree to the licencing terms, a choice of
versions available. The one you want to download installation options becomes available. You can opt
has mingw-setup.exe at the end of the current version number. At for a smaller install, missing out on some of the components but we
the time of writing this is: codeblocks-17.12mingw-setup.exe. The recommend that you opt for the Full option, as default.
difference is that the mingw-setup version includes a C++ compiler
and debugger from TDM-GCC (a compiler suite).

40 BDM’s Coding for Beginners


How to Set Up C++ in Windows

STEP 5 Next choose an install location for the Code::Blocks STEP 8 There’s a lot you can do in Code::Blocks, so you need
files. It’s your choice but the default is generally to dig in and find a good C++ tutorial to help you
sufficient (unless you have any special requirements of course). get the most from it. However, to begin with, click on File > New >
When you click Next, the install begins; when it’s finished a Empty File. This creates a new, blank window for you to type in.
notification pops up asking you if you want start Code::Blocks now,
so click Yes.

STEP 6 The first time Code::Blocks loads it runs an auto- STEP 9 In the new window, enter the following:
detect for any C++ compilers you may already have
installed on your system. If you don’t have any, click on the #include <iostream>
first detected option: GNU GCC Compiler and click the Default
Int main()
button to set it as the system’s C++ compiler. Click OK when you’re
{
ready to continue.
//My first C++ program
Std::cout << “Hello World!\n”;
}
Notice how Code::Blocks auto-inserts the braces and speech quotes.

STEP 7 The program starts and another message appears STEP 10 Click File > Save as and save the code with a
informing you that Code::Blocks is currently not .cpp extension (helloworld.cpp, for example).
the default application for C++ files. You have two options, to leave Code::Blocks changes the view to colour code according to C++
everything as it is or allow Code::Blocks to associate all C++ file standards. To execute the code, click on the Build and Run icon
types. Again, we would recommend you opt for the last choice, to along the top of the screen. It’s a green play icon together with a
associate Code::Blocks with every supported file type. yellow cog.

www.bdmpublications.com BDM’s Coding for Beginners 41


Say Hello to C++

How to Set Up C++


on a Mac
To start C++ coding on a Mac you need to install Apple’s Xcode. This is a free, full
featured IDE that’s designed to create native Apple apps. However, it can also be
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.

STEP 1 Start by opening the App Store on your Mac, Apple STEP 3 When you’re ready, click on the Get button which
Menu > App Store. In the Search box enter Xcode and then turns into ‘Install App’. Enter your Apple ID
press Return. There will be many suggestions filling the App Store and Xcode begins to download and install. It may take some time
window but it’s the first option, Xcode, that you need to click on. depending on the speed of your Internet connection.

STEP 2 Take a moment to browse through the app’s STEP 4 When the installation is complete, click on the Open
information, including the compatibility to ensure button to launch Xcode. Click Agree to the licence
you have the correct version of macOS. Xcode requires macOS terms and enter your password to allow Xcode to make changes
10.12.6 or later to install and work. to the system. When you’ve done that, Xcode begins to install
additional components.

42 BDM’s Coding for Beginners


How to Set Up C++ on a Mac

STEP 5 With everything now installed, including the STEP 8 The next step asks where to create a Git Repository
additional components, Xcode launches, displaying for all your future code. Choose a location on your
the version number along with three choices and any recent projects Mac, or a network location, and click the Create button. When
that you’ve worked on; although for a fresh install, this shows blank. you’ve done all that, you can start to code. The left-hand pane
details the files used in the C++ program you’re coding. Click on the
main.cpp file in the list.

STEP 6 Start by clicking on Create New Xcode Project; this STEP 9 You can see that Xcode has automatically
opens a template window from which to choose the completed a basic Hello World program for you.
platform you’re developing code for. Click the macOS tab, then the The differences here are that the int main () function now contains
Command Line Tool option and finally, Next to continue. multiple functions and the layout is slightly different. This is just
Xcode utilising the content that’s available to your Mac.

STEP 7 Fill in the various fields but ensure that the STEP 10 When you want to run the code, click on Product >
Language option at the bottom is set to C++. Simply Run. You may be asked to enable Developer Mode
choose it from the drop-down list. When you’ve filled in the fields, on the Mac; this is to authorise Xcode to perform functions without
and made sure that C++ is the chosen language, click on 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.

www.bdmpublications.com BDM’s Coding for Beginners 43


Say Hello to C++

How to Set Up C++


in Linux
Linux is a great C++ coding environment. Most Linux distros already have the
essential components preinstalled, such as a compiler and the text editors are
excellent for entering code into, including colour coding; there’s also tons of extra
software available to help you out.

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.

STEP 1 The first step with ensuring Linux is ready for your STEP 3 Amazingly, that’s it. Everything is all ready for you
C++ code is check the system and software are to start coding. Here’s how to get your first C++
up to date. Open a Terminal and enter: sudo apt-get update program up and running. In Linux Mint the main text editor is Xed
&& sudo apt-get upgrade. Press Return and enter your can be launched by clicking on the Menu and typing Xed into the
password. These commands updates the entire system and any search bar. Click on the Text Editor button in the right-hand pane to
installed software. open Xed.

STEP 2 Most Linux distros come preinstalled with all the STEP 4 In Xed, 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, it’s always worth checking to see if everything is present, World program. To remind you, its:
so still within the Terminal, enter: sudo apt-get install
#include <iostream>
build-essential and press Return. If you have the right
components, nothing is installed but if you’re missing some then int main()
they are installed by the command.
{
//My first C++ program
std::cout << “Hello World!\n”;

44 BDM’s Coding for Beginners


How to Set Up C++ in Linux

STEP 5 When you’ve entered your code, click File > Save As STEP 8 Before you can execute the C++ file you need to
and choose a folder where you want to save your compile it. In Linux it’s common to use g++, an open
program. Name the file as helloworld.cpp, or any other name just as source C++ compiler and as you’re now in the same folder as the
long as it has .cpp as the extension. Click Save to continue. C++ file, go to the Terminal, enter: g++ helloworld.cpp and
press return.

STEP 6 The first thing you can see is that Xed has STEP 9 There will be a brief pause as the code is compiled
automatically recognised this as a C++ file, since the by g++ and providing there are no mistakes or
file extension is now set to .cpp. The colour coding is present in the errors in the code you are returned to the command prompt. The
code and if you open up the file manager you can also see that the compiling of the code has created a new file. If you enter ls into the
file’s icon has C++ stamped on it. Terminal you can see that alongside your C++ file is a.out.

STEP 7 With your code now saved, drop into the Terminal STEP 10 The a.out file is the compiled C++ code. To run the
again. You need to navigate to the location of code enter: ./a.out and press Return. The words
the C++ file you’ve just saved. Our example is in the Documents ‘Hello World!’ appears on the screen. However, a.out isn’t very friendly.
folder, so we can navigate to it by entering: cd Documents. To name it something else post-compiling, you can recompile with:
Remember, the Linux Terminal is case sensitive, so any capitals must g++ helloworld.cpp -o helloworld. This creates an output
be entered correctly. file called helloworld which can be run with: ./helloworld.

www.bdmpublications.com BDM’s Coding for Beginners 45


Say Hello to C++

Other C++ IDEs to Install


If you want to try a different approach to working with your C++ code, then there are
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.

ECLIPSE Eclipse is a hugely popular C++ IDE that offers CODELITE CodeLite is a free and open source IDE that’s
the programmer a wealth of features. It has a regularly updated and available for Windows,
great, clean interface, is easy to use and available for Windows, Linux and macOS. It’s lightweight, uncomplicated and extremely
Linux and Mac. Head over to www.eclipse.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 install it at www.codelite.org/.
for more information.

GNAT The GNAT Programming Studio (GPS) is a powerful NETBEANS Another popular choice is NetBeans. This
and intuitive IDE that supports testing, debugging is another excellent 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
Pro version costs; however, the Community Edition is available for templates for C++ that give you the ability to build applications with
Windows, Mac, Linux and even the Raspberry Pi. You can find it at dynamic and static libraries. Find out more at www.netbeans.org/
www.adacore.com/download. features/cpp/index.html.

46 BDM’s Coding for Beginners


Other C++ IDEs to Install

VISUAL STUDIO Microsoft’s Visual Studio is a ANJUTA The Anjuta DevStudio is a Linux-only IDE that
mammoth C++ IDE that allows you features some of the more advanced features you
to create applications for Windows, Android, iOS and the web. The would normally find in a paid software development studio. There’s
Community version is free to download and install but the other a GUI designer, source editor, app wizard, interactive debugger and
versions allow a free trial period. Go to www.visualstudio.com/ to much more. Go to www.anjuta.org/ for more information.
see what it can do for you.

QT CREATOR This cross-platform IDE is designed to MONODEVELOP This excellent IDE allows developers
create C++ applications for desktop and to write C++ code for desktop and
mobile environments. It comes with a code editor and integrated web applications across all the major platforms. There’s an advanced
tools for testing and debugging, as well as deploying to you chosen text editor, integrated debugger and a configurable workbench to
platform. It’s not free but there is a trial period on offer before help you create your code. It’s available for Windows, Mac and Linux
requiring purchasing: www.qt.io/qt-features-libraries-apis-tools- and is free to download and use: www.monodevelop.com/.
and-ide/.

DEV C++ Bloodshed Dev C++, despite its colourful name, U++ Ultimate++ is a cross-platform C++ IDE that boats a rapid
is an older IDE that is for Windows systems only. development of code through the smart and aggressive
However, many users praise its clean interface and uncomplicated use of C++. For the novice, it’s a beast of an IDE but behind its
way of coding and compiling. Although there’s not been much complexity is a beauty that would make a developer’s knees go
updating for some time, it’s certainly one to consider if you want wobbly. Find out more at www.ultimatepp.org/index.html.
something different: www.bloodshed.net/devcpp.html.

www.bdmpublications.com BDM’s Coding for Beginners 47


Coding 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 Why Linux?
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 5
76 Command Line Quick Reference
78 A-Z of Linux Commands

48 BDM’s Coding for Beginners


Index

Coding
on Linux

www.bdmpublications.com BDM’s Coding for Beginners 49


Coding on Linux

Why Linux?
Many developers, across all the available programming languages, use Linux as
an operating system base for their coding and testing, but why? Linux has many
advantages over other systems and while it also has some quirks, it makes for a great
place to learn to code.

FREE AND OPEN


Linux is 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 is no such operating Linux works considerably differently to Windows or macOS. It’s
system called Linux. Linux is in fact the operating system kernel, the free for a start, free to download, install on as many computers as
core component of an OS. When talking about Linux what we, and you like and use for an unlimited amount of time. It’s also free to
others, are referring to are one of the many distributions, or distros, upgrade and extend using equally free programs and applications.
that use the Linux kernel. No doubt you’ve heard of at least one of This free to use element is one of the biggest draws for the
the current popular distros: Ubuntu, Linux Mint, Fedora, openSUSE, developer. While a Windows license can cost up to £100 and a Mac
Debian, the list goes on. Each one of these distros offers something one considerably more, a developer can quickly download a distro
a little different for the user. While each has a the Linux kernel at and get to work coding in a matter of minutes.
its core, they provide the user with a different looking desktop
environment, different preloaded applications, different ways in Alongside the free to use aspect comes a level of freedom to
which to update the system and get more apps installed and a slightly customise and mould the system to your own use. Each of the
different look and feel throughout the entire system. However, at available distros available on the Internet have a certain ‘spin’,
the centre lies Linux which is why we collectively say, Linux. in that some offer increased security, a fancy looking desktop, a

Linux is a great operating system in


which to start coding.

50 BDM’s Coding for Beginners


Why Linux?

gaming specific spin or something directed towards students. This However it’s not all about C++, Python or any of the other more
extensibility makes Linux a more desirable platform to learn coding popular programming languages. Using the command line of Linux,
on, as you can quickly shape the system into a development base, also called the Terminal, you’re able to create Shell scripts, which are
including many different kinds of IDEs for the likes of Python, web programs that are designed to run from the command line and are
development, C++, Java and so on. 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
Another remarkable advantage is that Linux comes with most of operation. They are surprisingly powerful and we look at how to
the popular coding environments built-in. Both Python and C++ are create them within this section.
preinstalled in a high percentage of available Linux distros, which
means you can start to program almost as soon as you install the Finally, although there are many more advantages to list, there
system and boot it up for the first time. are thousands and thousands of free programs and apps available
that cover near every aspect of computing. Known as packages,
Generally speaking, Linux doesn’t take up as many system resources there are (at the time of writing) over 8,700 specific programming
as Windows or macOS. By system resources we mean memory, hard applications just for Linux Mint alone.
drive space and CPU load; the Linux code has been streamlined and
is free from third-party ‘bloatware’ which hogs those systems Linux therefore, is a great resource and environment for
resources. A more efficient system of course means more available programming in. It’s perfectly suited for developers and is
resources for the coding and testing environment, and the programs continually improving and evolving. If you’re serious about getting
you eventually create. Less use of resources also means you can use into coding, then give Linux a try and see how it works for you.
Linux on older hardware that would normally struggle or even refuse
to run the latest versions of Windows or macOS. So rather than
throwing away an old computer, it can be reused with a Linux distro.

There are thousands of free packages Each distro offers something unique to the
available for programmers under Linux. user but all have Linux at the core.

A Linux programming environment can be


as simple or as complex as you need it to be.

www.bdmpublications.com BDM’s Coding for Beginners 51


Coding on Linux

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
with Linux Mint.

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 will be, and quicker too.

CPU 700MHz

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 or
DVD. We’ll look into each a little later on but if you’re already
familiar with the process or you’re thinking of USB and just
gathering the hardware you need, then you’re going to need a
minimum 4GB USB flash drive to contain the Linux Mint ISO.

52 BDM’s Coding for Beginners


Equipment You Will Need

DVD INSTALLATION INTERNET CONNECTION


DVD installation of Linux Mint simply requires a blank DVD-R It goes without saying really, that an Internet connection is
disc. Of course, you also need a DVD Writer drive before you vital for making sure that Linux Mint is up to date with the
can transfer or burn the ISO image to the disc. latest updates and patches, as well as the installation of
further software. Although you don’t need an internet
connection to use Linux Mint, you’re sure to miss out on a
world of free software available for this distro.

MAC HARDWARE
Although Linux Mint can be installed onto a Mac, there’s
a school of thought that recommends Mac owners use a
virtual environment, such as VirtualBox or Parallels; and why
not, macOS is already a splendid operating system. If you’re
wanting to breathe new life into an older Mac, make sure it’s
an Intel CPU model and not the PowerPC models.

VIRTUAL ENVIRONMENT
Installation to a virtual environment is a favourite method of
testing and using Linux distros. Linux Mint works exceedingly
well when used in a 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.org.

www.bdmpublications.com BDM’s Coding for Beginners 53


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. If you’re using a version of Windows from 7 onward the
process is extremely easy.

STEP 1 First locate the ISO image of Mint you’ve already STEP 3 Right-click the Mint ISO and from the menu select
downloaded. You can usually find this in the Burn Disc Image. Depending on the speed of the PC,
Downloads folder of Windows 7, 8.1 and 10 computers; unless you it may take a few seconds before anything happens. Don’t worry too
specified a different location when saving it. 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 Image Burner should launch.

STEP 2 Next insert a recordable DVD disc into your STEP 4 Right-click the Mint ISO and from the menu select
computer’s optical drive. After a few seconds, while Burn Disc Image. Depending on the speed of the PC,
the disc is read, Windows will display a pop-up message asking you it may take a few seconds before anything happens. Don’t worry too
what to do with the newly inserted disc; ignore this, as you’re going much, unless it takes more than a minute in which case it might be
to use the built-in image burning function. worth restarting your PC and trying again. With luck, the Windows
Disc Image Burner should launch.

54 BDM’s Coding for Beginners


Transfer Mint to DVD or USB?

USB BOOTABLE MEDIA


USB media is 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.

STEP 1 First open up a web browser and go to www.rufus. STEP 4 When you’re ready, click on the Start button at the
akeo.ie. Scroll down the page a little and you come to bottom of the Rufus app. This will open up another
a Download heading, under which you can see the latest version of dialogue box asking you to download and use a new version of
Rufus (2.12 in this instance). Left click the link to start the download. SysLinux. SysLinux is a selection of boot loaders used to allow a
modern PC to access and boot from a USB flash drive. It is necessary,
so click on ‘Yes’ to continue.

STEP 2 Double-click the downloaded Rufus executable; you STEP 5 The next step asks which image mode you want
can click ‘Yes’ to the Windows security question and the Mint ISO to be written to the USB flash drive
‘Yes’ to checking for updates. With Rufus launched it should have in. Both methods work for different situations but generally, the
already identified your inserted USB flash drive; if not just remove recommended ISO Image Mode is the more popular. Make sure this
and reinsert. mode is preselected and click OK to continue, followed by OK again
to confirm the action.

STEP 3 At first glance the Rufus interface can look a little STEP 6 The Mint ISO is now being transferred to the USB
confusing, don’t worry though it’s really quite flash drive. The process shouldn’t take too long,
simple. To begin with, click on the disc and drive icon next to the again depending on the speed of the USB device and the PC. You
‘Create a bootable disk using..’ section and the ‘FreeDOS’ pull-down may find Rufus will auto-open the USB drive in Windows Explorer
menu. This will launch a Windows Explorer window where you can during the process; don’t worry you can minimise or close it if you
locate and select the Linux Mint ISO. want. When the process is complete, click on the Close button.

www.bdmpublications.com BDM’s Coding for Beginners 55


Coding on Linux

Installing VirtualBox
If you don’t want to dedicate an entire computer to running Mint, one option is to use
a Virtual Machine. VirtualBox is one of the best VMs and with it you can run a virtual
version of other operating systems within your already installed OS.

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.

STEP 1 The first task is getting hold of VirtualBox. If you STEP 3 With the correct packages downloaded, and before
haven’t already, head over to www.virtualbox.org we install anything, you need to make sure that the
and click on the large ‘Download VirtualBox 5.1’ box. This will take computer you’re using is able to host a VM. To do this, reboot the
you to the main download page. Locate the correct host for your computer and enter the BIOS. As the computer starts up, press the
system, Windows or Mac, the host is the current installed operating Del, F2 or whichever key is necessary to Enter Setup.
system, and click to begin the download.

STEP 2 Next, while still at the VirtualBox download page, STEP 4 As each BIOS is laid out differently it’s very difficult
locate the VirtualBox Extension Pack link. The to assess where to look in each personal example.
Extension Pack supports USB devices, as well as numerous other However, as a general rule of thumb, you’re looking for Intel
extras that can help make the VM environment a more accurate Virtualisation Technology or simply Virtualisation; it’s usually within
emulation of a ‘real’ computer. the Advanced section of the BIOS. When you’ve located it, Enable it,
save the settings, exit the BIOS and reboot the computer.

56 BDM’s Coding for Beginners


Installing VirtualBox

STEP 5 With the computer back up and running, locate STEP 8 When installing VirtualBox your network connection
the downloaded main VirtualBox application and will be disabled for a very brief period. This is due
double-click to begin the installation process. Click Next to continue, to VirtualBox creating a linked, virtual network connection so that
when you’re ready. any VM installed will be able to access the Internet, and your home
network resources, via the computer’s already established network
connection. Click Yes then Install to begin the installation.

STEP 6 The default installation location of VirtualBox STEP 9 You may well be asked by Windows to accept a
should satisfy most users but if you have any special security notification; click Yes for this and you may
location requirements click on the Browse button and change the encounter a dialogue box asking you to trust the installation from
install folder. Then, make sure that all the icons in the VirtualBox Oracle. Again, click yes and accept the installation of the VirtualBox
feature tree are selected and none of them have a red X next to application. When it’s complete, click finish to start VirtualBox.
them. Click Next to move on.

STEP 7 This section can be left alone to the defaults, should STEP 10 With VirtualBox up and running you can now
you wish. It simply makes life a little easier when install the VirtualBox Extension Pack. Locate the
dealing with VMs; especially when dealing with downloaded VMs, as downloaded add-on and double-click. There may be a short pause
you may encounter in the future. Again, clicking Next will move you while VirtualBox analyses the pack but eventually you receive a
on to the next stage. message to install it; obviously click Install to begin the process, scroll
down the next screen to accept the agreement and click ‘I Agree’.

www.bdmpublications.com BDM’s Coding for Beginners 57


Coding on Linux

Testing Linux Mint’s


Live Environment
With the DVD or USB boot media ready you can now test Mint in a Live Environment
before deciding to install it. A Live Environment is a functioning version of Mint that’s
running from the boot media as opposed to running off your computer’s hard drive.

UEFI BIOS
The Unified Extensible Firmware Interface (UEFI) is used to identify hardware and protect a PC during its boot-up process. It
replaces the traditional BIOS but can cause issues when installing Linux Mint.

STEP 1 Insert your DVD or USB flash drive into your PC and, STEP 3 With UEFI turned to Legacy mode, there are
if you haven’t already, shutdown Windows. In this now two ways of booting into the Mint Live
instance we’re using the USB boot media but the process is virtually Environment. The first is via the BIOS you’re already in. Locate the
identical. Start the PC and when prompted press the appropriate Boot Sequence and change the first boot device from its original
keys to enter the BIOS or SETUP; these could be, for example, F2, setting, usually Internal HDD or similar, to USB Storage Device for
Del or even F12. the USB media option; or DVD Drive, for the DVD media option.

STEP 2 There are different versions of a UEFI BIOS, so STEP 4 Alternatively use the Boot Option Menu. With this
covering them all would be impossible. What you’re option you can press F12 (or something similar)
looking for is a section that details the Boot Sequence or Boot to display a list of boot media options; from there, you can choose
Mode. Here you have the option to turn off UEFI and choose Legacy the appropriate boot media. Either way, you can now save and exit
or disable Secure Booting. Mint does work with UEFI but it can be a the BIOS by navigating to the Save & Exit option and choosing Save
tricky process to enable it to boot. Changes and Exit.

58 BDM’s Coding for Beginners


Testing Linux Mint’s Live Environment

TESTING MINT
With the UEFI BIOS side of things behind us, it’s time to see what the Linux Mint desktop has to offer, albeit in the test,
Live Environment.

STEP 1 Linux Mint now boots up and you are taken directly STEP 4 To the far right of the Panel, you can see several
to the Mint default desktop; we have the Cinnamon icons; these indicate the current logged in user
mainstream version in the screenshot here. You can see three icons account (which is Live Session User at present), active network
on the desktop: Computer, Home and Install Linux Mint. connections (where you can adjust or setup your Wi-Fi or wired
internet connection), volume controls, time and date, and All
Windows, which when clicked displays all opened apps.

STEP 2 Along the bottom of the desktop is the Mint Panel STEP 5 There are also some quick launch icons on the
and the Mint Menu. Click the Menu and it displays Panel next to the Mint Menu: Show Desktop, which
the core applications along with a search bar and various icons lined will return you to a blank desktop while minimising all open apps;
up down the left-hand side. These are quick launch icons that will Firefox web browser; the Terminal command line; and Nemo file
change to the more recently used apps as you use Mint. manager. You can use any of these in a live session but anything
stored won’t be saved on quitting.

STEP 3 The three icons to the bottom of the quick launch STEP 6 Before you install Mint, you need to make sure you
strip indicate the session options: Lock Screen, have an active Internet connection. If you have a
Logout and Quit (shutdown Linux Mint). Just above the Lock Screen wired, Ethernet connection, and it’s not already plugged into the
icon is Files, clicking this will launch Nemo, the Linux Mint Cinnamon computer, do so now. If you’re using Wi-Fi, click on the network
file manager. connection icon in the bottom right of the Panel, find your router id
and enter the details.

www.bdmpublications.com BDM’s Coding for Beginners 59


Coding on Linux

Installing Linux Mint


on a PC
You’ve picked your Linux Mint desktop version and you’ve played around in the Live
Environment. Now it’s time to get Mint onto your PC as a permanent replacement for
Windows. Thankfully the process is extremely easy.

GOING MINT
We’re assuming at this point that you’re still in the Live Environment and that you’ve set up and activated your Wi-Fi
connection, or plugged your computer into your router via a wired connection.

STEP 1 Providing you’re connected to the Internet (if not STEP 3 After clicking Continue you’re asked if you want
then do so now) and you’re in the Live Environment, to Install Third-Party Software. Providing you’re
start the installation process by double-clicking on the Install Linux connected to the Internet, as from Step 1, then tick the box. This
Mint icon on the desktop. will make sure that hardware drivers, Adobe Flash and codecs for
MP3 and video files are installed with the main Mint system. Click
Continue for the next stage.

STEP 2 Launching the Install Linux Mint app will open up STEP 4 This next stage asks you how you want to manage
the Welcome screen. Make sure your language is the installation of Linux Mint onto your PC. In our
selected from the list on the left and if you want to click the Release example, we’re going to Erase Disk and Install Linux Mint, which will
Notes link to read what the latest changes and additions are to Linux wipe the current OS and ALL DATA replacing it with Mint; make sure
Mint 18.1 Cinnamon. When you’re ready, click the Continue button. you have a good backup, just in case. Click Install Now to continue.

60 BDM’s Coding for Beginners


Installing Linux Mint on a PC

STEP 5 Before the installation process can begin, you’re STEP 8 In this stage you need to set up your Mint username
asked if the choice you made regarding the erasure and password. Enter your Name to begin with, then
of the hard drive is correct. This is your last chance to back out. If Computer Name, which is the name it’s identified on the network as.
you’re certain you don’t mind wiping everything and starting again Next choose a Username, followed by a good Password. You can tick
with Linux Mint, click Continue. the Login Automatically option but leave the Encrypt Home Folder
option for now.

STEP 6 This next stage determines your location. You can STEP 9 The installation process will now begin and you can
enter the nearest major city, or even try your local see what’s being installed along the bottom of the
town and see if it’s in the list of available choices. When you’re install window. You can also use the arrows on the screen to browse
ready, click Continue. through some of the features available in Linux Mint.

STEP 7 Next up, use the options to pick which keyboard STEP 10 When the installation is complete you are
you’re using. In most cases it will be the option presented with a completion box, asking you if
with the Extended WinKeys. Use the Type Here… box to test your you want to continue with the Live Environment or restart the PC
keyboard setup is correct. Click Continue when you’re ready to with Linux Mint as the main operating system. Click on the Restart
move on. Now button, followed by Enter and remove the Installation Media
when asked. Congratulations, Linux Mint is now installed.

www.bdmpublications.com BDM’s Coding for Beginners 61


Coding on Linux

Installing Linux Mint


in VirtualBox
With Oracle’s VirtualBox now up and running, and continuing from the previous
section, the next task is to create the Virtual Machine (VM) environment into which
you install Linux Mint.

CREATING THE VM
There are plenty of options to choose from when creating a VM. For now though, you can set up a VM adequate to run Mint
Cinnamon and perform well.

STEP 1 With VirtualBox open, click on the New icon in STEP 3 The next section will define the amount of system
the top right of the app. This will open the new memory (RAM) the VM has allocated. Remember
VM Wizard. this amount will be taken from the available memory installed in
your computer, so don’t give the VM too much. For example, we
have 8GB of memory installed and we’re giving 2GB to the VM.
When you’re ready, click Next to continue.

STEP 2 In the box next to Name, type Linux Mint and STEP 4 This section is where you start to create the virtual
VirtualBox should automatically choose Linux hard disk that the VM will use to install Mint on to.
as the Type and Ubuntu (64-bit) as the Version. If not then use The default option, ‘Create a virtual hard disk now’, is the one we’re
the drop-down boxes to select the correct settings; remember using. Click Create to move on.
Mint mainstream is based on Ubuntu. Click Next when you’re ready
to proceed.

62 BDM’s Coding for Beginners


Installing Linux Mint in VirtualBox

STEP 5 The pop-up window that appears after clicking STEP 8 After clicking Create the initial set up of the VM
Create is asking you what type of virtual hard disk is complete; you should now be looking at the
you want to create. Use the default VDI (VirtualBox Disk Image) in newly created VM within the VirtualBox application. Before you
this case, as the others are often used to move VMs from one VM begin though, click the Settings button and within the General
application to the next. Make sure VDI is selected and click Next. section click the Advanced tab. Using the pull-down menus, choose
‘Bidirectional’ for both Shared Clipboard and Drag’n’Drop.

STEP 6 The question of whether to opt for Dynamically STEP 9 Follow that by clicking on the System section,
or Fixed sized virtual hard disks may come across then the Processor tab. Depending on your CPU
as being somewhat confusing to the newcomer. Basically, a allocate as many cores as you can without detriment to your host
Dynamically Allocated virtual hard disk is a more flexible storage system; we’ve opted for two CPUs. Now click on the Display section,
management option. It won’t take up much space within your slide the Video Memory up to the maximum and tick ‘Enable 3D
physical hard disk to begin with either. Ensure Dynamically Allocated Acceleration’. Click OK to commit the new settings.
is selected and click Next.

STEP 7 The virtual hard disk will be a single folder, up to the STEP 10 Click on the Start button and use the explorer
size you state in this section. Ensure the location button in the ‘Select Start-up Disk’ window to
of the virtual hard disk, on your computer, has enough free space locate the downloaded ISO of Mint; the explorer button is a folder
available. For example, we’ve used a bigger storage option on our with a green arrow. Click Start to boot the VM with the Linux Mint
D:\ drive, named it Linux Mint and allocated 25.50GB of space to the Live Environment. You can now install Linux Mint as detailed in the
virtual hard disk. previous Installing Linux Mint on a PC section.

www.bdmpublications.com BDM’s Coding for Beginners 63


Coding on Linux

Getting Ready to
Code in Linux
Coding in Linux mostly happens in the Terminal or the Command Line. While it
can be a scary looking place to begin with, the Terminal is an extremely powerful
environment. Before you can start to code, it’s best to master the Terminal.

TAKING COMMAND
The command line is at the core of Linux and when you program with it, this is called scripting. These are self-contained
programs designed to be run in the Terminal.

STEP 1 The Terminal is where you begin your journey STEP 3 What you currently see in the Terminal is your login
with Linux, through the command line and thus name followed by the name of the computer, as you
any scripting from. In Linux Mint, it can be accessed by clicking on named it when you first installed the OS on to the computer. The
the Menu followed by the Terminal icon in the panel, or entering line then ends with the current folder name; at first this is just a tilde
‘Terminal’ into the search bar. (~), which means your Home folder.

STEP 2 The Terminal will give you access to the Linux STEP 4 The flashing cursor at the very end of the line is
Mint Shell, called BASH; this gives you access to where your text-based commands will be entered.
the underlying operating system, which is why scripting is such a You can begin to experiment with a simple command, Print Working
powerful language to learn and use. Everything in Mint, and Linux Directory (pwd), which will output to the screen the current folder
as a whole, including the desktop and GUI, is a module running from you’re in. Type: pwd and press Enter.
the command line.

64 BDM’s Coding for Beginners


Getting Ready to Code in Linux

STEP 5 All the commands you enter will work in the same STEP 6 The list of available Linux commands is vast,
manner. You enter the command, include any with some simply returning the current working
parameters to extend the use of the command and press Enter to directory, while others are capable of deleting the entire system in
execute the command line you’ve entered. Now type: uname -a an instant. Getting to know the commands is part
and press Enter. This will display information regarding Linux Mint. of learning how to script. By using the wrong command, you could
In scripting, you can use all the Linux command-line commands end up wiping your computer. Type compgen -c to view the
within your own scripts. available commands.

HERE BE DRAGONS!
There’s an urban myth on the Internet that an employee at Disney Pixar nearly ruined the animated movie Toy Story by
inadvertently entering the wrong Linux command and deleting the entire system the film was stored on.

STEP 1 Having access to the Terminal means you’re STEP 3 Therefore it’s always a good idea to work in the
bypassing the GUI desktop method of working Terminal using a two-pronged approach. First, use
with the system. The Terminal is a far more powerful environment the desktop to make regular backups of the folders you’re working
than the desktop, which has several safeguards in place in case you in when in the Terminal. This way, should anything go wrong, there’s
accidentally delete all your work, such as Rubbish Bin to recover a quick and handy backup waiting for you.
deleted files.

STEP 2 However, the Terminal doesn’t offer that luxury. If STEP 4 Second, research before blindly entering a
you were to access a folder with files within via the command you’ve seen on the Internet. If you see the
Terminal and then enter the command: rm *.*, all the files in that command: sudo dd if=/dev/random of=/dev/sda and use
folder would be instantly deleted. They won’t appear in the Rubbish it in a script, you’ll soon come to regret the action as the command
Bin either, they’re gone for good. will wipe the entire hard drive and fill it with random data. Take a
moment to Google the command and see what it does.

www.bdmpublications.com BDM’s Coding for Beginners 65


Coding on Linux

Creating Bash Scripts


– Part 1
Eventually, as you advance with Linux Mint, you’ll want to start creating your own automated
tasks and programs. These are essentially scripts, Bash Shell scripts to be exact, and they
work in the same way as a DOS Batch file does, or any other programming language.

GET SCRIPTING
A Bash script is simply a series of commands that Mint will run through to complete a certain task. They can be simple or
remarkably complex, it all depends on the situation.

STEP 1 You’ll be working within the Terminal and with a STEP 3 To begin with, and before you start to write any
text editor throughout the coming pages. There scripts, you need to create a folder where you can
are alternatives to the text editor, which we’ll look at in a moment put all our scripts into. Start with mkdir scripts, and enter the
but for the sake of ease, we’ll be doing our examples in Xed. Before folder cd scripts/. This will be our working folder and from here
you begin, however, run through the customary update check: sudo you can create sub-folders if you want of each script you create.
apt-get update && sudo apt-get upgrade.

STEP 2 There are several text editors we can use to create STEP 4 Windows users will be aware that in order for a
a Bash script: Xed, Vi, Nano, Vim, GNU Emacs and batch file to work, as in be executed and follow the
so on. In the end it all comes down to personal preference. Our programming within it, it needs to have a .BAT file extension. Linux
use of Xed is purely due to making it easier to read the script in the is an extension-less operating system but the convention is to give
screenshots you see below. scripts a .sh extension.

66 BDM’s Coding for Beginners


Creating Bash Scripts – Part 1

STEP 5 Let’s start with a simple script to output something STEP 8 When you enter ls again, you can see that the
to the Terminal. Enter xed helloworld.sh. helloworld.sh script has now turned from being
This will launch Xed and create a file called helloworld.sh. In Xed, white to green, meaning that it’s now an executable file. To run
enter the following: #!/bin/bash, then on a new line: echo the script, in other words make it do the things you’ve typed into it,
Hello World!. enter: ./helloworld.sh.

STEP 6 The #!/bin/bash line tells the system what Shell STEP 9 Although it’s not terribly exciting, the words ‘Hello
you’re going to be using, in this case Bash. The hash World!’ should now be displayed in the Terminal.
(#) denotes a comment line, one that is ignored by the system, the The echo command is responsible for outputting the words after
exclamation mark (!) means that the comment is bypassed and will it in the Terminal, as we move on you can make the echo command
force the script to execute the line as a command. This is also known output to other sources.
as a Hash-Bang.

STEP 7 You can save this file, clicking File > Save, and exit STEP 10 Think of echo as the old BASIC Print command. It
back to the Terminal. Entering ls, will reveal the displays either text, numbers or any variables that
script in the folder. To make any script executable, and able to are stored in the system, such as the current system date. Try this
run, you need to modify its permissions. Do this with chmod +x example: echo Hello World! Today is $(date +%A). The
helloworld.sh. You need to do this with every script you create. $(date +%A) is calling the system variable that stores the current day
of the week.

www.bdmpublications.com BDM’s Coding for Beginners 67


Coding on Linux

Creating Bash Scripts


– Part 2
Previously we looked at creating your first Bash script, Hello World, and adding a
system variable. Now you can expand these and see what you can do when you start
to play around with creating your own unique variables.

VARIABLES
Just as in every other programming language a Bash script can store and call certain variables from the system, either generic
or user created.

STEP 1 Let’s start by creating a new script called hello.sh; STEP 3 The output now will be Hello David. This is because
xed hello.sh. In it enter: #!/bin/bash, then, Bash automatically assigns variables for the user,
echo Hello $1. Save the file and exit Xed. Back in the Terminal which are then held and passed to the script. So the variable
make the script executable with: chmod +x hello.sh. ‘$1’ now holds ‘David’. You can change the variable by entering
something different: ./hello.sh Mint.

STEP 2 As the script is now executable, run it with ./ STEP 4 You can even rename variables. Modify the hello.
hello.sh. Now, as you probably expected a simple sh script with the following: firstname=$1,
‘Hello’ is displayed in the Terminal. However, if you then issue the surname=$2, echo Hello $firstname $surname. Putting
command with a variable, it begins to get interesting. For example, each statement on a new line. Save the script and exit back into
try ./hello.sh David. the Terminal.

68 BDM’s Coding for Beginners


Creating Bash Scripts – Part 2

STEP 5 When you run the script now you can use two STEP 8 Let’s expand things further. Create a new script
custom variables: ./hello.sh David Hayward. called greetings.sh. Enter the scripting as below
Naturally change the two variables with your own name; unless in the screenshot, save it and make it executable with the chmod
you’re also called David Hayward. At the moment we’re just printing command. You can see that there are a few new additions to the
the contents, so let’s expand the two-variable use a little. script now.

STEP 6 Create a new script called addition.sh, using STEP 9 We’ve added a –n to the echo command here
the same format as the hello.sh script, but which will leave the cursor on the same line as the
changing the variable names. Here we’ve added firstnumber and question, instead of a new line. The read command stores the
secondnumber, and used the echo command to output some users’ input as the variables firstname and surname, to then read
simple arithmetic by placing an integer expression, echo The sum back later in the last echo line. And the clear command clears
is $(($firstnumber+$secondnumber)). Save the script, and the screen.
make it executable (chmod +x addition.sh).

STEP 7 When you now run the addition.sh script we can STEP 10 As a final addition, let’s include the date variable
enter two numbers: ./addition.sh 1 2. The we used in the last section. Amend the last line
result will hopefully be 3, with the Terminal displaying ‘The sum of the script to read: echo Hello $firstname $surname, how
is 3’. Try it with a few different numbers and see what happens. are you on this fine $(date +%A)?. The output should
See also if you can alter the script and rename it do multiplication, display the current day of the week, calling it from a system variable.
and subtraction.

www.bdmpublications.com BDM’s Coding for Beginners 69


Coding on Linux

Creating Bash Scripts


– Part 3
In the previous pages we looked at some very basic Bash scripting, which involved
outputting text to the screen, getting a user’s input, storing it and outputting that to
the screen; as well as including a system variable using the Date command. Now let’s
combine what you’ve achieved so far and introduce Loops.

IF, THEN, ELSE


With most programming structures there will come a time where you need to loop through the commands you’ve entered to
create better functionality, and ultimately a better program.

STEP 1 Let’s look at the If, Then and Else statements now, STEP 3 The next line, ELSE, is what happens if the variable
which when executed correctly, compare a set of doesn’t equal ‘David’. In this case it simply outputs
instructions and simply work out that IF something is present, THEN to the screen the now familiar ‘Hello…’. The last line, the FI
do something, ELSE do something different. Create a new script statement, is the command that will end the loop. If you have an If
called greeting2.sh and enter the text in the screenshot below command without a Fi command, then you get an error.
into it.

STEP 2 Greeting2.sh is a copy of greeting.sh but with a STEP 4 You can obviously play around with the script a
slight difference. Here we’ve added a loop starting little, changing the name variable that triggers a
at the if statement. This means, IF the variable entered is equal to response; or maybe even issuing a response where the first name
David the next line, THEN, is the reaction to what happens, in this and surname variables match a specific variable.
case it will output to the screen ‘Awesome name,’ followed by the
variable (which is David).

70 BDM’s Coding for Beginners


Creating Bash Scripts – Part 3

MORE LOOPING
You can loop over data using the FOR, WHILE and UNTIL statements. These can be handy if you’re batch naming, copying or
running a script where a counter is needed.

STEP 1 Create a new script called count.sh. Enter the STEP 4 The UNTIL loop works much the same way as the
text in the screenshot below, save it and make it WHILE loop only, more often than not, in reverse.
executable. This creates the variable ‘count’ which at the beginning So our counting to a hundred, using UNTIL, would be: until
of the script equals zero. Then start the WHILE loop, which WHILE [ $count -gt 100 ]; do. The difference being, UNTIL count is
count is less than (the LT part) 100 will print the current value of greater than (the gt part) one hundred, keep on looping.
count in the echo command.

STEP 2 Executing the count.sh script will result in the STEP 5 You’re not limited to numbers zero to one hundred.
numbers 0 to 99 listing down the Terminal screen; You can, within the loop, have whatever set of
when it reaches 100 the script will end. Modifying the script with the commands you like and execute them as many times as you want
FOR statement, makes it work in much the same way. To use it in our the loop to run for. Renaming a million files, creating fifty folders
script, enter the text from the screenshot into the count.sh script. etc. For example, this script will create ten folders named folder1
through to folder10 using the FOR loop.

STEP 3 The addition we have here is: for count in STEP 6 Using the FOR statement once more, we can
{0..100}; do. Which means: FOR the variable execute the counting sequence by manipulating the
‘count’ IN the numbers from zero to one hundred, then start the {0..100} part. This section of the code actually means {START..END..
loop. The rest of the script is the same. Run this script, and the same INCREMENT}, if there’s no increment then it’s just a single digit up to
output should appear in the Terminal. the END. For example, we could get the loops to count up to 1000 in
two’s with: for count in {0..1000..2}; do.

www.bdmpublications.com BDM’s Coding for Beginners 71


Coding on Linux

Creating Bash Scripts


– Part 4
You’ve encountered user interaction with your scripts, asking what the user’s name
is and so on. You’ve also looked at creating loops within the script to either count or
simply do something several times. Let’s combine and expand some more.

CHOICES AND LOOPS


Let’s bring in another command, CHOICE, along with some nested IF and ELSE statements. Start by creating a new script called
mychoice.sh.

STEP 1 STEP 3 You can, of course, increase the number of choices


but you need to make sure that you match the
The mychoice.sh script number of choices to the number of IF statements. The script can
is beginning to look a quickly become a very busy screen to look at. This lengthy script
lot more complex. What is another way of displaying a menu, this time with a fancy colour
we have here is a list scheme too.
of four choices, with
three possible options.
The options: Mint, Is,
and Awesome will be
displayed if the user
presses the correct
option key. If not, then
the menu will reappear,
the fourth choice.

STEP 2 If you follow the script through you soon get the
hang of what’s going on, based on what we’ve
already covered. WHILE, IF, and ELSE, with the FI closing loop
statement will run through the options and bring you back to the
start if you pick the wrong option.

STEP 4 You can use the


arrow keys and Enter
in the menu setup in the script. Each
choice is an external command that
feeds back various information. Play
around with the commands and
choices, and see what you can come
up with. It’s a bit beyond what we’ve
looked at but it gives a good idea of
what can be achieved.

72 BDM’s Coding for Beginners


Creating Bash Scripts – Part 4

CREATING A BACKUP TASK SCRIPT


One of the most well used examples of Bash scripting is the creation of a backup routine, one that automates the task as well
as adding some customisations along the way.

STEP 1 A very basic backup script would look something STEP 4 Once the ~/backups folder is created, we can now
along the lines of: #!/bin/bash, then, create a new subfolder within it based on the
tar cvfz ~/backups/my-backup.tgz ~/Documents/. This Time Stamp variables you set up at the beginning. Add mkdir -p
will create a compressed file backup of the ~/Documents folder, $dest/”$day $month $year”. It’s in here that you put the
with everything in it, and put it in a folder called /backups with the backup file relevant to that day/month/year.
name my-backup.tgz.

STEP 2 While perfectly fine, we can make the simple script STEP 5 With everything in place, you can now enter the
a lot more interactive. Let’s begin with defining actual backup routine, based on the Tar command
some variables. Enter the text in the screenshot into a new backup. from Step 5. Combined with the variables, you have: tar cvfz
sh script. Notice that we’ve misspelt ‘source’ as ‘sauce’, this is $dest/”$day $month $year”/DocumentsBackup.tgz
because there’s already a built-in command called ‘source’ hence the $sauce. In the screenshot, we added a handy “Now backing up...”
different spelling on our part. echo command.

STEP 3 The previous script entries allowed you to create STEP 6 Finally, you can add a friendly message: echo
a Time Stamp, so you know when the backup was “Backup complete. All done...”. The
taken. You also created a ‘dest’ variable, which is the folder where completed script isn’t too over-complex and it can be easily
the backup file will be created (~/backups). You can now add a customised to include any folder within your Home area, as well as
section of code to first check if the ~/backups folder exits, if not, the entire Home area itself.
then it creates one.

www.bdmpublications.com BDM’s Coding for Beginners 73


Coding on Linux

Creating Bash Scripts


– Part 5
The backup script we looked at previously can be further amended to incorporate
choices, or in other words , user-interaction with regards to where the backup file
will be copied to and so on. Automating tasks is one of the main benefits of Bash
scripting, a simple script can help you out in many ways.

EASY AUTOMATION AND HANDY SCRIPTS


Entering line after line of commands to retrieve system information, find a file or rename a batch of files? A script is a
better answer.

STEP 1 Let’s start by creating a script to help display the STEP 3 Each of the sections runs a different Terminal
Mint system information; always a handy thing command, outputting the results under the
to have. Create a new script called sysinfo.sh and enter the appropriate heading. You can include a lot more, such as the current
following into Xed, or the text editor of your choice. aliases being used in the system, the current time and date and so
on. Plus, you could also pipe all that information into a handy HTML
file, ready to be viewed in a browser.

STEP 4 Although there are simple Terminal commands to


help you look for a particular file or folder, it’s often
more fun to create a script to help you. Plus, you can use that script
for other non-technical users. Create a new script called look4.sh,
entering the content from the screenshot below.

STEP 2 We’ve included a couple of extra commands in


this script. The first is the -e extension for echo,
this means it’ll enable echo interpretation of additional instances
of a new line, as well as other special characters. The proceeding
‘31;43m’ element enables colour for foreground and background.

74 BDM’s Coding for Beginners


Creating Bash Scripts – Part 5

STEP 5 When executed the script waits for input from the STEP 8 The output from colours.sh can, of course, be
user, in this case the file extension, such as jpg, mixed together, bringing different effects
mp4 and so on. It’s not very friendly though. Let’s make it a little depending on what you want to the output to say. For example,
friendlier. Add an echo, with: echo -n “Please enter the white text in a red 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 to
before the read command. change to a different Terminal.

STEP 6 Here’s an interesting, fun kind of script using the


app espeak. Install espeak with sudo apt-get
install espeak, then enter the text below into a new script called
speak.sh. As you can see it’s a rehash of the first greeting script
we ran. Only this time, it uses the variables in the espeak output.

STEP 7 We briefly looked at putting some colours in the


output for our scripts. Whilst it’s too long to dig a STEP 9 Whilst we’re on making fancy scripts, how about
little deeper into the colour options, here’s a script that outputs using Zenity to output a graphical interface?
what’s available. Create a new script called colours.sh and enter Enter what you see below into a new script, mmenu.sh. Make it
the text (see below) into it. executable and then run it. You should have a couple of dialogue
boxes appear, followed by a final message.

STEP 10 While gaming in a Bash script isn’t something


that’s often touched upon, it is entirely possible,
albeit, a little basic. If you fancy playing a game, enter wget
http://bruxy.regnet.cz/linux/housenka/housenka.sh,
make the script executable and run it. It’s in Polish, written by
Martin Bruchanov but we’re sure you can modify it. Hint: the title
screen is in Base64.

www.bdmpublications.com BDM’s Coding for Beginners 75


Coding on Linux

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 cd command is one of the commands you The mv command moves a file to a different
will use the most at the command line in Linux. It location or renames a file. For example mv file
cd allows you to change your working directory. You mv sub renames the original file to sub. mv sub
use it to move around within the hierarchy of your ~/Desktop moves the file ‘sub’ to your desktop
file system. You can also use chdir. directory but does not rename it. You must specify
a new filename to rename a file.

The ls command shows you the files in your The chown command changes the user and/
current directory. Used with certain options, it lets or group ownership of each given file. If only an
ls you see file sizes, when files where created and file chown owner (a user name or numeric user ID) is given,
permissions. For example, ls ~ shows you the files that user is made the owner of each given file, and
that are in your home directory. the files’ group is not changed.

The cp command is used to make copies of files The chmod command changes the permissions on
and directories. For example, cp file sub makes the files listed. Permissions are based on a fairly
cp an exact copy of the file whose name you entered cmod simple model. You can set permissions for user,
and names the copy sub but the first file will still group and world and you can set whether each can
exist with its original name. read, write and or execute the file.

The pwd command prints the full pathname of The rm command removes (deletes) files or
the current working directory (pwd stands for directories. The removal process unlinks a filename
pwd “print working directory”). Note that the GNOME rm in a filesystem from data on the storage device
terminal also displays this information in the title and marks that space as usable by future writes. In
bar of its window. other words, removing files increases the amount
of available space on your disk.

The clear command clears your screen if this Short for “make directory”, mkdir is used to
is possible. It looks in the environment for the create directories on a file system, if the specified
clear terminal type and then in the terminfo database mkdir directory does not already exist. For example,
to figure out how to clear the screen. This is mkdir work creates a work directory. More than
equivalent to typing Control-L when using the one directory may be specified when calling mkdir.
bash shell.

76 BDM’s Coding for Beginners


Command Line Quick Reference

C:\Commonly_Used_Commands

USEFUL HELP/INFO COMMANDS


The following commands are useful for when
you are trying to learn more about the system or
program you are working with in Linux. You might
not need them every day, but when you do, they
will be invaluable.

The free command displays the total amount The sed command opens a stream editor.
free of free and used physical and swap memory in sed A stream editor is used to perform text
the system. For example, free -m gives the transformations on an input stream: a file or input
information using megabytes. from a pipeline.

The df command displays filesystem disk space


The adduser command adds a new user to the
df usage for all partitions. The command df-h adduser system. Similarly, the addgroup command adds a
is probably the most useful (the -h means
new group to the system.
human-readable).

The top program provides a dynamic real-time The deluser command removes a user from
view of a running system. It can display the system. To remove the user’s files and
top system summary information, as well as a list deluser home directory, you need to add the -remove-
of processes. home option.

The uname command with the -a option prints The delgroup command removes a group from
unmame-a all system information, including machine name, delgroup the system. You cannot remove a group that is the
kernel name, version and a few other details. primary group of any users.

The ps command allows you to view all the


The man man command brings up the manual
processes running on the machine. Every
ps operating system’s version of ps is slightly man man entry for the man command, which is a great place
to start when using it.
different but all do the same thing.

The grep command allows you to search inside a


The man intro command is especially useful.
number of files for a particular search pattern and
grep then print matching lines. An example would be: man intro It displays the Introduction to User Commands,
which is a well written, fairly brief introduction to
grep blah file.
the Linux command line.

www.bdmpublications.com BDM’s Coding for Beginners 77


Coding on Linux

A-Z of Linux Commands


There are literally thousands of commands, so while this is not a complete A-Z, it does
contain many of the commands you will most likely need. You will probably find that
you end up using a smaller set of commands over and over again but having an overall
knowledge is still very useful.

Aadduser Add a new user dd Data Dump, convert and


Ggawk Find and Replace text
copy a file within file(s)
arch Print machine architecture
diff Display the differences grep Search file(s) for lines that
awk Find and replace text
between two files match a given pattern
within file(s)
dirname Convert a full path name groups Print group names a user

B
to just a path is in
du Estimate file space usage gzip Compress or decompress
bc An arbitrary precision named file(s)

E
calculator language

C echo Display message on screen Hhead Output the first part


ed A line oriented text editor
cat Concatenate files and print of file(s)
(edlin)
on the standard output
hostname Print or set system name
egrep Search file(s) for lines
chdir Change working directory
that match an
chgrp Change the group
ownership of files
extended expression
env Display, set or remove
Iid Print user and group ids
chroot Change root directory environment variables
info Help info
cksum Print CRC checksum and expand Convert tabs to spaces
byte counts install Copy files and
expr Evaluate expressions
set attributes
cmp Compare two files
comm Compare two sorted files
line by line Ffactor Print prime factors
J
cp Copy one or more files to join Join lines on a
another location fdisk Partition table common field
manipulator for Linux
crontab Schedule a command to
run at a later time
csplit Split a file into context-
fgrep Search file(s) for lines that
match a fixed string K
kill Stop a process
determined pieces find Search for files that meet
from running
a desired criteria
cut Divide a file into

L
several parts fmt Reformat paragraph text
fold Wrap text to fit a

D
date Display or change the
format
specified width
Format disks or tapes
less Display output one screen
at a time
ln Make links between files
date & time fsck Filesystem consistency
check and repair locate Find files
dc Desk calculator

78 BDM’s Coding for Beginners


A-Z of Linux Commands

logname
lpc Line printer
Print current login name rcp Copy files between
two machines Uumount Unmount a device
control program rm Remove files
unexpand Convert spaces to tabs
lpr Off line print rmdir Remove folder(s)
uniq Uniquify files
lprm Remove jobs from the rpm Remote Package Manager
print queue units Convert units from one
rsync Remote file copy
scale to another
(synchronise file trees)

M unshar Unpack shell archive scripts

man
mkdir
See Help manual
Create new folder(s)
S
screen Terminal window manager
useradd
usermod
Create new user account
Modify user account
users List users currently
mkfifo Make FIFOs (named pipes) sdiff Merge two files interactively
logged in
mknod Make block or character select Accept keyboard input

V
special files
seq Print numeric sequences
more Display output one screen
shutdown Shutdown or restart Linux
at a time vdir Verbosely list directory
sleep Delay for a specified time contents (`ls -l -b’)
mount Mount a file system
sort Sort text files

N split Split a file into


fixed-size pieces
W
watch Execute or display a
nice Set the priority of a
su Substitute user identity program periodically
command or job
sum Print a checksum for a file wc Print byte, word, and
nl Number lines and
line counts
write files symlink Make a new name for
a file whereis Report all known
nohup Run a command immune
instances of a command
to hangups sync Synchronise data on disk
with memory which Locate a program file in

P
the user’s path

passwd Modify a user password T


tac Concatenate and write
who Print all usernames
currently logged in
paste Merge lines of files whoami Print the current user id
files in reverse
and name
pathchk Check file name portability
tail Output the last part

X
pr Convert text files of files
for printing
tar Tape Archiver
printcap Printer capability database xargs Execute utility, passing
tee Redirect output to
constructed argument list(s)
printenv Print environment variables multiple files

Y
printf Format and print data test Evaluate a
conditional expression

Q time Measure Program


Resource Use
yes Print a string
until interrupted
quota Display disk usage touch Change file timestamps
and limits
top List processes running on
quotacheck Scan a file system for the system
disk usage
traceroute Trace Route to Host
quotactl Set disk quotas
tr Translate, squeeze and or
delete characters

Rram Ram disk device


tsort Topological sort

www.bdmpublications.com BDM’s Coding for Beginners 79


Programming with the FUZE

The Raspberry Pi is the powerhouse


for many excellent projects. However,
one project stands head and shoulders
above the rest, the FUZE Project.
FUZE is a 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 in a 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.

82 Introducing the FUZE Project


84 Setting Up the FUZE
86 Getting Started with FUZE BASIC
88 Coding with FUZE BASIC – Part 1
90 Coding with FUZE BASIC – Part 2
92 Coding with FUZE BASIC – Part 3
94 Using a Breadboard
96 Using the FUZE IO Board
98 Using a Robot Arm with FUZE BASIC
100 FUZE BASIC Examples – Part 1
102 FUZE BASIC Examples – Part 2

80 BDM’s Coding for Beginners


Index

Programming
with the FUZE

www.bdmpublications.com BDM’s Coding for Beginners 81


Programming with the FUZE

Introducing the
FUZE Project
The FUZE Project is a learning environment that’s built around the Raspberry Pi
and a custom programming language based on BASIC. The FUZE Workstation is the
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 Inside the FUZE workstation is


a BBC Micro Model B from the ‘80s, the beating heart of the project, a
constructed with a metal body and Raspberry Pi 3. It’s connected to the
high quality keyboard complete with FUZE IO board via the 40-pin GPIO pins
programmable red coloured F-keys. with a ribbon cable, with the other
Note the holes at the top edges: these connections branching from it: HDMI,
are compatible with many popular power, SD Card and USB. The USB
plastic building blocks and electronic ports have been routed to a powered
construction kits. USB hub, attached to the rear of the
workstation, providing the user with
four USB ports accessible through the
rear IO back plate; there’s an Ethernet
port too.

The Rear IO back plate is where you


plug in your power, connection to a
monitor, mouse, SD card, audio and
any USB devices you want to include.
From left to right, across the back plate,
there’s an on/off switch, a power port,
a bank of four USB ports, the Ethernet The FUZE IO board, located in the wide
port, SD card slot and HDMI port. You slot at the top of the workstation, is
can remove the four corner screws of the connection to extended hardware.
the back plate to gain access to the With it you can connect, program and
Raspberry Pi, USB hub and cables inside use sensors, LEDs, robotics and all
the workstation if needed. manner of amazing electronic projects.

82 BDM’s Coding for Beginners


Introducing the FUZE Project

You also receive an electronics kit as part of


the FUZE workstation, to help you get started
on some of the projects the FUZE is designed
to support. Within the kit you can find 24
coloured LEDs, 1 seven-segment LED, 1 light
dependant resistor, 8 micro switches, 30 mixed
specification resistors, 20 jumper cables and 60
jumper wires.

Complementing the electronics project kit,


the FUZE team also bundles an 840-socket
solderless breadboard which you can use
to wire up interesting projects and use
FUZE BASIC together with the Raspberry
Pi and the FUZE IO board to control the
components from the electronics kit. In
case you’re wondering why it’s called a
breadboard, it’s because in the early days
of electronics users would use a bread
board for the base of their projects.

Alongside the other components with


the FUZE workstation, you also get either
a wired USB or wireless (batteries are
included if necessary) mouse and ‘FUZE’
logo mouse mat.

The kit comes with two ring-bound books


containing project ideas for the electronics
kit and a programmer’s reference guide
for FUZE BASIC. If you’ve purchased the
FUZE kit, then it’s certainly worth your
while reading through this book and
familiarising 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 D-sized batteries, a BBC
micro:bit or even a Capacitive Touch kit.
Needless to say, there’s plenty of project
potential with the FUZE.

www.bdmpublications.com BDM’s Coding for Beginners 83


Programming with the FUZE

Setting Up the FUZE


Thankfully the FUZE Project comes with everything you need to get up and running;
you just need to supply the monitor and an Ethernet cable to your network (or you
can go Wi-Fi with the Raspberry Pi 3). Before you begin though, let’s see how to set
up the workstation.

LIGHT THE FUZE


Getting the FUZE up and running is as simple as plugging in a standard desktop computer; but it’s always worth running
through the process for those who don’t know what to do.

STEP 1 Before you power up your FUZE, make sure that the STEP 3 For now, use the Ethernet port, LAN cable, for
provided SD card is inserted into the SD card slot the FUZE’s connection to the home network and
on the rear IO back plate of the FUZE workstation. The chances are ultimately the outside world. You can set up the Wi-Fi but it’s always
the SD card is already inserted but depending on how the FUZE was easier to establish a wired connection first if possible. Connect the
packaged, it may be in the electronics kit box. Ethernet cable to rear IO back plate of the FUZE.

STEP 2 Grab a spare monitor or if your existing monitor (or STEP 4 Next, open up the box containing the mouse and
TV) can support more than one HDMI connection plug it into one of the USB ports on the rear IO of
even better. The FUZE comes with a quality HDMI cable, remove it the FUZE workstation back plate.
from its bag and connect one end to the HDMI port on the rear IO
back plate of the FUZE and the other to the rear of the monitor or TV.

84 BDM’s Coding for Beginners


Setting Up the FUZE

STEP 5 Now open the box containing the power pack and STEP 8 If you want the Wi-Fi to be the active network
plug it into the power point at the wall and finally connection, look to the bottom right of the
to the FUZE workstation itself. The FUZE will power up immediately desktop for the two arrows (one pointing up, the other down). Click
and start to boot into the custom FUZE Raspbian OS on the SD card. the arrows and the current Wi-Fi access points will be displayed.
Connect to yours as you would normally. You can now unplug the
Ethernet cable if you wish.

STEP 6 You may need to change the source of the monitor STEP 9 Beyond the different desktop presentation, the
or TV’s input to the HDMI, or the numbered HDMI 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
the monitor it displays the FUZE desktop. F on a black background) to open the system menu detailing the
available apps and programs. The second F launches FUZE BASIC,
which we’ll look at in the next tutorial.

STEP 7 The first thing to notice is that it’s significantly STEP 10 To ensure you’re running the latest software and
different to that of the standard Raspberry Pi programs, click on the F start button, followed
Raspbian interface. The launch panel and buttons are located along by Accessories > Terminal. In the Terminal enter: sudo apt-get
the bottom of the screen, as with a Windows-type setup, with a update && sudo apt-get upgrade and accept any changes
couple of icons on the desktop itself. and updates the system has to offer. This will update all your
installed software and system files.

www.bdmpublications.com BDM’s Coding for Beginners 85


Programming with the FUZE

Getting Started with


FUZE BASIC
FUZE BASIC is a marvellous programming language to begin learning to code with. It
greatly mimics the ’80s BASIC versions from the 8-bit machines of the time, such as
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.

STEP 1 In the bottom right panel, the one that’s coloured STEP 3 The retro style interface of FUZE BASIC has several
white on a red background? Click it and you launch themes that you can cycle through, depending
the FUZE BASIC, complete with a C64-style retro interface. You can on your taste. The default view is 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 no doubt recognise some of them, so find
one you like.

STEP 2 Don’t worry if you don’t have a FUZE Workstation. STEP 4 The screen you’re looking at now is called
FUZE BASIC is available for Windows, the BBC Immediate Mode; pressing the Enter key will reveal
micro:bit and the Raspberry Pi (since it’s already running on a RPi). a cursor where you can start to enter code. Try this: press Enter,
Open a browser to www.fuze.co.uk/download-fuze.html and then type: Hello everyone and press Enter again. The output on the
follow the download instructions for FUZE BASIC for Windows and screen will display whatever you’ve typed into the quotation marks.
the step-by-step instructions to install it on a Raspberry Pi.

86 BDM’s Coding for Beginners


Getting Started with FUZE BASIC

STEP 5 You can also Print the total output of several STEP 8 Before we get into variables and other such
numbers from within the Immediate Mode. For programming terms, let’s have a little play around
example, try: print 10 + 20 + 30, and press Enter. The sum of with a quick listing to ask for user input. Enter this:
the numbers you’ve entered will now be displayed on the screen,
10 cls
in this case the number 60. Try more numbers and even different
20 input “What is your name? “, n$
mathematical symbols.
30 print
40 print “Hello “; n$
Enter run to execute the code.

STEP 6 If you find the screen getting a little full, enter cls
to clear the BASIC display. BASIC in Immediate Mode
is also capable of storing variables, something which we’ll look at
in more depth in the next tutorial. For now, try this and press Enter
after each line:
A=10
Print a

STEP 9 Dissecting the previous code, we have the command


to clear the screen [CLS], then the Input command
asking for user input and storing the input as the variable n$. The
Print at line 30 puts a blank line on the screen, whilst the Print
command at line 40 displays the message Hello and the contents
of the variable n$.

STEP 7 If you’re old enough to recall BASIC from the early


days of computing, you’ll no doubt remember that
coding came with line numbers. FUZE BASIC works the same way.
Whilst still in Immediate Mode, enter:
10 print “Hello”
20 goto 10
Now enter run. The word Hello should now cycle down the screen.
Press the Escape key to exit it.
STEP 10 There’s a lot you can do in Immediate Mode;
however, to unleash the full potential of FUZE
BASIC you’re best working in the Program Editor. To enter the
Program Editor type in the command new to clear any programs
already stored in memory and press the F2 key. As you can see,
Program Editor looks significantly different to Immediate Mode.

www.bdmpublications.com BDM’s Coding for Beginners 87


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.

STEP 1 Enter the Program Editor, by pressing the F2 key. STEP 3 Press F2 to enter Editor mode and click on New. Now
Within the Program Editor enter the following, let’s expand on the simple code. Enter the following:
pressing Enter after each line:
Let x=10
Let x=10 Let y=20
Print x Let z=30
Print x + y + z
Now click on the Save button, along the top of the screen and save
the program as ‘Variables1’. Click the OK button to return to the Save as ‘Variables2’ and Run it. You now 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.

STEP 4 What if we wanted to change the value of a


variable? Enter this listing:
Let x=10
STEP 2 After clicking Run you drop back into Immediate
Let x=x-1
Mode and the display will output the number 10. To
Print x
break down this simple 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 this as lives in a game,
starting with 10 lives, losing 1 and leaving 9 left.

88 BDM’s Coding for Beginners


Coding with FUZE BASIC – Part 1

STEP 5 We can extend this further with more commands. STEP 8 The code from Step 7 introduced some new
Try this: commands. First we clear the screen, then ask
for user input and store it in the variable name $. Line 3 starts the
Let x=10
conditional statement, if the user enters the name ‘Dave’ then the
Cycle
program will print HAL’s 2001 infamous lines. If another name is
Print x
inputted, then it will print something else.
Let x=x-1
Repeat until x=0
Print “Blast Off!”
End
This creates a loop that will minus 1 from X until it reaches 0, then
prints Blast Off!

STEP 9 Programs store all manner of information, retrieving


it from memory in different ways:
cls
Data “Monday”, “Tuesday”, “Wednesday”
Data “Thursday”, “Friday”, “Saturday”
Data “Sunday”
Dim DaysOfWeek$(7)
STEP 6 Variables can do more than store numbers:
For DayNo = 1 TO 7 loop
Input “Hello, what is your first name? Read DaysOfWeek$(DayNo)
“, f$ Repeat
Print For DayNo = 1 TO 7 loop
Input “Thanks, and what is your surname? “, s$ Print “Day of the week number “; DayNo;
Cls Print “ is “; DaysOfWeek$(DayNo)
Print “Hello “; f$; “ “; s$; “. How are you Repeat
today?” End
End
The variables f$ and s$ store input from the user, then printed it
back to them on the same line.

STEP 7 Conditional statements allow you to make your


program do different things depending on the user
input. For example:
STEP 10 The code from Step 9 is beginning to look quite
cls complex, using the Data command to store
Input “Enter your name: “, name$ constant data, creating a variable called DaysOfWeek using the Dim
If name$=”Dave” then command and assigning it an indexed dimension (7). The code then
Print “I am sorry “; name$ Reads the stored Data, assigns it a variable dimension from 1 to 7
Print “I am afraid I can’t do that” and prints the result.
Else
Print “That is not a problem “; name$
Endif
End
Save as ‘HAL’ and Run.

www.bdmpublications.com BDM’s Coding for Beginners 89


Programming with the FUZE

Coding with FUZE


BASIC – Part 2
Moving on from the previous FUZE BASIC tutorial, let’s expand everything you’ve
done so far and see if we can apply it to something other than counting numbers or
asking for someone’s name. In the grand tradition of BASIC programming, let’s create
a text adventure.

“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.

STEP 1 Enter the Program Editor and begin with a simple STEP 3 Let’s add a way whereby the user is required to
clear screen, as it’s always a good way to start. What press a key to continue, this way you can leave
we need to do is set some basic parameters first, so start with the instructions on the screen for an indefinite period:
number of lives a player has, for example 3.
Printat (15,15); “Press the Spacebar to continue…”
Cls While inkey <> 32 cycle
Let lives=3 Repeat
This prints the message whilst waiting for the specific key to be
pressed on the keyboard: the Spacebar.

STEP 2 Now you can introduce the game and let the player STEP 4 Now we can start the ‘story’ part of the adventure:
know how many lives they currently have. You can
Cls
do this by adding the following to the code:
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$
The printat command will specify a location on the screen to display
If button$=”Red” then
the text using x,y.
Let lives=lives-1
Print “You just opened the airlock into space. You
are dead!”
Print “You now have “;lives; “ lives left.”

90 BDM’s Coding for Beginners


Coding with FUZE BASIC – Part 2

STEP 5 Now add: STEP 8 We can now continue the game from line 29, adding
another press the Spacebar routine, followed by a
If lives=0 then goto 25
clear screen ready for the next part of the adventure.
Print “Press the Spacebar to try again.”
While inkey <> 32 cycle Print “Press the Spacebar to continue…”
Repeat While inkey <> 32 cycle
Goto 8 Repeat
Else Cls
Print “The door to the interior of the space
station opens, lucky for you.”
The Goto command goes to a line number and continues with the
code. Here you can use it to start an end of game routine.

STEP 9 You can now Save the code, call it Adventure (or
something), and Run it from the menu. Whilst it’s not
the most elegant code you will ever see, it brings in many different
elements and shows you what can be done with FUZE BASIC.

STEP 6 Let’s finish this 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 If statements, then goes to line 29 (if you pressed the
Green button) to continue the game, skipping the end of
game routine.

STEP 10 Before you continue with the adventure, and map


STEP 7 From line 25 we start the end of game routine as
the fate of our reluctant space hero, we’re going
stated on line 15, goto 25. This only works if the
to improve our code with some graphics. FUZE BASIC has some
variable lives equals 0; the player’s lives have run out. It prints a
great graphical commands at its disposal, along with some other
‘sorry you are dead’ message and asks to press the Spacebar to start
useful and interesting extras.
the game all over again from line 1, the goto 1 part.

www.bdmpublications.com BDM’s Coding for Beginners 91


Programming with the FUZE

Coding with FUZE


BASIC – Part 3
The last tutorial had you creating the foundations for a text-based adventure game.
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.

STEP 1 You’re going to start by making the game full STEP 3 Now create a new line 13, by getting the cursor to
screen, then adding an appropriate image that sets the end of line 12 and pressing Enter. For the new
the theme of the adventure. From line 2 press Enter, to create a new line, type in:
line 3, and type in the following:
Hidesprite (spriteindex)
Fullscreen=1
This command will remove the image from the screen, allowing you
Spriteindex=newsprite(1)
to include a new image for the next step in the game.
Earth$=”planetEarth.png”
Loadsprite (earth$, spriteindex, 0)
Plotsprite (spriteindex, 200, 200, 0)

STEP 4 You may need to source your own images for your
game. In our example, we found an image of red
and green buttons and copied to the /Desktop/fuze-basic/extras/
images folder. Now we need to add it to our code from line 15:
buttons$=”buttons.png”
loadsprite (buttons$, spriteindex, 0)
plotsprite (spriteindex, 300, 400, 0)
STEP 2 The code from Step 1 will import and display an
image of the Earth; the image itself is already Make sure the image is called before the Input command!
available in the /Desktop/fuze-basic/extras/images folder. It’s now
classed as a sprite and can be manipulated through the various
graphical commands of FUZE BASIC. Any unique images you want to
include should be copied to this folder to add to your game.

STEP 5 Continuing, we can use images of the interior of the


ISS if the Green button is pressed. Download the
image, put it in the images folder, name it ISS.png and call it from
the code whilst hidesprite hides the previous image.
Hidesprite (spriteindex)
U;date
Print “The door to space station opens..”
ISS$=”ISS.png”
Loadsprite (ISS$, spriteindex, 0)
Plotsprite (spriteindex, 200, 200, 0)

92 BDM’s Coding for Beginners


Coding with FUZE BASIC – Part 3

STEP 6 By now your code is getting quite hefty. Don’t STEP 9 Naturally you can continue with Cosmic Adventure
forget that with each new line you’re entering, the yourself, adding choices, graphics and keeping tabs
original Goto values will be different. It’s best to return to the code on the number of lives and whatever else you can think of. As we
and update the lines where Goto is referenced. said, it’s not the most elegant code and it’s as far from a triple-A
game as you can imagine; but at least it’s given you a head start
with FUZE Basic.

STEP 7 Additionally we can add an image for the End of


Game routine and insert the code from line 39:
Print “Sorry, you are dead.”
Gameover$=”gameover.png”
Loadsprite (gameover$, spriteindex, 0)
Plotsprite (spriteindex, 200, 200, 0)
While inkey <> 32 cycle
Repeat
Hidesprite (spriteindex)
Goto 1

STEP 10 Here’s a recap of the images we’ve used for the


graphics in our adventure game. The FUZE BASIC
manual comes with countless more commands to make better
use of the system, so read through it and expand on what you’ve
learned here.

STEP 8 Once more, the code has now expanded and as such
you need to ensure that any reference to another
line is updated to reflect the new numbering; especially lines 24
and 38, which call either End of Game routine or continue the game
if the Green Button has been pressed.

www.bdmpublications.com BDM’s Coding for Beginners 93


Programming with the FUZE

Using a Breadboard
A great way to learn circuits is to use a breadboard. You can use a breadboard with
FUZE BASIC, or Scratch and Python, to control LEDs and other simple circuits. Here
we’ll show you how a breadboard works.

GPIO
The Raspberry Pi enables you to access electronic pins, known as GPIO (General Purpose Input and Output). These are used to
interact with external electronics like LED lights and switches. Below you’ll learn to build circuits using a Breadboard.

STEP 1 The FUZE Workstation comes with a breadboard STEP 3 The red and blue lines are power rails: red is for
and some basic electronics components - you can positive and blue is for negative. The holes do not
follow along with this tutorial by getting a breadboard, 1 x blue and provide any power themselves; instead they just connect to each
1 x red breadboard wires, a 5mm LED, a 22Ohms 5% resistor, 9V other. So if you plug an item into one hole, and another item into
battery, and a 9V snap battery clip. Your local electronics shop will a connected hole (along the line), then the two are connected as if
help you out. you’d physically joined the two things together.

STEP 2 Get out the breadboard, hold it up vertically and STEP 4 The two columns of holes on the outside are
take a good look at it. You should see four vertical connected all the way down the line from the top
columns. The two pairs, on the left and right, both have a red and to the bottom. Take a 9V battery and attach a snap battery clip.
blue line running vertically alongside them. In the middle are vertical Connect the positive wire (red) to the topmost red hole on the left,
columns with letters and numbers. There are typically two main it will provide positive power to any wire or component connected
columns, lettered A-E and F-J. in any red hole all the way down to the bottom. Add the blue
(negative) wire to the topmost blue hole on the right.

94 BDM’s Coding for Beginners


Using a Breadboard

STEP 5 The two STEP 6 Get the LED and look at it closely. Notice how one
columns leg is longer than the other. That’s the positive wire;
on the inside of the the shorter one is negative. Take a resistor and wrap one end of it
breadboard work around the shorter wire on the LED. Take the positive wire from the
completely differently. PP3 battery clip and touch the LED; touch the negative wire to the
They are not wired resistor and see the LED light up. We’ve numbered these 1, 2 and 3
vertically, but horizontally so you can match them in the next steps.
along the row of each
columns. So if you look at
row 1, the holes marked
A, B, C, D and E are
connected; and the holes
in rows F, G, H, I and J are
connected. What do we
mean by “connected”?
Let’s do it physically first
to find out.

RECREATING THIS IN A BREADBOARD


Wrapping wires and circuits around each other isn’t going to be much fun, especially when you’re trying to figure out how
something works. That’s what a breadboard is for: the holes enable you to connect one item to another.

STEP 1 Let’s now recreate this simple LED circuit on a STEP 3 This is
breadboard. With the positive and negative cables the part
from the battery connected to the top of the power rails, take a red where most people mess
connector and slot one end into a hole on the red line, and the other up. Take the other leg
end into hole A1. of the LED and connect
it to hole D2. This is the
next row down. If you
connected it to another
hole on line 1, such
as D1, it would be the
equivalent of touching
both LED legs together.

STEP 4 Now take your resistor and place it next to the LED
leg in slot E2 (also on the second line). If you look at
the photo from Step 6, this is the equivalent of 2 (the part where the
LED and resistor are connected. Insert the other end of the resistor in
a hole on the negative power rail and your LED will light up.

STEP 2 Now
take the
LED, find the long end,
and slot this into hole B1.
This is the equivalent of
number 1 in our physical
connection. The red cable
is connected vertically
along the powerline,
and then to row 1 on the
breadboard where it is
connected horizontally to
the LED on row 1.

www.bdmpublications.com BDM’s Coding for Beginners 95


Programming with the FUZE

Using the FUZE IO Board


So far our breadboard hasn’t been connected to the FUZE or Raspberry Pi in any way,
but all that’s about to change. We’re now going to remove the battery and slot our
breadboard into the FUZE.

GPIO PINS
The Raspberry Pi’s GPIO pins act as a physical interface between the Raspberry Pi and electronic items. On the FUZE these are
safely connected to the IO board, and can then be connected to your breadboard.

STEP 1 Remove the 9V battery and battery clip if it is STEP 3 The pins
still connected to the breadboard, and slide the marked
breadboard into the top of the FUZE so the wires and LED are near the “GPIO” and numbered
IO board. Let’s take a closer look at what the IO board has to offer. 1-7 are more interesting.
These can be turned
on or off from inside
programs, or at the
command line. When
turned on they provide
3.3V, and when off they
provide nothing. These
On/Off switches can
be used to activate and
deactivate components
you attach to the
Raspberry Pi.

STEP 4 Start by connecting a blue cable to the pin marked


GND in the Supply section on the top right of the
FUZE IO board. Connect the other end to the leftmost hole in the
blue rail, now running along the top of the breadboard. Connect
a red cable to the socket marked 3.3V on the supply section in
STEP 2 If you look closely at the IO board you’ll see a section the bottom right of the IO board. Connect the other end of the
of pins marked “RPI Header”. These match the pins cable to first hole in the red rail running along the bottom of the
that are on your Raspberry Pi. On the right side of the board are a breadboard. The LED will come on.
number of output sockets. The PWM and
supply sockets provide steady power
(3.3V or 5.0V as marked).

96 BDM’s Coding for Beginners


Using the FUZE IO Board

STEP 5 This STEP 6 Start FUZE BASIC and enter:


isn’t any
different to what we
PinMode (0, 1)
had before, so let’s spice
DigitalWrite (0, 1)
things up. Remove the
red cable from the 3.3V The LED turns on. The first part, PinMode, tells the Raspberry Pi that
IO socket and connect GPIO 0 is going to be used, and the 1 part says it will be output. The
it to the socket marked DigitalWrite command sets GPIO 0 on. Enter DigitalWrite (0, 0) to
0 underneath GPIO. The turn the LED off.
LED will turn off. This is
because this socket won’t
provide any power until
we tell it to.

GETTING INPUT
We’re now really steaming along. Our Raspberry Pi-powered FUZE is turning on LED lights in the outside world. Next we need
to look at input; how we can get information from our breadboard to our Raspberry Pi.

STEP 1 Remove the LED and resistor from the breadboard STEP 3 Press F2 to open the Program Editor. Enter the
and remove the GPIO 0 and GND cables. Place the following program:
Push button switch in the same place as the LED (B1 and D2) and
PinMode (0, 0)
place the blue cable in the hole next to it (E2). Take a look at the
Until DigitalRead(0) Cycle
photo if you need help placing the items in the right holes.
Repeat
Print “Button Pushed”
Press F3 to run the program.

STEP 2 Now take the blue cable in E2 and connect the STEP 4 Here’s what happens. Power is flowing from the
other end to GPIO 0. Finally, connect the red cable 3.3V socket to the switch where it stops. Meanwhile
from the first hole in the power rail to 3.3V. Our circuit is complete. our program has set GPIO 0 to 0 (input mode) and a Cycle Repeat
Current will go from the 3.3V to the power rail, and from the power loop is waiting until input comes through on 0 (via DigitalRead).
rail to our switch. The switch is connected to our blue cable, which When we push the button a connection is made, power flows to
connects to GPIO. GPIO 0 and it alerts the program. It then prints the message
“Button Pushed”.

www.bdmpublications.com BDM’s Coding for Beginners 97


Programming with the FUZE

Using a Robot Arm


with FUZE BASIC
As part of the educational kit, the FUZE Workstation can be purchased with an
accompanying robot arm. This is a 149 piece kit-form robotic arm, that requires
assembly and is powered by four D-type batteries. It’s connected to the RPi or FUZE
via a USB cable and is also Windows compatible.

I, ROBOT
We won’t go into the construction of the robot arm here, the instructions which come with the arm are easy to follow and it
can be completed and ready for use within a couple of hours or so. Let’s look at how to get it working.

STEP 1 The robot arm is one of the first external hardware STEP 3 To begin with, let’s look at a few commands to make
components that was released and fully compatible the robot arm move. In Immediate Mode, in FUZE
with the Raspberry Pi; as such, it’s an excellent project to get into, BASIC, enter:
from the construction of the arm itself, to operating it via the
ArmBody (1)
FUZE Workstation.
This starts the arm rotating clockwise (looking down on it).

STEP 4 Once the arm begins to rotate clockwise it will get


to the limit of its range and start clicking. When it
starts this quickly enter the command:
STEP 2 Start by plugging the robot arm into one of
ArmBody (0)
the spare USB ports on the back of the FUZE
workstation. Ensure that the arm has its batteries correctly in place This will stop the arm from moving.
and that its power switch is On. Now open FUZE BASIC and remain
in the Immediate Mode.

98 BDM’s Coding for Beginners


Using a Robot Arm with FUZE BASIC

STEP 5 Now enter: STEP 8 Press F2, and type in the following:
ArmBody (-1) PROC ResetArm
PROC DisplayInstructions
This will start moving the arm anti-clockwise. Again, when it starts to
End
click enter the command:
DEF PROC ResetArm
ArmBody (0) ArmBody (0)
ArmShoulder (0)
To stop it from moving.
ArmElbow (0)
ArmWrist (0)
ArmGripper (0)
ArmLight (0)
ENDPROC
DEF PROC DisplayInstructions
CLS
FONTSCALE (2,2)
Ink = Red
Print “I, Robot”
STEP 6 The other commands to make the arm move are:
Ink = White
ArmShoulder (x) – where x can be 1, -1 HVTAB (0,2)
or 0
This is the start of the program, resetting the arm and preparing the
ArmElbow (x) – where x can be 1, -1 or 0
on-screen display.
ArmWrist (x) – where x can be 1, -1 or 0
ArmGripper (x) – where x can be 1 -1, or 0
ArmLight (x) – where x can be 1 or 0
Note: you can press the up arrow key to re-enter the previously
typed commands, so you can quickly stop the arm’s movement
when it reaches its limit.

STEP 9 Now to expand the program to control the arm:


Print “Press:”
Print
Print “1 or 2 for Body Left & Right”
Print “3 or 4 for Shoulder Up & Down”
Print “5 or 6 for Elbow Up & Down”
Print “7 or 8 for Wrist Up & Down”
STEP 7 Let’s create a program allowing you to move the arm Print “9 or 0 for Gripper Open & Close”
around freely. There are some new commands here: Print “Enter to turn the Light On or Off”
PROC and DEF PROC, that enables BASIC to jump to a PROCedure, Ink = Red
another part of the program, then back with ENDPROC. FONTSCALE Print “Spacebar to stop all movement and turn off
determines the size of the on-screen print display and HVTAB is an X the light.”
and Y coordinate system to print on-screen. ENDPROC

STEP 10 Now we need to process the user input. There’s


a lot here but type the content as shown in the
screenshot. Save the code and Run; you can now control the robot
arm using the number keys 1 to 0, the Enter key for the light and
Spacebar to reset everything.

www.bdmpublications.com BDM’s Coding for Beginners 99


Programming with the FUZE

FUZE BASIC Examples –


Part 1
FUZE BASIC has an impressive following of coding experts and enthusiasts who have
selflessly provided their code for others to learn from and use. These stalwarts of
FUZE BASIC have forged some amazingly detailed examples, which we’ll take a look
at over the coming pages.

CODE REPOSITORY
From fractal generators to encryption programs and animation, here are ten excellent examples of what others have done
with a little patience and a lot of code.

FRACTALS James Cook’s Tree of Pythagoras is an SCROLLING IMAGES This code will load any image
impressive fractal, constructed from squares, and make it scroll across the
that looks remarkably complex but takes up surprisingly little code. screen from right to left. Put your image either in the /extras/
You can find it at www.fuze.co.uk/code-repository; just enter the images folder or simply in the same folder as the code itself. Save
code and Run it to be amazed. and Run and enjoy the image moving across the screen. See if you
can modify it to full screen, or more.

SHOOTER In the Program Editor click the Load button and


browse through the folder /fuze-basic/Demos
until you find Shooter.fuze. With the program listing loaded, scroll
CARDIOIDS Simon Plouffe is a Mathematician who, back down to line 247 and change the “player2.png” entry to “Player2.
in the ‘70s, created some incredible cardioid png” – adding a capital P. This is a basic side-scrolling shooter and
images by dividing a circle into prime parts and drawing lines based you’ve just fixed an error in the code.
on mathematical spaced points on the circumference. Anyway,
enter this and be amazed:

100 BDM’s Coding for Beginners


FUZE BASIC Examples – Part 1

3D BOX While in the same folder as Shooter.fuze, look for BEAT ‘EM UP FuzeFighter, also found in the Games
Box.fuze. This is a great animation program that folder, is another prime example of what
displays a rotating three dimensional box on the screen until you can be done with FUZE BASIC. There’s in-game music, sound effects,
press the Escape key. It’s a fantastic learning resource and with a animations, collision detection, scoring and a two-player element
little time you can bend it to your will and use it in your own code. that can be worked into your own routines.

DOGS IN SPACE Dogs in Space is a fun little game ROBOT CONTROL The Robot.fuze file, in the Games
(found in /fuze-basic/Demos) that folder, is an extension to the
features in-game music, sprite animation, collision detection, scoring previous tutorial’s robot movement BASIC program that you entered.
and keyboard controls. Whilst it may not amuse you for too long, However, this time there’s graphics and animations to help improve
it’s benefit lies in the code examples that you can turn to your own the process and make it a more flexible (excuse the pun) program.
future programs.

SPACE INVADERS Click the Load button, and browse SNAKE Finally, snake.fuze is a good example of a
to /fuze-basic/Games. Open the combination of programming elements. Graphics,
file silv.fuze and have a look through the 784 lines of code before scoring, collision detection and some interesting routines to help
clicking the Run button. It’s quite complex but when you run it you improve your overall program can be found within this code.
can see why. Those of a certain age will no doubt recall spending a
fortune on Space Invaders in the arcades!

www.bdmpublications.com BDM’s Coding for Beginners 101


Programming with the FUZE

FUZE BASIC Examples –


Part 2
Continuing from the previous pages, here are ten more excellent examples of what
can be done with FUZE BASIC. Take what you want from the code, alter it and insert it
into your own routines to fine-tune your program.

CODE STRIPPING
Many of the legendary programmers from the golden era of home computing stripped the code from snippets posted in the
magazines of the time. They bent the code to their will and created something as close to magic as possible.

AMIGA BALL Amiga owners will have fond memories KEYBOARD INPUT Scankeyboard.fuze is an extremely
of their futuristic computer back in the handy bit of code to load up. It’s a
late ‘80s and early ‘90s. The Amiga was a pretty impressive home simple program that will display the key pressed on the keyboard,
computer, even by today’s standards and its iconic Bouncing Ball which is a great resource when it comes to creating keyboard
routine will forever be remembered by those who grew up with interactions with the user and the program, such as a game. Just
one. Load up aball.fuze from Demos and see what you can use. take the key codes you need and insert them in your own programs.

ANALOGUE CLOCK Whilst an analogue clock on the BBC MICRO::BIT This code snippet will look for and
screen, complete with second detect any attached BBC micro:bit or
hand, may not sound too interesting, there’s a surprising amount of Arduino compatible devices that you’ve attached to the FUZE IO or
useful code within this particular routine. Clock.fuze is in the Demos Raspberry Pi GPIO pins. It’s incredibly handy for helping you create
folder and once loaded up you can strip all manner of handy code the code behind your hardware project.
snippets from it.

102 BDM’s Coding for Beginners


FUZE BASIC Examples – Part 2

FONTS This little snippet MOUSE CONTROL If you want to incorporate mouse
of code, although pointer and button use in your
simple, will display some of the code, then this will certainly help you out. It’s a fairly simple bit of
available font sizes of FUZE BASIC. code but remarkably effective and it can easily be inserted into your
The maximum size is 20, so alter as own programs.
you wish:
CLS
FOR size = 1 TO 7 LOOP
INK = RND(30)
FONTSIZE( size )
PRINT “Hello”
REPEAT
END

RPI SENSEHAT If you’re working with a Raspberry Pi


SenseHAT, then the following code will
return the current value of the HAT’s accelerometer:
CLS
LOOP
JOYSTICK CONTROL Including the use of a gamepad
PRINT “Sense Accelerometer X=”; SENSEACCELX
or joystick in your games or
PRINT “Sense Accelerometer Y=”; SENSEACCELY
code is a great addition to also being able to redefine the keyboard.
PRINT “Sense Accelerometer Z=”; SENSEACCELZ
This code will detect and display the states of each of the axis
REPEAT
and buttons.
END

HAT COMPASS And this code will return the value of


the SenseHAT’s compass:
CLS
LOOP REACTION TIMER Finally, if you’re after something a
PRINT “Sense Compass X=”; SENSECOMPASSX little competitive with your family,
PRINT “Sense Compass Y=”; SENSECOMPASSY then load up reaction.fuze from the Demos folder. When run, this code
PRINT “Sense Compass Z=”; SENSECOMPASSZ will test your reaction time by hitting the Spacebar when indicated. See
REPEAT how fast you can get it, and see if you can hack the code.
END

www.bdmpublications.com BDM’s Coding for Beginners 103


Coding with Windows 10 Batch Files

Did you know that Windows has its


own built-in scripting language? Batch
files have been around since the
early days of Windows and while they
are overshadowed by the might of
the modern Windows graphical user
interface, they are still there and still
just as capable as they were thirty
years ago.
Batch file programming is a skill
that system administrators still use,
so it’s worth spending a bit of time
learning how they work and what
you can do with them. This section
introduces batch files and covers user
interactions, variables, loops and even
a batch file quiz game to inject an
element of fun.

106 What is a Batch File?


108 Getting Started with Batch Files
110 Getting an Output
112 Playing with Variables
114 Batch File Programming
116 Loops and Repetition
118 Creating a Batch File Game

104 BDM’s Coding for Beginners


Index

Coding with Windows


10 Batch Files

www.bdmpublications.com BDM’s Coding for Beginners 105


Coding with Windows 10 Batch Files

What is a Batch File?


The Windows batch file has been around since the early days of DOS, and was once a
critical element of actually being able to boot into a working system. There’s a lot you
can do with a batch file but let’s just take a moment to see what one is.

.BAT MAN
A Windows batch file is simply a script file that runs a series of commands, one line at a time, much in the same fashion as a
Linux script. The series of commands are executed by the command line interpreter and stored in a plain text file with the .BAT
extension; this signifies to Windows that it’s an executable file, in this case, a script.

Batch files have been around since the earliest versions of Microsoft requirements and hardware drivers, allocate them a slot in the
DOS. Although not exclusively a Microsoft scripting file, batch files available memory, assign any memory managers and tell the
are mainly associated with Microsoft’s operating systems. In the system where the Command.com file, which is the command line
early days, when a PC booted into a version of DOS (which produced interpreter for DOS, was. Once it had done that, then the Autoexec.
a simple command prompt when powered up), the batch file was bat file took over and ran through each line in turn, loading
used in the form of a system file called Autoexec.bat. Autoexec. programs that would activate the mouse or optical drive into the
bat was a script that automatically executed (hence Autoexec) memory areas assigned by the Config.sys file.
commands once the operating system had finished dealing with the
Config.sys file. The DOS user of the day could opt to create different Autoexec.
bat files depending on what they wanted to do. For example, if
When a user powered up their DOS-based computer, and once they wanted to play a game and have as much memory available
the BIOS had finished checking the system memory and so on, as possible, they’d create a Config.sys and Autoexec.bat set of files
DOS would look to the Config.sys file to load any specific display that loaded the bare minimum of drivers and so on. If they needed

The Autoexec.bat file was a PC user’s first experience with a batch file.

106 BDM’s Coding for Beginners


What is a Batch File?

BATCH FILE POWER


Just like any other programming interface that can directly
interrogate and manipulate the system, batch files require
a certain amount of care when programming. It’s hard to
damage your system with a batch file, as the more important
elements of the modern Windows system are protected by
the User Account Control (UAC) security; UAC works by only
allowing elevated privileges access to important system files.
Therefore if you create a batch file that somehow deletes a
system file, the UAC activates and stop the process.

Batch files are plain text and often created using Notepad. However, if you’re working in the command prompt with
elevated privileges to begin with, as the Administrator, then
the UAC won’t question the batch file and continue regardless
of what files are being deleted.

That said, you’re not likely to create a batch file that


intentionally wipes out your operating system. There are
system controls in place to help prevent that; but it’s worth
mentioning as there are batch files available on the Internet
that contain malicious code designed to create problems.
Much like a virus, a rogue batch file (when executed with
Administrator privileges) can cause much mayhem and system
damage. In short, don’t randomly execute any batch file
downloaded from the Internet as an Administrator, without
first reviewing what it does.
Batch files were often used as utility programs, to help users with
complex tasks. You can learn more about batch files in the coming pages, so
don’t worry too much about destroying your system with one.
access to the network, an Autoexec.bat file could be created to All this just demonstrates how powerful the humble batch file
load the network card driver and automatically gain access to the can be.
network. Each of these unique setups would be loaded on to a
floppy disk and booted as and when required by the user.

The Autoexec.bat was the first such file many users came across in
their PC-based computing lives; since many had come from a 16-bit
or even 8-bit background; remember, this was the late eighties
and early nineties. The batch file was the user’s primary tool for
automating tasks, creating shortcuts and adventure games and
translating complex processes into something far simpler.

Nowadays however, a batch file isn’t just for loading in drivers and
such when the PC boots. You can use a batch file in the same way
as any other scripting language file, in that you can program it to
ask for user input and display the results on the screen; or save to
a file and even send it to a locally or network attached printer. You
can create scripts to back up your files to various locations, compare
date stamps and only back up the most recently changed content as
well as program the script to do all this automatically. Batch files are
remarkably powerful and despite them not being as commonly used
as they were during the older days of DOS, they are still there and
can be utilised even in the latest version of Windows 10; and can be
as complex or simple as you want them to be.

So what do you need to start batch file programming in Windows?


Well, as long as you have Windows 10, or any older version of
Windows for that matter, you can start batch file programming
immediately. All you need is to be able to open Notepad and get to
the command prompt of Windows. We show you how it all works, so You can create complex batch files or simple ones that display
read on. ASCII images on screen.

www.bdmpublications.com BDM’s Coding for Beginners 107


Coding with Windows 10 Batch Files

Getting Started with


Batch Files
Before you begin to program with batch files, there are a few things you need to
know. A batch file can only be executed once it has the .bat extension and editing one
with Notepad isn’t always straightforward.

A NEW BATCH
Throughout this section on batch files we’re going to be working with Notepad, the command prompt and within a folder
called ‘Batch Files’. To begin with, let’s see how you get to the Windows command prompt.

STEP 1 The Windows STEP 3 While at the command prompt window, enter:
command dir/w. This lists all the files and directories from
prompt may look a little where you are at the moment in the system. In this case, that’s your
daunting to the newcomer Home directory that Windows assigns every user that logs in. You
but it’s simply another can navigate by using the CD command (Change Directory). Try:
interface (or Shell) used to
cd Documents
access the filesystem. You
can go anywhere you like in Then press Return.
the command prompt, as
you would with the graphical
interface. To begin, click on
the Windows Start button and
enter CMD into the search box.

STEP 2 Click on the search result labelled Command Prompt STEP 4 The prompt should change and display \
(Desktop App) and a new window pops up. The Documents>; this means you’re in the Documents
Command Prompt window isn’t much to look at to begin with but directory. Now, create a new directory call Batch Files. Enter:
you can see the Microsoft Windows version number and copyright
md “Batch Files”
information followed by the prompt itself. The prompt details the
current directory or folder you’re in, together with your username. You need the quotations because without them, Windows creates
two directories: Batch and Files. Now change directory into the
newly created Batch Files.
cd Batch Files
You won’t need the quotes to change directories.

108 BDM’s Coding for Beginners


Getting Started with Batch Files

STEP 5 Now that you have the directory set up, where you STEP 8 Back at the command prompt window, enter:
store your batch files, here is how you can create dir/w again to list the newly created Test.bat file.
one. Leave the command prompt window open and click on the By the way, the /w part of dir/w means the files are listed across
Windows Start button again. This time enter Notepad and click on the screen as opposed to straight down. Enter dir if you want
the search result to open the Notepad program. Notepad is a simple (although you need more files to view) but it’s considered easier to
text editor but ideal for creating batch scripts with. read with the /w flag.

STEP 6 To create your first batch file, enter the following STEP 9 To execute the batch file you’ve just created, simply
into Notepad: enter its name, Test, in the command prompt
window. You don’t need to add the .bat part, as Windows recognises
@echo off
it as an executable file, and the only one with that particular name in
echo Hello World!
the current directory. Press return and see how you’re greeted with
By default, a batch file displays all the commands that it runs Hello World! in the command prompt.
through, line by line. What the @echo off command does is turn
that feature off for the whole script; with the ‘@’ (at) sign to apply
that command to itself.

STEP 7 When saving anything in Notepad the default


extension is .txt, to denote a text file. However, you
STEP 10 The echo command displays whatever is after it
want the extension to be .bat. Click on File > Save As and navigate
to the screen. Right-click the Test.bat file from
to the newly created Batch Files directory in Documents. Click the
Windows Explorer and select Edit to add more echo commands if
drop-down menu Save as Type, and select All Files from the menu. In
you like. Try this:
File Name, call the file Test.bat.
@echo off
echo Hello World!
echo This is my first batch file
echo.
echo With a blank line between!
Remember to save each new change to the batch file.

www.bdmpublications.com BDM’s Coding for Beginners 109


Coding with Windows 10 Batch Files

Getting an Output
While it’s great having the command prompt window display what you’re putting
after the echo command in the batch file, it’s not very useful at the moment, or
interactive for that matter. Let’s change up a gear and get some output.

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.

STEP 1 Let’s keep things simple to begin with. Create a new STEP 3 You have no doubt noticed that there is no
batch file called ‘dirview.bat’, short for Directory indication that the batch file worked as there’s
View. Start with the @echo off command and under that add: no meaningful output on the screen. However, if you now open
Explorer and browse to c:\Users\YOURNAME, remembering to
dir “c:\users\YOURNAME\Documents\Batch Files” >
substitute YOURNAME with your Windows username, and double-
c:\users\YOURNAME\dirview.txt
click the dirview.txt file, you can see the batch file’s output.
Substitute YOURNAME with your Windows username.

STEP 2 The new line uses the dir command to list the STEP 4 If you want to automate the task of opening the
contents of the directory Batch Files, in your Home text file that contains the output, add the following
directory, dumping the output to a text file called dirview.txt in line to the batch file:
the root of your Home directory. This is done, so that the Windows
notepad.exe c:\users\YOURNAME\dirview.txt
UAC doesn’t require elevated permissions, as everything is in your
own Home area. Save and run the batch file. Save the file and once again run from the command prompt. This
time, it creates the output and automatically opens Notepad with
the output contents.

110 BDM’s Coding for Beginners


Getting an Output

OUTPUT 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.

STEP 1 Create a new batch file and call it name.bat. Start STEP 4 This is extremely useful if you want to create a
with the @echo off command, then add the unique, personal batch file that automatically runs
following lines: when a user logs into Windows. Using the default systems variables
that Windows itself creates, you can make a batch file that greets
set /p name= What is your name?
each user:
echo Hello, %name%
@echo off
Note: there’s a space after the question mark. This is to make it look
neater on the screen. Save it and run the batch file. echo Hello, %USERNAME%.
echo.
echo Thanks for logging in. Currently the network
is operating at 100%% efficiency.
echo.
echo Your Home directory is located at: %HOMEPATH%
echo The computer name you’re logged in to is:
%COMPUTERNAME%
echo.

The set /p name creates a variable called name, with


STEP 2 the /p part indicating that an ‘=prompt string’ is to
follow. The Set command displays, sets or removes
system and environmental variables. For example, while in the
command prompt window enter:
STEP 5 Save and execute the batch file changes; you can
set overwrite and still use name.bat if you want. The
batch file takes the current system variables and reports them
To view the current system variables. Note the name= variable we
accordingly, depending on the user’s login name and the name of
just created.
the computer. Note: the double percent symbol means the percent
sign will be displayed, and is not a variable.

STEP 6 Alternatively, you can run the batch file and display
it on the user’s desktop as a text file:
@echo off
echo Hello, %USERNAME%. > c:%HOMEPATH%\user.txt
STEP 3 Variables stored with Set can be called with the
echo. >> c:%HOMEPATH%\user.txt
%VARIABLENAME% syntax. In the batch file, we
echo Thanks for logging in. Currently the network
used the newly created %name% syntax to call upon the contents of
is operating at 100%% efficiency. >> c:%HOMEPATH%\
the variable called name. Your username, for example, is stored as a
user.txt
variable. Try this in a batch file:
echo. >> c:%HOMEPATH%\user.txt
echo Hello, %USERNAME%. What are you doing? echo Your Home directory is located at: %HOMEPATH%
>> c:%HOMEPATH%\user.txt
echo The computer name you’re logged in to is:
%COMPUTERNAME% >> c:%HOMEPATH%\user.txt
echo. >> c:%HOMEPATH%\user.txt
notepad c:%HOMEPATH%\user.txt
The > outputs to a new file called user.txt, while the >> adds the
lines within the file.

www.bdmpublications.com BDM’s Coding for Beginners 111


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
batch file and when combined with other commands, the effect is really impressive.

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.

STEP 1 Create a new batch file called list.bat and start it off STEP 3 Now, create a batch file that displays the contents
with the @echo off command. Begin by clearing of any directory and post it as a text file to the user’s
the command prompt screen and displaying a list of the current screen. Add the following to the list.bat batch file:
directories on the computer:
echo Hello, %USERNAME%.
cls echo From the list, which folder would you like to
dir “c:\” > list.txt view?
type list.txt set /p view= (enter as c:\folder)
echo. dir “%view%” > view.txt
notepad.exe view.txt

STEP 2 Save and execute the batch file. Within the STEP 4 What’s happening here is the batch file asks the user
command prompt you can see the contents of all to enter any of the directories displayed in the list it
the files and directories from the root of the C:\ drive; and as any generated, in the form of ‘c:\directory’. Providing the user enters a
user under Windows has permission to see this, there’s no UAC valid directory, its contents are displayed as a text file. We created
elevated privileges required. the view variable here along with %HOMEPATH%, to store the input
and the text file.

112 BDM’s Coding for Beginners


Playing with Variables

STEP 5 It’s always a good idea, when creating text files STEP 8 Instead of left clicking on the Command Prompt
for the user to temporarily view, to clean up after result, as you did the first time you opened it,
yourself. There’s nothing worse than having countless, random right-click it and from the menu choose Run as Administrator. There
text files cluttering up the file system. That being the case, let’s is a risk that you could damage system files as the Administrator
clear up with: but as long as you’re careful and don’t do anything beyond viewing
directories, you will be okay.
cls
del /Q view.txt
del /Q list.txt
echo All files deleted. System clean.

STEP 6 The additions to the batch file simply clear the


command prompt window (using the cls command)
and delete both the view.txt and list.txt files that were created by
the batch file. The /Q flag in the del command means it deletes
the files without any user input or notification. The final message
STEP 9 This action triggers the UAC warning message,
informs the user that the files are removed.
asking you if you’re sure you want to run the
Windows command prompt with the elevated Administrator
privileges. Most of the time we wouldn’t recommend this course
of action: the UAC is there to protect your system. In this case,
however, click Yes.

STEP 7 Depending
on how
your system is configured,
you may not get any
directory information
at all or a message
stating Access Denied.
This is because the UAC STEP 10 With the UAC active, the command prompt looks
is blocking access to a little different. For starters, it’s now defaulting
protected areas of the to the C:\WINDOWS\system32 folder and the top of the windows is
system, like c:\Windows labelled Administrator. To run the batch file, you need to navigate to
or C:\Program Files. the Batch Files directory with: cd \Users\USERNAME\Documents\
Therefore, you need to Batch Files. To help, press the Tab key to auto-complete the
run the batch file as an directory names.
Administrator. Click the
Windows Start button and
enter CMD again.

www.bdmpublications.com BDM’s Coding for Beginners 113


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
become more useful. While the Windows graphical interface is still king, the command
line can do just as much, and this is where batch files come into their own.

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.

STEP 1 We are introducing a couple of new commands STEP 3 Now let’s extend the seek.bat batch file:
into the mix here but we think they’re really useful.
Create a new batch file called seek.bat and in it put: @echo off
cls
@echo off
color 2
cls
echo Please enter the type of file you want to
color 2
search for (MP3, DOC, JPG for example)
echo Please enter the type of file you want to
echo.
search for (MP3, DOC, JPG for example)
set /p ext=
echo.
where /R c:\ *.%ext% > found.txt
notepad.exe found.txt
cls
color
del /Q found.txt

STEP 2 The new command in this instance is color STEP 4 Another new command, Where, looks for a 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 that the user
color attributes are specified by two hex digits, the first corresponds can enter the file type in, which then searches using Where and
to the background colour of the Command console and the second dumps the results in a text file called found.txt. Save and run the
to the foreground, and can be any of the following values: batch file.

114 BDM’s Coding for Beginners


Batch File Programming

CHOICE MENUS
Creating a menu of choices is a 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 all works.

STEP 1 Rather than using a variable to process a user’s STEP 4 ErrorLevels are essentially variables and the /M
response, batch files can instead use the Choice switch of Choice allows a descriptive message string
command in conjunction with an ErrorLevel parameter to make a to be displayed. Extend this menu with something new:
menu. Create a new file called menu.bat and enter the following:
@echo off
@echo off cls
cls echo.
choice /M “Do you want to continue? Y/N” echo ---------------------------------------------
if errorlevel 2 goto N echo.
if errorlevel 1 goto Y echo Please choose a directory.
goto End: echo.
echo Press 1 for c:\Music
echo.
echo Press 2 for c:\Documents
echo.
echo Press 3 for c:\Pictures
echo.
echo Press 4 for c:\Videos
echo.
echo ---------------------------------------------
Running the code produces an error as we’ve called
STEP 2 choice /C 1234
a Goto command without any reference to it in the
if errorlevel 4 goto Videos
file. Goto does exactly that, goes to a specific line in
if errorlevel 3 goto Pictures
the batch file. Finish the file with the following and run it again:
if errorlevel 2 goto Documents
:N if errorlevel 1 goto Music
echo.
echo You chose No. Goodbye.
STEP 5 Now add the Goto sections:
goto End
:Y
:Videos
echo.
cls
echo You chose Yes. Hello
CD %HOMEPATH%\Videos
:End echo You are now in the Videos directory.
goto End
:Pictures
cls
CD %HOMEPATH%\Pictures
echo You are now in the Pictures directory.
goto End
:Documents
cls
CD %HOMEPATH%\Documents
echo You are now in the Documents directory.
STEP 3 The output from your choice is different depending on
goto End
whether you pick Y or N. The :End part simply signifies
the end of the file (also known as EOF). Without it the batch file runs :Music
through each line and display the Y response even if you enter N; so it’s cls
important to remember to follow your Goto commands. CD %HOMEPATH%\Music
echo you are now in the Music directory.
goto End
:End

STEP 6 When executed, the batch file displays a menu and with
each choice the code changes directory to the one the
user entered. The %HOMEPATH% system variable will enter the currently
logged in user’s Music, Pictures and so directories, and not anyone else’s.

www.bdmpublications.com BDM’s Coding for Beginners 115


Coding 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
countdown or even make numbered files or directories in the system.

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 a little more, alongside more variables, and introduce the Else, Timeout and eof (End of File) commands.

STEP 1 Start by creating a new batch file called count.bat. STEP 3 The count.bat is a rough way of demonstrating a
Enter the following, save it and run: loop; a better approach would be to use a for loop.
Try this example instead:
@echo off
cls @echo off
set /a counter=0 for /L %%n in (1,1,99) do echo %%n
:numbers
set /a counter=%counter%+1
if %counter% ==100 (goto :eof) else (echo
%counter%)
timeout /T 1 /nobreak > nul
goto :numbers

STEP 4 Breaking it
down, there’s
For, then the /L switch, which
handles a range of numbers.
Then the parameter labelled as
STEP 2 The count.
%%n to denote a number. Then
bat code
the in (1,1,99) part, which tells
starts at number one and
the statement how to count,
counts, scrolling down the
as in 1 (start number), 1 (steps
screen, until it reaches 100.
to take), 99 (the end number).
The Timeout command
The next part is do, meaning DO
leaves a one second gap
whatever command is after.
between numbers and the
Else statement continues
until the counter variable
equals 100 before going to
the eof (End Of File), thus
closing the loop.

116 BDM’s Coding for Beginners


Loops and Repetition

STEP 5 You can include the pause between the numbers STEP 8 There are different ways of using the For loop. In
easily enough within the far simpler For loop by this example, the code creates 26 directories, one
adding multiple commands after the Do For loop. The brackets and for each letter of the alphabet, within the directory c:\test which the
ampersand (&) separate the different commands. Try this: batch file makes using the MD command:
@echo off @echo off
for /L %%n in (1,1,99) do (echo %%n & timeout /T 1 FOR %%F IN (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,
/nobreak > nul) s,t,u,v,w,x,y,z) DO (md C:\test\%%F)

STEP 6 One of the great time saving uses of batch files is to STEP 9 Loops can be powerful and extremely useful
create multiple, numbered files. Assume that you elements in a batch file. While creating 26
want twenty five text files within a directory, all numbered from 1 to directories may not sound too helpful, imagine having to create
25. A For loop much like the previous example does the trick: 1,000 users on a network and assign each one their own set of
unique directories. This is where a batch file saves an immense
@echo off
amount of time.
for /L %%n in (1,1,25) do copy nul %%n.txt

STEP 7 If you open Windows Explorer, and navigate to the STEP 10 Should you ever get stuck when using the various
Batch Files directory where you’re working from, commands within a batch file, drop into the
you can now see 25 text files all neatly numbered. Of course, you command prompt and enter the command followed by a question
can append the file name with something like user1.txt and so on by switch. For example, for /? or if /?. You get an on-screen help file
altering the code to read: detailing the commands’ use. For easier reading, pipe it to a text file:
@echo off For /? > forhelp.txt
for /L %%n in (1,1,25) do copy nul User%%n.txt

www.bdmpublications.com BDM’s Coding for Beginners 117


Coding with Windows 10 Batch Files

Creating a Batch File Game


Based on what we’ve looked at DIGCLOCK.PY
so far with batch files, you can This is a surprisingly handy little script and one that we’ve
probably come up with your own used in the past instead of relying on a watch or even the
clock in the system tray of the operating system.
simple text adventure or multiple-
choice game. Here’s one that we @echo off
Cls
created, that you’re free to fiddle :start
with and make your own. set /a score=0
set /a question=0
cls
set /p name= What is your name?

Make up your own questions but how about also :menu


including an introductory or loading screen? Make your cls
loading screen in a separate batch file and save it as echo.
screens.bat (for example). Then, from the main game echo ****************************************************
batch file, you can load it at the beginning of the file echo.
with the call command followed by color to reset the echo Welcome %name% to the super-cool trivia game.
game’s colours: echo.
echo Press 1 to get started
echo.
@echo off
echo Press 2 for instructions
Cls
echo.
Call screens.bat
echo Press Q to quit
color
echo.
:start
echo *****************************************************
set /a score=0
choice /C 12Q
set /a question=0
if errorlevel 3 goto :eof
cls
if errorlevel 2 goto Instructions
set /p name= What is your name?
if errorlevel 1 goto Game

:Instructions
cls
echo.
echo **************************************
echo.
echo The instructions are simple. Answer the
questions correctly.
echo.
echo **************************************
pause
cls
goto menu

:Game
set /a question=%question%+1
cls
if %question% ==5 (goto end) else (echo you are on
question %question%)
echo.
echo get ready for the question...
echo.
timeout /T 5 /nobreak > nul
if %question% ==5 (goto end) else (goto %question%)

118 BDM’s Coding for Beginners


Creating a Batch File Game

:1 echo C. Windows 7
cls echo.
echo. choice /C abc
echo ****************************** if errorlevel 3 goto wrong
echo. if errorlevel 2 goto wrong
echo Your current score is %score% if errorlevel 1 goto correct
echo.
echo ****************************** :4
echo. cls
echo. echo.
echo Question %question%. echo ******************************
echo. echo.
echo Which of the following version of Windows is the best? echo Your current score is %score%
echo. echo.
echo A. Windows 10 echo ******************************
echo. echo.
echo B. Windows ME echo.
echo. echo Question %question%.
echo C. Windows Vista echo.
echo. echo Which of the following Windows uses DirectX 12?
choice /C abc echo.
if errorlevel 3 goto wrong echo A. Windows 10
if errorlevel 2 goto wrong echo.
if errorlevel 1 goto correct echo B. Windows 3.11
echo.
:2 echo C. Windows XP
cls echo.
echo. choice /C abc
echo ****************************** if errorlevel 3 goto wrong
echo. if errorlevel 2 goto wrong
echo Your current score is %score% if errorlevel 1 goto correct
echo.
echo ****************************** :Wrong
echo. cls
echo. echo ******************
echo Question %question%. echo.
echo. echo WRONG!!!!
echo Which of the following version of Windows is the echo.
most stable? echo ******************
echo. set /a score=%score%-1
echo A. Windows 10 pause
echo. goto :game
echo B. Windows 95
echo. :correct
echo C. Windows ME cls
echo. echo ******************
choice /C abc echo.
if errorlevel 3 goto wrong echo CORRECT. YIPEE!!!
if errorlevel 2 goto wrong echo.
if errorlevel 1 goto correct echo ******************
set /a score=%score%+1
:3 pause
cls goto :game
echo.
echo ****************************** :end
echo. cls
echo Your current score is %score% echo ******************************
echo. echo.
echo ****************************** echo Well done, %name%, you have answered all the questions
echo. echo.
echo. echo And your final score is....
echo Question %question%. echo.
echo. echo %score%
echo Which of the following Windows version is the latest? echo.
echo. echo ********************************
echo A. Windows 10 choice /M “play again? Y/N”
echo. if errorlevel 2 goto :eof
echo B. Windows 98 if errorlevel 1 goto start
echo.

www.bdmpublications.com BDM’s Coding for Beginners 119


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

120 BDM’s Coding for Beginners


Index

Programming with
Scratch and Python

www.bdmpublications.com BDM’s Coding for Beginners 121


Programming with Scratch and Python

Getting Started
with Scratch
If you are completely new to programming then Scratch is the perfect place to
start. With Scratch you can learn the building blocks of programming and important
programming concepts in a highly visual interface.

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.

STEP 1 Scratch runs from inside the web browser. Click STEP 3 Let’s take a look at Scratch Cat. Use click 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 button on the top, just above Scripts, you’ll see two icons for Grow and Shrink.
your browser so you have plenty of space to view the window and Click one and click the cat to resize him. Shift-click on Scratch Cat
all its contents. and choose Info to access rotation controls. Click the blue back
button to get back to the Sprites pane.

STEP 2 You can see the Scratch interface with a list of blue STEP 4 Scratch Cat looks a little lonely on his white space,
items in the Block Palette, an empty Script Area so let’s give him a background. Click the Stage icon
and a Stage. On the Stage will be an orange cartoon cat, known to the left of the Sprites Pane. The Script Area switches to Backdrop
as “Scratch Cat”. This is the default sprite that comes with all new Library displaying the available backgrounds. Click Music and Dance
projects; you will also see smaller versions of the sprite above the and choose spotlight-stage. Click OK.
Script Area and in the Sprites Panel.

122 BDM’s Coding for Beginners


Getting Started with Scratch

STEP 5 The background appears on the Stage and Scratch STEP 6 Drag the turn [15] degrees block (with an
Cat looks a lot happier. Let’s create a script that anti-clockwise symbol) from the Block Palette
moves him to the stage. Click Sprite1 in the Sprites Pane to select to the Script Area. Now drag the move [10] steps block and
the cat and click the Scripts tab to return to the Script Area. Now connect it to the bottom of the Turn 15 Degrees block. They will
click the blue Motion tab at the top of the Block Palette. snap together. Change the 10 in move [10] steps to 100. Our
program is now ready. Click the script (the two blocks) to see what it
does. Scratch Cat will rotate and move towards the stage.

SAVING SCRATCH FILES


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 Click File > Save Now to save your project. Enter STEP 3 Lots of example Scratch files can be found on the
a name in the New Filename box; we called ours MIT website by clicking Explore. Here you can see
“Scratch_Cat_On_Stage”. As we mentioned in both Python and a huge range of projects built by other users and you’ll also be
Unix tutorials, it’s important to avoid any special characters and able to share your own projects. Choose a project from Explore to
spaces in your filenames. Use underscores “_” instead. open it.

STEP 2 Choose File > Go to My Stuff to exit the stage and STEP 4 You can run the project directly inside the main
view the saved file. Click the Scratch_Cat_On_ window by clicking the Green Flag icon. Click the
Stage link to view your file. You can add Instructions, Notes and Star icon to Favourite or bookmark the project and the Heart icon
Credits here, and Tags. Click See Inside to head back to viewing to like it. More importantly, click the See Inside to see the code
your code again. used to create the project. This is a good way to learn how Scratch
code is being used.

www.bdmpublications.com BDM’s Coding for Beginners 123


Programming with Scratch and Python

Creating Scripts in Scratch


The program you make in Scratch is a script, or a bunch of scripts. In this tutorial we’ll
take a look at how you construct your scripts to build up a great program. This is great
starter practice for creating objects in Python.

VISUAL CODING
The scripts in Scratch are created by snapping together blocks. These blocks are similar to the code you find in more complex
programming languages, such as Python, but much easier to understand.

STEP 1 Click Create to start a new Scratch project and STEP 3 Click the Motion tab and drag the move [10]
name it Dancing Cat. You’re going to put your cat steps block and connect it beneath the when
and some other characters on a dance floor and get them to bust flag clicked block. A quick word about that [10]. When you write
some moves. Click Stage, then Music and Dance and choose party- a number or word inside those square brackets, that’s the way of
room. Drag the Scratch Cat graphic around the Stage to find a good saying you can choose a value. It’s the equivalent of a variable”,
starting position. because it varies. We’ll tell you which number or selection we’re
using but you can use any you want. Play around.

STEP 2 Click on Sprite1 in the Sprites Panes and click the STEP 4 It’s not much of a disco, so let’s add some sound.
Scripts tab above the Scripts area. Now click Events Click the sound tab and drag play drum [8] for
in the Blocks Pane and drag the when flag clicked block into the [0.2] beats and connect it to the bottom of the stack of blocks.
Scripts area. This block represents the start of your program. It tells Click on the blocks and Scratch Cat will move and a sound will come
Scratch to run through the blocks below it when we click the Green from your speaker.
Flag icon above the Stage window.

124 BDM’s Coding for Beginners


Creating Scripts in Scratch

STEP 5 Dancing is a back and forth affair, so let’s get Scratch STEP 6 Scratch Cat only moves back and forth once, which
Cat moving back. Drag another move [10] steps isn’t much of a party. Click Control and drag the
block to the bottom of the stack. Now click the 10 and change it to forever block to the Script Area. Carefully position it beneath the
-10 (minus 10). Entering minus figures moves the cat backwards. when [flag] clicked block but above the move [10] steps
Drag another play drum block to the bottom of the script. Pick a block. The script should nest within the two prongs of the forever
different drum sound. We chose 13. block. Click the Green Flag icon to start the disco. Click the red Stop
icon to end the program.

EDITING SCRIPTS
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
the Script Area. Scratch is far more forgiving than other programming languages for experimentation.

STEP 1 It’s pretty bad form to use the forever block STEP 3 Now drag a repeat [10] block from the block list
or a forever loop in programming. Programs are and connect it to the when [flag] clicked block
supposed to run from start to a finish. Even programs like Scratch in the Script Area. Now drag the top play drum block of the stack
have an end point when you quit the program. You want to replace inside the repeat [10] block. If you drag the top block all the
the forever block with a repeat one. Click the forever block in blocks underneath move with it and the whole lot will be nested
your script and drag it down to separate it from the other blocks. inside the repeat [10] stack.

STEP 2 Your move and play drum blocks are still nested STEP 4 You can position the stack anywhere on the Script
within the forever block though and you want Area and even keep the unused blocks around,
to keep them. Click the topmost move block and drag it out of the although we think it’s good practice to keep only what you are
forever block. It’s now good to get rid of the forever block so using in the Script Area and remove any unused blocks. Click the
drag it to the left and back to the Blocks List to get rid of it. Green Flag icon above the Stage Window to view Scratch Cat doing
a short dance.

www.bdmpublications.com BDM’s Coding for Beginners 125


Programming with Scratch and Python

Interaction in Scratch
Your Scratch Cat is now dancing back and forth but wouldn’t it be great if you could
control him. In this tutorial you’re going to look at creating keyboard interactions in
Scratch. Let’s get our disco cat really grooving!

INTERACTIVE CONTROL
The only Control option we’ve really looked at so far is the when [flag] clicked block, which starts the program. Once the program
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.

STEP 1 Open the Dancing Cat program from previous STEP 3 We’re going to make Scratch Cat jump up and down
tutorials. Select Sprite1 and click on Events so you when we press the space bar. Click Motion and drag
can see the when [flag] clicked script. Now click Control in the change y by [10] and clip it to the when [space] key
Block Palette and drag the when [space] key pressed block to pressed block. What’s with the “y”? This is what’s known as
an empty part of the Script Area. a “coordinate”.

STEP 2 You can drag and rearrange the block scripts to any STEP 4 The position of each sprite on the stage is shown
part of the Script Area. We like to have our when using two variables, x and y. These are referred
[flag] clicked scripts in the top left but it really doesn’t matter to as the “coordinates”. The x is the sprites horizontal position
where they are. It’s also worth spotting that we now have more than on the stage whilst the y coordinate is the vertical position. Click
one script for Sprite1; you can have multiple scripts for each sprite in and drag the sprite around the Stage and you’ll see the x and
your program. numbers change.

126 BDM’s Coding for Beginners


Interaction in Scratch

STEP 5 The centre of the Stage is x: 0 and y: 0. As you move STEP 6 What goes up must come back down. So drag
the sprite up and to the right the numbers increase another change y by [10] block and attach it
and as you move it left and down they decrease (going into negative to the bottom of the when [space] key pressed script. Now
numbers). So when we use the change y by [10] block it says, change [10] to [-10]. Click the Green Flag and run the program.
take the current value of y (the vertical position) and increase it by Now press the space bar and… oh no, nothing happens. We’ve just
10. That makes our cat jump up. encountered our first “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 The problem is that programs are super-fast and STEP 3 Drag a wait [1] secs block from the Blocks
highly visual programs like Scratch can move in Palette and insert it underneath the change [y]
the blink of an eye and that’s what is happening here. If you tap by 10 block. Now press the space bar on the keyboard to see
the space bar repeatedly while the program is running you’ll see Scratch cat jump up, and then back down. Notice that you don’t
Scratch Cat flickering as it jumps up and down. need to press the Green Flag icon to run the program; the Green
Flag starts our other script.

STEP 2 The challenge is that our motion controls move the STEP 4 We think Scratch Cat stays in the air a bit too long.
cat instantly from one place to another, so fast that We want a jump, not a levitation effect. Change
we can’t see. Sometimes this is fine, like our back and forth dance, the wait [1] secs variable to [0.25]. This is a quarter of a
but obviously we need to slow down the jump. Help is at hand. second and will give us a more fun hop. Press the Green Flag to
Click the Motion tab to view the Motion blocks. start the script and tap the space bar whenever you want Scratch
Cat to jump.

www.bdmpublications.com BDM’s Coding for Beginners 127


Programming with Scratch and Python

Using Sprites in Scratch


So far we’ve just got the one sprite in Scratch, the eponymous Scratch Cat. In this
tutorial we’re going to add a second sprite and see how to make the two sprites
interact with each other.

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.

STEP 1 We’re going to add another sprite to our project and STEP 3 All the blocks on the Script Area have vanished. The
a 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. This opens not to our new sprite. Click on Sprite1 in the Sprites pane to view
the Sprite Library that displays all the different characters available. the Scratch Cat scripts again. Then click Giga to return to your
Giga character.

STEP 2 Click on the Fantasy link in the sidebar and choose STEP 4 Now that we have more than one sprite, it’s a
Giga. Click OK to add the character to the stage. good idea to name them. Click the “i” icon next to
Click and drag the sprite to reposition Giga to the right of Scratch Sprite1. Change Sprite1 in the text box to Scratch Cat. Take a look at
Cat. Notice that a Giga icon has joined Sprite1 in the Sprites pane. the other options here. You can remove a sprite from the stage by
unticking the Show checkbox, without deleting it from the project.

128 BDM’s Coding for Beginners


Using Sprites in Scratch

STEP 5 Select Giga and choose Events. Drag a when STEP 6 We’re quite sure you can see where this is going.
[space] key pressed and change [space] to Press the Green Flag icon and our Scratch Cat object
[right arrow]. Add a change x by [10] block beneath. will start to dance and still jumps with space, whilst our other
Shift-click the script and choose duplicate to create another. For the object, Giga, can be moved left and right using the arrow keys on
second script change the when [right arrow] key pressed to our keyboard.
[left arrow] and change x by [10] to [-10].

CHANGING COSTUMES
Our two objects, Giga and Scratch Cat don’t have to look like the original characters. That’s just 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 Giga in the Sprite Pane and click the STEP 3 Attach a repeat [10] block and inside it place
Costumes tab. The Scripts Area now displays the wait [1] secs. Change [1] to [0.5]. Click
costumes being used by Giga, including the current look. Choose Looks and drag a next costume block into the repeat block.
giga-c in the list on the sidebar; this gives our sprite a different Now Giga will switch to the next costume every half a second,
pose. Switch back to giga-a for now. creating an animation effect.

STEP 2 Let’s use costume changes to animate Giga. Click STEP 4 Click the Green Flag icon to start the animation.
Events and drag when flag clicked block to Scratch Cat now moves back and forth, tapping out
the Scripts Area. This block will activate at the same time as the a beat, and Giga animates through four different poses. You can
Scratch Cat scripts when the Green Flag icon is clicked. move Giga left and right using the arrow keys. It’s starting to form
into an interactive scene.

www.bdmpublications.com BDM’s Coding for Beginners 129


Programming with Scratch and Python

Sensing and Broadcast


Get your sprites and scripts to communicate with each other. The concept of Sensing
and Broadcast is similar to the way objects communicate in Python. This tutorial will
walk you through the process.

MORE INTERACTION
Earlier we looked at how you could interact with scripts, using the keyboard to move the sprites but scripts and sprites can
interact with each other, sending messages and responding to events.

STEP 1 Scripts can broadcast messages to each other. These STEP 3 The options for interaction between the sprites are
can be used to start other scripts or respond to found in the Sensing part of the Block Palette. The
events. You’re going to get Scratch Cat to respond to the Giga and one we are looking for is touching, at the top. Notice that this is a
say “Watch Out!!!” if the two sprites touch. Select Scratch Cat in the different shape to ones you are used to. It is designed to fit in the
Sprites Pane so you can view its Script Area. slot next to our if block. Drag the touching block into the spare
slot in the if block.

STEP 2 You ‘ve looked at ‘if’ and ‘else’ in Python, so now STEP 4 The touching block responds to the condition
you need to look at them in Scratch. Programs work of our sprite; in this case if it’s touching another
around a few simple terms and ‘if this then do that’ is one of them. On sprite. However, we need to tell it which one. Click the arrow in the
our stage, you want to say, “if Giga touches Scratch then Scratch says touching block and choose Giga from the list. There are a couple of
‘Watch Out!!!’” Click Control and drag an if block to the Script Area. default options, mouse pointer and edge. These are handy if you’re
making games.

130 BDM’s Coding for Beginners


Sensing and Broadcast

STEP 5 We’ve got our if, what we now need is a response. STEP 6 How do we get our ‘if’ script to run alongside the
Click Looks and drag a say [Hello!] for 2 other scripts? We could put the if block inside
secs block and insert it inside the if block. Change [Hello!] to when flag clicked but it would look big and ugly and do two
[Watch Out!!!]. Try to run the program. Nothing happens! That’s different things. We could add a second when [flag] clicked block to
because our if script isn’t part of the when flag clicked script. the if block but that would only work if they were touching at the
start. The answer is to use a broadcast block.

BROADCASTING
The broadcast block enables one script to interact with the others. It can be used to tell scripts to run and is ideal for bigger
projects where each sprite does several things at once.

STEP 1 Click the Events tab in Scripts and look for the STEP 3 Now we need to broadcast that ‘init’ message
when I receive block. Drag this and connect from our when [flag] clicked script so it runs at the
it to the top of the if block. We need to set the receiver, i.e. the same time. Drag a broadcast block to the Script Area and insert
message it gets from the other script. Click the arrow next to between the when flag clicked block and the repeat [10]
receive to reveal the Message name window. block. Now click the arrow in broadcast and choose ‘init’.

STEP 2 You can call the message anything you want but STEP 4 Our program is almost ready but our if script only
it should start with a lowercase letter and in this works once, when the Green Flag icon is clicked.
instance you are going to use the word “init”. This stands for We’re going to place it inside a Forever block. This is okay though
“initialize” and getting the lingo right now will make your life much because it’s not our main program and we are also going to add
easier when you move to a more complex language. Click OK. a stop all block to the end of our when flag clicked block.
Click the Green Flag to see your program run.

www.bdmpublications.com BDM’s Coding for Beginners 131


Programming with Scratch and Python

Objects and
Local Variables
You’ve already met variables but Scratch makes them easy to understand. What
isn’t so obvious in Python is how variables are stored locally to objects. This is where
Scratch helps. You’re going to create a dice game to help understand this.

ARE YOU LOCAL OR GLOBAL?


Objects, like your Scratch Cat sprite, can have their own variables. This could be the player score or the amount of ammunition
left. These are stored inside the object and are known as “local”. Variables used by all objects are known as ‘global’.

STEP 1 You’re going to leave the disco behind. Choose File > STEP 3 Click Make a variable and enter dice1 into the ?
New. You start with a blank stage containing a single window making sure that your variable starts with a
Scratch Cat sprite. Click Control and drag a when flag clicked lowercase letter. There are two options here: For all sprites
block to the Script Area. and For this sprite only. For all sprites allows every
sprite to use the dice; this is known as a global variable.

STEP 2 You ‘re going to create a simple game where Scratch STEP 4 For this sprite only means that only this
Cat rolls two dice and wins if they’re both the same sprite can use the two dice variables. this is known
number. Click Data. Unlike other sections there are no blocks here; as a local variable. This is useful if you want to create another
instead we have to create the variables we need. We need two, one character with their own set of dice and play against each other.
for each dice. We’re doing that in the next tutorial, so choose For this sprite only
and click OK.

132 BDM’s Coding for Beginners


Objects and Local Variables

STEP 5 A whole bunch of blocks appears in the Block STEP 6 Both the dice1 and dice2 variables are currently
Palette. We can now use our dice1 variable but empty. They could be anything we wanted, but
we want two dice, so click Make a variable again and this time we want them to be a random number between 1 and 6. Drag the
enter dice2. Remember to choose For this sprite only and set [dice1] to [0] block and click it underneath the when
click OK. flag clicked block. Drag another set [dice1] to [0] block
underneath and change the [dice1] setting to [dice2].

SMOOTH OPERATORS
Operators are used to change the values of variables. Some of these will be familiar; you’ve used the addition operator ‘+’ to
add two numbers together. Programs can also check if numbers are equal, bigger or smaller than each other or even not equal.

STEP 1 Click the Operator tab and drag a pick random STEP 3 The = operator checks if two things are the same
1 to 10 block and drop it into the [0] in set but we need to tell it to check our variables. Click
dice1 to [0]. Change the [10] to a [6] so it reads set dice1 Data and drag dice1 to the space on the left of the = block. Drag
to pick random [1] to [6]. When we click the Green Flag dice2 to the space on the right of the = block.
it will pick a number between 1 and 6 and store it in the dice1
variable. Add a pick random [1] to [10] block to dice 2 and
also set it to [6].

STEP 2 We need to check the two dice. Click the Control STEP 4 Finally click the Looks tab and drag say [Hello!]
tab and drag the if else block to the script. blocks into the if and else spaces. Change the
This block is like the if block we used before but it says, “if this say [Hello!] text in if to [I win!!!] and in else to [Oh no.
happens, do this; if not, do this instead.” Now click operators and I lose!]. Click the Green Flag to play the game.
look for the = block. Drag it into the space next to if.

www.bdmpublications.com BDM’s Coding for Beginners 133


Programming with Scratch and Python

Global Variables
and a Dice Game
We’re going to create a game where two sprites play dice with each other and the
sprite with the highest score wins. This lets us examine the idea of more than one
object, each with its own set of local variables.

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.

STEP 1 Let’s add a second character to the Stage. Shift click STEP 3 You can check this out by clicking the Green Flag
on Scratch Cat on the stage and choose Duplicate. icon. Vic and Bob will both roll dice1 and dice2 but
Click OK. Rearrange the two characters on the stage so they’re each gets its own random result (shown in the Stage). We’re going
stood side by side. Use the Sprite Info Window to give them names: to change the game to one where the two dice are added together
“Vic” and “Bob”. (highest score wins). Disconnect the If block from the script and drag
it to the Block Palette.

STEP 2 Select Bob and click Data in the Script Palette and STEP 4 We need two new variables: one for Vic’s total, and
you’ll see dice1 and dice2. Bob received his own one for Bob’s. Click Make a variable and enter
set of dice when we duplicated him but he doesn’t share dice1 and vic_total. This time choose For all sprites then click OK.
dice2 with Vic. Place checks in the boxes next to dice1 and dice2 so With Vic still selected, click Make a variable again and enter
you can see them on the Stage. bob_total. Click OK.

134 BDM’s Coding for Beginners


Global Variables and a Dice Game

STEP 5 Imagine both characters writing their totals on a STEP 6 Drag set­[dice2] to [0] from the block
blackboard that they share, but each has its own palette and connect it to the script. Change dice2
pair of dice. The totals are global and shared across both characters; to vic_total. Now click Operators and drag the + block to the
the dice are local to each object. [0]. Click Data and drag dice1 to the left side of the + block and
dice2 to the right side. This adds up the dice1 and dice2 variables,
and stores the combined value in vic_total.

GREATER THAN
The sprite with the highest score is going to win our game. This is decided using the greater than symbol >. This sits between
two numbers, i.e. 3 > 2 and lets you know if the number on the left is bigger than the one on the right.

STEP 1 Both sprites are going to announce their score and STEP 3 Bob needs to run the same script, only with bob_
the one with the highest score will say, “I win!”. total in place of cat_total. We could write Bob with
Click Looks and drag say [hello] for 2 secs. Now click Data the same code but the point of objects is that you can stamp out
and drag vic_total to replace [hello]. The first part of the copies. Shift-click Bob and choose Delete. Now Shift-click Vic and
game is ready, we’re going to use an if block with an > operator choose Duplicate. Click the Info icon and rename Vic2 as Bob.
for the next part of the game.

STEP 2 Click Control and drag an if block to the script. STEP 4 You need to change Bob’s variables. Change
Now click Operators and drag the > operator to the set vic_total to set bob_total and say
slot in the if block. Click Variables and drag vic_total to the left vic_total to say bob_total. Finally swap around the vic_
of the > block and bob_total to the right. Finally click Looks and total and bob_total in the if block. Now click the Green
drag a say [hello!] block inside the if block and change the Flag icon to play the game. Vic and Bob role their dice, and the
text to [I win!]. winner is announced.

www.bdmpublications.com BDM’s Coding for Beginners 135


Programming with Scratch and Python

Classes and Objects


Modern coding uses a style called Object Orientated Programming, or OOP for short.
In OOP you group together variables and functions into small blocks of code called
objects. These objects then make up your program.

SCRATCH THAT
OOP can be hard to explain, but makes sense when you start using it. If you’ve used Scratch then you already have an idea of
what an object looks like, it looks like a sprite. This is why we detoured into Scratch. It’s great for learning OOP.

STEP 1 In this tutorial we’re going to open the dice_game STEP 3 In OOP we don’t design objects. Instead we design
program that we created earlier in Scratch. Resize a blueprint for our object, called a “Class”. Think of
the window and place Scratch on the left-hand side of the screen. it like a blueprint or stamp. Vic and Bob are both dice-rolling cats, so
Next we’re going to recreate this game in Python using objects, so we create a blueprint for a dice-rolling animal. We then stamp out
you can see how objects are similar to Scratch sprites. two identical objects from that blueprint. One called “Vic” the other
called “Bob”. We’re going to need the random number module, so
enter this line:
from random import randint

STEP 2 Open Python 2 and choose File > New Window. STEP 4 Now let’s define our class, which we’re going to call
Resize the Editor window to the right-hand size of DiceAnimal. Enter:
the screen. Choose File > Save As and name it dice_game. Now let’s
class DiceAnimal():
have a look at the objects in Scratch. We have two: Vic and Bob.
dice1 = 0
Each has three variables (two dice and a total); both pick random
dice2 = 0
numbers between 1 and 6 and check to see if their total is bigger
total = 0
than the other.
Notice the funny capitalisation of DiceAnimal. This is known as
CamelCase and class definitions should be named in this fashion.

136 BDM’s Coding for Beginners


Classes and Objects

STEP 5 Now we’re going to define a function that rolls both STEP 6 Look at Scratch, and you’ll see this is the same as
dice, and adds the two together to create the total. the set dice1 to pick random 1 to 6 block. But what
Inside the class, indented four lines to line up with dice1, dice2 and are those self bits about? Remember that Vic and Bob have their
total, enter this: own dice. Vic’s dice are going to be accessed use vic.dice1 and vic.
dice2 and Bob’s using bob.dice1 and bob.dice2. But the class doesn’t
def rolldice(self):
know what we’re going to call each object; instead it uses “self” as a
self.dice1 = random.randint(1, 6)
placeholder. This works no matter what name each object has.
self.dice2 = random.randint(1, 6)
self.total = self.dice1 + self.dice2

CREATING OBJECTS
Now that our class is ready, we need to create two characters from it. One ‘vic’ and one ‘bob’. 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 Creating an object in OOP has a big fancy name: STEP 3 Now we’re going to use dot notation to access
“instantiation”. Don’t be impressed by the the values inside both the cat and lobster. Enter
language, all it means is creating an instance of your class. And this this code:
is exactly the same as creating a variable, only instead of passing in
print “Vic rolled a”, vic.dice1, “and a”,
a number, or string, you make it equal to your class. Enter this.
vic.dice2
vic = DiceAnimal() print “Bob rolled a”, bob.dice1, “and a”,
bob = DiceAnimal() bob.dice2
There, that wasn’t hard at all. Finally, we’re going to use if, elif and else statements to create
the game.

STEP 2 You now have two objects, a vic and a bob. You STEP 4 Enter this code:
access the variables and functions inside the object
if vic.total > bob.total:
using the objects name followed by a dot. To access Vic’s dice, you
print “Vic wins!”
usevic.dice1 and vic.dice2. We’re going to get both objects to roll
elif bob.total > vic.total:
their dice and store the total in their own self.total. Enter this:
print “Bob wins”
vic.rolldice() else:
bob.rolldice() print “It’s a draw”
Press F5 to run the game.

www.bdmpublications.com BDM’s Coding for Beginners 137


Working 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

138 BDM’s Coding for Beginners


Index

Working
with Code

www.bdmpublications.com BDM’s Coding for Beginners 139


Working with Code

Common Coding Mistakes


When you start something new you’re inevitably going to make mistakes, this is purely
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 can.

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 it is when you start to move into more advanced territory.

SMALL CHUNKS EASY VARIABLES


It would be wonderful to be able to Meaningful naming for variables is a must to eliminate
work like Neo from The Matrix movies. common coding mistakes. Having letters of the alphabet
Simply ask, your operator loads it into is fine but what happens when the code states there’s
your memory and you instantly know a problem with x variable. It’s not too difficult to name
everything about the subject. Sadly variables lives, money, player1 and so on.
though, we can’t do that. The first
major pitfall is someone trying to learn
too much, too quickly. So take coding in
small pieces and take your time.

//COMMENTS
Use comments. It’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 PLAN AHEAD
through the sections of code that are causing problems;
also useful if you need to review an older piece of code.
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 code requires a good working plan to stick to and
help iron out the bugs.

140 BDM’s Coding for Beginners


Common Coding Mistakes
USER ERROR
User input is often a paralysing mistake in code. For
example, when the user is supposed to enter a number for
their age and instead they enter it in letters. Often a user
can enter so much into an input that it overflows some BACKUPS
internal buffer, thus sending the code crashing. Watch those
user inputs and clearly state what’s needed from them.
Always make a backup of your work, with a secondary
backup for any changes you’ve made. Mistakes can be
rectified if there’s a good backup in place to revert to for
those times when something goes wrong. It’s much easier
to start where you left off, rather than starting from the
beginning again.

RE-INVENTING WHEELS
You can easily spend days trying to fathom out a section
SECURE DATA
of code to achieve a given result and it’s frustrating and
often time-wasting. While it’s equally rewarding to solve the If you’re writing code
problem yourself, often the same code is out there on the to deal with usernames
Internet somewhere. Don’t try and re-invent the wheel, look and passwords, or other
to see if some else has done it first. such sensitive data,
then ensure that the
data isn’t in cleartext.
Learn how to create
a function to encrypt
sensitive data, prior to
feeding into a routine
that can transmit or
store it where someone
may be able to get to
view it.

HELP! MATHS
Asking for help is something most of us has struggled If your code makes multiple calculations then you need
with in the past. Will the people we’re asking laugh at us? to ensure that the maths behind it is sound. There are
Am I wasting everyone’s time? It’s a common mistake for thousands of instances where programs have offered
someone to suffer in silence. However, as long as you ask incorrect data based on poor Mathematical coding, which
the in the correct manner, obey any forum rules and be can have disastrous effects depending on what the code is
polite, then your question isn’t silly. set to do. In short, double check your code equations.

BDM’s Coding for Beginners 141


Working with Code

Beginner Python Mistakes


Python is a relatively easy language to get started in, where there’s plenty of
room for the beginner to find their programming feet. However, as with any other
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.

VERSIONS To add to the confusion that most beginners INDENTS, TABS AND SPACES Python uses precise
already face when coming into programming, indentations when
Python has two live versions of its language available to download displaying its code. The indents mean that the code in that section
and use. There is Python version 2.7.x and Python 3.6.x. The 3.6.x is a part of the previous statement, and not something linked with
version is the most recent, and the one we’d recommend starting. another part of the code. Use four spaces to create an indent, not
But, version 2.7.x code doesn’t always work with 3.6.x code and the Tab key.
vice versa.

THE INTERNET Every programmer has and does at some COMMENTING Again we mention commenting.
point go on the Internet and copy some It’s a hugely important factor in
code to insert into their own routines. There’s nothing wrong with programming, even if you’re the only one who is ever going to view
using others’ code, but you need to know how the code works and the code, you need to add comments as to what’s going on. Is this
what it does before you go blindly running it on your own computer. function where you lose a life? Write a comment and help you, or
anyone else, see what’s going on.

142 BDM’s Coding for Beginners


Beginner Python Mistakes

COUNTING LOOPS Remember that in Python a loop COLONS It’s common for beginners to forget to add a
doesn’t count the last number you colon to the end of a structural statement, such as:
specify in a range. So if you wanted the loop to count from 1 to 10,
class Hangman:
then you will need to use:
def guess(self, letter):
n = list(range(1, 11))
And so on. The colon is what separates the code, and creates the
Which will return 1 to 10. indents to which the following code belongs to.

CASE SENSITIVE Python is a case sensitive


programming language, so you will
need to check any variables you assign. For example, Lives=10 is a
different variable to lives=10, calling the wrong variable in your code
can have unexpected results.

OPERATORS Using the wrong operator is also a common


mistake to make. When you’re performing
a comparison between two values, for example, you need to use
the equality operator (a double equals, ==). Using a single equal (=)
is an assignment operator that places a value to a variable (such as,
lives=10).

BRACKETS Everyone forgets to include that extra


bracket they should have added to the end
of the statement. Python relies on the routine having an equal
OPERATING SYSTEMS Writing code for multiple
amount of closed brackets to open brackets, so any errors in
platforms is difficult,
your code could be due to you forgetting to count your brackets;
especially when you start to utilise the external commands of the
including square brackets.
operating system. For example, if your code calls for the screen
to be cleared, then for Windows you would use cls. Whereas, for
Linux you need to use clear. You need to solve this by capturing
the error and issuing it with an alternative command.

www.bdmpublications.com BDM’s Coding for Beginners 143


Working with Code

Beginner C++ Mistakes


There are many pitfalls the C++ developer can encounter, especially as this is a more
complex and often unforgiving language to master. Beginners need to take C++ a
step at a time and digest what they’ve learned before moving on.

VOID(C++, MISTAKES)
Admittedly it’s not just C++ beginners that make the kinds of errors we outline on these pages, even hardened coders are
prone to the odd mishap here and there. Here are some common issues to try and avoid.

UNDECLARED IDENTIFIERS A common C++ STD NAMESPACE Referencing the Standard Library is
mistake, and to be common for beginners throughout
honest a common mistake with most programming languages, is their code, but if you miss the std:: element of a statement, your
when you try and output a variable that doesn’t exist. Displaying the code errors out when compiling. You can combat this by adding:
value of x on-screen is fine but not if you haven’t told the compiler
using namespace std;
what the value of x is to begin with.
Under the #include part and simply using cout, cin and so on from
then on.

SEMICOLONS Remember that each line of a C++ GCC OR G++ If you’re compiling in Linux then you will no
program must end with a semicolon. doubt come across gcc and g++. In short,
If it doesn’t then the compiler treats the line with the missing gcc is the Gnu Compiler Collection (or Gnu C Compiler as it used to
semicolon as the same line with the next semicolon on. This creates be called) and g++ is the Gnu ++ (the C++ version) of the compiler.
all manner of problems when trying to compile, so don’t forget If you’re compiling C++ then you need to use g++, as the incorrect
those semicolons. compiler drivers will be used.

144 BDM’s Coding for Beginners


Beginner C++ Mistakes

COMMENTS (AGAIN) Indeed the mistake of never TOO MANY BRACES The braces, or curly brackets, are
making any comments on beginning and ending markers
code is back once more. As we’ve previously bemoaned, the lack around blocks of code. So for every { you must have a }. Often it’s
of readable identifiers throughout the code makes it very difficult easy to include or miss out one or the other facing brace when
to look back at how it worked, for both you and someone else. Use writing code; usually when writing in a text editor, as an IDE adds
more comments. them for you.

QUOTES Missing quotes is a common mistake to make, for


every level of user. Remember that quotes need
to encase strings and anything that’s going to be outputted to the
screen or into a file, for example. Most compilers errors are due to
missing quotes in the code.
INITIALISE VARIABLES In C++ variables aren’t
initialised to zero by default.
This means if you create a variable called x then, potentially, it is
given a random number from 0 to 18,446,744,073,709,551,616,
which can be difficult to include in an equation. When creating a
variable, give it the value of zero to begin with: x=0.

EXTRA SEMICOLONS While it’s necessary to have a


semicolon at the end of every
C++ line, there are some exceptions to the rule. Semicolons need to
be at the end of every complete statement but some lines of code
aren’t complete statements. Such as:
A.OUT A common mistake when compiling in Linux is
#include
forgetting to name your C++ code post compiling.
if lines
When you compile from the Terminal, you enter:
switch lines
g++ code.cpp
If it sounds confusing don’t worry, the compiler lets you know where
you went wrong. This compiles the code in the file code.cpp and create an a.out file
that can be executed with ./a.out. However, if you already have code
in a.out then it’s overwritten. Use:
g++ code.cpp -o nameofprogram

www.bdmpublications.com BDM’s Coding for Beginners 145


Working with Code

Beginner Linux
Scripting Mistakes
Linux scripting is a fantastic way to automate tasks and even create some cool
command line-based games. Bash hackers around the world often post some clever
scripts to try out but before you go copying and pasting them, it’s worth highlighting
some of the common mistakes.

BASH HACKERS
Even bearded seasoned Bash programmers make a mistake from time to time – including the non-bearded ones. Being able to
eliminate the common errors saves a lot of time when scripting.

HASH-BANG Forgetting to add the #!/bin/bash, the DOT SLASH Remember, Linux scripts don’t run when you
Hash-Bang, is one of the most common type the name of the file in. If you simply
mistakes to make for the beginner scripter. The Hash-Bang is the enter MyScript into the Terminal, it will attempt to execute a built-in
interpreter that tells the system what shell to use and that what command called MyScript – which doesn’t exist. Instead, you need to
you’re running is in fact a shell script. place ./ at the start: ./MyScript.

WHITESPACES Most of us automatically continue


writing script code without entering
whitespaces after a variable but if you’ve been using other
programming languages then it can become habit to hit the space
bar frequently. In scripting, there’s no spaces on either side of the
PERMISSIONS The second most common issue for
equals sign for variables. So, word = Hello is wrong, whereas
beginners, when their script doesn’t want
word=Hello is correct.
to work, is that they’ve forgotten to give it executable permissions.
After you’ve created your script you need to chmod +x it to allow
the system to flag the file as executable. Once it’s an executable you
can then run the script.

146 BDM’s Coding for Beginners


Beginner Linux Scripting Mistakes

COPYING Setting a script that copies files from one place CHECK FIRST Always be cautious when copying scripts
to another, such as a backup script, can be tricky. you’ve found online into your system
The part that stumps most folks is the naming of some files. If you and executing them. There are some Linux commands that kill
set variables as the file and target, you need to encapsulate them your system beyond repair, forcing you to reinstall the OS. The rm
in quotes. This way any whitespaces and extensions are considered. -rf command, for example, wipes all the files and folders off your
Such as, cp -- “$file” “$target”. system. Always research script contents before executing.

CHECK SPELLING It’s all too easy to mistype a


command in the Terminal. When you
do it in a script though the end result can be failure or something MORE BEWARE Following on from the previous
totally different. Before you save and execute the script, have a common mistake, never blindly enter
quick look through to check you’ve not mistyped a command. a website into a script or the Terminal that downloads and executes
a script. There’s a good chance it could contain something malicious
or wipe your files. The command wget http://somewebsite -O | sh
downloads a script and automatically executes it.

MISSING OPERATORS A popular mistake with most


Bash scripters is missing out
vital operators in their code. Missing quotations marks in an echo
command, or square brackets when using loop, and even flags for
external commands can have undesired results when you execute
the script. Best to check through your code before running it.

WRONG OS While frustrating to the coder, it’s always


amusing to see someone who’s written
a script and inserted a Microsoft command instead of a Linux
command. Clearing the screen is popular, where in Linux you use
clear, someone who’s got their DOS head on uses cls.

www.bdmpublications.com BDM’s Coding for Beginners 147


Working with Code

Code Checklist
If you want your code to be effective, portable and useable by others, then you need to
submit it to various checks. The checks themselves don’t have to be industry standard,
unless you’re writing code for an App Store, but they do need to identify issues.

PLAN AHEAD
We’ve compiled a brief checklist that you can start using to
help you iron out any issues. Then you can ready your code so
it’s well on the way to being used elsewhere.

Recent research by the Software Engineering Institute suggested


that programmers can make between fifteen to twenty mistakes
in their code, and these are experienced coders. The rest of us
probably make significantly more as we earn our coding stripes
and build our skills.

Therefore, having an effective plan that you can run through once
you’ve successfully created a program helps you immensely and
ensures that common issues are identified and dealt with. The
checklist we’ve created here is merely an example you can use to
start with; as you build on your experiences as a coder, and as you
stretch your coding skills, you will undoubtedly expand the list to
include your own identified checks.

Don’t forget also, to continually add to the last part of the


checklist, the Mistakes check. Being able to see your past mistakes
helps you form a muscle memory that gets rid of them before the
actual checks begin.

148 BDM’s Coding for Beginners


Code Checklist

Checklist

Does the
code wor
intended k? Does it
function? perform t
he
Is the cod
e easily u
Have you nderstoo
added co d?
mments
througho
Can the c ut?
ode work
on other
Do all the operating
variables systems?
make sen
Is output se? Are th
ted sensit ey readab
ive data e le?
Do any th n crypted?
ird-party
utilities r
equire lic
Does the ensing?
code or p
fashion fo r ogram te
r the user rminate in
? a suitable
Are there
any accom
to use the panying in
program? struction
s on how
Have you
tested ev
ery outco
Is the cod me of the
e as efficie program?
Have you n t as possib
eliminate le?
d any per
Mistakes formance
– enter an bottlenec
y mistake ks?
rid of the s you find to
m next tim help get
e.

www.bdmpublications.com BDM’s Coding for Beginners 149


Working with Code

Where to Find Help


with Code
Before the Internet was readily available, coders would pour over immense books
like sorcerers in search of the fabled Philosopher’s Stone when they came across
something they couldn’t fix. These days, help is just a click or two away.

HELP == CODE
Here are ten top places you should bookmark as a beginner coder. These places offer invaluable advice, help, hacks, tips, fixes
and everything else to do with your code.

STACKOVERFLOW One of the biggest programming REDDIT Many experienced and serious programmers use
communities on the Internet, Reddit as a resource of useful information. There
StackOverflow has millions of experienced and beginner users who are many communities within dedicated to coding and there are
are ready to offer help and advice. Within you can ask questions also a lot of coding jokes, the sort that only programmers would get.
about Python, C++, scripting, networking and countless other topics. Find out more at: www.www.reddit.com/r/programming/.
Check it out at: www.stackoverflow.com/.

QUORA Quora deals with a wide range of topics, from who STACKEXCHANGE A part of the StackOverflow
would win a fight between Popeye and the Hulk network of communities,
to how do I pass a sudo password through C++ code. Once you’ve StackExchange is by far the largest programming led community on
logged in you can browse the questions, search for specifics and the Internet. You can ask any programming specific questions (as
post your own. Login at: www.www.quora.com/. long as it follows the rules) and it gets answered professionally and
expediently: www.stackexchange.com/.

150 BDM’s Coding for Beginners


Where to Find Help with Code

CODEPROJECT With articles, discussions, source DZONE DZone offers the user a wide range of help on
code and an excellent community, topics such as AI, Big Data, Cloud, Databases,
CodeProject is certainly worth bookmarking and paying daily visits Java, IOT and much more. There are guides, Zones, where you can
to. It covers virtually every programming language you can think of, get specific help and information and tons of tips for upcoming
and questions are quickly answered in a professional manner: developers. You can find it at: www.dzone.com/.
www.www.codeproject.com/.

GOOGLE GROUPS Google Groups has encompassed all FINDNERD This is a kind of a social media network for
the alt.comp IRC groups these days developers, where you can ask a fellow ‘nerd’
and made them viewable without too much difficulty. There are a question and they answer you as quickly as possible. There are
countless programming specific groups available; all you need to do also blogs, tutorials, projects and much more to discover:
is find one that suits you and get posting: www.groups.google.com. www.findnerd.com/.

CODERANCH This friendly discussion board is a great CHEGG This site is aimed more at students who are
place for new coders to start looking for studying coding at school, college or university
help or advice. It’s an easy to use setup where you can learn about levels. However, that doesn’t mean non-students are excluded from
and ask questions on programming languages, books, careers, the huge resources available. There are plenty of sections that cover
engineering and much more. Check it out at www.coderanch.com/. programming, so dive in and have a look around: www.chegg.com/.

www.bdmpublications.com BDM’s Coding for Beginners 151


Working with Code

Test Your Code Online


The modern Internet has drastically changed the way developers work and test
their code. The bare metal testing still applies, where you test your code in a virtual
machine for example, but these days you can test it online in a perfectly safe and
secure environment.

WWW.TESTINGCODE.COM
You can test all kinds of programming languages online or just one in particular. It all depends on what language your working
in and how you want it tested. Here are ten testing sites for bookmarking.

CODEPAD Codepad is arguably one of the most popular JS BIN This simple JavaScript editor and compiler offers a
code testing and online compilers on the clean interface and simple to use controls to help
Internet. With it you’re able to paste in snippets of code for testing you rest your JS code snippets alongside HTML and CSS. There are
that cover C, C++, PHP, Python, Ruby and a lot more. There are also tons of other features available via the many links at the top of site,
examples available and you can see what others have pasted in too. so it’s worth registering and getting to know JS Bin.
www.codepad.org/. www.jsbin.com/?html,output.

WRITE PHP ONLINE For those of you looking to JS FIDDLE JS Fiddle is another excellent online resource
learn PHP for future web where you can experiment and test using
development, Write PHP Online is a great resource to bookmark. HTML, JavaScript and CSS, and see the output from the code you’re
This is an online PHP editor that also allows you to execute your inputting. There are links to collaborations, exporting to GitHub, and
code, displaying the results in a separate window at the bottom of a code tidy feature to help iron out any bad habits. You can find it at
the page. It currently runs PHP 5.4 and can be found at www.jsfiddle.net/.
www.writephponline.com/.

152 BDM’s Coding for Beginners


Test Your Code Online

CSSDESK Beyond scripting and using stylesheet CLOUD9 Using the Amazon Web Services (AWS) cloud
languages, CSSDesk is a splendidly developed infrastructure, Cloud9 is an excellent IDE
site that displays HTML, CSS and the output from both in a large designed for collaborations, testing, debugging and editing. It
screen area to one side. You can set certain options and either share includes essential tools for the major programming languages
or download your finished code when you’re done. including Python, PHP, JavaScript and more. Being cloud based, you
www.cssdesk.com/. can quickly share your work with others and create a development
environment. www.aws.amazon.com/cloud9/?origin=c9io.

GOOGLE CODE Google’s commitment to creating and CODECHEF This online platform helps developers work
maintaining good code is certainly through and test their code in a huge range
commendable, regardless of what you may think of the company of supported languages. There’s a dedicated section to help hone
as a whole. Its embraced the open source community and created your coding craft and even a monthly contest and Code Cook-offs
Google Code, where you can test code, see great examples, get hold with cash prizes available. www.codechef.com/ide.
of APIs and tools and much more. www.code.google.com/.

IDEONE.COM This online code editor and compiler JSBEEB Purely for fun, those of you old enough to recall
supports over 60 different programming the heady days of the ‘80s when the C64, ZX
languages for you to test and debug. There’s Linux Bash, C++, Spectrum and other marvellous 8-bit computers ruled will certainly
Python and Python 3, Java, JavaScript and many more to try out. warm to jsbeeb. In the ‘80s, British classrooms were filled with BBC
There are samples available and you can view recent code entered. Microcomputers. Jsbeeb fills the nostalgic gap with a BBC Micro
www.ideone.com/. emulator where you can code, save, share and more.
www.bbc.godbolt.org/.

www.bdmpublications.com BDM’s Coding for Beginners 153


Working with Code

Python OS Module
Error Codes
The Python OS module enables the coder to interact with the operating system. You
can read files, write to them, manipulate paths and even run built-in operating system
specific commands. It’s one of the most used modules, and one of the most problematic.

OS.ERROR
The interaction between Python and the operating system brings about its own set of problems and error codes. Filename too
long, path not valid and so on are represented as errno. values. Here’s a list of common ones.

errno.EPERM Operation not permitted errno.EPROTO Protocol error


errno.ENOENT No such file or directory errno.ELIBBAD Accessing a corrupted shared library
errno.ESRCH No such process errno.EUSERS Too many users
errno.EINTR Interrupted system call errno.EDESTADDRREQ Destination address required
errno.EIO I/O error errno.EMSGSIZE Message too long
errno.ENXIO No such device or address errno.ENOPROTOOPT Protocol not available
errno.ENOMEM Out of memory errno.EPROTONOSUPPORT Protocol not supported
errno.EACCES Permission denied errno.EADDRINUSE Address already in use
errno.EEXIST File exists errno.ENETDOWN Network is down
errno.EISDIR Is a directory errno.ENETUNREACH Network is unreachable
errno.EINVAL Invalid argument errno.ECONNRESET Connection reset by peer
errno.EMFILE Too many open files errno.ENOBUFS No buffer space available
errno.ETXTBSY Text file busy errno.ETIMEDOUT Connection timed out
errno.EFBIG File too large errno.ECONNREFUSED Connection refused
errno.ENOSPC No space left on device errno.EHOSTDOWN Host is down
errno.EROFS Read-only file system errno.EHOSTUNREACH No route to host
errno.ENAMETOOLONG File name too long errno.EALREADY Operation already in progress
errno.ENOTEMPTY Directory not empty errno.EINPROGRESS Operation now in progress
errno.ENONET Machine is not on the network errno.ESTALE Stale NFS file handle
errno.ENOPKG Package not installed errno.EREMOTEIO Remote I/O error
errno.ECOMM Communication error on send

154 BDM’s Coding for Beginners


Python OS Module Error Codes

www.bdmpublications.com BDM’s Coding for Beginners 155


Working with Code

Python Errors
It goes without saying that you’ll eventually come across an error in your code, where
Python declares it’s not able to continue due to something being missed out, wrong
or simply unknown. Being able to identify these errors makes for a good programmer.

DEBUGGING
Errors in code are called bugs and are perfectly normal. They can often be easily rectified with a little patience. The important
thing is to keep looking, experimenting and testing. Eventually your code will be bug free.

Code isn’t as fluid as the written word, no matter Thankfully Python is helpful when it comes to
STEP 1 STEP 3
how good the programming language is. Python is displaying error messages. When you receive an
certainly easier than most languages but even it is prone to some error, in red text from the IDLE Shell, it will define the error itself
annoying bugs. The most common are typos by the user and whilst along with the line number where the error has occurred. Whilst in
easy to find in simple dozen-line code, imagine having to debug the IDLE Editor this is a little daunting for lots of code; text editors
multi-thousand line code. help by including line numbering.

The most common of errors is the typo, as we’ve Syntax errors are probably the second most
STEP 2 STEP 4
mentioned. The typos are often at the command common errors you’ll come across as a programmer.
level: mistyping the print command for example. However, they also Even if the spelling is correct, the actual command itself is wrong.
occur when you have numerous variables, all of which have lengthy In Python 3 this often occurs when Python 2 syntaxes are applied.
names. The best advice is to simply go through the code and check The most annoying of these is the print function. In Python 3 we use
your spelling. print(“words”), whereas Python2 uses print “words”.

156 BDM’s Coding for Beginners


Python Errors

Pesky brackets are also a nuisance in programming An excellent way to check your code step-by-step
STEP 5 STEP 8
errors, especially when you have something like: is to use Python Tutor’s Visualise web page, found
print(balanced_check(input())) at www.pythontutor.com/visualize.html#mode=edit. Simply
Remember that for every ‘(‘ there must be an equal number of ‘)’. paste your code into the editor and click the Visualise Execution
button to run the code line-by-line. This helps to clear bugs and
any misunderstandings.

There are thousands of online Python resources, Planning makes for good code. Whilst a little old
STEP 6 STEP 9
code snippets and lengthy discussions across forums school, it’s a good habit to plan what your code
on how best to achieve something. Whilst 99 per cent of it is good will do before sitting down to type it out. List the variables that will
code, don’t always be lured into copying and pasting random code be used and the modules too; then write out a script for any user
into your editor. More often than not, it won’t work and the worst interaction or outputs.
part is that you haven’t learnt anything.

Indents are a nasty part of Python programming Purely out of interest, the word debugging in
STEP 7 STEP 10
that a lot of beginners fall foul of. Recall the If loop computing terms comes from Admiral Grace
from the Conditions and Loops section, where the colon means Hopper, who back in the ‘40s was working on a monolithic Harvard
everything indented following the statement is to be executed as Mark II electromechanical computer. According to legend Hopper
long as it’s true? Missing the indent, or having too much of indent, found a moth stuck in a relay, thus stopping the system from
will come back with an error. working. Removal of the moth was hence called debugging.

www.bdmpublications.com BDM’s Coding for Beginners 157


Working with Code

Where Next?
Coding, like most subjects, is a continual learning experience. You may not class
yourself as a beginner any more but you still need to test your code, learn new
tricks and hacks to make it more efficient and even branch out and learn another
programming language.

#INCLUDE<KEEP ON LEARNING>
What can you do to further your skills, learn new coding practises, experiment and present your code and even begin to help
others using what you’ve experienced so far?

STEP 1 Twitter isn’t all trolls and antagonists, among the well STEP 3 Look for open source projects that you like the sound
publicised vitriol are some genuine people who are of and offer to contribute to the code to keep it
more than willing to spread their coding knowledge. We recommend alive and up to date. There are millions of projects to choose from, so
you find a few who you can relate to and follow them. Often they contact a few and see where they need help. It may only be a minor
post great tips, hacks and fixes for common coding problems. code update but it’s a noble occupation for coders to get into.

STEP 2 If you’ve mastered Python fairly well, then turn your STEP 4 Become more active on coding and development
attention to C++ or even C#. Still keep your Python knowledge sites, such as StackExchange. If you have
skills going but learning a new coding language keeps the old brain the skills to start and help others out, not only will you feel really
ticking over nicely and give you a view into another community, and good for doing so but you can also learn a lot yourself by interacting
how they do things differently. with other members.

158 BDM’s Coding for Beginners


Where Next?

STEP 5 The mobile market is a great place to test your STEP 8 If you’ve learned how to code with an eye for a
coding skills and present any games or apps you’ve developer job in the future, then it’s worth starting
created. If your app is good, then who knows, it could be the to build up an online portfolio of code. Look at job postings and see
next great thing to appear on the app stores. It’s a good learning what skills they require, then learn and code something with those
experience nevertheless, and something worth considering. skills and add it to the portfolio. When it comes to applying, include
a link to the portfolio.

STEP 6 Online courses are good examples of where to STEP 9 Can you teach? If your coding skills are spot on,
take your coding skills next, even if you start consider approaching a college or university to see
from the beginner level again. Often, an online course follows a if they have need for a programming language teacher, perhaps a
strict coding convention, so if you’re self-taught then it might be part-time or evening course. If not teaching, then consider creating
worth seeing how other developers lay out their code, and what’s your own YouTube how to code channel.
considered acceptable.

STEP 7 Get sharing, even if you think your code isn’t very STEP 10 Contributing to hardware projects is a great
good. The criticism, advice and comments you resource for proving your code with others and
receive back help you iron out any issues with your code, and you learning from other contributors. Many of the developer boards have
add them all to your checklist. Alternatively your code might be postings for coders to apply to for hardware projects, using unique
utterly amazing but you won’t know unless you share it. code to get the most from the hardware that’s being designed.

www.bdmpublications.com BDM’s Coding for Beginners 159


Working with Code

Glossary of Terms
Trying to include definitions for every programming language would require many
more pages than we have here. However, we have created a list of some of the most
common terms you will encounter as you get started on your coding journey. As you
gain experience and try new things, your coding vocabulary will naturally expand.

A CONSTANT
F
(Boolean operators) to limit,
broaden or define your search. A variable that never changes its

ALGORITHM BUG value. Example: the PI constant


FLASK
A mistake in the program. A has the value 3.14.
A process or set of rules to be A micro web application

D
point of error that causes the
followed in calculations or other framework written in Python and
program to stop, or behave
problem solving operations, based on the Werkzeug toolkit
differently than expected.
especially by a computer. and Jinja2 template engine.
BRACKETS DATA STRUCTURES
ANGULAR.JS Characters often used to A data structure is a method of FRAMEWORK
Angular.js is an open source web organisation of data in a computer A framework is often a layered
surround text. The different
application framework types of brackets are: Parenthesis, so that it can be used efficiently. structure indicating what kind of
maintained by Google. programs can or should be built
Curly Brackets, Angle Brackets DEPLOYMENT and how they would interrelate.
APACHE and Square Brackets. Software deployment is all of the
FULL STACK
C
Apache is an open source activities that make a software
Unix-based Web server. It was system available for use. A full stack, also known as a
created by the Apache Software software stack or bundle, is a
Foundation. CALL DJANGO set of software components
To run the code in a function; A free open source web needed to create a complete
AJAX also referred to as “running”, application framework written web application.
AJAX stands for: asynchronous “executing” or “invoking” in Python that follows the
JavaScript and XML. It is a set of model-view-controller FUNCTION
a function.
web development techniques (MVC) framework. A set of instructions that are
utilising many web technologies on CLASS written once to obtain a particular
the client side in order to create In Python, a template for DUMP result and can then be used
asynchronous web applications. creating user-defined objects. A list of data that is saved if a whenever necessary by ‘calling’ it.

G
Class definitions normally program crashes, often as a
API contain method definitions text file. It is very useful for
An API is an application which operate on instances of diagnosing problems.
programming interface. It is a set

E
the class. GIT/GITHUB
of routines, protocols and tools
for building software CODING A micro web application
Coding is the act of computer framework written in Python and
applications. APIs express
software components in terms programming in a given EXECUTABLE based on the Werkzeug toolkit
coding language. A program, usually a single file, and Jinja2 template engine.
of their operations, inputs,
ready to be run.
outputs and underlying types. COFFEESCRIPT GUI

B CoffeeScript is a programming EXPRESSION General User Interface, refers to


language that trans compiles A piece of syntax which can be the ‘front end’ of a piece of
to JavaScript. evaluated to some value; An software that the end user
BACKBONE.JS accumulation of expression actually sees and interacts with.
COMPILER
H
Backbone.js is a JavaScript elements like literals, names,
This is a program that takes the attribute access, operators or
framework with a RESTful JSON
code you have written and function calls.
interface and is based on the
translates it into the binary ones
model-view-presenter (MVP)
and zeros of actual machine code. EXPRESS.JS HAML
application design paradigm. HTML Abstraction Markup
Express.js is a Node.js web
BOOLEAN SEARCHING CONCATENATION Language is a lightweight markup
application server framework,
Combining two things together, language that’s used to describe
Boolean searches allow you to designed for building single-
such as two lists or strings of text. the HTML of a web document.
combine words and phrases page, multi-page and hybrid
using the words and, or, not web applications.

160 BDM’s Coding for Beginners


Glossary of Terms

HASHABLE
An object is hashable if it has a
hash value which never changes
J N S
during its lifetime (it needs a JQUERY NESTED SANDBOX
__hash__() method), and can be jQuery is a cross-platform When one thing is contained A place to run a program for
compared to other objects. JavaScript library designed to within another it is said to testing and experimenting.
simplify the client-side scripting of be ‘nested’.
HTML HTML. jQuery is the most popular
SASS
HyperText Markup Language, JavaScript library in use today.
NODE.JS Sass is a scripting language that
commonly referred to as HTML, Node.js is an open source, is interpreted into Cascading
is the standard markup language JSON cross-platform runtime Style Sheets (CSS). SassScript is
used to create web pages. This is A format for transmitting environment for developing the scripting language itself and
often the very first technology information between locations server-side web applications. consists of two syntaxes.
that beginners to web that is based on JavaScript. Many Node.js applications are written
in JavaScript and can be run
SLICE
development will learn. APIs use JSON.
within the Node.js runtime on An object usually containing a
HTTP REQUEST
L multiple systems. portion of a sequence. A slice is
created using the subscript

O
HyperText Transfer Protocol is an
application protocol for notation, [] with colons between
distributed, collaborative,
LAMP STACK numbers when several are given.
hypermedia information LAMP is an archetypal model of
web service solution stacks: OBJECT ORIENTED SOFTWARE
systems. HTTP is the foundation DEVELOPMENT KITS
of data communication for the Linux operating system, the PROGRAMING (OOP)
Apache HTTP Server, MySQL OOP is a programming paradigm A ‘software development kit’ or
World Wide Web. SDK is a bundle of software tools
relational database management based on the concepts of ‘objects’

I system and the PHP


programming language.
that are data structures containing
data, in the form of fields, often
known as attributes; and code, in
for the creation of new
applications for a specific
platform or framework.
INTEGRATED LBYL the form of procedures, often
DEVELOPER Look before you leap. This SUBROUTINE
known as methods.
ENVIRONMENT (IDE) coding style explicitly tests for A function or other portion of
An Integrated Development pre-conditions before making OBJECT RELATIONAL code that can be run anywhere
calls or lookups. MAPPER (ORM) within a program.
Environment is a basic editor and
code interpreter which allows LINUX ORM is a programming SYNTAX
you to work with a specific technique for converting data Programming languages are just
Linux is a Unix-like computer between incompatible type
coding language. The Python IDE like human languages, they have
operating system assembled systems in object-oriented
is known as IDLE. their own ‘syntax’ or rules to
under the model of free and programming languages. describe how statements should
INTERPRETED open source software

P
development and distribution. be written.
Python is an interpreted
language, as opposed to a
compiled one, though the
distinction can be blurry because
LOGICAL OPERATION
The use of simple Boolean logical
such as and, or and not.
PHP T
of the presence of the bytecode
PHP is a server-side scripting TYPE
language designed for web
compiler. LOOP The type of a Python object
development but also used determines what kind of object it
A piece of code that keeps
INTERPRETER running until a certain condition
as a general purpose is; every object has a type.
Some languages do not need a programming language.

V
is fulfilled; or isn’t fulfilled in the
compiler but instead use an
case of an ‘infinite loop’ that will PYTHON
‘interpreter’ that translates to
crash the system running it. Python is a widely used general
machine code as the program
VALUE
M
purpose, high level programming
is run.
language. Its design philosophy A piece of data that can be
IOS SWIFT emphasises code readability and contained inside a variable. Every
iOS Swift is a multi-paradigm MONGODB its syntax allows programmers to value has a type.
compiled programming express concepts in fewer lines
MongoDB is a cross-platform
of code than would be possible VARIABLE
language created by Apple Inc. document oriented database.
in languages such as C++ or Java. A way, used by many
for iOS, macOS and watchOS and Classified as a NoSQL database. programming languages, to

R
tvOS development.
MVC store a piece of data that can
ITERATION Model-view-controller (MVC) is a then be modified at any time.

W
A sequence of instructions that software architectural pattern for RECURSION
are repeated. For example, to implementing user interfaces. It When something refers to itself.
perform an action for every item divides a given software application For example a variable may add
in a list you would ‘iterate’ over into three interconnected parts. something to itself for each WRITE
that list. Each time it is repeated To send output data values to an
is one iteration.
MYSQL iteration of a code loop.
external destination, usually to a
MySQL is an open source RUN TIME file. Can also refer to sending
relational database management The time during which a program data over a network.
system (RDBMS). is actively running.

www.bdmpublications.com BDM’s Coding for Beginners 161


BDM Publications
Innovate, Educate, Inspire...

Buy in stores or from our website:


www.bdmpublications.com
Many BDM titles are also available as digital editions:
BDM’s
Python Power

Coding
The world of programming is vast, with dozens
of programming languages available for multiple
different platforms. It’s confusing at the best of
times, so we’re here to help you find your way
through the labyrinthine coding universe.
Python is one of the most popular programming
languages available today. It’s used throughout the

for Beginners
Internet, in businesses and education. It’s easy to
learn and powerful to use and has a vast knowledge
base online for you to dip into for inspiration or help.
We look at how you get started with Python and
what you need to become a Python programmer.

There’s a wealth of choice for anyone wanting C++


C++ is one of the most powerful, high performing
to learn how to program but which language and efficient programming languages you can
do you start with? Python is widely accepted learn. Web browsers, games, applications and even
entire operating systems are coded using C++,
as the best beginners programming language which makes understanding it a highly sought after
but C++ is one of the most powerful. Linux skill to have.
It’s not too difficult to start coding in C++ but
scripting is a useful skill in today’s job market we’re here to help you out with our comprehensive
step-by-step guides and tutorials.
and coding on the Raspberry Pi with the FUZE
is perfect for projects. Coding on Linux
Linux is an open source operating system that’s a
In Coding for Beginners, we take a look at all superb foundation for any would-be programmer
to build on. It’s free to download, install and use and
these languages as well as Windows batch with it you can use all the popular and mainstream
programming languages, through a variety of
file programming and Scratch. You can learn different front-end apps.
where to start coding, how to get everything Scripting is a must have skill sought by
employers; it’s a powerful platform where you
you need and even how to avoid common can interact with the entire system and its users
beginner mistakes. as well as any Python and C++ code you’ve
already created.
Read on and become inspired to code. More Coding, More to Discover
We not only cover Python, C++ and Linux scripting
but also FUZE BASIC, Object Oriented Programming
with Scratch, and Windows batch file programming.
Our tutorials help you get up and running in the
amazing world of programming and we even cover
some common mistakes you’re likely to run into as
well as where to get help with your future coding.
There’s plenty to learn within these pages, where
the only limit is your imagination.

This guidebook can be used with the following


programming languages:

python Linux

You might also like