BDM's Coding For Beginners - 2018 UK
BDM's Coding For Beginners - 2018 UK
Learn
Python,
100% Independent
Scratch and
BASIC!
. ..
i de un
eed tok
ns Packed with top Featuring C++, Become the
All yo
I
no
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
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
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.
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.
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.
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.
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.
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?
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?
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.
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
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
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.
Java is a powerful
language that’s used in
web pages, set-top boxes,
TVs and even cars.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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++ 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.
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.
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.
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.
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.
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.
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).
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.
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.
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.
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”;
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.
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.
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.
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
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.
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
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.
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.
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
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.
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.
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.
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.
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.
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.
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’.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
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.
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 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.
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 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.
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.
C:\Commonly_Used_Commands
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 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.
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
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
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)
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
P
the user’s path
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
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.
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.
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.
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.
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 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 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 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.”
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.
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 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 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.
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.
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.
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.
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.
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”.
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 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.
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.
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!
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.
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
.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.
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.
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.
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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
: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%)
: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.
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.
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.
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.
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.
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.
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.
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”.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Working
with Code
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.
//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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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/.
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.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/.
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/.
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.
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”.
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.
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.
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.
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
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
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’
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.
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.
python Linux