0% found this document useful (0 votes)
997 views161 pages

The Complete Coding Manual - Issue 4 - February 2024

Coding is found everywhere in modern technology. Behind all this code are programmers who develop our digital world using various programming languages. The book aims to help readers improve their programming skills in languages like C++, Python, and Linux scripting. It provides tutorials, projects, and tips to take readers from beginners to advanced programmers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
997 views161 pages

The Complete Coding Manual - Issue 4 - February 2024

Coding is found everywhere in modern technology. Behind all this code are programmers who develop our digital world using various programming languages. The book aims to help readers improve their programming skills in languages like C++, Python, and Linux scripting. It provides tutorials, projects, and tips to take readers from beginners to advanced programmers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 161

LINUX, PYTHON, C++ & WINDOWS



Manual OVER
Master programming and 920
GUIDES
improve your Python, &TIPS
Linux & C++ skills

www.pclpublications.com 100% INDEPENDENT


Manual
Coding is everywhere. From your TV through to the
International Space Station, you’ll find millions of lines of
code controlling and delivering the services that we take for
granted. Behind all this code are the programmers who
develop our digital world, using a multitude of different
languages to weave the fabric of the Internet, operating
systems, games and modern entertainment. Whether it’s
inside the world’s most powerful supercomputer or
automating tasks aboard the ISS, scripting is the key to
effective interaction between systems and people.

The Complete Coding Manual Series aims to help you get


the most from your coding experience. Inside this book, you
will find ideas, concepts, tutorials, hints and projects that
will take you from being a beginner to an advanced
programmer who understands several languages and how
to form your own code.

www.pclpublications.com
6 Coding Foundations 34 Coding with C++
8 %HLQJD3URJUDPPHU 36 <RXU)LUVW&3URJUDP
10 $%ULHI+LVWRU\RI&RGLQJ 38 Compile and Execute
12 &KRRVLQJD3URJUDPPLQJ/DQJXDJH 40 Using Comments
14 &UHDWLQJD&RGLQJ3ODWIRUP 42 9DULDEOHV
44 Data Types
16 Introducing C++ 46 Strings
48 C++ Maths
18 Why C++?
50 User Interaction
20 C++ Facts & Figures
22 Equipment You Will Need
24 6WUXFWXUHRI&&RGH 52 Introducing Python
26 +RZWR6HW8S&LQ:LQGRZV
54 :K\3\WKRQ"
28 +RZWR6HW8S&RQD0DF
56 :KDW&DQ<RX'RZLWK3\WKRQ"
30 +RZWR6HW8S&LQ/LQX[
58 3\WKRQLQ1XPEHUV
32 Other C++ IDEs to Install
60 Equipment You Will Need
62 *HWWLQJWR.QRZ3\WKRQ
64 +RZWR6HW8S3\WKRQLQ:LQGRZV
66 +RZWR6HW8S3\WKRQLQ/LQX[
68 3\WKRQRQWKH3L

70 Coding with Python


72 6WDUWLQJ3\WKRQIRUWKH)LUVW7LPH
74 Your First Code
76 Saving and Executing Your Code
78 ([HFXWLQJ&RGHIURPWKH&RPPDQG/LQH
80 1XPEHUVDQG([SUHVVLRQV
82 Using Comments

4 &RGLQJ 3URJUDPPLQJ
Contents

84 :RUNLQJZLWK9DULDEOHV 120 ,QVWDOOLQJ/LQX[RQD3&


86 User Input 122 Installing a Virtual Environment
88 Creating Functions 124 Installing Linux in a Virtual Environment
90 Conditions and Loops 126 Getting Ready to Code in Linux
92 3\WKRQ0RGXOHV 128 &UHDWLQJ%DVK6FULSWVs3DUW
130 &UHDWLQJ%DVK6FULSWVs3DUW
132 &UHDWLQJ%DVK6FULSWVs3DUW
94 Coding with Windows 10 Batch Files 134 &UHDWLQJ%DVK6FULSWVs3DUW
136 &UHDWLQJ%DVK6FULSWVs3DUW
96 What is a Batch File?
138 &RPPDQG/LQH4XLFN5HIHUHQFH
98 Getting Started with Batch Files
100 Getting an Output
102 3OD\LQJZLWK9DULDEOHV
104 %DWFK)LOH3URJUDPPLQJ
140 Code Projects and Ideas
106 Loops and Repetition 142 3ODQQLQJ\RXU&RGH
108 Creating a Batch File Game 144 Finding Resources
146 Creating a Loading Screen
148 3ODQQLQJD7H[W$GYHQWXUH
110 Coding on Linux
150 Text Adventure Script
112 Why Linux? 152 Retro Coding
114 7KH%HVW/LQX['LVWULEXWLRQV 156 &RPPRQ&RGLQJ0LVWDNHV
116 Equipment You Will Need 158 3\WKRQ%HJLQQHUoV0LVWDNHV
118 Creating a Linux Installer on Windows 160 &%HJLQQHUoV0LVWDNHV

&RGLQJ 3URJUDPPLQJ 5
Welcome, Future Coder

Everything you do online, every time


you power on your smart TV, whenever
you use your in-car GPS, use your phone,
play a game on a tablet, console or PC,
it’s all been coded by a group of people.
All these ones and zeros are developed
by those who have learned how to
code, and with this book you too can
learn how to get started on the road to
becoming a programmer.

We cover C++, Python, and Linux


Scripting within these pages. There’s
a huge section of project ideas, type-
in listings, and in-depth looks at how
FRGHZRUNV%XWƬUVWOHWoVEHJLQZLWKD
good foundation.

8 Being a Programmer
10 A Brief History of Coding
12 Choosing a Programming Language
14 Creating a Coding Platform

6 &RGLQJ 3URJUDPPLQJ
Index

&RGLQJ 3URJUDPPLQJ 7
Welcome, Future Coder

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?

8 &RGLQJ 3URJUDPPLQJ
Being a Programmer

MORE THAN CODE


For those of you old enough to remember the ‘80s, the golden era of home
FRPSXWLQJWKHZRUOGRIFRPSXWLQJZDVDYHU\GLƪHUHQWVFHQHWRKRZLWLV
today. 8-bit computers that you could purchase as a whole, as opposed to
EHLQJLQNLWIRUPDQG\RXKDYLQJWRVROGHUWKHSDUWVWRJHWKHUZHUHWKHVWXƪ
of dreams; and getting your hands on one was sheer bliss contained within
a large plastic box. However, it wasn’t so much the new technology that
FRPSXWHUVWKHQRƪHUHGPRUHRYHULWZDVWKHIDFWWKDWIRUWKHƬUVWWLPH
ever, you could control what was being viewed on the ‘television’.

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


Times have changed since programming in the ‘80s, time, many users decided they wanted to create their own content, their
but the core values still remain. own games; or simply something that could help them with their homework
RUKRPHƬQDQFHV7KHVLPSOLFLW\RIWKHELWKRPHFRPSXWHUPHDQWWKDW

“It’s up to you
creating something from a few lines of BASIC code was achievable and so
WKHƬUVWJHQHUDWLRQRIKRPHEUHGSURJUDPPHUZDVERUQ

how far to take


From that point on, programming expanded exponentially. It wasn’t long
before the bedroom coder was a thing of the past and huge teams of
designers, coders, artists and musicians were involved in making a single

your coding
JDPH7KLVRIFRXUVHOHGWRWKHSURJUDPPHUEHFRPLQJPRUHWKDQVLPSO\
someone who could fashion a sprite on the screen and make it move at the
press of a key.

adventure!” 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?

7KHVLQJOHPRVWFRPPRQWUDLWRIDQ\SURJUDPPHUUHJDUGOHVVRIZKDW
they’re doing, is the ability to see a logical pattern. By this we mean
VRPHRQHZKRFDQORJLFDOO\IROORZVRPHWKLQJIURPVWDUWWRƬQLVKDQG
envisage the intended outcome. While you may not feel you’re such a
person, it is possible to train your brain into this way of thinking. Yes, it
takes time but once you start to think in this particular way you will be able
to construct and follow code.

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


at a genius level but you do need to understand the rudiments of maths.
Maths is all about being able to solve a problem and code mostly falls under
the umbrella of mathematics.

%HLQJDEOHWRVHHWKHELJSLFWXUHLVFHUWDLQO\EHQHƬFLDOIRUWKHPRGHUQ
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
RIGHVLJQHUVDOORIZKRPDUHFUHDWLQJDƬQDOSURGXFW:KLOH\RXPD\RQO\
EHH[SHFWHGWRFUHDWHDVPDOOHOHPHQWRIWKDWƬQDOSURGXFWEHLQJDEOHWR
understand what everyone else is doing will help you create something
that’s ultimately better than simply being locked in your own coding cubicle.

Finally, there’s also a level of creativity needed to be a good programmer.


Again though, you don’t need to be a creative genius, just have the
imagination to be able to see the end product and how the user will interact
with it.

7KHUHLVRIFRXUVHDORWPRUHLQYROYHGLQEHLQJDSURJUDPPHULQFOXGLQJ
learning the actual code itself. However, with time, patience and the
determination to learn, anyone can become a programmer. Whether
Being able to follow a logical pattern and you want to be part of a triple-A video game team or simply create an
see an end result is one of the most valued automated routine to make your computing life easier, it’s up to you how
skills of a programmer. far to take your coding adventure!

&RGLQJ 3URJUDPPLQJ 9
Welcome, Future Coder

A Brief History of Coding


It’s easy to think that programming a machine to automate a process or calculate a value
LVDPRGHUQFRQFHSWWKDWoVRQO\UHDOO\KDSSHQHGLQWKHODVWƬIW\\HDUVRUVR+RZHYHU
that assumption is quite wrong, coding has actually been around for quite some time.

01000011 01101111 01100100 01100101


(VVHQWLDOO\DOOIRUPVRIFRGLQJDUHPDGHXSRIRQHVDQG]HURVRQRURƪVWDWHV7KLVZRUNVIRUDPRGHUQFRPSXWHU
and even the oldest known computational device.

~87 BC a$' 1800 Ǖ Ǖ

,WoVGLƯFXOWWRSLQSRLQWDQH[DFW
start of when humans began to
‘program’ a device. However,
it’s widely accepted that the
Antikythera Mechanism is possibly
Joseph Marie Jacquard invents a
WKHƬUVWnFRGHGoDUWHIDFW,WoV
programmable loom, which used cards with
dated to about 87 BC and is an
punched holes to create the textile design.
ancient Greek analogue computer
However, it is thought that he based his
and orrery used to predict
design on a previous automated weaving
astronomical positions.
process from 1725, by Basile Bouchon.

Ada Lovelace translated


the memoirs of the Italian
mathematician, Francis
Maneclang, regarding
Charles Babbage’s
Analytical Engine. She
made copious notes
within her writing,
detailing a method of
7KH%DQŅ0ŅVÜEURWKHUVWKUHH3HUVLDQ calculating Bernoulli
scholars who worked in the House of Numbers using the
Wisdom in Baghdad, published the HQJLQH7KLVLVUHFRJQLVHG
Book of Ingenious Devices in around DVWKHƬUVWFRPSXWHU
850 AD. Among the inventions listed program. Not bad,
was a mechanical musical instrument, considering there were
a hydro-powered organ that played no computers available at
interchangeable cylinders automatically. the time.

10 &RGLQJ 3URJUDPPLQJ
A Brief History of Coding

During the Second World War, From the 1970s, the development of the likes of C, SQL, C with
WKHUHVLJQLƬFDQWDGYDQFHV &ODVVHV & 0$7/$%&RPPRQ/LVSDQGPRUHFDPHWRWKH
were made in programmable IRUH7KHnVZDVXQGRXEWHGO\WKHJROGHQDJHRIWKHKRPH
machines. Most notably, the computer, a time when silicon processors were cheap enough
cryptographic machines used IRURUGLQDU\IRONWREX\7KLVOHGWRDERRPLQKRPHEHGURRP
to decipher military codes coders with the rise of 8-bit machines.
XVHGE\WKH1D]LV7KH(QLJPD
was invented by the German
engineer Arthur Scherbius
but was made famous by Alan
7XULQJDW%OHWFKOH\3DUNoV
codebreaking centre.

Ǖ  Ǖ Ǖ 1990s-Present Day

Computer programming was


mainly utilised by universities,
the military and big
corporations during the ‘60s
and the ‘70s. A notable step
toward a more user-friendly,
or home user language, was
the development of BASIC
(Beginners All-purpose
Symbolic Instruction Code) in
the mid-sixties.

7KH,QWHUQHWDJHEURXJKWDZHDOWK
of new programming languages and
allowed people access to the tools and
knowledge needed to learn coding in a
better way. Not only could a user learn
how to code but they could freely share
their code and source other code to
improve their own.

7KHƬUVWWUXHFRPSXWHUFRGHZDV
Assembly Language (ASM) or
Regional Assembly Language. Admiral Grace Hopper was part of
$60ZDVVSHFLƬFWRWKH the team that developed the UNIVAC
architecture of the machine I computer and she eventually
it was being used on. In 1951 developed a compiler for it. In time,
programming languages fell under the compiler she developed became
the generic term Autocode. Soon COBOL (Common Business-oriented
ODQJXDJHVVXFKDV,3/)2575$1 Language), a computer language that’s
and ALGOL 58 were developed. still in use today.

&RGLQJ 3URJUDPPLQJ 11
Welcome, Future Coder

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.

12 &RGLQJ 3URJUDPPLQJ
Choosing a Programming Language

SQL SQL stands for Structured Query Language. SQL is a standard language
for accessing and manipulating databases. Although SQL is an ANSI
$PHULFDQ1DWLRQDO6WDQGDUGV,QVWLWXWH VWDQGDUGWKHUHDUHGLƪHUHQWYHUVLRQVRI
the SQL language. However, to be compliant, they all support at least the major
commands such as Select, Update and Delete in a similar manner.

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


LQWHUSUHWHGREMHFWRULHQWHGODQJXDJHZLWKƬUVWFODVV
functions. JavaScript runs on the client side of the web, that can be used to design
or program how the web pages behave on the occurrence of an event. JavaScript is
an easy to learn and also powerful scripting language, widely used for controlling
web page behaviour.

JAVA Java is the foundation for virtually every type of networked


application and is the global standard for developing enterprise
VRIWZDUHZHEEDVHGFRQWHQWJDPHVDQGPRELOHDSSV7KHWZRPDLQFRPSRQHQWV
of the Java platform are the Java Application Programming Interface (API) and the
Java Virtual Machine (JVM) that translates Java code into machine language.

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


EXLOGDYDULHW\RIVHFXUHDQGUREXVWDSSOLFDWLRQVWKDWUXQRQWKH1(7
Framework. You can use C# to create Windows client applications, XML Web services,
FOLHQWVHUYHUDSSOLFDWLRQVGDWDEDVHDSSOLFDWLRQVDQGPXFKPRUH7KHFXUO\EUDFH
syntax of C# will be instantly recognisable to anyone familiar with C, C++ or Java.

PYTHON Python is a widely used high level programming language used


for general purpose programming, created by Guido van
5RVVXPDQGƬUVWUHOHDVHGLQ$QLQWHUSUHWHGODQJXDJH3\WKRQKDVDGHVLJQ
philosophy that emphasises code readability and a syntax that allows programmers
WRH[SUHVVFRQFHSWVLQIHZHUOLQHVRIFRGH7KLVFDQPDNHLWHDVLHUIRUQHZ
programmers to learn.

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


language. It has imperative, object-oriented and generic programming
features. It was designed with a bias toward system programming and embedded,
UHVRXUFHFRQVWUDLQHGDQGODUJHV\VWHPVZLWKSHUIRUPDQFHHƯFLHQF\DQGƮH[LELOLW\
of use as its design highlights.

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


Matsumoto, blended parts of his favourite languages (Perl, Smalltalk,
(LƪHO$GDDQG/LVS WRIRUPDQHZODQJXDJH)URPLWVUHOHDVHLQ5XE\KDV
GUDZQGHYRWHGFRGHUVZRUOGZLGH5XE\LVVHHQDVDƮH[LEOHODQJXDJHHVVHQWLDO
SDUWVRI5XE\FDQEHUHPRYHGRUUHGHƬQHGDWZLOO([LVWLQJSDUWVFDQEHDGGHGWR

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


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

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


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

&RGLQJ 3URJUDPPLQJ 
Welcome, Future Coder

Creating a Coding
Platform
7KHWHUPn&RGLQJ3ODWIRUPoFDQVLJQLI\DW\SHRIKDUGZDUHRQZKLFK\RXFDQFRGH
a particular operating system, or even a custom environment that’s pre-built and
designed for easy game creation. In truth it’s quite a loose term, as a Coding Platform
can be a mixture of all of these ingredients, it’s simply down to which programming
language you intend to code in and what your end goals are.

Coding can be one of those experiences that sounds fantastic,


but is often confusing to tackle. After all, there’s a plethora
of languages to choose from, countless apps that will enable
\RXWRFRGHLQDVSHFLƬFRUUDQJHRIODQJXDJHVDQGDQHTXDOO\
huge amount of third-party software to consider. In addition, by
accessing the Internet, you will discover that there are countless
coding tutorials available for the language in which you’ve decided
you want to program, alongside even more examples of code. It’s
DOODOLWWOHWRRPXFKDWƬUVW

7KHWULFNLVWRVORZGRZQDQGWREHJLQZLWKQRWORRNWRRGHHSO\
into coding. Like all good projects, you need a solid foundation
on which to build your skillset and to have all the necessary tools
DYDLODEOHWRHQDEOH\RXWRFRPSOHWHWKHEDVLFVWHSV7KLVLVZKHUH
creating a coding platform comes in, as it will be your learning
IRXQGDWLRQZKLOH\RXEHJLQWRWDNH\RXUƬUVWWHQWDWLYHVWHSVLQWR
the wider world of coding.

HARDWARE SOFTWARE
Thankfully, coding at the In terms of software,
foundation level doesn’t most of the development
require specialist equipment, environments have the
or a top of the range, liquid tools that allow you to
hydrogen-cooled PC. If code, compile the code
you own a computer, no matter how basic, you can begin to and execute it, freely
learn how to code. Naturally, if the computer in question is a available to download and install. There are some specialist
&RPPRGRUHWKHQ\RXPD\KDYHVRPHGLƯFXOW\IROORZLQJD tools available that will cost, but at this level they’re not
modern language tutorial, but some of the best programmers necessary, so don’t be fooled into thinking you need to purchase
around today started on an 8-bit machine, so there’s hope yet. any extra software in order to start learning how to code.

You will need access to the Internet to download, install and 2YHUWLPH\RXPD\ƬQG\RXUVHOISURJUHVVLQJIURPWKH
update the coding development environment, alongside a mainstream development environment and using a collection
computer with Windows 10, macOS, or Linux, installed. You of your own, discovered, tools to write your code. It’s all
can use other operating systems, but these are the ‘big three’ personal preference in the end and as you become more
DQG\RXZLOOƬQGWKDWPRVWFRGHUHVRXUFHVDUHZULWWHQZLWK H[SHULHQFHG\RXZLOOVWDUWWRXVHGLƪHUHQWWRROVWRJHWWKH
one, or all, of these in mind. job done.

14 &RGLQJ 3URJUDPPLQJ
Creating a Coding Platform

OPERATING SYSTEMS VIRTUAL MACHINES


Windows 10 is the most widely used operating system in the A virtual machine is a piece of software that allows you to install a
world, so it’s natural that the vast majority of coding tools are IXOO\ZRUNLQJRSHUDWLQJV\VWHPZLWKLQWKHFRQƬQHVRIWKHVRIWZDUH
written for Microsoft’s leading operating system. However, LWVHOI7KHLQVWDOOHG26ZLOODOORFDWHXVHUGHƬQHGUHVRXUFHVIURPWKH
don’t discount macOS and especially Linux. host computer, providing memory, hard drive space etc., as well as
sharing the host computer’s Internet connection.
macOS users enjoy an equal number of coding tools to their
:LQGRZVFRXQWHUSDUWV,QIDFW\RXZLOOSUREDEO\ƬQGWKDWD The advantage of a virtual machine is that you can work with
lot of professional coders use a Mac over a PC, simply because /LQX[IRUH[DPSOHZLWKRXWLWDƪHFWLQJ\RXUFXUUHQWO\LQVWDOOHG
of the fact that the Mac operating system is built on top of host OS. This means that you can have Windows 10 running and
Unix (the command-line OS that powers much of the world’s launch your virtual machine client, boot into Linux and use all
ƬOHV\VWHPVDQGVHUYHUV 7KLV8QL[OD\HUOHWV\RXWHVWSURJUDPV the functionality of Linux, while still being able to use Windows.
in almost any language without using a specialised IDE.

This, of course, makes it a fantastic coding platform, as you can


However, Linux is, by far and away, one of the most popular KDYHGLƪHUHQWLQVWDOODWLRQVRIRSHUDWLQJV\VWHPVUXQQLQJIURP
and important coding operating systems available. Not only WKHKRVWFRPSXWHUZKLOHXVLQJGLƪHUHQWFRGLQJODQJXDJHV
does it have a Unix-like backbone, it’s also free to download, You can test your code without fear of breaking your host OS
install and use and comes with most of the tools necessary to DQGLWoVHDV\WRUHWXUQWRDSUHYLRXVFRQƬJXUDWLRQZLWKRXWWKH
start learning how to code. Linux powers most of the servers need to reinstall everything again.
that make up the Internet. It’s used on nearly all of the top
VXSHUFRPSXWHUVDVZHOODVVSHFLƬFDOO\LQRUJDQLVDWLRQVVXFK Virtualisation is the key to most big companies now. You
as NASA, CERN and the military, it also forms the base of ZLOOSUREDEO\ƬQGUDWKHUWKDQKDYLQJDVLQJOHVHUYHUZLWKDQ
Android-powered devices, smart TVs and in-car systems. Linux, installation of Windows Server, for example, the IT team have
as a coding platform, is an excellent idea and it can be installed instead opted for a virtualised environment whereby each
LQVLGHDYLUWXDOPDFKLQHZLWKRXWHYHUDƪHFWLQJWKHLQVWDOODWLRQ Windows Server instance is a virtual machine running from
of Windows or macOS. several powerful machines. This cuts down on the number
of physical machines, allows the team to better manage
resources and enables them to deploy an entire server
dedicated to a particular task in a fraction of the time.

THE RASPBERRY PI
If you haven’t already heard of the Raspberry Pi, then we
YOUR OWN CODING PLATFORM
suggest you head over to www.raspberrypi.org and check Whichever method you choose, remember that your coding
it out. In short, the Raspberry Pi is a small, fully functional platform will probably change, as you gain experience
computer. It comes with its own customised, Linux- and favour one language over another. Don’t be
based operating system that’s pre-installed with afraid to experiment along the way, as
everything you need to start learning how to you will eventually create your
code in Python, C++, Scratch and more. own unique platform that
can handle all the code
Costing around £35, it’s incredibly you enter into it.
cheap and allows you to utilise
GLƪHUHQWKDUGZDUHLQ
the form of robotics and
electronics projects, as well
DVRƪHULQJDFRPSOHWHGHVNWRS
experience. Although not the most
powerful computing device in the world, the
Raspberry Pi has a lot going for it, especially in terms
of being one of the best coding platforms available.

&RGLQJ 3URJUDPPLQJ 
Introducing C++

C++ is an amazing programming


language. Most of what you see in
front of you when you power up your
computer, regardless of whether
you’re using Windows, macOS or
Linux, is created using C++. Being able
to code in C++ will open a whole new
world for you, in terms of desirable
professional skills and the ability to
code amazing apps and games.

&LVDQHƯFLHQWDQGSRZHUIXO
language that’s used to develop
operating systems, applications,
games and much more. It’s used
in science, engineering, banking,
education, the space industry, and
much more.

18 Why C++?
20 C++ Facts & Figures
22 Equipment You Will Need
24 Structure of C++ Code
26 How to Set Up C++ in Windows
28 How to Set Up C++ on a Mac
30 How to Set Up C++ in Linux
32 Other C++ IDEs to Install

16 &RGLQJ 3URJUDPPLQJ
Index

&RGLQJ 3URJUDPPLQJ 17
Introducing C++

Why C++?
C++ is one of the most popular programming languages available today. Originally
called C with Classes, the language was renamed to 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 both the complexity of the language 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 using C++. For example, all of Adobe’s major applications, such as
computing, C++, or rather C with Classes, was the brainchild of 3KRWRVKRS,Q'HVLJQDQGVRRQDUHGHYHORSHGLQ&<RXZLOOƬQG
Danish computer scientist Bjarne Stroustrup, while working on that the browser you use to surf the Internet is written in C++, as
his Ph.D. thesis. Stroustrup’s plan was to further the original C ZHOODV:LQGRZV0LFURVRIW2ƯFHDQGWKHEDFNERQHWR*RRJOHoV
language, which had been widely used since the early seventies. search engine. Apple’s macOS is written largely in C++ (with some
other languages mixed in depending on the function), and the likes
C++ proved to be popular among the developers of the 80s, since of NASA, SpaceX, and even CERN use C++ for various applications,
it was a much easier environment with which to get to grips, programs, controls, and umpteen other computing tasks.
and, more importantly, it was 99% compatible with the original C
language. This meant that, beyond the mainstream computing labs, As well as being an easier addition to the core C language, C++ is
regular people who didn’t have access to the mainframes and large DOVRH[WUHPHO\HƯFLHQWDQGSHUIRUPVZHOODFURVVWKHERDUG7KLV
computing data centres could use it. higher level of performance over other languages, such as Python,
BASIC and such, makes it an ideal development environment for
C++’s impact in the digital world is immense. Many of the programs, modern computing; hence the aforementioned companies using it
applications, games, and even operating systems are coded so widely.

C++ code is much faster than other


programming languages.

18 &RGLQJ 3URJUDPPLQJ
Why C++?

Microsoft’s Visual Studio is a great, free


environment in which to learn C++.

C++ puts the developer in a much wider world of coding. By improvements to the engine, or when creating a new game, if
PDVWHULQJ&\RXZLOOƬQG\RXUVHOIEHLQJDEOHWRGHYHORSFRGHIRU the developers want to add something that the engine can’t do,
WKHOLNHVRI0LFURVRIW$SSOHDQGVRRQ*HQHUDOO\&GHYHORSHUV they will use C++ to create the new content or link between two
enjoy a higher salary than programmers of some other languages, GLƪHUHQWHQJLQHV7KHHQGUHVXOWRIFRXUVHLVDJDPHWKDWFRQWDLQV
and, due to its versatility, the C++ programmer can move between the latest graphical technology, while being seamlessly bound
MREVDQGFRPSDQLHVZLWKRXWWKHQHHGWRUHOHDUQDQ\WKLQJVSHFLƬF together with some pretty clever C++ coding.

You will discover, as you become a more advanced coder, that many *HWWLQJWRXVH&LVTXLWHHDV\DOO\RXQHHGLVWKHULJKWVHWRIWRROV
of the developers in various coding jobs around the world tend to in which to communicate with the computer in C++, and you can
use pre-designed development engines. For example, when creating start your journey. A C++ IDE is free of charge, even the immensely
games, the likes of Bethesda, the team behind Oblivion and Skyrim, powerful Visual Studio from Microsoft is freely available to
utilise a 3D game engine called The Creation Engine. This enables download and use. You can get into C++ from any operating system,
the team to quickly create animations, characters, items, terrains, be it macOS, Linux, Windows, or even mobile platforms.
rooms, and just about everything else you’d see in the game. The
HQJLQHLWVHOIKDVEHHQPRGLƬHGWRPDNHWKHPRVWRIWKHFXUUHQW So, to answer the question of Why C++, the answer is because it’s fast,
graphics card hardware, and computer or console processing HƯFLHQWDQGGHYHORSHGE\PRVWRIWKHDSSOLFDWLRQV\RXUHJXODUO\
power. These engines are mostly written in C++, and when making use. It’s cutting edge, and a fantastic language to have mastered.

Indeed, the operating system


you’re using is written in C++.

&RGLQJ 3URJUDPPLQJ 19
Introducing C++
C++ Facts & Figures
C++ is one of the top
programming languages
in the industry. It’s quick,
powerful, and used by
nearly every major tech
and gaming company in
the world. Here’s some
interesting facts about
the rather wonderful C++.
C++ is
one of the
predominant
programming
languages for the
development of all
kinds of technical
NASA, CERN, and commercial
MICROSOFT, software.
ORACLE, PAYPAL,
LINKEDIN, AMAZON AND
THE MILITARY USE C++.

C++ IS USED FREQUENTLY C++ has


IN ANIMATION PROCESSES. LQƮXHQFHGRWKHU
programming
3D ANIMATION, languages, such as
MODELLING, C# and Java.
AND
SIMULATIONS
ALL UTILISE C++.

A lot of the
Linux operating
system is coded
using C++, therefore
you could say that most
of the world’s Internet
hosting servers are
available thanks to C++.

SUPERCOMPUTING USES C++ CODE More than 70% of all


TO CALCULATE VAST AMOUNTS OF trading is known as
High Frequency Trading
'$7$,1&/8',1*7+(1$6$Ǖ%$6(' (HFT), and the software
SUPERCOMPUTING FARM THAT RUNS responsible is written in
C++ to make use of its
SIMULATIONS OF THE UNIVERSE.
high speed.

20 &RGLQJ 3URJUDPPLQJ
Sources: ITJobsWatch,
Google, Quora, Stack C++ Facts & Figures
Exchange, eduCBA,
6WDFN2YHUƮRZ
stackShare, The Xbox
AppDynamics operating system
uses C++ as its
backbone.

Gaming is one of the


biggest users of C++.
It handles the
Many database applications complexities of 3D games,
are built using C++, such supports multiplayer Google Chrome, Mozilla’s
as MySQL, it’s also used options, and enables Firefox, and even Microsoft’s
by Wikipedia, Yahoo and intensive CPU and Edge web browsers are
YouTube. GPU hardware coded in C++.
functions.

90
THE
C++ is
used in computer
networking as the
main code behind the
th
Programmable Logic Most of Adobe’s
PERCENTILE SALARY stable of products
Controller, connecting )25$8.Ǖ%$6('& are developed
servers, processors, other DEVELOPER IS using C++.

£120,000
hardware, and
even robotics.

MRI scanning
machines and
Windows 95, 98, 2000, Computer Aided Design The Unreal 4 Engine,
XP, 7, 8.1 and 10, as well as all use C++ to help with which is coded in C++,
0LFURVRIW2ƯFHXVH& the enhanced imagery is used for hundreds
as the backbone programming produced by these of games, including
language of choice.
systems. Fortnite.

RADAR
PROCESSING
TECHNOLOGIES
USE C++, AS
WELL AS
ADVANCED
MISSILE
DETECTION
SYSTEMS.
FLIGHT CONTROL SYSTEMS IN
MODERN AIRCRAFT, INCLUDING
MILITARY AIRCRAFT, USE C++.

&RGLQJ 3URJUDPPLQJ 21
Introducing C++

Equipment You
Will Need
You don’t need to invest a huge amount of money in order to learn C++, and you
don’t need an entire computing lab at your disposal either. Providing you have a fairly
modern computer, everything else is freely available.

C++ SETUPS
As most, if not all, operating systems have C++ at their code, it stands to reason that you can learn to program in C++ no
matter what OS you’re currently using.

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
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 enhancements for Windows 10.

COMPILER
A compiler is a program that converts 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 use 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
WRWKH,QWHUQHWLWoVH[WUDRUGLQDULO\GLƯFXOW<RXZLOOQHHGWRLQVWDOOWKHUHOHYDQW
software, keep it up to date, install any extras or extensions, and look for help when
coding. All of which require access to the Internet.

TIME AND PATIENCE


<RXoUHJRLQJWRQHHGWRVHWDVLGHVLJQLƬFDQWWLPHWRVSHQGRQOHDUQLQJKRZWRFRGH
in C++. Sadly, unless you’re a genius, it’s not going to happen overnight, or even in a
week. A good C++ coder has spent many years honing their craft, so be patient, start
small and keep learning.

22 &RGLQJ 3URJUDPPLQJ
Equipment You Will Need

OS SPECIFIC NEEDS
C++ will work in any operating system; however, getting all the necessary pieces together can be confusing to a newcomer. Here’s
VRPH26VSHFLƬFVIRU&

LINUX WINDOWS
Linux users are lucky in that they already have a compiler and As we’ve mentioned previously, one 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 to type out your C++ code, when it’s saved with Code::Blocks, which is kept regularly up to date with a new
a .cpp extension, use g++ to compile it. release twice yearly, or so. Otherwise, Windows users can
HQWHUWKHLUFRGHLQ1RWHSDGWKHQFRPSLOHLWZLWK0LQ*:s
which Code::Blocks uses.

RASPBERRY PI MAC
The Raspberry Pi’s operating Mac owners will need to
system is Raspbian, which is download and install Xcode,
Linux based. Therefore, you’re in order to compile their
able to write your code out C++ code natively. Other
using a text editor and 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.

&RGLQJ 3URJUDPPLQJ 23
Introducing C++

Structure of C++ Code


C++ is an amazing programming language to learn. If your dream is to become a games
designer, or work at the cutting edge of science or engineering technology, then being
able to code in C++ is a must. Remember, you’re never too old to learn how to code.

#INCLUDE <C++ IS ACE!>


As you learn the basics of programming, you will begin to understand the structure of a program. The commands may be
GLƪHUHQWEXW\RXZLOOVWDUWWRVHHKRZWKHFRGHZRUNV

C++ #INCLUDE
The structure of a C++ program
Danish student Bjarne can look complex, but once you
Stroustrup invented C++ in get familiar with it you’ll begin to
1979, as a part of his Ph.D. VHHKRZLWƮRZV(YHU\&FRGH
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++.

,170$,1Ǔǔ
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 lies within the main body of
the code.

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

24 &RGLQJ 3URJUDPPLQJ
Structure of C++ Code

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 are to be inserted into the
are they there? Comments are designed to help you, or another std::cout statement. In this case, they are the words ‘Hello World’,
programmer looking at your code, explain what’s going on. There which are to be displayed on the screen when you compile and
are two types of comment: /* covers multiple line comments, // a execute the code.
single line.

STD OUTPUTS
In C++, STD means Standard. It’s a part of the Standard Namespace Leading on, (“Hello World!”) is the part that we want to appear on
LQ&ZKLFKFRYHUVDQXPEHURIGLƪHUHQWVWDWHPHQWVDQG the screen when the code is executed. You can enter whatever you
commands. You can leave the std part out of a code, but it must be like, as long as it’s inside the quotation marks. The brackets aren’t
declared at the start with: using namespace std. needed, but some compilers insist on them. The \n part indicates a
new line is to be inserted.

COUT $1'ǜ
In this example we’re using cout, which is a part of the Standard Finally you will notice that lines within a function code block
1DPHVSDFHsKHQFHZK\LWoVWKHUHDV\RXoUHDVNLQJ&WRXVHLWIURP (except comments) end with a semicolon. This marks the end of
that particular namespace. Cout means Character OUTput, which the statement, and all statements in C++ must have one at the end
displays, or prints, something to the screen. If we leave std:: out we or 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.

&RGLQJ 3URJUDPPLQJ 25
Introducing C++

How to Set Up
C++ in Windows
Windows users have a wealth of choice when it comes to programming in C++. There
are loads of IDEs and compilers available, including Visual Studio from Microsoft.
However, in our opinion, the best C++ IDE to begin with is Code::Blocks.

CODE::BLOCKS
Code::Blocks is a free C++, C and Fortran IDE that is feature rich and easily extendible with plugins. It’s easy to use, comes with
a compiler and has a vibrant community behind it too.

STEP 1 Start by visiting the Code::Blocks download site, at STEP 3 :KHQ\RXoYHORFDWHGWKHƬOHFOLFNRQWKH


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 GRZQORDGQRWLƬFDWLRQZLQGRZDSSHDUVFOLFNRQ6DYH)LOHWRVWDUW
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.
GLƪHUHQFHLVWKDWWKHPLQJZVHWXSYHUVLRQLQFOXGHVD&FRPSLOHU
DQGGHEXJJHUIURP7'0*&& DFRPSLOHUVXLWH 

26 &RGLQJ 3URJUDPPLQJ
How to Set Up C++ in Windows

STEP 5 Next choose an install location for the Code::Blocks STEP 8 There’s a lot you can do in Code::Blocks, so you need
ƬOHV,WoV\RXUFKRLFHEXWWKHGHIDXOWLVJHQHUDOO\ WRGLJLQDQGƬQGDJRRG&WXWRULDOWRKHOS\RX
VXƯFLHQW XQOHVV\RXKDYHDQ\VSHFLDOUHTXLUHPHQWVRIFRXUVH  get the most from it. However, to begin with, click on File > New >
:KHQ\RXFOLFN1H[WWKHLQVWDOOEHJLQVZKHQLWoVƬQLVKHGD Empty File. This creates a new, blank window for you to type in.
QRWLƬFDWLRQSRSVXSDVNLQJ\RXLI\RXZDQWVWDUW&RGH%ORFNVQRZ
so click Yes.

STEP 6 7KHƬUVWWLPH&RGH%ORFNVORDGVLWUXQVDQ STEP 9 In the new window, enter the following:


autodetect for any C++ compilers you may already
have installed on your system. If you don’t have any, click on the #include <iostream>
ƬUVWGHWHFWHGRSWLRQ*18*&&&RPSLOHUDQGFOLFNWKH'HIDXOW
Int main()
button to set it as the system’s C++ compiler. Click OK when you’re
{
ready to continue.
0\¿UVW&SURJUDP
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).
WKHGHIDXOWDSSOLFDWLRQIRU&ƬOHV<RXKDYHWZRRSWLRQVWROHDYH Code::Blocks changes the view to colour code according to C++
HYHU\WKLQJDVLWLVRUDOORZ&RGH%ORFNVWRDVVRFLDWHDOO&ƬOH 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
DVVRFLDWH&RGH%ORFNVZLWKHYHU\VXSSRUWHGƬOHW\SH yellow cog.

&RGLQJ 3URJUDPPLQJ 27
Introducing C++

How to Set Up C++


on a Mac
To begin C++ coding on a Mac you can use Apple’s own developer platform: Xcode. This
is a free, full featured IDE that’s designed to create native Apple apps. However, it’s
also able to be used to create C++ code relatively easily.

XCODE
Apple’s Xcode is primarily designed for users to develop apps for macOS, iOS, tvOS and watchOS applications in Swift or
Objective-C, but we can use it for C++ too.

STEP 1 Start by opening the App Store on your Mac, Apple STEP 3 :KHQ\RXoUHUHDG\FOLFNRQWKH*HWRUFORXGLFRQ
Menu > App Store. In the Search box enter Xcode, button which will install the Xcode app. Enter your
DQGSUHVV5HWXUQ7KHUHZLOOEHPDQ\VXJJHVWLRQVƬOOLQJWKH$SS Apple ID, and Xcode will begin to download and install. It may take
6WRUHZLQGRZEXWLWoVƬUVWRSWLRQ;FRGHWKDW\RXQHHGWRFOLFNRQ some time depending on the speed of your Internet connection, as
;FRGHLVLQH[FHVVRI*%

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 will begin to install
additional components.

28 &RGLQJ 3URJUDPPLQJ
How to Set Up C++ on a Mac

STEP 5 With everything now installed, including the STEP 8 7KHQH[WVWHSDVNVZKHUHWRFUHDWHD*LW5HSRVLWRU\


additional components, Xcode will launch 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
WKDW\RXoYHZRUNHGRQsDOWKRXJKIRUDIUHVKLQVWDOOWKLVZLOOEHEODQN you’ve done all that, you can start to code. The left-hand pane
GHWDLOVWKHƬOHVXVHGLQWKH&SURJUDP\RXoUHFRGLQJ&OLFNRQWKH
PDLQFSSƬOHLQWKHOLVW

STEP 6 Start by clicking on Create New Xcode Project, this STEP 9 You will notice that Xcode has automatically
opens a template window to choose which platform completed a basic Hello World program for you.
you’re developing code for. Click the macOS tab, then click the 7KHGLƪHUHQFHVKHUHDUHWKDWWKHLQWPDLQ IXQFWLRQQRZFRQWDLQV
Command Line Tool option. Click Next to continue. PXOWLSOHIXQFWLRQVDQGWKHOD\RXWLVVOLJKWO\GLƪHUHQW7KLVLVMXVW
Xcode utilising the content that’s available to your Mac.

STEP 7 )LOOLQDOOWKHƬHOGVEXWHQVXUHWKDWWKH/DQJXDJH STEP 10 When you want to run the code, click on Product >
option at the bottom is set to C++. Simply choose Run. You may be asked to enable Developer Mode
LWIURPWKHGURSGRZQOLVW:KHQ\RXoYHƬOOHGLQWKHƬHOGVDQG on the Mac, this is to authorise Xcode to perform functions without
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 will be displayed at the bottom of the Xcode window.

&RGLQJ 3URJUDPPLQJ 29
Introducing C++

How to Set Up C++


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

LINUX++
7KHUHDUHPDQ\GLƪHUHQWYHUVLRQVRI/LQX[DYDLODEOHIRUWKLVH[DPSOHZHoUHXVLQJRQHRIWKHPRUHSRSXODUGLVWULEXWLRQV/LQX[
Mint. However, these steps will work in any Debian-based Linux.

STEP 1 7KHƬUVWVWHSZLWKHQVXULQJ/LQX[LVUHDG\IRU\RXU STEP 3 Amazingly, that’s it. Everything is all ready for you
C++ code is check the system and software are WRVWDUWFRGLQJ+HUHoVKRZWRJHW\RXUƬUVW&
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, it’s:
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.
{
0\¿UVW&SURJUDP
std::cout << “Hello World!\n”;

30 &RGLQJ 3URJUDPPLQJ
How to Set Up C++ in Linux

STEP 5 When you’ve entered your code, click File > Save As STEP 8 %HIRUH\RXFDQH[HFXWHWKH&ƬOH\RXQHHGWR
and choose a folder where you want to save your compile it. In Linux it’s common to use g++, an open
SURJUDP1DPHWKHƬOHDVKHOORZRUOGFSSRUDQ\RWKHUQDPHMXVWDV 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. &ƬOHJRWRWKH7HUPLQDOHQWHUJKHOORZRUOGFSS and
press return.

STEP 6 7KHƬUVWWKLQJ\RXFDQVHHLVWKDW;HGKDV STEP 9 There will be a brief pause as the code is compiled
DXWRPDWLFDOO\UHFRJQLVHGWKLVDVD&ƬOHVLQFHWKH by g++ and providing there are no mistakes or
ƬOHH[WHQVLRQLVQRZVHWWRFSS7KHFRORXUFRGLQJLVSUHVHQWLQWKH errors in the code you are returned to the command prompt. The
FRGHDQGLI\RXRSHQXSWKHƬOHPDQDJHU\RXFDQDOVRVHHWKDWWKH FRPSLOLQJRIWKHFRGHKDVFUHDWHGDQHZƬOH,I\RXHQWHUls into the
ƬOHoVLFRQKDV&VWDPSHGRQLW 7HUPLQDO\RXFDQVHHWKDWDORQJVLGH\RXU&ƬOHLVDRXW

STEP 7 With your code now saved, drop into the Terminal STEP 10 7KHDRXWƬOHLVWKHFRPSLOHG&FRGH7RUXQWKH
again. You need to navigate to the location of code enter: DRXW and press Return. The words
WKH&ƬOH\RXoYHMXVWVDYHG2XUH[DPSOHLVLQWKH'RFXPHQWV ‘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 JKHOORZRUOGFSSRKHOORZRUOG. This creates an output
be entered correctly. ƬOHFDOOHGKHOORZRUOGZKLFKFDQEHUXQZLWKKHOORZRUOG.

&RGLQJ 3URJUDPPLQJ 31
Introducing C++

Other C++ IDEs to Install


,I\RXZDQWWRWU\DGLƪHUHQWDSSURDFKWRZRUNLQJZLWK\RXU&FRGHWKHQWKHUHDUH
SOHQW\RIRSWLRQVDYDLODEOHWR\RX:LQGRZVLVWKHPRVWSUROLƬFSODWIRUPIRU&,'(V
but there are plenty for Mac and Linux users too.

DEVELOPING C++
+HUHDUHWHQJUHDW&,'(VWKDWDUHZRUWKORRNLQJLQWR<RXFDQLQVWDOORQHRUDOORIWKHPLI\RXOLNHEXWƬQGWKHRQHWKDW
works best for you.

ECLIPSE (FOLSVHLVDKXJHO\SRSXODU&,'(WKDWRƪHUV 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 SRZHUIXO<RXFDQƬQGRXWPRUHLQIRUPDWLRQDVZHOODVKRZWR
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 7KH*1$73URJUDPPLQJ6WXGLR *36 LVDSRZHUIXO 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
:LQGRZV0DF/LQX[DQGHYHQWKH5DVSEHUU\3L<RXFDQƬQGLWDW dynamic and static libraries. Find out more at www.netbeans.org/
www.adacore.com/download. features/cpp/index.html.

32 &RGLQJ 3URJUDPPLQJ
Other C++ IDEs to Install

VISUAL STUDIO Microsoft’s Visual Studio is a ANJUTA The Anjuta DevStudio is a Linux-only IDE that
mammoth C++ IDE that allows you features some of the more advanced features you
to create applications for Windows, Android, iOS and the web. The ZRXOGQRUPDOO\ƬQGLQDSDLGVRIWZDUHGHYHORSPHQWVWXGLR7KHUHoV
Community version is free to download and install but the other D*8,GHVLJQHUVRXUFHHGLWRUDSSZL]DUGLQWHUDFWLYHGHEXJJHUDQG
YHUVLRQVDOORZDIUHHWULDOSHULRG*RWRwww.visualstudio.com/ to PXFKPRUH*RWRwww.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 WH[WHGLWRULQWHJUDWHGGHEXJJHUDQGDFRQƬJXUDEOHZRUNEHQFKWR
SODWIRUP,WoVQRWIUHHEXWWKHUHLVDWULDOSHULRGRQRƪHUEHIRUH 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.
VRPHWKLQJGLƪHUHQWwww.bloodshed.net/devcpp.html.

&RGLQJ 3URJUDPPLQJ 33
Coding with C++

This section contains the building


block of C++, from learning how to
FRPSLOHDQGH[HFXWH\RXUƬUVW&
code, through to developing user
interaction. There’s a lot to learn with
C++, but these tutorials, tips and tricks
will lead you in the right direction.

&LVGLƪHUHQWWRWKHRWKHU
programming languages in this book,
and it’s continually evolving as the
applications that require it are forever
improving. If you know C++, then
you’re well on your way to becoming
a much sought-after coder and a vital
member of the coding community.

36 Your First C++ Program


38 Compile and Execute
40 Using Comments
42 Variables
44 Data Types
46 Strings
48 C++ Maths
50 User Interaction

34 &RGLQJ 3URJUDPPLQJ
Index

&RGLQJ 3URJUDPPLQJ 35
Coding with C++

Your First C++ Program


You may have followed the Mac and Linux examples previously but you’re going to be
working exclusively in Windows and Code::Blocks from here on. Let’s begin by writing
\RXUƬUVW&SURJUDPDQGWDNLQJWKHƬUVWVPDOOVWHSLQWRDODUJHUFRGLQJZRUOG

+(//2:25/'
,WoVWUDGLWLRQDOLQSURJUDPPLQJIRUWKHƬUVWFRGHWREHHQWHUHGWRRXWSXWWKHZRUGVn+HOOR:RUOGoWRWKHVFUHHQ,QWHUHVWLQJO\
this dates back to 1968 using a language called BCPL.

67(3 We’re going to use Windows 10 and the excellent 67(3 At the moment it doesn’t look like much, and
IDE Code::Blocks for the rest of the C++ code and it makes even less sense, but we’ll get to that
tutorials in this book. Begin by launching Code::Blocks. When open, LQGXHFRXUVH1RZFOLFNRQ)LOH!6DYH)LOH$V&UHDWHRUƬQGD
click on File > New > Empty File or press Ctrl+Shift+N on the keyboard. suitable location on your hard drive and in the File Name box, call
LWKHOORZRUOGFSS&OLFNWKH6DYHDVW\SHER[DQGVHOHFW&&ƬOHV
Click the Save button.

67(3 Now you can see a blank screen, with the tab 67(3 You can see that Code::Blocks has now changed
labelled *Untitled1, and the number one in the top WKHFRORXUFRGLQJUHFRJQLVLQJWKDWWKHƬOHLVQRZ
left of the main Code::Blocks window. Begin by clicking in the main C++ code. This means that code can be auto-selected from the
window, so the cursor is next to the number one, and entering: Code::Blocks repository. Delete the #include <iostream> line and
re-enter it. You can see the auto-select boxes appearing.
#include <iostream>

36 &RGLQJ 3URJUDPPLQJ
Your First C++ Program

67(3 Auto-selection of commands is extremely handy and 67(3 Note again the colour coding change. Press Return at
cuts out potential mistyping. Press Return to get to the end of the previous step’s line, and then enter:
line 3, then enter:
std::cout << “Hello, world!\n”;
int main()
Note: there’s no space between the brackets.

67(3 On the next line below int main(), enter a curly bracket: 67(3 Just as before, Code::Blocks auto-completes the
code you’re entering, including placing a closing
{
VSHHFKPDUNDVVRRQDV\RXHQWHUWKHƬUVW'RQoWIRUJHWWKH
This can be done by pressing Shift and the key to the right of P on an VHPLFRORQDWWKHHQGRIWKHOLQHWKLVLVRQHRIWKHPRVWLPSRUWDQW
English UK keyboard layout. elements to a C++ program and we’ll tell you why in the next
section. For now, move the cursor down to the closing curly bracket
and press Return.

67(3 Notice that Code::Blocks has automatically created 67(3 That’s all you need to do for the moment. It may
a corresponding closing curly bracket a couple of not look terribly amazing but C++ is best absorbed
lines below, linking the pair, as well as a slight indent. This is due to in small chunks. Don’t execute the code at the moment as you need
the structure of C++ and it’s where the meat of the code is entered. WRORRNDWKRZD&SURJUDPLVVWUXFWXUHGƬUVWWKHQ\RXFDQEXLOG
Now enter: DQGUXQWKHFRGH)RUQRZFOLFNRQ6DYHWKHVLQJOHƮRSS\GLVFLFRQ
0\¿UVW&SURJUDP

&RGLQJ 3URJUDPPLQJ 
Coding with C++

Compile and Execute


<RXoYHFUHDWHG\RXUƬUVW&SURJUDPDQG\RXQRZXQGHUVWDQGWKHEDVLFVEHKLQGWKH
structure of one. Let’s actually get things moving and compile and execute, or run if
you prefer, the program and see how it looks.

*5((7,1*6)520&
Compiling and executing C++ code from Code::Blocks is extraordinarily easy; it’s just a matter of clicking an icon and seeing
WKHUHVXOW+HUHoVKRZLWoVGRQH

67(3 Open Code::Blocks, if you haven’t already, and 67(3 Start by clicking on the Build icon, the yellow cog.
load up the previously saved Hello World code you At this point, your code has now been run through
created. Ensure that there are no visible errors, such as missing the Code::Blocks compiler and checked for any errors. You can see
semicolons at the end of the std::cout line. the results of the Build by looking to the bottom window pane. Any
messages regarding the quality of the code are displayed here.

67(3 If your code is looking similar to the one in our 67(3 Now click on the Run icon, the green play button.
screenshot, then look to the menu bar along the top A command line box appears on your screen
of the screen. Under the Fortran entry in the topmost menu you can displaying the words: Hello, world!, followed by the time it’s taken
see a group of icons: a yellow cog, green play button and a cog/play to execute the code, and asking you press a key to continue. Well
button together. These are Build, Run, Build and Run functions. GRQH\RXMXVWFRPSLOHGDQGH[HFXWHG\RXUƬUVW&SURJUDP

38 &RGLQJ 3URJUDPPLQJ
Compile and Execute

67(3 Pressing any key in the command line box closes it, 67(3 Create a deliberate error in the code. Remove the
returning you to Code::Blocks. Let’s alter the code semicolon from the cout line, so it reads:
slightly. Under the #include line, enter:
cout << “Hello, world!\n”
XVLQJQDPHVSDFHVWG
7KHQGHOHWHWKHVWGSDUWRIWKH&RXWOLQHOLNHVR
cout << “Hello, world\n”;

67(3 In order to apply the new changes to the code, you 67(3 Now click the Build and Run icon again to apply the
need to re-compile, build, and run it again. This time, changes to the code. This time Code::Blocks refuses
however, you can simply click the Build/Run icon, the combined to execute the code, due to the error you put in. In the Log pane at
yellow cog and green play button. the bottom of the screen you are informed of the error, in this case:
([SHFWHGnoEHIRUHn`oWRNHQLQGLFDWLQJWKHPLVVLQJVHPLFRORQ

67(3 Just as we mentioned in the previous pages, you 67(3 Replace the semicolon and under the cout line,
don’t need to have std::cout if you already declare enter a new line to your code:
XVLQJQDPHVSDFHVWGDWWKHEHJLQQLQJRIWKHFRGH:HFRXOGKDYH
FRXW³$QGJUHHWLQJVIURP&?Q´
easily clicked the Build/Run icon to begin with but it’s worth going
through the available options. You can also see that by building and The \n simply adds a new line under the last line of outputted text.
UXQQLQJWKHƬOHKDVEHHQVDYHG Build and Run the code, to display your handiwork.

&RGLQJ 3URJUDPPLQJ 39
Coding with C++

Using Comments
While comments may seem like a minor element to the many lines of code that
combine to make a game, application or even an entire operating system, in actual fact
they’re probably one of the most important factors.

7+(,03257$1&(2)&200(17,1*
Comments inside code are basically human readable descriptions equalling zero is something that drastically changes the program for
that detail what the code is doing at that particular point. They don’t the user, such as, they’ve run out of lives, then it certainly needs to
sound especially important but code without comments is one of commented on.
the many frustrating areas of programming, regardless of whether
you’re a professional or just starting out. Even if the code is your own, you should write comments as if you
were going to publicly share it with others. This way you can return
In short, all code should be commented in such a manner as to to that code and always understand what it was you did or where it
HƪHFWLYHO\GHVFULEHWKHSXUSRVHRIDOLQHVHFWLRQRULQGLYLGXDO was you went wrong or what worked brilliantly.
elements. You should get in to the habit of commenting as much as
possible, by imagining that someone who doesn’t know anything Comments are good practise and once you understand how to add a
about programming can pick up your code and understand what it’s comment where needed, you soon do it as if it’s second nature.
going to do simply by reading your comments.

In a professional environment, comments are vital to the success


of the code and ultimately, the company. In an organisation, many
programmers work in teams alongside engineers, other developers,
hardware analysts and so on. If you’re a part of the team that’s
writing a bespoke piece of software for the company, then your
comments help save a lot of time should something go wrong, and
another team member has to pick up and follow the trail to pinpoint
the issue.

3ODFH\RXUVHOILQWKHVKRHVRIVRPHRQHZKRVHMRELWLVWRƬQGRXW
what’s wrong with a program. The program has in excess of 800,000
OLQHVRIFRGHVSUHDGDFURVVVHYHUDOGLƪHUHQWPRGXOHV<RXFDQVRRQ
appreciate the need for a little help from the original programmers
in the form of a good comment.

The best comments are always concise


and link the code logically, detailing what
happens when the program hits this line
or section. You don’t need to comment on
every line. Something along the lines of: if
x==0 doesn’t require you to comment that if x
HTXDOV]HURWKHQGRVRPHWKLQJWKDWoVJRLQJ
to be obvious to the reader. However, if x

 &RGLQJ 3URJUDPPLQJ
Using Comments

&&200(176
&RPPHQWLQJLQ&LQYROYHVXVLQJDGRXEOHIRUZDUGVODVKnoRUDIRUZDUGVODVKDQGDQDVWHULVNn o<RXoYHDOUHDG\VHHQVRPH
brief examples but this is how they work.

67(3 Using the Hello World code as an example, you can 67(3 Be careful when commenting, especially with block
HDVLO\FRPPHQWRQGLƪHUHQWVHFWLRQVRIWKHFRGH comments. It’s very easy to forget to add the closing
using the double forward slash: asterisk and forward slash and thus negate any code that falls inside
the comment block.
0\¿UVW&SURJUDP
cout << “Hello, world!\n”;

67(3 However, you can also add comments to the end 67(3 Obviously if you try and build and execute the
of a line of code, to describe in a better way what’s code it errors out, complaining of a missing curly
going on: EUDFNHWn`oWRƬQLVKRƪWKHEORFNRIFRGH,I\RXoYHPDGHWKH
error a few times, then it can be time consuming to go back and
FRXW³+HOORZRUOG?Q´7KLVOLQHRXWSXWVWKH
rectify. Thankfully, the colour coding in Code::Blocks helps identify
words ‘Hello, world!’. The \n denotes a new line.
comments from code.
Note, you don’t have to put a semicolon at the end of a comment.
This is because it’s a line in the code that’s ignored by the compiler.

67(3 You can comment out several lines by using the 67(3 If you’re using block comments, it’s good practise
forward slash and asterisk: in C++ to add an asterisk to each new line of the
comment block. This also helps you to remember to close the
/* This comment can
FRPPHQWEORFNRƪEHIRUHFRQWLQXLQJZLWKWKHFRGH
cover several lines
without the need to add more slashes */ /* This comment can
* cover several lines
-XVWUHPHPEHUWRƬQLVKWKHEORFNFRPPHQWZLWKWKHRSSRVLWH
* without the need to add more slashes */
asterisk and forward slash.

&RGLQJ 3URJUDPPLQJ 41
Coding with C++

Variables
9DULDEOHVGLƪHUVOLJKWO\ZKHQXVLQJ&DVRSSRVHGWR3\WKRQ,Q3\WKRQ\RXFDQ
simply state that ‘a’ equals 10 and a variable is assigned. However, in C++ a variable has
to be declared with its type before it can be used.

7+('(&/$5$7,212)9$5,$%/(6
<RXFDQGHFODUHD&YDULDEOHE\XVLQJVWDWHPHQWVZLWKLQWKHFRGH7KHUHDUHVHYHUDOGLVWLQFWW\SHVRIYDULDEOHV\RXFDQ
GHFODUH+HUHoVKRZLWZRUNV

67(3 2SHQXSDQHZEODQN&ƬOHDQGHQWHUWKHXVXDO 67(3 You can build and run the code but it won’t do
code headers: much, other than store the values 10 and 5 to the
integers a and b. To output the contents of the variables, add:
#include <iostream>
XVLQJQDPHVSDFHVWG cout << a;
cout << ”\n”;
int main()
cout << b;
{
7KHFRXWp?QqSDUW
}
simply places a new line
between the output of
10 and 5.

67(3 Start simple by creating two variables, a and b, with 67(3 Naturally you can declare a new variable, call it
one having a value of 10 and the other 5. You can result and output some simple arithmetic:
use the data type int to declare these variables. Within the curly
int result;
brackets, enter:
UHVXOW DE
int a;
cout << result;
int b;
Insert the above into the code as per the screenshot.
a = 10;
b = 5;

 &RGLQJ 3URJUDPPLQJ
Variables

67(3 You can assign a value to a variable as soon as you 67(3 The previous step creates the variable StartLives,
declare it. The code you’ve typed in could look like which is a global variable. In a game, for example,
this, instead: a player’s lives go up or down depending on how well or how bad
they’re doing. When the player restarts the game, the StartLives
int a = 10;
returns to its default state: 3. Here we’ve assigned 3 lives, then
int b = 5;
subtracted 1, leaving 2 lives left.
LQWUHVXOW DE
cout << result;

67(3 The modern C++ compiler is far more intelligent


than most programmers give it credit. While there
are numerous data types you can declare for variables, you can in
fact use the auto feature:
#include <iostream>
XVLQJQDPHVSDFHVWG
DXWRSL 

67(3 6SHFLƬFWR&\RXFDQDOVRXVHWKHIROORZLQJ int main()


to assign values to a variable as soon as you
{
declare them:
double area, radius = 1.5;
int a (10);
DUHD SL UDGLXV UDGLXV
int b (5);
cout << area;
Then, from the C++ 2011 standard, using curly brackets:
}
LQWUHVXOW^DE`

67(3 You can create global variables, which are variables


that are declared outside any function and used in
67(3 $FRXSOHRIQHZHOHPHQWVKHUHƬUVWDXWRZRQoW
any function within the entire code. What you’ve used so far are
work unless you go to Settings > Compiler and
local variables: variables used inside the function. For example:
tick the box labelled ‘Have G++ follow the C++11 ISO C++ Language
#include <iostream> Standard [-std=c++1]’. Then, the new data type, double, which
XVLQJQDPHVSDFHVWG PHDQVGRXEOHSUHFLVLRQƮRDWLQJSRLQWYDOXH(QDEOH&WKHQ
int StartLives = 3; build and run the code. The result should be 7.06858.
int main ()
{
startLives = StartLives – 1;
cout << StartLives;
}

&RGLQJ 3URJUDPPLQJ 43
Coding with C++

Data Types
Variables, as we’ve seen, store information that the programmer can then later call up,
and manipulate if required. Variables are simply reserved memory locations that store
the values the programmer assigns, depending on the data type used.

7+(9$/8(2)'$7$
7KHUHDUHPDQ\GLƪHUHQWGDWDW\SHVDYDLODEOHIRUWKHSURJUDPPHU incredibly accurate numbers but those numbers are only accurate
LQ&VXFKDVDQLQWHJHUƮRDWLQJSRLQW%RROHDQFKDUDFWHUDQGVR XSWRWKHƬIWHHQWKGHFLPDOSODFH7KHUHoVDOVRWKHSUREOHPZKHQ
on. It’s widely accepted that there are seven basic data types, often displaying such numbers in C++ using the cout function, in that cout
FDOOHG3ULPLWLYH%XLOWLQ7\SHVKRZHYHU\RXFDQFUHDWH\RXURZQ E\GHIDXOWRQO\RXWSXWVWKHƬUVWƬYHGHFLPDOSODFHV<RXFDQFRPEDW
data types should the need ever arise within your code. that by adding a cout.precision () function and adding a value inside
the brackets, but even then you’re still limited by the accuracy of the
The seven basic data types are:
double data type. For example, try this code:
#include <iostream>
7<3( &200$1' XVLQJQDPHVSDFHVWG
Integer ,QWHJHU GRXEOH3, 
int main()
)ORDWLQJ3RLQW ÀRDW {
cout << PI;
Character char }

Boolean bool

'RXEOH)ORDWLQJ3RLQW double

:LGH&KDUDFWHU wchar_t

1R9DOXH void

7KHVHEDVLFW\SHVFDQDOVREHH[WHQGHGXVLQJWKHIROORZLQJPRGLƬHUV
/RQJ6KRUW6LJQHGDQG8QVLJQHG%DVLFDOO\WKLVPHDQVWKHPRGLƬHUV
can expand the minimum and maximum range values for each data
type. For example, the int data type has a default value range of
-2147483648 to 2147483647, a fair value, you would agree.
1RZLI\RXZHUHWRXVHRQHRIWKHPRGLƬHUVWKHUDQJHDOWHUV
Unsigned int = 0 to 4294967295
Signed int = -2147483648 to 2147483647
Short int = -32768 to 32767
Unsigned Short int = 0 to 65,535 Build and run the code and as you can see the output is only
Signed Short int = -32768 to 32767 3.14159, representing cout’s limitations in this example.
Long int = -2147483647 to 2147483647
You can alter the code including the aforementioned cout.precision
Signed Long int = -2147483647 to 2147483647
function, for greater accuracy. Take precision all the way up to 22
Unsigned Long int = 0 to 4294967295
decimal places, with the following code:
Naturally you can get away with using the basic type without the
#include <iostream>
PRGLƬHUDVWKHUHoVSOHQW\RIUDQJHSURYLGHGZLWKHDFKGDWDW\SH
XVLQJQDPHVSDFHVWG
However, it’s considered good C++ programming practise to use the
GRXEOH3, 
PRGLƬHUVZKHQSRVVLEOH
int main()
7KHUHDUHLVVXHVZKHQXVLQJWKHPRGLƬHUVWKRXJK'RXEOH
{
UHSUHVHQWVDGRXEOHƮRDWLQJSRLQWYDOXHZKLFK\RXFDQXVHIRU

44 &RGLQJ 3URJUDPPLQJ
Data Types

FRXWSUHFLVLRQ  
This is mainly due to the conversion from binary in the compiler
cout << PI;
and that the IEEE 754 double precision standard occupies 64-bits
} RIGDWDRIZKLFKELWVDUHGHGLFDWHGWRWKHVLJQLƬFDQW WKH
VLJQLƬFDQWGLJLWVLQDƮRDWLQJSRLQWQXPEHU DQGURXJKO\ELWV
are taken holding the values 0 to 9. If you divide 53 by 3.5, then you
arrive at 15.142857 recurring, which is 15-digits of precision.
To be honest, if you’re creating code that needs to be accurate to
PRUHWKDQƬIWHHQGHFLPDOSODFHVWKHQ\RXZRXOGQoWEHXVLQJ&
\RXZRXOGXVHVRPHVFLHQWLƬFVSHFLƬFODQJXDJHZLWK&DVWKH
connective tissue between the two languages.
You can create your own data types, using an alias-like system called
typedef. For example:

$JDLQEXLOGDQGUXQWKHFRGHDV\RXFDQVHHIURPWKHFRPPDQG
OLQHZLQGRZWKHQXPEHUUHSUHVHQWHGE\WKHYDULDEOH3,LVGLƪHUHQW
to the number you’ve told C++ to use in the variable. The output
reads the value of PI as 3.141592653589793115998, with the
QXPEHUVJRLQJDZU\IURPWKHƬIWHHQWKGHFLPDOSODFH

#include <iostream>
XVLQJQDPHVSDFHVWG
W\SHGHILQWPHWUHV
int main()
{
metres distance;
distance = 15;
cout << “distance in metres is: “ << distance;
}

This code when executed creates a new int data type called metres.
Then, in the main code block, there’s a new variable called distance,
ZKLFKLVDQLQWHJHUVR\RXoUHEDVLFDOO\WHOOLQJWKHFRPSLOHUWKDW
there’s another name for int. We assigned the value 15 to distance
and displayed the output: distance in metres is 15.
It might sound a little confusing to begin with but the more you use
C++ and create your own code, the easier it becomes.

&RGLQJ 3URJUDPPLQJ 45
Coding with C++

Strings
Strings are objects that represent and hold sequences of characters. For example, you
could have a universal greeting in your code ‘Welcome’ and assign that as a string to be
called up wherever you like in the program.

675,1*7+(25<
7KHUHDUHGLƪHUHQWZD\VLQZKLFK\RXFDQFUHDWHDVWULQJRIFKDUDFWHUVZKLFKKLVWRULFDOO\DUHDOOFDUULHGRYHUIURPWKHRULJLQDO
C language, and are still supported by C++.

67(3 To create a string you use the char function. Open a 67(3 Build and run the code, and ‘Welcome’ appears
QHZ&ƬOHDQGEHJLQZLWKWKHXVXDOKHDGHU RQWKHVFUHHQ:KLOHWKLVLVSHUIHFWO\ƬQHLWoV
QRWDVWULQJ$VWULQJLVDFODVVZKLFKGHƬQHVREMHFWVWKDWFDQEH
#include <iostream>
represented as a stream of characters and doesn’t need to be
XVLQJQDPHVSDFHVWG
terminated like an array. The code can therefore be represented as:
int main ()
#include <iostream>
{ XVLQJQDPHVSDFHVWG
} int main ()
{
FKDUJUHHW>@ ³:HOFRPH´
FRXWJUHHW³?Q´
}

67(3 It’s easy to confuse a string with an array. Here’s an 67(3 In C++ there’s also a string function, which works in
array, which can be terminated with a null character: much the same way. Using the greeting code again,
you can enter:
#include <iostream>
XVLQJQDPHVSDFHVWG #include <iostream>
XVLQJQDPHVSDFHVWG
int main ()
int main ()
{
FKDUJUHHW>@ ^µ:¶µH¶µO¶µF¶µR¶µP¶ {
‘e’, ‘\0’}; VWULQJJUHHW ³:HOFRPH´
FRXWJUHHW³?Q´ FRXWJUHHW³?Q´
} }

46 &RGLQJ 3URJUDPPLQJ
Strings

67(3 7KHUHDUHDOVRPDQ\GLƪHUHQWRSHUDWLRQVWKDW\RX 67(3 Just as you might expect, you can mix in an integer
can apply with the string function. For instance, to and store something to do with the string. In this
get the length of a string you can use: example, we created int length, which stores the result of string.
size() and outputs it to the user:
#include <iostream>
XVLQJQDPHVSDFHVWG #include <iostream>
XVLQJQDPHVSDFHVWG
int main ()
int main ()
{
VWULQJJUHHW ³:HOFRPH´ {
FRXW³7KHOHQJWKRIWKHVWULQJLV³ LQWOHQJWK
FRXWJUHHWVL]H ³?Q´ VWULQJJUHHW ³+HOOR´
VWULQJJUHHW ³ZRUOG´
}
VWULQJJUHHW JUHHWJUHHW
OHQJWK JUHHWVL]H 
FRXW³7KHOHQJWKRIWKHFRPELQHGVWULQJV
LV³OHQJWK³?Q´
}

67(3 Using the available operations that come with the


string function, you can manipulate the contents of a
string. For example, to remove characters from a string you could use:
67(3 You can see that we used greet.size() to output the
#include <iostream>
length, the number of characters there are, of the
XVLQJQDPHVSDFHVWG
contents of the string. Naturally, if you call your string something
RWKHUWKDQJUHHWWKHQ\RXQHHGWRFKDQJHWKHFRPPDQGWRUHƮHFW int main ()
this. It’s always stringname.operation. Build and run the code to see
{
the results.
VWULQJVWUJ ³+HUHLVDORQJVHQWHQFHLQD
VWULQJ´ 
FRXWVWUJµ?Q¶
VWUJHUDVH  
FRXWVWUJµ?Q¶
VWUJHUDVH VWUJEHJLQ  
FRXWVWUJµ?Q¶
67(3 You can of course add strings together, or rather
VWUJHUDVH VWUJEHJLQ VWUJHQG  
combine them to form longer strings:
FRXWVWUJµ?Q¶
#include <iostream>
}
XVLQJQDPHVSDFHVWG
int main ()
67(3 It’s worth spending some time playing around with
{
the numbers, which are the character positions
VWULQJJUHHW ³+HOOR´
in the string. Occasionally, it can be hit and miss whether you get it
VWULQJJUHHW ³ZRUOG´
right, so practice makes perfect. Take a look at the screenshot to see
VWULQJJUHHW JUHHWJUHHW
the result of the code.
FRXWJUHHW³?Q´
}

&RGLQJ 3URJUDPPLQJ 
Coding with C++

C++ Maths
Programming is mathematical in nature and as you might expect, there’s plenty of
EXLOWLQVFRSHIRUVRPHTXLWHLQWHQVHPDWKV&KDVDORWWRRƪHUVRPHRQHZKRoV
implementing mathematical models into their code. It can be extremely complex or
relatively simple.

& 0&
7KHEDVLFPDWKHPDWLFDOV\PEROVDSSO\LQ&DVWKH\GRLQPRVWRWKHUSURJUDPPLQJODQJXDJHV+RZHYHUE\XVLQJWKH&
0DWK/LEUDU\\RXFDQDOVRFDOFXODWHVTXDUHURRWVSRZHUVWULJDQGPRUH

67(3 C++’s mathematical operations follow the 67(3 Multiplication and division can be applied as such:
same patterns as those taught in school, in that
#include <iostream>
multiplication and division take precedence over addition and
XVLQJQDPHVSDFHVWG
VXEWUDFWLRQ<RXFDQDOWHUWKDWWKRXJK)RUQRZFUHDWHDQHZƬOH
and enter: int main ()
{
#include <iostream>
ÀRDWQXPEHUV 
XVLQJQDPHVSDFHVWG
QXPEHUV QXPEHUV 7KLVPXOWLSOLHV
int main ()
by 10
{
ÀRDWQXPEHUV  cout << numbers << “\n”;
QXPEHUV QXPEHUV7KLVDGGVWRWKH numbers = numbers / 10; // And this divides
initial 100 1000 by 10
cout << numbers << “\n”; cout << numbers << “\n”;
QXPEHUV QXPEHUV7KLVVXEWUDFWV }
IURPWKHQHZ
cout << numbers << “\n”;
}

67(3 While simple, it does get the old maths muscle


ZDUPHGXS1RWHWKDWZHXVHGDƮRDWIRUWKH
numbers variable. While you can happily use an integer, if you 67(3 Again, execute the simple code and see the results.
suddenly started to use decimals, you would need to change to a While not particularly interesting, it’s a start into C++
ƮRDWRUDGRXEOHGHSHQGLQJRQWKHDFFXUDF\QHHGHG5XQWKHFRGH PDWKV:HXVHGDƮRDWKHUHVR\RXFDQSOD\DURXQGZLWKWKHFRGH
and see the results. and multiply by decimal places, as well as divide, add and subtract.

48 &RGLQJ 3URJUDPPLQJ
C++ Maths

67(3 The interesting maths content comes when you call 67(3 Calculating powers of numbers can be done with:
upon the C++ Math Library. Within this header are
dozens of mathematical functions along with further operations. #include <iostream>
Everything from computing cosine to arc tangent with two #include <cmath>
parameters, to the value of PI. You can call the header with: XVLQJQDPHVSDFHVWG
#include <iostream> int main ()
#include <cmath> {
XVLQJQDPHVSDFHVWG ÀRDWQXPEHU 
int main () FRXWQXPEHU³WRWKHSRZHURILV³
{ SRZ QXPEHU ³?Q´
FRXWQXPEHU³WRWKHSRZHURILV³
}
SRZ QXPEHU ³?Q´
FRXWQXPEHU³WRWKHSRZHURILV³
SRZ QXPEHU ³?Q´
}

67(3 Start by getting the square root of a number: 67(3 +HUHZHFUHDWHGDƮRDWFDOOHGQXPEHUZLWKWKH


value of 12, and the pow(variable, power) is where
the calculation happens. Of course, you can calculate powers and
#include <iostream>
square roots without using variables. For example, pow (12, 2)
#include <cmath>
RXWSXWVWKHVDPHYDOXHDVWKHƬUVWFRXWOLQHLQWKHFRGH
XVLQJQDPHVSDFHVWG
int main ()
{
ÀRDWQXPEHU 
FRXW³7KHVTXDUHURRWRI³QXPEHU³
is: “ << sqrt(number) << “\n”;
}

67(3 The value of Pi is also stored in the cmath header


library. It can be called up with the M_PI function.
(QWHUFRXW0B3,LQWRWKHFRGHDQG\RXJHWRU\RXFDQ
use it to calculate:
#include <iostream>
#include <cmath>
XVLQJQDPHVSDFHVWG
int main ()
{
double area, radius = 1.5;
area = M_PI * radius * radius;
67(3 +HUHZHFUHDWHGDQHZƮRDWFDOOHGQXPEHUDQG
used the sqrt(number) function to display the cout << area << “\n”;
square root of 134, the value of the variable, number. Build and run
}
the code, and your answer reads 11.5758.

&RGLQJ 3URJUDPPLQJ 49
Coding with C++

User Interaction
There’s nothing quite as satisfying as creating a program that responds to you. This
basic user interaction is one of the most taught aspects of any language and with it
you’re able to do much more than simply greet the user by name.

+(//2'$9(
<RXKDYHDOUHDG\XVHGFRXWWKHVWDQGDUGRXWSXWVWUHDPWKURXJKRXWRXUFRGH1RZ\RXoUHJRLQJWREHXVLQJFLQWKHVWDQGDUG
input stream, to prompt a user response.

67(3 Anything that you want the user to input into the 67(3 The cin command works in the opposite way from
program needs to be stored somewhere in the WKHFRXWFRPPDQG:LWKWKHƬUVWFRXWOLQH\RXoUH
system memory, so it can be retrieved and used. Therefore, any outputting ‘What is your age’ to the screen, as indicated with the
LQSXWPXVWƬUVWEHGHFODUHGDVDYDULDEOHVRLWoVUHDG\WREHXVHGE\ chevrons. Cin uses opposite facing chevrons, indicating an input. The
WKHXVHU6WDUWE\FUHDWLQJDEODQN&ƬOHZLWKKHDGHUV input is put into the integer age and called up in the second cout
command. Build and run the code.

67(3 If you’re asking a question, you need to store the


LQSXWDVDVWULQJWRDVNWKHXVHUWKHLUQDPH\RX
would use:
#include <iostream>
67(3 The data type of the variable must also match the XVLQJQDPHVSDFHVWG
type of input you want from the user. For example,
int main ()
to ask a user their age, you would use an integer like this:
{
#include <iostream> VWULQJQDPH
XVLQJQDPHVSDFHVWG cout << “what is your name: “;
cin >> name;
int main ()
{ FRXW³?Q+HOOR³QDPH³,KRSH\RX¶UH
LQWDJH well today?\n”;
FRXW³ZKDWLV\RXUDJH³
}
FLQ!!DJH
FRXW´?Q<RXDUH³DJH³\HDUVROG?Q´
}

 &RGLQJ 3URJUDPPLQJ
User Interaction

67(3 The principal works the same as the previous code. 67(3 While cin works well for most input tasks, it does
The user’s input, their name, is stored in a string, have a limitation. Cin always considers spaces as a
because it contains multiple characters, and retrieved in the second terminator, so it’s designed for just single words not multiple words.
cout line. As long as the variable ‘name’ doesn’t change, then you +RZHYHUJHWOLQHWDNHVFLQDVWKHƬUVWDUJXPHQWDQGWKHYDULDEOHDV
can recall it wherever you like in your code. the second:
#include <iostream>
XVLQJQDPHVSDFHVWG
int main ()
{
VWULQJP\VWU
cout << “Enter a sentence: \n”;
67(3 You can chain input requests to the user but just
JHWOLQH FLQP\VWU 
make sure you have a valid variable to store the
input to begin with. Let’s assume you want the user to enter two FRXW³<RXUVHQWHQFHLV³P\VWUVL]H 
whole numbers: ³FKDUDFWHUVORQJ?Q´
#include <iostream> }
XVLQJQDPHVSDFHVWG
int main ()
{
LQWQXPQXP
cout << “Enter two whole numbers: “;
FLQ!!QXP!!QXP
cout << “you entered “ << num1 << “ and “ <<
QXP³?Q´ 67(3 Build and execute the code, then enter a sentence
with spaces. When you’re done the code reads the
}
number of characters. If you remove the getline line and replace it
with cin >> mystr and try again, the result displays the number of
FKDUDFWHUVXSWRWKHƬUVWVSDFH

67(3 Likewise, inputted data can be manipulated once


you have it stored in a variable. For instance, ask the 67(3 Getline is usually a command that new C++
user for two numbers and do some maths on them: programmers forget to include. The terminating
ZKLWHVSDFHLVDQQR\LQJZKHQ\RXFDQoWƬJXUHRXWZK\\RXUFRGH
#include <iostream>
isn’t working. In short, it’s best to use getline(cin, variable) in future:
XVLQJQDPHVSDFHVWG
#include <iostream>
int main ()
XVLQJQDPHVSDFHVWG
{
ÀRDWQXPQXP int main ()
{
cout << “Enter two numbers: \n”;
FLQ!!QXP!!QXP VWULQJQDPH
FRXW³(QWHU\RXUIXOOQDPH?Q´
FRXWQXP³³QXP³LV³
JHWOLQH FLQQDPH 
QXPQXP³?Q´
cout << “\nHello, “ << name << “\n”;
}
}

&RGLQJ 3URJUDPPLQJ 51
Introducing Python

Python is one of the most respected


and used programming languages
in the world. It’s designed to help
beginners get into code, but also has
some amazingly powerful features
that are utilised by data scientists and
engineers around the world.

You don’t need to look too far to


Python at work. It’s used throughout
the Internet, and helps drive some of
the biggest projects and companies in
a multitude of industries.

In this section, we will look at what


you will need to get started with
Python. First steps into a new learning
experience are always the hardest, but
we’re here to help.

54 Why Python?
56 What Can You Do with Python?
58 Python in Numbers
60 Equipment You Will Need
62 Getting to Know Python
64 How to Set Up Python in Windows
66 How to Set Up Python in Linux
68 Python on the Pi

52 &RGLQJ 3URJUDPPLQJ
Index

&RGLQJ 3URJUDPPLQJ 53
Introducing Python

Why Python?
7KHUHDUHPDQ\GLƪHUHQWSURJUDPPLQJODQJXDJHVDYDLODEOHIRUWKHPRGHUQFRPSXWHU
DQGVRPHVWLOODYDLODEOHIRUROGHUDQGELWFRPSXWHUVWRR6RPHRIWKHVHODQJXDJHV
DUHGHVLJQHGIRUVFLHQWLƬFZRUNRWKHUVIRUPRELOHSODWIRUPVDQGVXFK6RZK\FKRRVH
3\WKRQRXWRIDOOWKHUHVW"

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’
WKDWoVXVHGWRXOWUDKLJKGHƬQLWLRQJUDSKLFVDQGRSHQZRUOGPXOWL 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 7KHODQJXDJHVLQXVHWRGD\GLƪHUGHSHQGLQJRQWKHVLWXDWLRQWKH
billion pound gaming empire that continually amazes us. platform, the device’s use and how the device will interact with its

54 &RGLQJ 3URJUDPPLQJ
:K\3\WKRQ"

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 HYHQ5,6&26,WKDVEHHQYRWHGRQHRIWKHWRSƬYHSURJUDPPLQJ
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, OHDUQH[FHSWLRQDOO\SRZHUIXOXQLYHUVDOO\DFFHSWHGHƪHFWLYHDQGD
variables, objects, arithmetic, subroutines, loops and countless superb learning and educational tool.
more interactions. Whilst it’s not as streamlined as a Low-Level
Language, which can deal directly with memory addresses, call
VWDFNVDQGUHJLVWHUVLWVEHQHƬWLVWKDWLWoVXQLYHUVDOO\DFFHVVLEOH
and easy to learn.

BASIC was once the starter language that early


8-bit home computer users learned.

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

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


and makes for an ideal beginner’s programming language.

&RGLQJ 3URJUDPPLQJ 55
Introducing Python

What Can You Do


with Python?
3\WKRQLVDQRSHQVRXUFHREMHFWRULHQWHGSURJUDPPLQJODQJXDJHWKDWoVVLPSOHWR
XQGHUVWDQGDQGZULWHZLWK\HWDOVRSRZHUIXODQGH[WUHPHO\PDOOHDEOH,WoVWKHVH
FKDUDFWHULVWLFVWKDWKHOSPDNHLWVXFKDQLPSRUWDQWODQJXDJHWROHDUQ

3\WKRQoVDELOLW\WRFUHDWHKLJKO\UHDGDEOHFRGHZLWKLQDVPDOOVHW <RXoOOƬQGORWVRIH[DPSOHVRIWKLVZKHUH3\WKRQLVDFWLQJEHKLQG
RILQVWUXFWLRQVKDVDFRQVLGHUDEOHLPSDFWRQRXUPRGHUQGLJLWDO WKHVFHQHV7KLVLVZK\LWoVVXFKDQLPSRUWDQWODQJXDJHWROHDUQ
ZRUOG)URPEHLQJDQLGHDOƬUVWSURJUDPPHUVoFKRLFHWKURXJKWR
EHLQJDEOHWRFUHDWHLQWHUDFWLYHVWRULHVDQGJDPHVIURPVFLHQWLƬF
DSSOLFDWLRQVWKURXJKWRDUWLƬFLDO,QWHOOLJHQFHDQGZHEEDVHG
DSSOLFDWLRQVWKHRQO\OLPLWWR3\WKRQLVWKHLPDJLQDWLRQRIWKH
person coding in it.

,WoV3\WKRQoVPDOOHDEOHGHVLJQWKDWPDNHVLWDQLGHDOODQJXDJHIRU
PDQ\GLƪHUHQWVLWXDWLRQVDQGUROHV(YHQFHUWDLQDVSHFWVRIWKH
FRGLQJZRUOGWKDWUHTXLUHPRUHHƯFLHQWFRGHVWLOOXVH3\WKRQ)RU
H[DPSOH1$6$XWLOLVHV3\WKRQERWKDVDVWDQGDORQHODQJXDJH
DQGDVDEULGJHEHWZHHQRWKHUSURJUDPPLQJODQJXDJHV7KLVZD\
1$6$VFLHQWLVWVDQGHQJLQHHUVDUHDEOHWRJHWWRWKHGDWDWKH\
QHHGZLWKRXWKDYLQJWRFURVVPXOWLSOHODQJXDJHEDUULHUV3\WKRQ
ƬOOVWKHJDSVDQGSURYLGHVWKHPHDQVWRJHWWKHMREGRQH

BIG DATA
%LJGDWDLVDEX]]ZRUG\RXoUHOLNHO\WRKDYHFRPHDFURVVLQWKHODVWFRXSOHRI\HDUV
%DVLFDOO\LWPHDQVH[WUHPHO\ODUJHGDWDVHWVWKDWDUHDYDLODEOHIRUDQDO\VLVWRUHYHDO
SDWWHUQVWUHQGVDQGLQWHUDFWLRQVEHWZHHQKXPDQVVRFLHW\DQGWHFKQRORJ\2IFRXUVH
LWoVQRWMXVWOLPLWHGWRWKRVHDUHDVELJGDWDLVFXUUHQWO\EHLQJXVHGLQDYDULHW\RI
LQGXVWULHVIURPVRFLDOPHGLDWRKHDOWKDQGZHOIDUHHQJLQHHULQJWRVSDFHH[SORUDWLRQ
and beyond.

3\WKRQSOD\VDVXEVWDQWLDOUROHLQWKHZRUOGRIELJGDWD,WoVH[WHQVLYHO\XVHGWRDQDO\VH
KXJHFKXQNVRIWKHDYDLODEOHELJGDWDDQGH[WUDFWVSHFLƬFLQIRUPDWLRQEDVHGRQZKDW
WKHXVHUFRPSDQ\UHTXLUHVIURPWKHZHDOWKRIQXPEHUVSUHVHQW7KDQNVWRDQ
LPSUHVVLYHVHWRIGDWDSURFHVVLQJOLEUDULHV3\WKRQPDNHVWKHDFWRIJHWWLQJWRWKHGDWD
LQDPRQJVWWKHQXPEHUVWKDWFRXQWVDQGSUHVHQWLQJLWLQDIDVKLRQWKDWoVUHDGDEOHDQG
XVHDEOHIRUKXPDQV

7KHUHDUHFRXQWOHVVOLEUDULHVDQGIUHHO\DYDLODEOHPRGXOHVWKDWHQDEOHIDVWVHFXUHDQG
PRUHLPSRUWDQWO\DFFXUDWHSURFHVVLQJRIGDWDIURPWKHOLNHVRIVXSHUFRPSXWLQJFOXVWHUV
)RUH[DPSOH&(51XVHVDFXVWRP3\WKRQPRGXOHWRKHOSDQDO\VHWKHPLOOLRQFROOLVLRQV
SHUVHFRQGWKDWWKH/DUJH+DGURQ&ROOLGHU /+& SURGXFHV$GLƪHUHQWODQJXDJHKDQGOHV
WKHUDZGDWDEXW3\WKRQLVSUHVHQWWRKHOSVLIWWKURXJKWKHGDWDVRVFLHQWLVWVFDQJHWWRWKH
FRQWHQWWKH\ZDQWZLWKRXWWKHQHHGWROHDUQDIDUPRUHFRPSOH[SURJUDPPLQJODQJXDJH

56 &RGLQJ 3URJUDPPLQJ
:KDW&DQ<RX'RZLWK3\WKRQ"

ARTIFICIAL INTELLIGENCE
$UWLƬFLDO,QWHOOLJHQFHDQG0DFKLQH/HDUQLQJDUHWZRRIWKH
PRVWJURXQGEUHDNLQJDVSHFWVRIPRGHUQFRPSXWLQJ$,LVWKH
XPEUHOODWHUPXVHGIRUDQ\FRPSXWLQJSURFHVVZKHUHLQWKH
PDFKLQHLVGRLQJVRPHWKLQJLQWHOOLJHQWZRUNLQJDQGUHDFWLQJ
LQVLPLODUZD\VWRKXPDQV0DFKLQH/HDUQLQJLVDVXEVHWRI$,
DQGSURYLGHVWKHRYHUDOO$,V\VWHPZLWKWKHDELOLW\WROHDUQ
IURPLWVH[SHULHQFHV

+RZHYHU$,LVQoWVLPSO\WKHFUHDWLRQRIDXWRQRPRXVURERWV
LQWHQWRQZLSLQJRXWKXPDQFLYLOLVDWLRQ,QGHHG$,FDQEH
IRXQGLQDYDULHW\RIGD\WRGD\FRPSXWLQJDSSOLFDWLRQVZKHUH
WKHnPDFKLQHoRUPRUHDFFXUDWHO\WKHFRGHQHHGVWROHDUQ
IURPWKHDFWLRQVRIVRPHIRUPRILQSXWDQGDQWLFLSDWHZKDW
WKHLQSXWLVOLNHO\WRUHTXLUHRUGRQH[W

7KLVPRGHOFDQEHDSSOLHGWR)DFHERRN*RRJOH7ZLWWHU
,QVWDJUDPDQGVRRQ+DYH\RXHYHUORRNHGXSDFHOHEULW\
RQ,QVWDJUDPDQGWKHQGLVFRYHUHGWKDW\RXUVHDUFKHVZLWKLQ
RWKHUVRFLDOPHGLDSODWIRUPVDUHQRZVSHFLƬFDOO\WDUJHWHG
WRZDUGVLPLODUFHOHEULWLHV"7KLVLVDSULPHH[DPSOHRIXVLQJ$,
LQWDUJHWHGDGYHUWLVLQJDQGEHKLQGWKHFRGHDQGDOJRULWKPV GAMING
WKDWSUHGLFWZKDW\RXoUHORRNLQJIRULV3\WKRQ
$OWKRXJK\RXZRQoWƬQGWRRPDQ\WULSOH$UDWHGJDPHVFRGHG
6SRWLI\IRUH[DPSOHXVHV3\WKRQEDVHGFRGH
using Python, you may be surprised to learn that Python is used as
DPRQJRWKHUWKLQJVWRDQDO\VH\RXUPXVLFDO
an extra on many of the high-ranking modern games.
KDELWVDQGRƪHUSOD\OLVWVEDVHGRQZKDW\RXoYH
OLVWHQHGWRLQWKHSDVW,WoVDOOFOHYHUVWXƪDQG
The main use of Python in gaming comes in the form of scripting,
PRYLQJIRUZDUG3\WKRQLVDWWKHIRUHIURQWRI
where a Python script can add customisations to the core game
WKHZD\WKH,QWHUQHWZLOOZRUNLQWKHIXWXUH
engine. Many map editors are Python compatible and you will also
come across it if you build any mods for games, such as The Sims.

A lot of the online, MMORPG (Massively Multiplayer Online Role-


Playing Game) games available utilise Python as a companion
WEB DEVELOPMENT language for the server-side elements. These include: code to
search for potential cheating, load balancing across the game’s
:HEGHYHORSPHQWKDVPRYHGRQFRQVLGHUDEO\VLQFHWKHHDUO\ servers, player skill matchmaking and to check whether the player’s
GD\VRI+70/VFULSWLQJLQDOLPLWHGWH[WHGLWRU7KHPDQ\ client-side game matches the server’s versions. There’s also a
IUDPHZRUNVDQGZHEPDQDJHPHQWVHUYLFHVDYDLODEOHQRZ Python module that can be included in a Minecraft server, enabling
means that building a page has become increasingly complex. the server admin to add blocks, send messages and automate a lot
of the background complexities of the game.
:LWK3\WKRQWKHZHEGHYHORSHUKDVWKHDELOLW\WRFUHDWH
G\QDPLFDQGKLJKO\VHFXUHZHEDSSVHQDEOLQJLQWHUDFWLRQZLWK
RWKHUZHEVHUYLFHVDQGDSSVVXFKDV,QVWDJUDPDQG3LQWHUHVW
3\WKRQDOVRDOORZVWKHFROOHFWLRQRIGDWDIURPRWKHUZHEVLWHV
DQGHYHQDSSVEXLOWZLWKLQRWKHUZHEVLWHV PYTHON EVERYWHERE
As you can see, Python is quite a versatile
programming language. By learning Python,
you are creating a well-rounded skillset that’s
able to take you into the next generation of
computing, either professionally or simply
as a hobbyist.

Whatever route you decide to take on your


coding journey, you will do well to have
Python in your corner.

&RGLQJ 3URJUDPPLQJ 57
Introducing Python
Pytho
n cre
Ross ator G
um n uido
amed V
There’s a readi
ng sc P ython an
Pyth ripts afte
lot to like about on’s F from Mon r
lying t
Python, but don’t just Circu y
s.
take our word for it. Here are
VRPHDPD]LQJIDFWVDQGƬJXUHV
surrounding one of the most popular
programming languages of recent years.

Alexa, Amazon’s Virtual Data analysis and


Personal Assistant, uses Machine Learning are the
Python to help with two most used Python
speech recognition. examples.

in PYTHON AND
LINUX SKILLS
N UMBERS

As of the end of 20,


ARE THE THIRD Disney Pixar uses Python
Python was the most MOST POPULAR in its Renderman software
discussed language on I.T. SKILLS IN to operate between other
the Internet. graphics packages.
THE UK.

OVER 75% OF 90% OF ALL IT’S ESTIMATED


RECOMMENDED FACEBOOK POSTS THAT OVER 75% OF
CONTENT FROM NETFLIX ARE FILTERED NASA’S WORKFLOW
IS GENERATED FROM 7+528*+3<7+21Ǖ AUTOMATION
0$&+,1(/($51,1*ǟ CODED MACHINE SYSTEMS ON BOARD
CODED BY PYTHON. LEARNING. THE I.S.S. USE PYTHON.

58 &RGLQJ 3URJUDPPLQJ
3\WKRQLQ1XPEHUV

16,000 3<7+216.,//Ǖ%$6('
POSITIONS ARE THE

th
0267628*+7Ǖ$)7(5
There are over 16,000 Python jobs
posted every six months in the UK. JOBS IN THE UK.

Python Data Science is Google is the top Data Science, Blockchain New York and San
thought to become the company for hiring Python and Machine Learning Francisco are the top
most sought-after job in developers, closely are the fastest growing Python developer cities
the coming years. followed by Microsoft. Python coding skills. in the world.

Python developers enjoy an average salary of

£60,000

95% OF ALL BEGINNER 75% OF ALL PYTHON 79% OF ALL 49% OF WINDOWS
CODERS START WITH DEVELOPERS USE PROGRAMMERS 10 DEVELOPERS
AND STILL USE, PYTHON 3, WHEREAS USE PYTHON USE PYTHON 3
PYTHON AS THEIR 25% STILL USE THE REGULARLY, 21% USE AS THEIR MAIN
PRIMARY OR OUTDATED PYTHON 2 IT AS A SECONDARY PROGRAMMING
SECONDARY LANGUAGE. VERSION. LANGUAGE. LANGUAGE.

&RGLQJ 3URJUDPPLQJ 59
Introducing Python

Equipment You
Will Need
<RXFDQOHDUQ3\WKRQZLWKYHU\OLWWOHKDUGZDUHRULQLWLDOƬQDQFLDOLQYHVWPHQW<RX
GRQoWQHHGDQLQFUHGLEO\SRZHUIXOFRPSXWHUDQGDQ\VRIWZDUHWKDWoVUHTXLUHGLV
IUHHO\{DYDLODEOH

WHAT WE’RE USING


Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linux, Raspberry Pi and more. If
you have one of those systems, then you can easily start using Python.

COMPUTER
Obviously you’re going to need a computer in order to learn how to program in
Python and to test your code. You can use Windows (from XP onward) on either a 32
or 64-bit processor, an Apple Mac or Linux installed PC.

AN IDE
An IDE (Integrated Developer Environment) is used to enter and execute Python
code. It enables you to inspect your program code and the values within the code, as
ZHOODVRƪHULQJDGYDQFHGIHDWXUHV7KHUHDUHPDQ\GLƪHUHQW,'(VDYDLODEOHVRƬQG
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,
VXFKDV6XEOLPH7H[WRU1RWHSDGRƪHUVPRUHDGYDQFHGIHDWXUHVDQGFRORXUFRGLQJ
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
HƯFLHQWODQJXDJH+DYLQJDFFHVVWRWKH,QWHUQHWZLOONHHS\RXXSWRGDWHKHOS\RX
out when you get stuck and give access to Python’s immense number of modules.

TIME AND PATIENCE


Despite what other books may lead you to believe, you won’t become a programmer
in 24-hours. Learning to code in Python takes time, and patience. You may become
VWXFNDWWLPHVDQGRWKHUWLPHVWKHFRGHZLOOƮRZOLNHZDWHU8QGHUVWDQG\RXoUHOHDUQLQJ
something entirely new, and you will get there.

60 &RGLQJ 3URJUDPPLQJ
(TXLSPHQW<RX:LOO1HHG

THE RASPBERRY PI
:K\XVHD5DVSEHUU\3L"7KH5DVSEHUU\3LLVDWLQ\FRPSXWHUWKDWoVYHU\FKHDSWRSXUFKDVHEXWRƪHUVWKHXVHUDIDQWDVWLFOHDUQLQJ
platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many modules and extras.

RASPBERRY PI
The Raspberry Pi  Model is the latest version,
incorporating a more powerful CPU, a choice of GBor
GB memory versions and Wi-Fi and Bluetooth support.
You can pick up a Pi from around £, increasing up to
£ for the GB memory version, or as part of Dkit
depending on the 3LPRGHO 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
WREXLOGDQGSURJUDP<RXFDQƬQGPRUHLQIRUPDWLRQRQWKH
FUZE at www.fuze.co.uk.

RASPBIAN
The Raspberry Pi’s main operating system is a Debian-based
Linux distribution that comes with everything you need in
a simple to use package. It’s streamlined for the Pi and is an
ideal platform for hardware and software projects, Python
programming and even as a desktop computer.
Introducing Python

Getting to Know Python


3\WKRQLVRQHRIWKHPRVWXVHGDQGSRSXODUSURJUDPPLQJODQJXDJHV,WoVDJUHDW
ODQJXDJHRQZKLFKWROHDUQKRZWRFRGHEXWLWoVDOVRSRZHUIXOHQRXJKWREHXVHGE\
FRPSDQLHVZKHQWUDZOLQJWKURXJKSHWDE\WHVRIUDZGDWD

PYTHON POWER
Python is a high-level, general-purpose programming language that was designed by Guido van Rossum in the late ‘80s, as a
successor to the ABC Programming Language, and became available to use in 1990.

Guido van Rossum, the


designer of Python.

7KH3\WKRQ6RIWZDUH)RXQGDWLRQDQRQSURƬWRUJDQLVDWLRQGHYRWHG Made up from over 5 Petabytes of data, spread across a


WRERWKIXUWKHULQJDQGLPSURYLQJ3\WKRQFXUUHQWO\GHYHORSVWKH WRQRIKDUGGULYHV3\WKRQKHOSHGVFLHQFHWRXQYHLOWKHƬUVW
ODQJXDJH7KHIRXQGDWLRQoVSXUSRVHLVWRpSURPRWHSURWHFWDQG image of a black hole.
DGYDQFHWKH3\WKRQSURJUDPPLQJODQJXDJHDQGWRVXSSRUWDQG
IDFLOLWDWHWKHJURZWKRIDGLYHUVHDQGLQWHUQDWLRQDOFRPPXQLW\RI
Python programmers.” $VDVLGHQRWHLWoVQRWMXVWWKHOLNHVRIWKH6WRFN([FKDQJHWKDW
XVH3\WKRQWRVWXG\ODUJHTXDQWLWLHVRIGDWDLQ$SULOWKHƬUVW
7KHVWUXFWXUHRI3\WKRQFRGHKDVEHHQGHVLJQHGWRƮRZHDVLO\ LPDJHRIDEODFNKROHZDVUHOHDVHGWKHVXSHUPDVVLYHEODFNKROHLQ
DOORZLQJWKRVHZKRDUHMXVWEHJLQQLQJWRFRGHWRIROORZLWZLWKRXW WKHJDOD[\FDOOHG0ORFDWHGURXJKO\PLOOLRQOLJKW\HDUVDZD\
WRRPXFKGLƯFXOW\<HWGHVSLWHLWVHDVHRIXVH3\WKRQLVUHJXODUO\ 7KDQNVWRWKHFROODERUDWLRQRIRYHUVFLHQWLVWVXVLQJDQDUUD\RI
XVHGWKURXJKRXWDQXPEHURILQGXVWULHVLQUHDOZRUOGVFHQDULRV WHOHVFRSHVVSDQQLQJWKHZRUOG FDOOHGWKH(YHQW+RUL]RQ7HOHVFRSH
3URMHFW WKHFRPELQHGSRZHURIWKHWHOHVFRSHVIRUPHGDQ
%LJ'DWDDQG$,DUHWKHWZRIDVWHVWJURZLQJ3\WKRQEDFNHG LPSUHVVLYHƬYHSHWDE\WHVRIGDWDVSUHDGDFURVVWHQVRIKDUGGULYHV
WHFKQRORJLHVDWWKHPRPHQW%LJ'DWDLVVLPSO\DPRGHUQWHUP ZHLJKLQJLQDWQHDUO\RQHWRQ)LYHSHWDE\WHVE\WKHZD\HTXDWHV
used to describe huge WRDURXQG\HDUVoZRUWKRI03ƬOHV2QFHDOOWKRVHKDUGGULYHV
DPRXQWVRIGDWD were gathered together and shipped to a central supercomputer
such as sequences FOXVWHUWKHWHDPWKHQXVHG3\WKRQWRSDLQVWDNLQJO\VWLWFKWRJHWKHU
RIQXPEHUVFROODWHG DOOWKHIUDJPHQWVRIGDWDIURPWKHƬYHSHWDE\WHVWRƬQDOO\IRUPWKH
GXULQJDGD\oVZRUWKRI PRVWWDONHGDERXWDVWURQRPLFHYHQWRIWKHGHFDGH
WUDGLQJRQWKH6WRFN
([FKDQJH3\WKRQ $,LI\RXoUHQRWIDPLOLDUZLWKWKHWHUPVWDQGVIRU$UWLƬFLDO
code is used to dig ,QWHOOLJHQFH$OWKRXJKZHoUHVWLOODORQJZD\RƪIURPWKHYLVLRQDU\
LQWRWKHYROXPLQRXV VWRULHVRI$UWKXU&&ODUNH$,LVIDVWEHFRPLQJRQHRIWKHPRVW
FROOHFWLRQRIQXPEHUV LQƮXHQWLDOWHFKQRORJLHVRIRXUPRGHUQDJH5DWKHUWKDQFRQWUROOLQJ
DQGWKHQIHHGEDFN URERWVWKH$,WKDW3\WKRQGULYHVLVGHVLJQHGWRFUHDWHDXWRQRPRXV
with reports on the ZD\VRILQWHUDFWLQJZLWKSHRSOHRQOLQH)RUH[DPSOHZKHQ\RX
Python code is both elegant and KLJKVDQGORZVZKDWoV VHDUFKIRUVRPHWKLQJRQWKH$PD]RQZHEVLWH\RXZLOOXVXDOO\QRWLFH
easy to read (when you know how). WUHQGLQJDQGVRRQ WKDWVLPLODUSURGXFWVVWDUWWRDSSHDUZKHWKHUZLWKLQ$PD]RQLWVHOI

62 &RGLQJ 3URJUDPPLQJ
Getting to Know Python

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.

<RXQHHGWREHFDUHIXOZKHQ\RXORRNXS3\WKRQFRGHRQOLQHDOWKRXJK
WKHUHDUHFRXQWOHVVZHEVLWHVWKDWRƪHUTXLFNWXWRULDOVFRGHVQLSSHWV
DQGVXSSRUWsDQGRIWKHVHVLWHDUHDJUHDWKHOSWRWKRVHVWDUWLQJ
RXWZLWK3\WKRQsDORWRIWKHVLWHVKDYHQoWEHHQXSGDWHGIRUVRPH
WLPHDQGDVVXFKXVH3\WKRQ,I\RXHQWHU3\WKRQFRGHLQWRWKH
3\WKRQ,'/(WKHFKDQFHVDUHLWZRQoWZRUNGXHWRLQFRPSDWLELOLWLHV
EHWZHHQWKHROGHUYHUVLRQDQGWKHQHZHU3\WKRQLVJRRGEXW
3\WKRQLVEHWWHU<RXFDQREYLRXVO\VSHQGWLPHFRQYHUWLQJWKH
3\WKRQFRGHLQWRYHUVLRQEXWWREHJLQZLWKLWoVEHVWWRPDNHVXUH
WKDWWKHFRGH\RXoUHORRNLQJDWLVIRUWKH3\WKRQOLEUDULHV'RQoW
Python 3 is the best option to
ZRUU\WKRXJKDOOWKHFRGHLQWKLVERRNLVGHVLJQHGIRU3\WKRQDQG
download, or update to.
WKDWLQFOXGHVDOOWKHVXEYHUVLRQVIURP3\WKRQWRWKHODWHVW[
3\WKRQLVWKHQHZHVWUHOHDVHRIWKHSURJUDPPLQJODQJXDJH
+RZHYHULI\RXGLJDOLWWOHGHHSHULQWRWKH3\WKRQVLWHDQGLQYHVWLJDWH 3\WKRQoVJURZLQJSRSXODULW\KDVPHDQWWKDWLWoVQRZSUXGHQWWRVWDUW
3\WKRQFRGHRQOLQH\RXZLOOXQGRXEWHGO\FRPHDFURVV3\WKRQ OHDUQLQJWRGHYHORSZLWKWKHQHZIHDWXUHVDQGEHJLQWRSKDVHRXWWKH
&UXFLDOO\DOWKRXJK\RXFDQUXQ3\WKRQDQG3\WKRQDORQJVLGH SUHYLRXVYHUVLRQ0DQ\GHYHORSPHQWFRPSDQLHVVXFKDV6SDFH;DQG
HDFKRWKHULWoVQRWUHFRPPHQGHG$OZD\VRSWIRUWKHODWHVWVWDEOH 1$6$XVH3\WKRQIRUVQLSSHWVRILPSRUWDQWFRGH
UHOHDVHDVSRVWHGE\WKH3\WKRQZHEVLWH<RXZLOOƬQGZKHQXVLQJ
PDF26RU/LQX[WKDW3\WKRQLVDOUHDG\LQVWDOOHG7KLVLVEHFDXVH +RZHYHUVXSSRUWIRU3\WKRQLVVHWWRHQGRQ-DQXDU\VWEXW
ERWKWKHVHRSHUDWLQJV\VWHPVXWLOLVHHOHPHQWVRIFRGHQHFHVVDU\WR WKLVGRHVQoWPHDQLWoOOEHWKHODVW\RXVHHRILW0DQ\/LQX[GLVWURVXVH
WKHFRUHIXQFWLRQDOLW\RIWKH26/LQX[XVHUVWHQGWREHEHWWHURƪ 3\WKRQOLEUDULHVDVGRHVPDF26DQGWREHIDLUIRUWKHGHYHORSHUV
DVPRVWGLVWULEXWLRQVSDFNDJHWKHODWHVWYHUVLRQRI3\WKRQRXWRI WRWUDQVIHUWKHH[LVWLQJ3\WKRQFRQWHQWWR3\WKRQPD\WDNHPRUH
WKHER[ZKHUHDVPDF26RIWHQKDV3\WKRQLWoVXVXDOO\DQROGHU WLPHWKDQWKH\KDYHDYDLODEOHLHEHIRUHWKHVWDUWRI,WoVOLNHO\
YHUVLRQ0LFURVRIWGRHVQoWXVHDQ\3\WKRQFRGHIRULWVFRUH:LQGRZV WKHQWKDWZHZLOOVWLOOEHVHHLQJ3\WKRQORQJDIWHULWKDVKDGWKHƬQDO
V\VWHPVZKLFKLVZK\\RXZRQoWƬQG3\WKRQLQKHUHQWWR:LQGRZVDQG QDLOKDPPHUHGLQWRLWVFRƯQsLQIDFWH[SHFWWRVHHWKDWFXWRƪGDWH
WKHUHIRUHQHHGWRLQVWDOOLWIURPVFUDWFK H[WHQGIXUWKHULQWRWKHIXWXUH

RUIURPDVHDUFKHQJLQHRUHYHQ)DFHERRN7KHFRGHEHKLQG
WKHVHWDUJHWHGVQLSSHWVLV3\WKRQDQGLWoVXVLQJDIRUPRI$,WR
KHOSGHWHUPLQHZKDWLWLV\RXZRXOGOLNHO\VHDUFKIRU ZEN OF PYTHON
'HVSLWHWKHIDFWWKDWPDQ\SHRSOHƬQGWKHWDUJHWLQJRI Python lets you access
DGYHUWLVLQJLQWUXVLYHRUHYHQDQLQYDVLRQRISULYDF\\RXKDYHWR all the power of a
DGPLWWKDWWKHFRGHWHFKQRORJ\EHKLQGLWDOOLVUDWKHULPSUHVVLYH computer in a language
:LWKVRPHYHU\FOHYHUWHFKQLTXHVD3\WKRQGHYHORSHULVDEOH that humans can
WRFUHDWHDPDFKLQHWKLQNLQJVFULSWWKDWQRWRQO\GLVSOD\VLWHPV understand. Behind all
QHZVVWRULHVERRNVRWKHUZHEVLWHVDQGLGHDVUHODWLQJWRZKDW this is an ethos called
\RXoYHVHDUFKHGIRUEXWLWFDQDOVRSUHGLFWZKDW\RXPD\EH “The Zen of Python”.
LQWHUHVWHGLQORRNLQJIRULQWKHIXWXUH$QRWKHUHOHPHQWWR This is a collection of 20
FRQVLGHUZLWKUHJDUGVWR$,LVWKDW3\WKRQFRGHFDQEHXVHGWR software principles that
KHOSDFRPSXWHUOHDUQKRZWRGRVRPHWKLQJPRUHHƯFLHQWO\,Q LQƮXHQFHVWKHGHVLJQRI
WKHFDVHRIQHXUDOQHWZRUNVLQ$,WKH3\WKRQFRGHLVGHVLJQHG the language. Principles The Zen of Python, as
WRUHWXUQDUHVXOWWKHQDVWKHFRGHLVUXQRYHUDQGRYHUDJDLQ include “Beautiful is seen when entering:
WKH$,SRUWLRQZLOOEHJLQWROHDUQKRZWRREWDLQDPRUHDFFXUDWH better than ugly” and import this, into the
UHVXOWRUGRWKHPDWKVEHKLQGWKHFRGHTXLFNHU,WDOOGHSHQGVRQ “Simple is better than Python IDLE.
ZKDWWKHGHYHORSHUZDQWVIURPWKHLU$,3\WKRQFRGH complex.” Type: import
this into Python and it will display all the principles.
An example of Python AI code, using a
As you will discover over the coming pages, Python is a
feedforward neural network.
fantastic language to learn. Get to grips with the basics, and
before long, you’ll be creating your own Python code for
games, tools, and maybe even something in AI. The only limit
with Python is your own imagination.

&RGLQJ 3URJUDPPLQJ 63
Introducing Python

How to Set Up
Python in Windows
:LQGRZVXVHUVFDQHDVLO\LQVWDOOWKH3\WKRQSURJUDPPLQJODQJXDJHYLDWKHPDLQ3\WKRQ
'RZQORDGVSDJH:KLOHPRVWVHDVRQHG3\WKRQGHYHORSHUVPD\VKXQ:LQGRZVDVWKH
SODWIRUPRIFKRLFHIRUEXLOGLQJWKHLUFRGHLWoVVWLOODQLGHDOVWDUWLQJSRLQWIRUEHJLQQHUV

INSTALLING PYTHON 3.X


Microsoft Windows doesn’t come with Python pre-installed as standard, so you’re going to have to install it yourself manually.
Thankfully, it’s an easy process to follow.

STEP 1 Start by opening your web browser to www.python. STEP 3 Choosing the Customise option allows you to
org/downloads/. Look for the button detailing the specify certain parameters, and while you may
Download link for Python 3.x. Python is regularly updated, changing stay with the defaults it’s a good habit to adopt as sometimes (not
WKHODVWGLJLWIRUHDFKEXJƬ[DQGXSGDWH7KHUHIRUHGRQoWZRUU\LI with Python, thankfully) installers can include unwanted additional
you see Python 3.7.0, or more, as long as it’s Python 3, the code in IHDWXUHV2QWKHƬUVWVFUHHQDYDLODEOHHQVXUHDOOER[HVDUHWLFNHG
WKLVERRNZLOOZRUNƬQH and click the Next button.

STEP 2 Click the download button for version 3.x, and save STEP 4 The next page of options include some interesting
WKHƬOHWR\RXU'RZQORDGVIROGHU:KHQWKHƬOHLV DGGLWLRQVWR3\WKRQ(QVXUHWKH$VVRFLDWHƬOHZLWK
downloaded, double-click the executable and the Python installation Python, Create Shortcuts, Add Python to Environment Variables,
wizard will launch. From here you’ll have two choices: Install Now and Precompile Standard Library, and Install for All Users options are
Customise Installation. We recommend opting for the Customise ticked – these make using Python later much easier. Click Install
Installation link, and that the Add Python 3.x to PATH option is ticked. when you’re ready to continue.

64 &RGLQJ 3URJUDPPLQJ
+RZWR6HW8S3\WKRQLQ:LQGRZV

STEP 5 <RXPD\QHHGWRFRQƬUPWKHLQVWDOODWLRQZLWKWKH STEP 8 If you now click on the Windows Start button again,
:LQGRZVDXWKHQWLFDWLRQQRWLƬFDWLRQ6LPSO\FOLFN and this time type CMD you’ll be presented with
Yes and Python will begin to install. Once the installation is complete the Command Prompt link. Click it and you’ll be at the Windows
WKHƬQDO3\WKRQZL]DUGSDJHZLOODOORZ\RXWRYLHZWKHODWHVWUHOHDVH command line environment. To enter Python within the command
notes, and follow some online tutorials. line, you need to type: python and press Enter.

STEP 6 :LQGRZVXVHUVZLOOQRZƬQGWKHLQVWDOOHG STEP 9 The command line version of Python works in much the
Python 3.x within the Start button Recently Added same way as the Shell you opened in Step 7; note the
VHFWLRQ7KHƬUVWOLQN3\WKRQ[ ELW sRU%LW PRUHRQWKDW WKUHHOHIWIDFLQJDUURZV !!! :KLOHLWoVDSHUIHFWO\ƬQHHQYLURQPHQW
in a moment) - will launch the command line version of Python it’s not too user-friendly, so we’ll leave the command line for now. Enter
when clicked (more on that in a moment). To open the IDLE, type exit() to leave, and close the Command Prompt window.
IDLE into Windows start.

STEP 7 Clicking on the IDLE (Python 3.x 64-bit) link will STEP 10 There are two versions of the latest Python
launch the Python Shell, where we’ll begin our available, 32-Bit and 64-Bit. Essentially, the 64-Bit
Python programming journey. Don’t worry if your version is version of Python allows you to utilise more than 4GB of memory.
newer, as long as it’s Python 3.x our code will work inside your While this is great for users with a lot of memory, and memory hungry
Python 3 interface. processes, it’s not an essential feature of Python. However, the 32-bit
version may provide more compatibility with existing modules.

&RGLQJ 3URJUDPPLQJ 65
Introducing Python

How to Set Up
Python in Linux
:KLOHWKH5DVSEHUU\3LoVRSHUDWLQJV\VWHPFRQWDLQVWKHODWHVWVWDEOHYHUVLRQRI3\WKRQ
RWKHU/LQX[GLVWURVGRQoWFRPHZLWK3\WKRQSUHLQVWDOOHG,I\RXoUHQRWJRLQJGRZQ
WKH3LURXWHWKHQKHUHoVKRZWRFKHFNDQGLQVWDOO3\WKRQIRU/LQX[

PYTHON PENGUIN
/LQX[LVVXFKDYHUVDWLOHRSHUDWLQJV\VWHPWKDWLWoVRIWHQGLƯFXOWWRQDLOGRZQMXVWRQHZD\RIGRLQJVRPHWKLQJ'LƪHUHQW
GLVWULEXWLRQVJRDERXWLQVWDOOLQJVRIWZDUHLQGLƪHUHQWZD\VVRIRUWKLVSDUWLFXODUWXWRULDOZHZLOOVWLFNWR/LQX[0LQW

First you need to ascertain which version of Python Once the update and upgrade completes, enter:
STEP 1 STEP 4
is currently installed in your Linux system. To begin python3 --version again to see if Python 3.x is
with, drop into a Terminal session from your distro’s menu, or hit the updated, or even installed. As long as you have Python 3.x, you’re
Ctrl+Alt+T keys. running the most recent major version, the numbers after the 3.
indicate patches plus further updates. Often they’re unnecessary,
but they can contain vital new elements.

Next, enter: python --version into the Terminal


STEP 2
screen. You should have the output relating to
version 2.x of Python in the display. Most Linux distro come with
both Python 2 and 3 by default, as there’s plenty of code out there
still available for Python 2. Now enter: python3 --version.

However, if you want the latest, cutting edge


STEP 5
version, you’ll need to build Python from source.
Start by entering these commands into the Terminal:
sudo apt-get install build-essential checkinstall
sudo apt-get install libreadline-gplv2-dev
libncursesw5-dev libssl-dev libsqlite3-dev tk-dev
In our case we have both Python 2 and 3 installed. libgdbm-dev libc6-dev libbz2-dev
STEP 3
As long as Python 3.x.x is installed, then the code in
our tutorials will work. It’s always worth checking to see if the distro
has been updated with the latest versions, enter: sudo apt-get
update && sudo apt-get upgrade to update the system.

66 &RGLQJ 3URJUDPPLQJ
+RZWR6HW8S3\WKRQLQ/LQX[

Open up your Linux web browser and go to the For the GUI IDLE, you’ll need to enter the following
STEP 6 STEP 9
Python download page: https://www.python.org/ command into the Terminal:
downloads. Click on the Downloads, followed by the button under
sudo apt-get install idle3
the Python Source window. This opens a download dialogue box,
choose a location, then start the download process. The IDLE can then be started with the command: idle3. Note, that
,'/(UXQVDGLƪHUHQWYHUVLRQWRWKHRQH\RXLQVWDOOHGIURPVRXUFH

In the Terminal, go to the Downloads folder


STEP 7
by entering: cd Downloads/. Then unzip the
contents of the downloaded Python source code with: tar -xvf
Python-3.Y.Y.tar.xz (replace the Y’s with the version numbers
you’ve downloaded). Now enter the newly unzipped folder with: cd
Python-3.Y.Y/. You’ll also need PIP (Pip Installs Packages), which is
STEP 10
a tool to help you install more modules and extras.
Enter: sudo apt-get install python3-pip
Once PIP is installed, check for the latest update with:
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.

Within the Python folder, enter:


STEP 8
FRQ¿JXUH
sudo make altinstall
This could take a while, depending on the speed of your computer.
2QFHƬQLVKHGHQWHUpython3.7 --version to check the latest
installed version. You now have Python 3.7 installed, alongside older
Python 3.x.x and Python 2.

PYTHON ON macOS
Installation of Python on macOS can be done in much the
same way as the Windows installation. Simply go to the Python
webpage, hover your mouse pointer over the Downloads
link and select Mac OS X from the options. You will then be
guided to the Python releases for Mac versions, along with the
necessary installers for macOS 64-bit for OS X 10.9 and later.

&RGLQJ 3URJUDPPLQJ 67
Introducing Python

Python on the Pi
,I\RXoUHFRQVLGHULQJRQZKLFKSODWIRUPWRLQVWDOODQGXVH3\WKRQWKHQJLYHVRPH
WKRXJKWWRRQHRIWKHEHVWFRGLQJEDVHVDYDLODEOHWKH5DVSEHUU\3L7KH3LKDVPDQ\
DGYDQWDJHVIRUWKHFRGHULWoVFKHDSHDV\WRXVHDQGH[WUDRUGLQDULO\ƮH[LEOH

THE POWER OF PI
While having a far more powerful coding platform on which to write and test your code is ideal, it’s not often feasible. Most of
XVDUHXQDEOHWRMXPSLQWRDVHYHUDOKXQGUHGSRXQGLQYHVWPHQWZKHQZHoUHVWDUWLQJRƪDQGWKLVLVZKHUHWKH5DVSEHUU\3LFDQ
help out.

:KLOHKDYLQJDIDUPRUHSRZHUIXOFRGLQJSODWIRUPRQZKLFKWR NLWVDYDLODEOHZLOOSURYLGHWKH3LZLWKDSUHORDGHG6'FDUG ZLWKWKH


ZULWHDQGWHVW\RXUFRGHLVLGHDOLWoVQRWRIWHQIHDVLEOH0RVWRIXV ODWHVW5DVSELDQ26 DFDVHSRZHUVRFNHWDQGFDEOHVWKLVLVDJRRG
DUHXQDEOHWRMXPSLQWRDVHYHUDOKXQGUHGSRXQGLQYHVWPHQWZKHQ LGHDDV\RXFRXOGZLWKYHU\OLWWOHHƪRUWOHDYHWKH3LSOXJJHGLQWRWKH
ZHoUHVWDUWLQJRƪDQGWKLVLVZKHUHWKH5DVSEHUU\3LFDQKHOSRXW ZDOOXQGHUDGHVNZKLOHVWLOOEHLQJDEOHWRFRQQHFWWRLWDQGFRGH

7KH5DVSEHUU\3LLVDIDQWDVWLFSLHFHRIPRGHUQKDUGZDUHWKDW 7KHPDLQDGYDQWDJHLVRIFRXUVHWKHH[WUDFRQWHQWWKDWWKH
KDVFUHDWHGRUUDWKHUUHFUHDWHGWKHIDVFLQDWLRQZHRQFHDOOKDG 5DVSEHUU\3L)RXQGDWLRQKDVLQFOXGHGRXWRIWKHER[7KHUHDVRQ
DERXWFRPSXWHUVKRZWKH\ZRUNKRZWRFRGHDQGIRXQGDWLRQ IRUWKLVLVWKDWWKH5DVSEHUU\3LoVJRDOLVWRKHOSHGXFDWHWKH
OHYHOHOHFWURQLFV7KDQNVWRLWVXQLTXHPL[RIKDUGZDUHDQGFXVWRP XVHUZKHWKHUWKDWoVFRGLQJHOHFWURQLFVRUVRPHRWKHUDVSHFWRI
VRIWZDUHLWKDVSURYHGLWVHOIWREHDQDPD]LQJSODWIRUPRQZKLFKWR FRPSXWLQJ7RDFKLHYHWKDWJRDOWKH3L)RXQGDWLRQLQFOXGHVGLƪHUHQW
OHDUQKRZWRFRGHVSHFLƬFDOO\XVLQJ3\WKRQ ,'(VIRUWKHXVHUWRFRPSLOH3\WKRQFRGHRQDVZHOODVERWK3\WKRQ
DQG3\WKRQWKHUHoVHYHQD3\WKRQOLEUDU\WKDWDOORZV\RXWR
:KLOH\RXoUHDEOHZLWKHDVHWRXVHWKH5DVSEHUU\3LWROHDUQWR FRPPXQLFDWHZLWK0LQHFUDIW
FRGHZLWKRWKHUSURJUDPPLQJODQJXDJHVLWoV3\WKRQWKDWKDVEHHQ
ƬUPO\SXVKHGWRWKHIRUHIURQW7KH5DVSEHUU\3LXVHV5DVSELDQDV 7KHUHDUHRWKHUDGYDQWDJHVVXFKDVEHLQJDEOHWRFRPELQH3\WKRQ
LWVUHFRPPHQGHGGHIDXOWRSHUDWLQJV\VWHP5DVSELDQLVD/LQX[ FRGHZLWK6FUDWFK DQ2EMHFW2ULHQWHGSURJUDPPLQJODQJXDJH
26RUWREHPRUHDFFXUDWHLWoVD'HELDQEDVHGGLVWULEXWLRQRI GHYHORSHGE\0,7IRUFKLOGUHQWRXQGHUVWDQGKRZFRGLQJZRUNV DQG
/LQX[7KLVPHDQVWKDWWKHUHoVDOUHDG\DEXLOWLQHOHPHQWRI3\WKRQ EHLQJDEOHWRFRGHWKH*3,2FRQQHFWLRQRQWKH3LWRIXUWKHUFRQWURO
SURJUDPPLQJDVRSSRVHGWRDIUHVKLQVWDOODWLRQRI:LQGRZV DQ\DWWDFKHGURERWLFVRUHOHFWURQLFVSURMHFWV5DVSELDQDOVRLQFOXGHV
ZKLFKKDVQR3\WKRQVSHFLƬFEDVH+RZHYHUWKH5DVSEHUU\3L D6HQVH+$7(PXODWRU D+$7LVDKDUGZDUHDWWDFKHGSLHFHRI
)RXQGDWLRQKDVJRQHWKHH[WUDPLOHWRLQFOXGHDYDVWUDQJHRI FLUFXLWU\WKDWRƪHUVGLƪHUHQWHOHFWURQLFVURERWLFVDQGPRWRULVDWLRQ
3\WKRQPRGXOHVH[WHQVLRQVDQGHYHQH[DPSOHVRXWRIWKHER[ SURMHFWVWRWKH3L ZKLFKFDQEHDFFHVVHGYLD3\WKRQFRGH
6RHVVHQWLDOO\DOO\RXQHHGWRGRLVEX\D5DVSEHUU\3LIROORZWKH
LQVWUXFWLRQVRQKRZWRVHWRQHXS E\XVLQJRQHRIRXUH[FHOOHQW &RQVHTXHQWO\WKH5DVSEHUU\3LLVDQH[FHOOHQWFRGLQJEDVHDVZHOO
5DVSEHUU\3LJXLGHVIRXQGDWwww.SFOpublications.com DQG\RX DVDVXSHUESURMHFWIRXQGDWLRQ,WLVIRUWKHVHDQGPDQ\RWKHU
FDQVWDUWFRGLQJZLWK3\WKRQDVVRRQDVWKHGHVNWRSKDVORDGHG UHDVRQVZHoYHXVHGWKH5DVSEHUU\3LDVRXUPDLQ3\WKRQFRGHEDVH
WKURXJKRXWWKLVWLWOH:KLOHWKHFRGHLVZULWWHQDQGSHUIRUPHGRQD
6LJQLƬFDQWO\WKHUHoVDORWPRUHWRWKH5DVSEHUU\3LZKLFKPDNHV 3L\RXoUHDOVRDEOHWRXVHLWLQ:LQGRZVRWKHUYHUVLRQVRI/LQX[DQG
LWDQH[FHOOHQWFKRLFHIRUVRPHRQHZKRLVVWDUWLQJWROHDUQKRZWR PDF26,IWKHFRGHUHTXLUHVDVSHFLƬFRSHUDWLQJV\VWHPWKHQGRQoW
FRGHLQ3\WKRQ7KH3LLVUHPDUNDEO\HDV\WRVHWXSDVDKHDGOHVV ZRUU\ZHZLOOOHW\RXNQRZLQWKHWH[W
QRGH7KLVPHDQVWKDWZLWKDIHZWZHDNVKHUHDQGWKHUH\RXoUHDEOH
WRUHPRWHO\FRQQHFWWRWKH5DVSEHUU\3LIURPDQ\RWKHUFRPSXWHU
Everything you need to learn to code with Python is
RUGHYLFHRQ\RXUKRPHQHWZRUN)RUH[DPSOHRQFH\RXoYHVHWXS
included with the OS!
WKHUHPRWHFRQQHFWLYLW\RSWLRQV\RXFDQVLPSO\SOXJWKH3LLQWRWKH
SRZHUVRFNHWDQ\ZKHUHLQ\RXUKRXVHZLWKLQUDQJHRI\RXUZLUHOHVV
URXWHU$VORQJDVWKH3LLVFRQQHFWHG\RXZLOOEHDEOHWRUHPRWHO\
DFFHVVWKHGHVNWRSIURP:LQGRZVRUPDF26DVHDVLO\DVLI\RXZHUH
VLWWLQJLQIURQWRIWKH3LZLWKDNH\ERDUGDQGPRXVH

8VLQJWKLVPHWKRGVDYHVDORWRIPRQH\DV\RXGRQoWQHHGDQRWKHU
NH\ERDUGPRXVHDQGPRQLWRUSOXV\RXZRQoWQHHGWRDOORFDWH
VXƯFLHQWVSDFHWRDFFRPPRGDWHWKRVHH[WUDVHLWKHU,I\RXoUHSXVKHG
IRUVSDFHDQGPRQH\WKHQIRUDURXQG~EX\LQJRQHRIWKHPDQ\

68 &RGLQJ 3URJUDPPLQJ
Python on the Pi

There’s no such
thing as too
much Pi!

3,Ǖ(9(5
Introduced on 24th June 2019, the Raspberry Pi 4 Model B ZDV
DVLJQLƬFDQWOHDSLQWHUPVRI3LSHUIRUPDQFHDQGKDUGZDU
I H
VSHFLƬFDWLRQV,WZDVDOVRRQHRIWKHTXLFNHVWPRGHOVDVLGHIURPWKH
RULJLQDO3LWRVHOORXW <RXoOODOVRƬQGDSDLURI86%SRUWV%OXHWRRWKDQGD*38
WKDWoVFDSDEOH RI KDQGLQJ.UHVROXWLRQVDQG2SHQ*/(6JUDSKLFV
:LWKDQHZ*+]ELWTXDGFRUH$50&RUWH[$SURFHVVRU ,QVKRUWWKH3LLVRQHRI WKHPRVWSRZHUIXORIWKHFXUUHQW
DQGDFKRLFHRI*%*%RU*%PHPRU\YHUVLRQVWKH3LLV 5DVSEHUU\3LPRGHOV+RZHYHUWKHGLIIHUHQWPHPRU\YHUVLRQVKDYH
RQHVWHSFORVHUWREHFRPLQJDWUXHGHVNWRSFRPSXWHU,QDGGLWLRQ DQ LQFUHDVHGFRVW7KH*%YHUVLRQFRVWV~
V *%LV~DQGWKH
WKH3LZDVODXQFKHGZLWKWKHVWDUWOLQJGHFLVLRQWRLQFOXGHGXDO *%3LZLOOVHW\
W RXEDFN~5HPHPEHUWRDOVRIDFWRULQRQHRU
I
PRQLWRUVXSSRUWLQWKHIRUPRIDSDLURIWZRPLFUR+'0,SRUWV WZRPLFUR+'0,FDEOHVZLWK\RXURUGHU

RASPBIAN BUSTER
In addition to releasing the Pi 4, the Raspberry Pi team also compiled
a new version of the Raspbian operating system, codenamed Buster.

In conjunction with the new hardware the Pi 4 boasts, Busterr does


RƪHUDIHZXSGDWHV$OWKRXJKRQWKHZKROHLWoVYHU\VLPLODUU LQ
appearance and operation to the previous version of Raspbian. The
XSGDWHVDUHPDLQO\LQOLQHZLWKWKH.oVGLVSOD\DQGSOD\EDFNJLYLQJWKH
Pi 4 a new set of graphical drivers and performance enhancements.

,QVKRUWZKDW\RXVHHLQWKLVERRNZLOOZRUNZLWKWKH5DVSEHUU\3L
4 5DVSEHUU\3L and Raspbian Buster!

Once set up, you can remotely connect to the Pi’s desktop You can even test connected hardware with Python
from any device/PC. remotely, via Windows.

&RGLQJ 3URJUDPPLQJ 69
Coding with Python

,WoVDORQJZD\IURPFUHDWLQJ\RXUƬVW
Python code to controlling a robot
on Mars, but it’s not impossible.
Every advanced and professional
Python coder started with the
EDVHIXQGDPHQWDOVWLSVDQGƬ[HV
mentioned in this section.

With these foundation Python


concepts, you will be able to advance
your skills and branch out into
whatever Python project you have in
mind. From printing Hello World on
the screen, looking into conditions
and loops, asking a user for input and
reacting to it, to using variables to
control your code, this is where your
Python skills are forged.

72 Starting Python for the First Time


74 Your First Code
76 Saving and Executing Your Code
78 Executing Code from the Command Line
80 Numbers and Expressions
82 Using Comments
84 Working with Variables
86 User Input
88 Creating Functions
90 Conditions and Loops
92 Python Modules

70 &RGLQJ 3URJUDPPLQJ
Index

&RGLQJ 3URJUDPPLQJ 71
Coding with Python

Starting Python for


the First Time
We’re using Python 3 under Windows 10 for these following examples. Don’t worry if
your version of Python is 3.4.2, or something lesser than the current version, as long as
you’re using Python 3, the code will work.

STARTING PYTHON
$VZKHQOHDUQLQJDQ\WKLQJQHZ\RXQHHGWRVWDUWVORZ<RXFDQSLFNXSWKHSDFHDV\RXUH[SHULHQFHJURZVEXWIRUQRZOHWoV
just get something appearing on the screen. Don’t worry, you’ll soon be coding like a pro!

STEP 1 Click on the Windows Start button, and start typing STEP 3 For example, in the Shell enter: 2+2
‘idle’. The result will be the currently installed After pressing Enter, the next line will display the
version of the Python IDLE on your system. You can Pin it to the answer: 4. Basically, Python has taken the ‘code’ and produced the
Start for convenience, otherwise simply click the icon to launch the relevant output.
Python Shell.

STEP 2 The Shell is where you can enter code and see the STEP 4 The Python Shell acts very much like a calculator,
responses and output of code you’ve programmed since code is basically a series of mathematical
into Python. This is a kind of sandbox, if you will, where you’re able LQWHUDFWLRQVZLWKWKHV\VWHP,QWHJHUVZKLFKDUHWKHLQƬQLWH
to try out some simple code and processes. sequence of whole numbers, can easily be added, subtracted,
multiplied, and so on.

72 &RGLQJ 3URJUDPPLQJ
Starting Python for the First Time

STEP 5 While that’s very interesting, it’s not particularly STEP 8 7KH3\WKRQ,'/(LVDFRQƬJXUDEOHHQYLURQPHQW,I
exciting. Instead, try this: you don’t like the way the colours are represented,
then you can always change them via 2SWLRQV!&RQƬJXUH,'/(, and
print(“Hello everyone!”)
clicking on the Highlighting tab. However, we don’t recommend that
Just enter it into the IDLE as you’ve done in the previous steps. as you won’t be seeing the same as our screenshots.

STEP 6 This is a little more like it, since you’ve just produced STEP 9 As with most programs available, regardless of the
\RXUƬUVWELWRIFRGH7KH3ULQWFRPPDQGLVIDLUO\ operating system, there are numerous shortcut
self-explanatory, it prints things. Python 3 requires the parentheses keys. We don’t have room for them all here, but within the Options
as well as quotes in order to output content to the screen, in this !&RQƬJXUH,'/(DQGXQGHUWKHKeys tab, you’ll see a list of the
case the ‘Hello everyone!’ bit. current bindings.

STEP 7 You’ll have noticed the colour coding within the STEP 10 The Python IDLE is a power interface, and one
3\WKRQ,'/(7KHFRORXUVUHSUHVHQWGLƪHUHQW that’s actually been written in Python using one
elements of Python code. They are: of the available GUI toolkits. If you want to know the many ins and
outs for the Shell, we recommend you take a few moments to view
Black – Data and Variables Blue – User Functions
https://docs.python.org/3/library/idle.html, which details many of
Green – Strings Dark Red – Comments
the IDLE’s features.
Purple – Functions Light Red – Error Messages
Orange – Commands

&RGLQJ 3URJUDPPLQJ 73
Coding with Python

Your First Code


(VVHQWLDOO\\RXoYHDOUHDG\ZULWWHQ\RXUƬUVWSLHFHRIFRGHZLWKWKHSULQW p+HOOR
HYHU\RQHq IXQFWLRQIURPWKHSUHYLRXVWXWRULDO+RZHYHUOHWoVH[SDQGWKDWDQGORRNDW
entering your code and playing around with some other Python examples.

3/$<,1*:,7+3<7+21
As with most languages, computer or human, it’s all about remembering and applying the right words to the right situation.
You’re not born knowing these words, so you need to learn them.

STEP 1 If you’ve closed Python 3 IDLE, re-open it as you STEP 3 You’ll notice that instead of the number 4, the
did in the previous page. In the Shell, enter the output is the 2+2 you asked to be printed to the
familiar following: VFUHHQ7KHTXRWDWLRQPDUNVDUHGHƬQLQJZKDWoVEHLQJRXWSXWWHG
to the IDLE Shell, to print the total of 2+2 you’ll need to remove
print(“Hello”)
the quotes:
print(2+2)

STEP 2 As predicted, the word Hello appears in the Shell STEP 4 You can continue as such, printing 2+2, 464+2343
as blue text indicating output from a string. It’s and so on to the Shell. An easier way is to use a
fairly straightforward, and doesn’t require too much explanation. variable, which is something we will cover in more depth later. For
Now try: now, enter:
print(“2+2”) a=2
b=2

74 &RGLQJ 3URJUDPPLQJ
Your First Code

STEP 5 What you have done here is assign the letters a STEP 8 Now let’s add a surname:
and b two values: 2 and 2. These are now variables,
surname=”Hayward”
which can be called upon by Python to output, add, subtract, divide
print(surname)
and so on, for as long as their numbers stay the same. Try this:
:HQRZKDYHWZRYDULDEOHVFRQWDLQLQJERWKDƬUVWQDPHDQGD
print(a)
surname, and we can print them independently.
print(b)

STEP 6 The output of the last step displays the current STEP 9 If we were to apply the same routine as before,
values of a and b individually, as essentially you’ve using the + symbol, the name wouldn’t appear
asked them to be printed separately. If you want to add them up, correctly in the output in the Shell. Try it:
you can use the following:
print(name+surname)
print(a+b)
:HQHHGDVSDFHEHWZHHQWKHWZRGHƬQLQJWKHPDVWZRVHSDUDWH
This code takes the value of both a and b, adds them together, and values and not something you mathematically play around with.
outputs the result.

STEP 7 <RXFDQSOD\DURXQGZLWKGLƪHUHQWNLQGVRIYDULDEOHV STEP 10 In Python 3 we can separate the two variables


together with the Print function. For example, we with a space by using a comma:
could assign variables for someone’s name:
print(name, surname)
name=”David”
Alternatively, you can add the space yourself:
print(name)
print(name+” “+surname)
As you can see, the use of the comma is much neater.
&RQJUDWXODWLRQV\RXoYHMXVWWDNHQ\RXUƬUVWVWHSVLQWRWKHZLGH
world of Python.

&RGLQJ 3URJUDPPLQJ 75
Coding with Python

Saving and Executing


Your Code
:KLOHZRUNLQJLQWKH,'/(6KHOOLVSHUIHFWO\ƬQHIRUVQLSSHWVRIFRGHLWoVQRWGHVLJQHG
for entering longer program listings. In this section, we’ll introduce you to the IDLE
Editor, where most of our code will be entered from now on.

EDITING CODE
You will eventually reach a point where you have to move on from inputting single lines of code into the Shell. Instead, the
,'/((GLWRUZLOODOORZ\RXWRVDYHDQGH[HFXWH\RXU3\WKRQFRGH

STEP 1 First, open the Python IDLE Shell. When it’s up, click STEP 3 As you can see the same colour coding is in place in
on File > New File, this will open a new window with the IDLE Editor as it is in the Shell, enabling you to
Untitled as its name. This is the Python IDLE Editor, and within it, you better understand what’s going on with your code. To execute the
can enter the code you need to create your future programs. FRGHKRZHYHU\RXQHHGWRƬUVWVDYHLW3UHVVF5 and you’ll have a
Save…Check box open.

STEP 2 The IDLE Editor is, for all intents and purposes, a STEP 4 Click on the OK button in the Save box, and select a
simple text editor with Python features, colour destination where you’ll save all your Python code.
coding and so on. You enter code as you would within the Shell, so The destination can be a dedicated folder called Python, or you can
taking an example from the previous tutorial, enter: MXVWGXPSLWZKHUHYHU\RXOLNH5HPHPEHUWRNHHSDWLG\ƬOHV\VWHP
though, it’ll help you out in the future.
print(“Hello everyone!”)

76 &RGLQJ 3URJUDPPLQJ
Saving and Executing Your Code

STEP 5 Enter a name for your code, ‘print hello’ for STEP 8 Let’s extend the code and enter a few examples
example, and click on the Save button. As soon from the previous tutorial:
as the Python code is saved, it’s executed and the output will be
a=2
detailed in the IDLE Shell; In this case, the words ‘Hello everyone!’.
b=2
name=”David”
surname=”Hayward”
print(name, surname)
print (a+b)
If you press F5QRZ\RXoOOEHDVNHGWRVDYHWKHƬOHDJDLQDVLWoVEHHQ
PRGLƬHGIURPEHIRUH

STEP 6 This is how the vast majority of your Python code STEP 9 If you click the OKEXWWRQWKHƬOHZLOOEHRYHUZULWWHQ
will be conducted. Enter it into the Editor, hit F5, with the new code entries, and executed; with the
save the code, and look at the output in the Shell. Sometimes things output in the Shell. It’s not a problem with just these few lines, but
ZLOOGLƪHUGHSHQGLQJRQZKHWKHU\RXoYHUHTXHVWHGDVHSDUDWH LI\RXZHUHWRHGLWDODUJHUƬOHRYHUZULWLQJFDQEHFRPHDQLVVXH
window, but essentially that’s the process and, unless otherwise Instead, use File > Save As from within the Editor to create a backup.
stated, this is the method we will use.

STEP 7 ,I\RXRSHQWKHƬOHORFDWLRQRIWKHVDYHG3\WKRQ STEP 10 1RZFUHDWHDQHZƬOH&ORVHWKH(GLWRUDQGRSHQ


code, you’ll notice that it ends in a .py extension. a new instance (File > New File from the Shell).
7KLVLVWKHGHIDXOW3\WKRQƬOHQDPHDQ\FRGH\RXFUHDWHZLOOEH Enter the following, and save it as hello.py:
whatever.py, and any code downloaded from the many Internet
a=”Python”
Python resource sites will be .py. Just ensure that the code is written
b=”is”
for Python 3.
c=”cool!”
print(a, b, c)
We will use this code in the next tutorial.

&RGLQJ 3URJUDPPLQJ 77
Coding with Python

Executing Code from


the Command Line
While we’re going to be working from the GUI IDLE, it’s worth taking a moment to look
at Python’s command line handling. Sometimes, depending on the code you write,
executing via the command line is a better solution over the IDLE.

COMMAND THE CODE


Using the code we created in the previous tutorial, the one we named hello.py, let’s see how we can run code that was made in
the GUI at the command line level.

STEP 1 :KHQ\RXƬUVWLQVWDOOHG3\WKRQWKHLQVWDOODWLRQ STEP 3 Now you’re at the command line, we can start
routine automatically included all the necessary Python using the command python and pressing
components to allow the execution of code outside of the GUI the Enter key. This will put you into the command line version of the
IDLE; in other words, the command line. To begin with, click on the Shell, with the familiar, three right-facing arrows as the cursor (>>>).
Windows Start Button, and type: cmd.

STEP 2 As you did when launching the Python IDLE, STEP 4 From here you’re able to enter the code you’ve
click on the returned result from the search, the looked at previously, such as:
Command Prompt App. This will launch a new window, with a black
a=2
background and white text. This is the command line, also called a
print(a)
Terminal in macOS, Linux, and Raspberry Pi operating systems.
As you can see, it works exactly the same.

78 &RGLQJ 3URJUDPPLQJ
Executing Code from the Command Line

STEP 5 Now enter exit() to leave the command line STEP 6 From within the same folder as the code you’re going
Python session, and return back to the command to run, enter the following into the command line:
prompt. Enter the folder where you saved the code from the
python hello.py
SUHYLRXVWXWRULDODQGOLVWWKHDYDLODEOHƬOHVZLWKLQ\RXVKRXOGVHH
the hello.pyƬOH This will execute the code we created, which to remind you is:
a=”Python”
b=”is”
c=”cool!”
print(a, b, c)

DIFFERENT VERSIONS OF PYTHON


If you’ve previously used Python 3 on a Mac or Linux, and This isn’t an issue with Windows, as it doesn’t use any Python
subsequently the Raspberry Pi, you may be a little confused as libraries other than the ones installed by the user themselves
to why the Windows version of Python uses the command line: when actually installing Python. When a Windows user installs
python, instead of python3. Python, the installation wizard will auto-include the command line
instance to the core Windows PATH variable, which you can view by
The reason behind this is that UNIX-like systems, such as macOS entering: path into the command line. This points to the python.
and Linux, already have Python libraries pre-installed. These older H[HƬOHUHTXLUHGWRH[HFXWH3\WKRQFRGHIURPWKHFRPPDQGOLQH
libraries are present because some of the macOS and Linux system
utilities rely on Python 2, and therefore installing a newer version We don’t recommend you install both Python 2 and Python 3
of Python, and thus altering the executable name, could have dire within Windows 10; naturally, you can if you want, but realistically,
consequences to the system. although Python 2 still has a foothold in the coding world, Python
3 is the newest version. However, if you do, then you will need to
As a result, developers decided that the best approach for macOS rename one of the Python versions names; as they will be installed
and Linux systems would be to leave the command line ‘python’ LQGLƪHUHQWIROGHUVDQGERWKXVHS\WKRQH[HDVWKHFRPPDQGOLQH
as exclusive Python 2 use, and newer versions of user-installed executable. It’s a little long-winded, so unless there’s a dire need to
Python would be ‘python3’. have both versions of Python installed, it’s best to stick to Python 3.

&RGLQJ 3URJUDPPLQJ 79
Coding with Python

Numbers and Expressions


We’ve seen some basic mathematical expressions with Python, simple addition and the
like. Now let’s expand on that, and see just how powerful Python is as a calculator. You
can work within the IDLE Shell, or in the Editor, whichever you like.

,7o6$//0$7+60$1
You can get some really impressive results from the mathematical powers of Python, as maths is the driving force behind the
code with most, if not all, programming languages.

STEP 1 Open up the GUI version of Python 3, as mentioned STEP 3 You can use all
you can use either the Shell or the Editor. For the the customary
time being, we’re going to use the Shell. If you’ve opted to use a Mathematical operations: divide,
third-party text editor, note that you need to get to the IDLE Shell multiply, brackets and so on.
for this part of the tutorial. Practise with a few, for example:
1/2
6/2
2+2*3
(1+2)+(3*4)

STEP 2 In the Shell enter the following: STEP 4 As you’ve no


doubt noticed,
2+2
division produces a decimal
54356+34553245
number. In Python, these are
99867344*27344484221
FDOOHGƮRDWVRUƮRDWLQJSRLQW
As you can see, Python can handle some quite large numbers. arithmetic. If however, you
need an integer as opposed to a
decimal answer, then you can use
a double slash:
1//2
6//2
and so on.

80 &RGLQJ 3URJUDPPLQJ
Numbers and Expressions

STEP 5 You can also use STEP 8 This will be


an operation to displayed as
see the remainder left over from ‘0b11’, converting the integer
division. For example: LQWRELQDU\DQGDGGLQJWKHSUHƬ[
0b to the front. If you want to
10/3
UHPRYHWKHESUHƬ[WKHQ\RX
will display 3.333333333, which can use:
is, of course, 3.3-recurring. If you
format(3, ‘b’)
now enter:
The Format command converts
10%3
a value, the number 3, to a
This will display 1, which is the formatted representation
remainder left over from dividing as controlled by the format
10 by 3. VSHFLƬFDWLRQWKHnEoSDUW

STEP 6 Next up we STEP 9 A Boolean Expression is a logical statement that will


have the power either be true or false. We can use these to compare
operator, or exponentiation data, and test to see if it’s equal to, less than, or greater than. Try
if you want to be technical. this in a New File:
To work out the power of
a = 6
something you can use a
b = 7
double multiplication symbol,
print(1, a == 6)
or double-star on the keyboard:
print(2, a == 7)
2**3 print(3, a == 6 and b == 7)
10**10 print(4, a == 7 and b == 7)
print(5, not a == 7 and b == 7)
Essentially, it’s 2x2x2, but we’re
print(6, a == 7 or b == 7)
sure you already know the
print(7, a == 7 or b == 6)
basics behind maths operators.
print(8, not (a == 7 and b == 6))
This is how you would work it
print(9, not a == 7 and b == 6)
out in Python.

STEP 7 Numbers and STEP 10 Execute the code from Step 9, and you’ll see a
expressions don’t series of True or False statements depending on
stop there. Python has numerous WKHUHVXOWRIWKHWZRGHƬQLQJYDOXHVDQG,WoVDQH[WHQVLRQRI
built-in functions to work out what we’ve looked at, and an important part of programming.
sets of numbers, absolute values,
complex numbers, and a host of
Mathematical expressions and
Pythogarian tongue-twisters. For
example, to convert a number to
binary, use:
bin(3)

&RGLQJ 3URJUDPPLQJ 81
Coding with Python

Using Comments
:KHQZULWLQJ\RXUFRGHWKHƮRZZKDWHDFKYDULDEOHGRHVKRZWKHRYHUDOOSURJUDP
will operate and so on, is all inside your head. Another programmer could follow the
code line by line, but when the code starts to hit thousands of lines, things get a little
GLƯFXOWWRUHDG

#COMMENTS!
$PHWKRGXVHGE\PRVWSURJUDPPHUVIRUNHHSLQJWKHLUFRGHUHDGDEOHLVE\FRPPHQWLQJRQFHUWDLQVHFWLRQV)RUH[DPSOHLID
variable is used, the programmer comments on what it’s supposed to do. It’s just good practise.

STEP 1 We’ll start by creating a new instance of the IDLE STEP 3 Re-save the code and execute it. You’ll see that the
Editor (File > New File), and then create a simple output in the IDLE Shell is still the same as before,
variable and print command: despite the extra lines being added. Simply put, the hash symbol (#)
denotes a line of text the programmer can insert, to inform them
a=10
and others of what’s going on, without the user being aware.
print(“The value of A is,”, a)
6DYHWKHƬOHDQGH[HFXWHWKHFRGH

STEP 2 Running the code will return the line: The value of STEP 4 Let’s assume that the variable A we’ve created is
A is, 10 into the IDLE Shell window – which is what the number of lives in a game. Every time the player
we expected. Now let’s add some of the types of comments you’d dies, the value decreases by 1. The programmer could insert a
normally see within code: routine along the lines of:
# Set the start value of A to 10 a=a-1
a=10 print(“You’ve just lost a life!”)
# Print the current value of A print(“You now have”, a, “lives left!”)
print(“The value of A is,”, a)

82 &RGLQJ 3URJUDPPLQJ
Using Comments

STEP 5 While we know that the variable A denotes number STEP 8 Inline Comments are comments that follow a
of lives and the player has just lost one, a casual section of code. Take our examples from above,
viewer, or someone checking the code, may not know. Imagine for a instead of inserting the code on a separate line, we could use:
moment that the code is twenty thousand lines long, instead of just
a=10 # Set the start value of A to 10
our seven. You can see how handy comments are.
print(“The value of A is,”, a) # Print the current
value of A
a=a-1 # Player lost a life!
print(“You’ve just lost a life!”)
print(“You now have”, a, “lives left!”) # Inform
player, and display current value of A (lives)

STEP 6 Essentially, the new code together with comments STEP 9 The comment, the hash symbol, can also be used to
could look like: comment out sections of code you don’t want to be
executed in your program. For instance, if you wanted to remove
# Set the start value of A to 10
WKHƬUVWSULQWVWDWHPHQW\RXZRXOGXVH
a=10
# Print the current value of A # print(“The value of A is,”, a)
print(“The value of A is,”, a)
# Player lost a life!
a=a-1
# Inform player, and display current value of A
(lives)
print(“You’ve just lost a life!”)
print(“You now have”, a, “lives left!”)

STEP 7 <RXFDQXVHFRPPHQWVLQGLƪHUHQWZD\V)RU STEP 10 You also use three single quotes to comment
example, Block Comments are a large section of out a Block Comment, or multi-line section of
text that details what’s going on in the code, such as telling the code comments. For them to work, place them before and after the areas
reader which variables you’re planning on using: you want to comment:
# This is the best game ever, and has been ‘’’
developed by a crack squad of Python experts This is the best game ever, and has been developed
# who haven’t slept or washed in weeks. Despite by a crack squad of Python experts
being very smelly, the code at least who haven’t slept or washed in weeks. Despite
# works really well. being very smelly, the code at least
works really well. ’’’

&RGLQJ 3URJUDPPLQJ 83
Coding with Python

Working with Variables


We’ve seen some examples of variables in our Python code already, but it’s always
worth going through the way they operate, and how Python creates and assigns
certain values to a variable.

9$5,2869$5,$%/(6
:HoOOEHZRUNLQJZLWKWKH3\WKRQ,'/(6KHOOLQWKLVWXWRULDO,I\RXKDYHQoWDOUHDG\RSHQ3\WKRQRUFORVHGRZQWKHSUHYLRXV
,'/(6KHOOWRFOHDUXSDQ\ROGFRGH

STEP 1 In some programming languages, you’re required STEP 3 As we’ve seen previously, variables can be
to use a dollar sign to denote a string, which is a concatenated using the plus symbol between the
variable made up of multiple characters, such as a name of a person. variable names. In our example, we can use: print (name + “:
In Python this isn’t necessary, so, for example, in the Shell enter: “ + title). The middle part, between the quotations, allows
name=”David Hayward” (use your own name, unless you’re also us to add a colon and a space. As variables are connected without
called David Hayward). spaces, we need to add them manually.

STEP 2 You can check the type of variable in use by issuing STEP 4 We can also
the type () command, placing the name of the combine variables
variable inside the brackets. In our example, this would be: within another variable. For
type (name). Add a new string variable: title=”Descended example, to combine both name
from Celts”. and title variables into a new
variable, we use:
character=name + “: “ +
title
Then output the content of the
new variable as:
print (character)
1XPEHUVDUHVWRUHGDVGLƪHUHQW
variables:
age=44
Type (age)
Which, as we know, are integers.

84 &RGLQJ 3URJUDPPLQJ
Working with Variables

STEP 5 However, you can’t combine both strings and STEP 8 This presents a bit of a problem when you want
integer type variables in the same command as you to work with a number that’s been inputted by
would a set of similar variables. You’ll need to turn one into the the user, for example, as age + 10 is both a string variable and an
other, or vice versa. When you do try to combine both, you’ll get an integer, it won’t work. Instead, you need to enter:
error message:
int(age) + 10
print (name + age)
This will TypeCast the age string into an integer that can be
worked with.

STEP 6 This is a process known as TypeCasting. The Python STEP 9 The use of TypeCasting is also important when
code is: GHDOLQJZLWKƮRDWLQJSRLQWDULWKPHWLFUHPHPEHU
numbers that have a decimal point in them. For example, enter:
print (character + “ is “ + str(age) + “ years
old.”) shirt=19.99
Alternatively, you can use: Now enter: type(shirt) and you’ll see that Python has allocated
WKHQXPEHUDVDnƮRDWoEHFDXVHWKHYDOXHFRQWDLQVDGHFLPDOSRLQW
print (character, “is“, age, “years old.”)
Notice again that in the last example, you don’t need the spaces
between the words in quotes, as the commas treat each argument
to print separately.

STEP 7 Another example of TypeCasting is when you ask STEP 10 :KHQFRPELQLQJLQWHJHUVDQGƮRDWV3\WKRQ


for input from the user, such as a number. for XVXDOO\FRQYHUWVWKHLQWHJHUWRDƮRDWEXWVKRXOG
example, enter: the reverse ever be applied, it’s worth remembering that Python
GRHVQoWUHWXUQWKHH[DFWYDOXH:KHQFRQYHUWLQJDƮRDWWRDQ
age= input (“How old are you? “)
integer, Python will always round down to the nearest integer,
All data stored from the Input command is stored as a string variable. called truncating; in our case instead of 19.99, it becomes 19.

&RGLQJ 3URJUDPPLQJ 85
Coding with Python

User Input
We’ve seen some basic user interaction with the code from a few of the examples
earlier, so now would be a good time to focus solely on how you get information from
the user, then store and present it.

86(5)5,(1'/<
7KHW\SHRILQSXW\RXZDQWIURPWKHXVHUZLOOGHSHQGJUHDWO\RQWKHW\SHRISURJUDP\RXoUHFRGLQJ$JDPHIRUH[DPSOHPD\
ask for a character’s name, whereas a database can ask for personal details.

STEP 1 If it’s not already, open the Python 3 IDLE Shell, STEP 3 Now that we have the user’s name stored in a
and start a New File in the Editor. Let’s begin with couple of variables, we can call them up whenever
something really simple, enter: we want:
print(“Hello”) SULQW ³:HOFRPH´¿UVWQDPHVXUQDPH³,KRSH
¿UVWQDPH LQSXW ³:KDWLV\RXU¿UVWQDPH"³ you’re well today.”)
print(“Thanks.”)
surname=input(“And what is your surname? “)

STEP 2 Save and execute the code, and, as you no doubt STEP 4 Run the code and you’ll notice a slight issue, the
suspected, in the IDLE Shell the program will ask full stop after the surname follows a blank space.
IRU\RXUƬUVWQDPHVWRULQJLWDVWKHYDULDEOHƬUVWQDPH, followed by To eliminate that, we can add a plus sign instead of the comma in
your surname; also stored in its own variable (surname). the code:
SULQW ³:HOFRPH´¿UVWQDPHVXUQDPH³,KRSH
you’re well today.”)

86 &RGLQJ 3URJUDPPLQJ
User Input

STEP 5 You don’t always have to include quoted text within STEP 8 What you’ve created here is a condition, based on
the input command. For example, you can ask the the user’s input. In short, we’re using the input
user their name, and have the input in the line below: from the user and measuring it against a condition. Therefore, if the
user enters David as their name, the guard will allow them to pass
SULQW ³+HOOR:KDW¶V\RXUQDPH"´
unhindered. If, however, they enter a name other than David, the
name=input()
JXDUGFKDOOHQJHVWKHPWRDƬJKW

STEP 6 The code from the previous step is often regarded STEP 9 As you learned previously, any input from a user
as being a little neater than having a lengthy is automatically a string, so you’ll need to apply a
amount of text in the input command, but it’s not a rule that’s set in TypeCast in order to turn it into something else. This creates some
stone, so do as you like in these situations. Expanding on the code, interesting additions to the input command. For example:
try this:
# Code to calculate rate and distance
SULQW ³+DOW:KRJRHVWKHUH"´ print(“Input a rate and a distance”)
name=input() UDWH ÀRDW LQSXW ³5DWH³

STEP 7 It’s a good start to a text adventure game, perhaps? STEP 10 $QGWRƬQDOLVHWKHUDWHDQGGLVWDQFHFRGHZHFDQDGG
Now we can expand on it, and use the raw input
GLVWDQFH ÀRDW LQSXW ³'LVWDQFH³
IURPWKHXVHUWRƮHVKRXWWKHJDPHDOLWWOH
print(“Time:”, (distance / rate))
if name==”David”:
Save and execute the code, and enter some numbers. Using the
SULQW ³:HOFRPHJRRGVLU<RXPD\SDVV´
ƮRDW LQSXW element, we’ve told Python that anything entered is a
else:
ƮRDWLQJSRLQWQXPEHUUDWKHUWKDQDVWULQJ
print(“I know you not. Prepare for battle!”)

&RGLQJ 3URJUDPPLQJ 87
Coding with Python

Creating Functions
Now that you’ve mastered the use of variables and user input, the next step is to tackle
functions. You’ve already used a few functions, such as the print command, but Python
HQDEOHV\RXWRGHƬQH\RXURZQIXQFWLRQ

FUNKY FUNCTIONS
A function is a command that you enter into Python in order to do something. It’s a little piece of self-contained code that
takes data, works on it, and then returns the result.

STEP 1 It’s not only data that a function works on. Functions STEP 3 You can pass variables through functions in much
can do all manner of useful things in Python, such as the same manner. Let’s assume you want the
sort data, change items from one format to another, and check the number of letters in a person’s surname, you could use the following
length or type of items. Basically, a function is a short word followed code (enter the text editor for this example):
by brackets. For example, len(), list(), or type().
name=input (“Enter your surname: “)
count=len(name)
print (“Your surname has“, count, “letters in
it.”)
Press F5 and save the code to execute it.

STEP 2 A function takes data, usually a variable, works on STEP 4 Python has tens of functions built into it, far too
it depending on what the function is programmed many to get into in the limited space available here.
to do, and returns the end value. The data being worked on goes However, to view the list of built-in functions available to Python
inside the brackets, so if you wanted to know how many letters 3, navigate to https://docs.python.org/3/library/functions.html.
are in the word antidisestablishmentarianism, then you’d enter: 7KHVHDUHWKHSUHGHƬQHGIXQFWLRQVEXWVLQFHXVHUVKDYHFUHDWHG
len(“antidisestablishmentarianism”), and the number 28 many more, they’re not the only ones available.
would return.

88 &RGLQJ 3URJUDPPLQJ
Creating Functions

STEP 5 Additional functions can be added to Python STEP 6 To use a function from a module, enter the name of
through modules. Python has a vast range of the module, followed by a full stop, then the name
modules available that can cover numerous programming duties. of the function. For instance, using the math module, since we’ve
They add functions and can be imported as and when required. For just imported it into Python, we can utilise the square root function.
example, to use advanced Mathematics functions enter: To do so, enter:
import math math.sqrt(16)
Once entered, you’ll have access to all the Math module functions. As you can see, the code is presented as module.function(data).

FORGING FUNCTIONS
7KHUHDUHPDQ\GLƪHUHQWIXQFWLRQVFUHDWHGE\RWKHU3\WKRQSURJUDPPHUVZKLFK\RXFDQLPSRUWDQG\RXoOOXQGRXEWHGO\FRPH
DFURVVVRPHH[FHOOHQWH[DPSOHVLQWKHIXWXUH+RZHYHU\RXFDQDOVRFUHDWH\RXURZQZLWKWKHdef command.

STEP 1 Choose File > New File to enter the editor, let’s STEP 3 To modify it further, delete the Hello(“David”) line,
FUHDWHDIXQFWLRQFDOOHG+HOORWKDWZLOOJUHHWD the last line in the script, and press Ctrl+S to save
user. Enter: WKHQHZVFULSW&ORVHWKH(GLWRUDQGFUHDWHDQHZƬOH File > New
File). Enter the following:
def Hello():
print (“Hello”) from Hello import Hello
Hello() Hello(“David”)
Press F5WRVDYHDQGUXQWKHVFULSW<RXoOOVHH+HOORLQWKH6KHOO Press F5 to save and execute the code.
type in Hello() and it’ll return the new function.

STEP 2 Let’s now expand the function to accept a variable, STEP 4 :KDW\RXoYHMXVWGRQHLVLPSRUWWKH+HOORIXQFWLRQ
the user’s name for example. Edit your script to read: IURPWKHVDYHG+HOORS\SURJUDPDQGWKHQXVHGLW
to say hello to David. This is how modules and functions work, you
def Hello(name):
import the module then use the function. Try this one, and modify
print (“Hello”, name)
it for extra credit:
Hello(“David”)
def add(a, b):
7KLVZLOOQRZDFFHSWWKHYDULDEOHQDPHRWKHUZLVHLWZLOOSULQW+HOOR
result = a + b
David. In the Shell, enter: name=(“Bob”), then, Hello(name).
return result
Your function can now pass variables through it.

&RGLQJ 3URJUDPPLQJ 89
Coding with Python

Conditions and Loops


Conditions and loops are what make a program interesting, they can be simple or rather
FRPSOH[+RZ\RXXVHWKHPGHSHQGVJUHDWO\RQZKDWWKHSURJUDPLVWU\LQJWRDFKLHYH
they could be the number of lives left in a game, or just displaying a countdown.

TRUE CONDITIONS
.HHSLQJFRQGLWLRQVVLPSOHWREHJLQZLWKPDNHVOHDUQLQJWRSURJUDPDPRUHHQMR\DEOHH[SHULHQFH/HWoVVWDUWWKHQE\
checking if something is TRUE, then doing something else if it isn’t.

STEP 1 Let’s create a new Python program that will ask the STEP 3 Now we’ll use an if statement to check if the word_
user to input a word, then check it to see if it’s a length variable is equal to four, and print a friendly
four-letter word or not. Start with File > New File, and begin with conformation if it applies to the rule:
the input variable:
word=input(“Please enter a four-letter word: “)
word=input(“Please enter a four-letter word: “) word_length=len(word)
if word_length == 4:
SULQW ZRUG³LVDIRXUOHWWHUZRUG:HOOGRQH´
The double equal sign (==) check if something is equal to
something else.

STEP 2 Now we can create a new variable, then use the len STEP 4 The colon at the end of if tells Python that if this
function and pass the word variable through it to statement is true, do everything after the colon
get the total number of letters the user has just entered: that’s indented. Next, move the cursor back to the beginning of
the Editor:
word=input(“Please enter a four-letter word: “)
word_length=len(word) word=input(“Please enter a four-letter word: “)
word_length=len(word)
if word_length == 4:
SULQW ZRUG³LVDIRXUOHWWHUZRUG:HOO
done.”)
else:
print (word, “is not a four-letter word.”)

90 &RGLQJ 3URJUDPPLQJ
Conditions and Loops

STEP 5 Press F5 and save the code to execute it. Enter STEP 6 Now expand the code to include other conditions.
a four-letter word in the Shell to begin with, you Eventually, it could become quite complex. We’ve
should have the returned message that the word is four letters. added a condition for three-letter words:
Now press F5 again, and re-run the program, but this time, enter a
word=input(“Please enter a four-letter word: “)
ƬYHOHWWHUZRUG7KH6KHOOZLOOGLVSOD\WKDWLWoVQRWDIRXUOHWWHUZRUG
word_length=len(word)
if word_length == 4:
SULQW ZRUG³LVDIRXUOHWWHUZRUG:HOO
done.”)
elif word_length == 3:
print (word, “is a three-letter word. Try again.”)
else:
print (word, “is not a four-letter word.”)

/2236
$OWKRXJKDORRSORRNVTXLWHVLPLODUWRDFRQGLWLRQWKH\DUHVRPHZKDWGLƪHUHQWLQWKHLURSHUDWLRQ$ORRSZLOOUXQWKURXJKWKH
same block of code a number of times, usually with the support of a condition.

STEP 1 Let’s start with a simple while statement. Like if, STEP 3 The for loop, is another example. For is used to
this will check to see if something is TRUE, then run loop over a range of data, usually a list stored as
the indented code: variables inside square brackets. For example:
x = 1 words=[“Cat”, “Dog”, “Unicorn”]
while x < 10:
for word in words:
print (x)
print (word)
x = x + 1

STEP 2 7KHGLƪHUHQFHEHWZHHQif and while is that when STEP 4 The for loop can also be used in the countdown
while gets to the end of the indented code, it goes example by using the range function:
back and checks the statement is still true. In our example x is less
for x in range (1, 10):
than 10. With each loop, it prints the current value of x, then adds
print (x)
one to that value. When x does eventually equal 10 it’ll stop.
The x=x+1 part isn’t needed here, because the range function
FUHDWHVDOLVWEHWZHHQWKHƬUVWDQGODVWQXPEHUVXVHG

&RGLQJ 3URJUDPPLQJ 91
Coding with Python

Python Modules
We’ve mentioned modules previously, using the Math module as an example, but since
using modules is such a large part of getting the most from Python it’s worth dedicating
a little more time to them.

0$67(5,1*02'8/(6
7KLQNRIPRGXOHVDVDQH[WHQVLRQWKDWoVLPSRUWHGLQWR\RXU3\WKRQFRGHWRHQKDQFHDQGH[WHQGLWVFDSDELOLWLHV7KHUHDUH
countless modules available, and as we’ve seen, you can even make your own.

STEP 1 Although good, the built-in functions within Python STEP 3 The result is an error in the IDLE Shell, as the
are limited. The use of modules, however, allows us Pygame module isn’t recognised or installed in
to make more sophisticated programs. As you are aware, modules Python. To install a module we can use PIP (Pip Installs Packages).
are Python scripts that are imported, such as import math. Close down the IDLE Shell and drop into a command prompt or
Terminal session. At an elevated admin command prompt, enter:
pip install pygame

STEP 2 Some modules, especially on the Raspberry Pi, are STEP 4 The PIP installation requires an elevated status due
included by default; the Math module is a prime WRLWLQVWDOOLQJFRPSRQHQWVDWGLƪHUHQWORFDWLRQV
example. Sadly, other modules aren’t always available. A good Start with a search for CMD, via the Start button, right-click the
example on non-Pi platforms is the Pygame module, which contains result, and then click Run as Administrator. Linux and Mac users can
many functions to help create games. Try: import pygame. use the Sudo command, with sudo pip install package.

92 &RGLQJ 3URJUDPPLQJ
Python Modules

STEP 5 Close the command prompt or Terminal, and re- STEP 8 Multiple modules can be imported within your code.
launch the IDLE Shell. When you now enter import To extend our example, use:
pygame, the module will be imported into the code without any
import random
SUREOHPV<RXoOOƬQGWKDWPRVWFRGHGRZQORDGHGRUFRSLHGIURP
import math
the Internet will contain a module, mainstream or unique, and their
absence is commonly the source of errors in execution. for I in range(5):
print(random.randint(1, 25))
print(math.pi)

STEP 6 The modules contain the extra code needed to STEP 9 The result is a string of random numbers followed
achieve a certain result within your own code, with by the value of Pi, as pulled from the math
which we’ve previously experimented. For example: module using the print(math.pi) function. You can also pull in
certain functions from a module by using the from and import
import random
commands, such as:
Brings in the code from the Random number generator module. We
from random import randint
can then use this module to create something like:
for i in range(5):
for i in range(10):
print(randint(1, 25))
print(random.randint(1, 25))

STEP 7 This code, when saved and executed, will display ten STEP 10 This helps create a more streamlined approach to
random numbers from 1 to 25. You can play around programming. You can also use: import module*,
with the code to display more or less, and from a greater or lesser ZKLFKZLOOLPSRUWHYHU\WKLQJGHƬQHGZLWKLQWKHQDPHGPRGXOH
range. For example: However, it’s often regarded as a waste of resources, but it works
nonetheless. Finally, modules can be imported as aliases:
import random
import math as m
for i in range(25):
print(random.randint(1, 100)) print(m.pi)
Of course, adding comments helps to tell others what’s going on.

&RGLQJ 3URJUDPPLQJ 93
Coding with Windows 10 Batch Files

Did you know that Windows has


its own built-in scripting language?
%DWFKƬOHVKDYHEHHQDURXQGVLQFH
the early days of Windows, and while
WKH\DUHRYHUVKDGRZHGE\WKHPLJKW
RI:LQGRZVoPRGHUQJUDSKLFDOXVHU
interface, they are still there and still
just as capable as they were thirty
years ago.

%DWFKƬOHSURJUDPPLQJLVDVNLOO
WKDWV\VWHPDGPLQLVWUDWRUVVWLOOXVH
VRLWoVZRUWKVSHQGLQJDELWRIWLPH
learning how they work, and what
\RXFDQGRZLWKWKHP7KLVVHFWLRQ
LQWURGXFHVEDWFKƬOHVDQGFRYHUVXVHU
LQWHUDFWLRQVYDULDEOHVORRSVDQGHYHQ
DEDWFKƬOHTXL]JDPHWRLQMHFWDQ
HOHPHQWRIIXQ

96 What is a Batch File?


98 Getting Started with Batch Files
100 Getting an Output
102 Playing with Variables
104 Batch File Programming
106 Loops and Repetition
108 Creating a Batch File Game

94 &RGLQJ 3URJUDPPLQJ
Index

&RGLQJ 3URJUDPPLQJ 95
Coding with Windows 10 Batch Files

What is a Batch File?


7KH:LQGRZVEDWFKƬOHKDVEHHQDURXQGVLQFHWKHHDUO\GD\VRI'26DQGZDVRQFHD
FULWLFDOHOHPHQWRIDFWXDOO\EHLQJDEOHWRERRWLQWRDZRUNLQJV\VWHP7KHUHoVDORW\RX
FDQGRZLWKDEDWFKƬOHEXWOHWoVMXVWWDNHDPRPHQWWRVHHZKDWRQHLV

%$70$1
$:LQGRZVEDWFKƬOHLVVLPSO\DVFULSWƬOHWKDWUXQVDVHULHVRIFRPPDQGVRQHOLQHDWDWLPHPXFKLQWKHVDPHIDVKLRQDVD
/LQX[VFULSW7KHVHULHVRIFRPPDQGVDUHH[HFXWHGE\WKHFRPPDQGOLQHLQWHUSUHWHUDQGVWRUHGLQDSODLQWH[WƬOHZLWKWKH%$7
H[WHQVLRQWKLVVLJQLƬHVWR:LQGRZVWKDWLWoVDQH[HFXWDEOHƬOHLQWKLVFDVHDVFULSW

%DWFKƬOHVKDYHEHHQDURXQGVLQFHWKHHDUOLHVWYHUVLRQVRI0LFURVRIW OLQHLQWXUQORDGLQJSURJUDPVWKDWZRXOGDFWLYDWHWKHPRXVHRU
'26$OWKRXJKQRWH[FOXVLYHO\D0LFURVRIWVFULSWLQJƬOHEDWFKƬOHV RSWLFDOGULYHLQWRWKHPHPRU\DUHDVDVVLJQHGE\WKH&RQƬJV\VƬOH
DUHPDLQO\DVVRFLDWHGZLWK0LFURVRIWoVRSHUDWLQJV\VWHPV,QWKH
HDUO\GD\VZKHQD3&ERRWHGLQWRDYHUVLRQRI'26 ZKLFKSURGXFHG 7KH'26XVHURIWKHGD\FRXOGRSWWRFUHDWHGLƪHUHQW$XWRH[HF
DVLPSOHFRPPDQGSURPSWZKHQSRZHUHGXS WKHEDWFKƬOHZDV EDWƬOHVGHSHQGLQJRQZKDWWKH\ZDQWHGWRGR)RUH[DPSOHLI
XVHGLQWKHIRUPRIDV\VWHPƬOHFDOOHG$XWRH[HFEDW$XWRH[HF WKH\ZDQWHGWRSOD\DJDPHDQGKDYHDVPXFKPHPRU\DYDLODEOH
EDWZDVDVFULSWWKDWDXWRPDWLFDOO\H[HFXWHG KHQFH$XWRH[HF  DVSRVVLEOHWKH\oGFUHDWHD&RQƬJV\VDQG$XWRH[HFEDWVHWRIƬOHV
FRPPDQGVRQFHWKHRSHUDWLQJV\VWHPKDGƬQLVKHGGHDOLQJZLWKWKH WKDWORDGHGWKHEDUHPLQLPXPRIGULYHUVDQGVRRQ,IWKH\QHHGHG
&RQƬJV\VƬOH DFFHVVWRWKHQHWZRUNDQ$XWRH[HFEDWƬOHFRXOGEHFUHDWHGWR

When a user powered


up their DOS-based
FRPSXWHUDQGRQFHWKH
%,26KDGƬQLVKHGFKHFNLQJ
the system memory
DQGVRRQ'26ZRXOG
ORRNWRWKH&RQƬJV\V
ƬOHWRORDGDQ\VSHFLƬF
display requirements
DQGKDUGZDUHGULYHUV
allocate them a slot in the
DYDLODEOHPHPRU\DVVLJQ
any memory managers
and tell the system where
WKH&RPPDQGFRPƬOH
which is the command line
LQWHUSUHWHUIRU'26ZDV
2QFHLWKDGGRQHWKDWWKHQ
WKH$XWRH[HFEDWƬOHWRRN
RYHUDQGUDQWKURXJKHDFK

7KH$XWRH[HFEDWƬOHZDV
D3&XVHUoVƬUVWH[SHULHQFH
ZLWKDEDWFKƬOH

96 &RGLQJ 3URJUDPPLQJ
What is a Batch File?

%$7&+),/(32:(5
-XVWOLNHDQ\RWKHUSURJUDPPLQJLQWHUIDFHWKDWFDQGLUHFWO\
LQWHUURJDWHDQGPDQLSXODWHWKHV\VWHPEDWFKƬOHVUHTXLUH
DFHUWDLQDPRXQWRIFDUHZKHQSURJUDPPLQJ,WoVKDUGWR
GDPDJH\RXUV\VWHPZLWKDEDWFKƬOHDVWKHPRUHLPSRUWDQW
HOHPHQWVRIWKHPRGHUQ:LQGRZVV\VWHPDUHSURWHFWHGE\
WKH8VHU$FFRXQW&RQWURO 8$& VHFXULW\8$&ZRUNVE\RQO\
DOORZLQJHOHYDWHGSULYLOHJHVDFFHVVWRLPSRUWDQWV\VWHPƬOHV
7KHUHIRUHLI\RXFUHDWHDEDWFKƬOHWKDWVRPHKRZGHOHWHVD
V\VWHPƬOHWKH8$&DFWLYDWHVDQGVWRSWKHSURFHVV

%DWFKƬOHVDUHSODLQWH[WDQGRIWHQFUHDWHGXVLQJ1RWHSDG +RZHYHULI\RXoUHZRUNLQJLQWKHFRPPDQGSURPSWZLWK
HOHYDWHGSULYLOHJHVWREHJLQZLWKDVWKH$GPLQLVWUDWRUWKHQ
WKH8$&ZRQoWTXHVWLRQWKHEDWFKƬOHDQGFRQWLQXHUHJDUGOHVV
RIZKDWƬOHVDUHEHLQJGHOHWHG

7KDWVDLG\RXoUHQRWOLNHO\WRFUHDWHDEDWFKƬOHWKDW
intentionally wipes out your operating system. There are
V\VWHPFRQWUROVLQSODFHWRKHOSSUHYHQWWKDWEXWLWoVZRUWK
PHQWLRQLQJDVWKHUHDUHEDWFKƬOHVDYDLODEOHRQWKH,QWHUQHW
that contain malicious code designed to create problems.
0XFKOLNHDYLUXVDURJXHEDWFKƬOH ZKHQH[HFXWHGZLWK
$GPLQLVWUDWRUSULYLOHJHV FDQFDXVHPXFKPD\KHPDQGV\VWHP
GDPDJH,QVKRUWGRQoWUDQGRPO\H[HFXWHDQ\EDWFKƬOH
GRZQORDGHGIURPWKH,QWHUQHWDVDQ$GPLQLVWUDWRUZLWKRXW
ƬUVWUHYLHZLQJZKDWLWGRHV
%DWFKƬOHVZHUHRIWHQXVHGDVXWLOLW\SURJUDPVWRKHOSXVHUVZLWK
FRPSOH[WDVNV <RXFDQOHDUQPRUHDERXWEDWFKƬOHVLQWKHFRPLQJSDJHVVR
GRQoWZRUU\WRRPXFKDERXWGHVWUR\LQJ\RXUV\VWHPZLWKRQH
$OOWKLVMXVWGHPRQVWUDWHVKRZSRZHUIXOWKHKXPEOHEDWFKƬOH
ORDGWKHQHWZRUNFDUGGULYHUDQGDXWRPDWLFDOO\JDLQDFFHVVWRWKH can be.
QHWZRUN(DFKRIWKHVHXQLTXHVHWXSVZRXOGEHORDGHGRQWRD
ƮRSS\GLVNDQGERRWHGDVDQGZKHQUHTXLUHGE\WKHXVHU

7KH$XWRH[HFEDWZDVWKHƬUVWVXFKƬOHPDQ\XVHUVFDPHDFURVVLQ
WKHLU3&EDVHGFRPSXWLQJOLYHVVLQFHPDQ\KDGFRPHIURPDELW
RUHYHQELWEDFNJURXQGUHPHPEHUWKLVZDVWKHODWHHLJKWLHV
DQGHDUO\QLQHWLHV7KHEDWFKƬOHZDVWKHXVHUoVSULPDU\WRROIRU
DXWRPDWLQJWDVNVFUHDWLQJVKRUWFXWVDQGDGYHQWXUHJDPHVDQG
WUDQVODWLQJFRPSOH[SURFHVVHVLQWRVRPHWKLQJIDUVLPSOHU

1RZDGD\VKRZHYHUDEDWFKƬOHLVQoWMXVWIRUORDGLQJLQGULYHUVDQG
VXFKZKHQWKH3&ERRWV<RXFDQXVHDEDWFKƬOHLQWKHVDPHZD\
DVDQ\RWKHUVFULSWLQJODQJXDJHƬOHLQWKDW\RXFDQSURJUDPLWWR
DVNIRUXVHULQSXWDQGGLVSOD\WKHUHVXOWVRQWKHVFUHHQRUVDYHWR
DƬOHDQGHYHQVHQGLWWRDORFDOO\RUQHWZRUNDWWDFKHGSULQWHU<RX
FDQFUHDWHVFULSWVWREDFNXS\RXUƬOHVWRYDULRXVORFDWLRQVFRPSDUH
GDWHVWDPSVDQGRQO\EDFNXSWKHPRVWUHFHQWO\FKDQJHGFRQWHQWDV
ZHOODVSURJUDPWKHVFULSWWRGRDOOWKLVDXWRPDWLFDOO\%DWFKƬOHVDUH
UHPDUNDEO\SRZHUIXODQGGHVSLWHWKHPQRWEHLQJDVFRPPRQO\XVHG
DVWKH\ZHUHGXULQJWKHROGHUGD\VRI'26WKH\DUHVWLOOWKHUHDQG
FDQEHXWLOLVHGHYHQLQWKHODWHVWYHUVLRQRI:LQGRZVDQGFDQEH
as complex or simple as you want them to be.

6RZKDWGR\RXQHHGWRVWDUWEDWFKƬOHSURJUDPPLQJLQ:LQGRZV"
:HOODVORQJDV\RXKDYH:LQGRZVRUDQ\ROGHUYHUVLRQRI
:LQGRZVIRUWKDWPDWWHU\RXFDQVWDUWEDWFKƬOHSURJUDPPLQJ
immediately. All you need is to be able to open Notepad and get to
WKHFRPPDQGSURPSWRI:LQGRZV:HVKRZ\RXKRZLWDOOZRUNVVR <RXFDQFUHDWHFRPSOH[EDWFKƬOHVRUVLPSOHRQHVWKDWGLVSOD\
read on. $6&,,LPDJHVRQVFUHHQ

&RGLQJ 3URJUDPPLQJ 97
Coding with Windows 10 Batch Files

Getting Started with


Batch Files
%HIRUH\RXEHJLQWRSURJUDPZLWKEDWFKƬOHVWKHUHDUHDIHZWKLQJV\RXQHHGWRNQRZ
$EDWFKƬOHFDQRQO\EHH[HFXWHGRQFHLWKDVWKHEDWH[WHQVLRQDQGHGLWLQJRQHZLWK
1RWHSDGLVQoWDOZD\VVWUDLJKWIRUZDUG

$1(:%$7&+
7KURXJKRXWWKLVVHFWLRQRQEDWFKƬOHVZHoUHJRLQJWREHZRUNLQJZLWK1RWHSDGWKHFRPPDQGSURPSWDQGZLWKLQDIROGHU
FDOOHGn%DWFK)LOHVo7REHJLQZLWKOHWoVVHHKRZ\RXJHWWRWKH:LQGRZVFRPPDQGSURPSW

67(3 The Windows 67(3 :KLOHDWWKHFRPPDQGSURPSWZLQGRZHQWHU


command dir/w.7KLVOLVWVDOOWKHƬOHVDQGGLUHFWRULHVIURP
SURPSWPD\ORRNDOLWWOH ZKHUH\RXDUHDWWKHPRPHQWLQWKHV\VWHP,QWKLVFDVHWKDWoV\RXU
daunting to the newcomer +RPHGLUHFWRU\WKDW:LQGRZVDVVLJQVHYHU\XVHUWKDWORJVLQ<RX
EXWLWoVVLPSO\DQRWKHU FDQQDYLJDWHE\XVLQJWKH&'FRPPDQG &KDQJH'LUHFWRU\ 7U\
LQWHUIDFH RU6KHOO XVHGWR
cd Documents
DFFHVVWKHƬOHV\VWHP<RX
FDQJRDQ\ZKHUH\RXOLNHLQ Then press Return.
WKHFRPPDQGSURPSWDV
you would with the graphical
LQWHUIDFH7REHJLQFOLFNRQ
the Windows Start button and
HQWHU&0'LQWRWKHVHDUFKER[

67(3 &OLFNRQWKHVHDUFKUHVXOWODEHOOHG&RPPDQG3URPSW 67(3 The prompt should change and display \


'HVNWRS$SS DQGDQHZZLQGRZSRSVXS7KH Documents>;WKLVPHDQV\RXoUHLQWKH'RFXPHQWV
&RPPDQG3URPSWZLQGRZLVQoWPXFKWRORRNDWWREHJLQZLWKEXW GLUHFWRU\1RZFUHDWHDQHZGLUHFWRU\FDOO%DWFK)LOHV(QWHU
\RXFDQVHHWKH0LFURVRIW:LQGRZVYHUVLRQQXPEHUDQGFRS\ULJKW
md “Batch Files”
LQIRUPDWLRQIROORZHGE\WKHSURPSWLWVHOI7KHSURPSWGHWDLOVWKH
FXUUHQWGLUHFWRU\RUIROGHU\RXoUHLQWRJHWKHUZLWK\RXUXVHUQDPH <RXQHHGWKHTXRWDWLRQVEHFDXVHZLWKRXWWKHP:LQGRZVFUHDWHV
WZRGLUHFWRULHV%DWFKDQG)LOHV1RZFKDQJHGLUHFWRU\LQWRWKH
newly created Batch Files.
cd Batch Files
<RXZRQoWQHHGWKHTXRWHVWRFKDQJHGLUHFWRULHV

98 &RGLQJ 3URJUDPPLQJ
*HWWLQJ6WDUWHGZLWK%DWFK)LOHV

67(3 1RZWKDW\RXKDYHWKHGLUHFWRU\VHWXSZKHUH\RX 67(3 %DFNDWWKHFRPPDQGSURPSWZLQGRZHQWHU


VWRUH\RXUEDWFKƬOHVKHUHLVKRZ\RXFDQFUHDWH dir/wDJDLQWROLVWWKHQHZO\FUHDWHG7HVWEDWƬOH
RQH/HDYHWKHFRPPDQGSURPSWZLQGRZRSHQDQGFOLFNRQWKH %\WKHZD\WKHZSDUWRIGLUZPHDQVWKHƬOHVDUHOLVWHGDFURVV
:LQGRZV6WDUWEXWWRQDJDLQ7KLVWLPHHQWHU1RWHSDGDQGFOLFNRQ WKHVFUHHQDVRSSRVHGWRVWUDLJKWGRZQ(QWHUdirLI\RXZDQW
the search result to open the Notepad program. Notepad is a simple DOWKRXJK\RXQHHGPRUHƬOHVWRYLHZ EXWLWoVFRQVLGHUHGHDVLHUWR
WH[WHGLWRUEXWLGHDOIRUFUHDWLQJEDWFKVFULSWVZLWK UHDGZLWKWKHZƮDJ

67(3 7RFUHDWH\RXUƬUVWEDWFKƬOHHQWHUWKHIROORZLQJ 67(3 7RH[HFXWHWKHEDWFKƬOH\RXoYHMXVWFUHDWHGVLPSO\


LQWR1RWHSDG HQWHULWVQDPH7HVWLQWKHFRPPDQGSURPSW
ZLQGRZ<RXGRQoWQHHGWRDGGWKHEDWSDUWDV:LQGRZVUHFRJQLVHV
@echo off
LWDVDQH[HFXWDEOHƬOHDQGWKHRQO\RQHZLWKWKDWSDUWLFXODUQDPHLQ
echo Hello World!
WKHFXUUHQWGLUHFWRU\3UHVVUHWXUQDQGVHHKRZ\RXoUHJUHHWHGZLWK
%\GHIDXOWDEDWFKƬOHGLVSOD\VDOOWKHFRPPDQGVWKDWLWUXQV Hello World! in the command prompt.
WKURXJKOLQHE\OLQH:KDWWKH#HFKRRƪFRPPDQGGRHVLVWXUQ
WKDWIHDWXUHRƪIRUWKHZKROHVFULSWZLWKWKHn#o DW VLJQWRDSSO\
WKDWFRPPDQGWRLWVHOI

67(3 :KHQVDYLQJDQ\WKLQJLQ1RWHSDGWKHGHIDXOW
H[WHQVLRQLVW[WWRGHQRWHDWH[WƬOH+RZHYHU\RX
67(3 7KHHFKRFRPPDQGGLVSOD\VZKDWHYHULVDIWHULW
ZDQWWKHH[WHQVLRQWREHEDW&OLFNRQ)LOH!6DYH$VDQGQDYLJDWH
WRWKHVFUHHQ5LJKWFOLFNWKH7HVWEDWƬOHIURP
WRWKHQHZO\FUHDWHG%DWFK)LOHVGLUHFWRU\LQ'RFXPHQWV&OLFNWKH
:LQGRZV([SORUHUDQGVHOHFW(GLWWRDGGPRUHHFKRFRPPDQGVLI
GURSGRZQPHQX6DYHDV7\SHDQGVHOHFW$OO)LOHVIURPWKHPHQX,Q
\RXOLNH7U\WKLV
)LOH1DPHFDOOWKHƬOH7HVWEDW.
@echo off
echo Hello World!
HFKR7KLVLVP\¿UVWEDWFK¿OH
echo.
HFKR:LWKDEODQNOLQHEHWZHHQ
5HPHPEHUWRVDYHHDFKQHZFKDQJHWRWKHEDWFKƬOH

&RGLQJ 3URJUDPPLQJ 99
Coding with Windows 10 Batch Files

Getting an Output
:KLOHLWoVJUHDWKDYLQJWKHFRPPDQGSURPSWZLQGRZGLVSOD\ZKDW\RXoUHSXWWLQJDIWHU
WKHHFKRFRPPDQGLQWKHEDWFKƬOHLWoVQRWYHU\XVHIXODWWKHPRPHQWRULQWHUDFWLYH
IRUWKDWPDWWHU/HWoVFKDQJHXSDJHDUDQGJHWVRPHRXWSXW

,1387287387
%DWFKƬOHVDUHFDSDEOHRIWDNLQJDQRUPDO:LQGRZVFRPPDQGDQGH[HFXWLQJLWZKLOHDOVRDGGLQJH[WUDRSWLRQVDQGƮDJVLQWR
WKHHTXDWLRQ

67(3 /HWoVNHHSWKLQJVVLPSOHWREHJLQZLWK&UHDWHDQHZ 67(3 <RXKDYHQRGRXEWQRWLFHGWKDWWKHUHLVQR


EDWFKƬOHFDOOHGnGLUYLHZEDWoVKRUWIRU'LUHFWRU\ LQGLFDWLRQWKDWWKHEDWFKƬOHZRUNHGDVWKHUHoV
9LHZ6WDUWZLWKWKH#HFKRRƪFRPPDQGDQGXQGHUWKDWDGG QRPHDQLQJIXORXWSXWRQWKHVFUHHQ+RZHYHULI\RXQRZRSHQ
([SORUHUDQGEURZVHWRc:\Users\YOURNAMEUHPHPEHULQJWR
dir “c:\users\YOURNAME\Documents\Batch Files” >
substitute YOURNAMEZLWK\RXU:LQGRZVXVHUQDPHDQGGRXEOH
c:\users\YOURNAME\dirview.txt
FOLFNWKHdirview.txWƬOH\RXFDQVHHWKHEDWFKƬOHoVRXWSXW
6XEVWLWXWH<2851$0(ZLWK\RXU:LQGRZVXVHUQDPH

67(3 The new line uses the dir command to list the 67(3 ,I\RXZDQWWRDXWRPDWHWKHWDVNRIRSHQLQJWKH
FRQWHQWVRIWKHGLUHFWRU\%DWFK)LOHVLQ\RXU+RPH WH[WƬOHWKDWFRQWDLQVWKHRXWSXWDGGWKHIROORZLQJ
GLUHFWRU\GXPSLQJWKHRXWSXWWRDWH[WƬOHFDOOHGdirview.txt in OLQHWRWKHEDWFKƬOH
WKHURRWRI\RXU+RPHGLUHFWRU\7KLVLVGRQHVRWKDWWKH:LQGRZV
notepad.exe c:\users\YOURNAME\dirview.txt
8$&GRHVQoWUHTXLUHHOHYDWHGSHUPLVVLRQVDVHYHU\WKLQJLVLQ\RXU
RZQ+RPHDUHD6DYHDQGUXQWKHEDWFKƬOH 6DYHWKHƬOHDQGRQFHDJDLQUXQIURPWKHFRPPDQGSURPSW7KLV
WLPHLWFUHDWHVWKHRXWSXWDQGDXWRPDWLFDOO\RSHQV1RWHSDGZLWK
the output contents.

 &RGLQJ 3URJUDPPLQJ


*HWWLQJDQ2XWSXW

287387:,7+9$5,$%/(6
9DULDEOHVRƪHUDPRUHLQWHUHVWLQJZD\RIRXWSXWWLQJVRPHWKLQJWRWKHVFUHHQDQGFUHDWHDKLJKHUOHYHORILQWHUDFWLRQEHWZHHQ
WKHXVHUDQGWKHEDWFKƬOH7U\WKLVH[DPSOHEHORZ

67(3 &UHDWHDQHZEDWFKƬOHDQGFDOOLWQDPHEDW. Start 67(3 7KLVLVH[WUHPHO\XVHIXOLI\RXZDQWWRFUHDWHD


with the @echo off FRPPDQGWKHQDGGWKH XQLTXHSHUVRQDOEDWFKƬOHWKDWDXWRPDWLFDOO\UXQV
IROORZLQJOLQHV ZKHQDXVHUORJVLQWR:LQGRZV8VLQJWKHGHIDXOWV\VWHPVYDULDEOHV
WKDW:LQGRZVLWVHOIFUHDWHV\RXFDQPDNHDEDWFKƬOHWKDWJUHHWV
set /p name= What is your name?
HDFKXVHU
echo Hello, %name%
@echo off
1RWHWKHUHoVDVSDFHDIWHUWKHTXHVWLRQPDUN7KLVLVWRPDNHLWORRN
QHDWHURQWKHVFUHHQ6DYHLWDQGUXQWKHEDWFKƬOH echo Hello, %USERNAME%.
echo.
HFKR7KDQNVIRUORJJLQJLQ&XUUHQWO\WKHQHWZRUN
LVRSHUDWLQJDWHI¿FLHQF\
echo.
echo Your Home directory is located at: %HOMEPATH%
HFKR7KHFRPSXWHUQDPH\RX¶UHORJJHGLQWRLV
&20387(51$0(
echo.

67(3 The set /pQDPHFUHDWHVDYDULDEOHFDOOHGQDPH


with the /pSDUWLQGLFDWLQJWKDWDQn SURPSWVWULQJo
LVWRIROORZ7KH6HWFRPPDQGGLVSOD\VVHWVRUUHPRYHVV\VWHP
DQGHQYLURQPHQWDOYDULDEOHV)RUH[DPSOHZKLOHLQWKHFRPPDQG
SURPSWZLQGRZHQWHU 67(3 6DYHDQGH[HFXWHWKHEDWFKƬOHFKDQJHV\RXFDQ
RYHUZULWHDQGVWLOOXVHQDPHEDWLI\RXZDQW7KH
set
EDWFKƬOHWDNHVWKHFXUUHQWV\VWHPYDULDEOHVDQGUHSRUWVWKHP
7RYLHZWKHFXUUHQWV\VWHPYDULDEOHV1RWHWKHQDPH YDULDEOHZH DFFRUGLQJO\GHSHQGLQJRQWKHXVHUoVORJLQQDPHDQGWKHQDPHRI
just created. WKHFRPSXWHU1RWHWKHGRXEOHSHUFHQWV\PEROPHDQVWKHSHUFHQW
VLJQZLOOEHGLVSOD\HGDQGLVQRWDYDULDEOH

67(3 $OWHUQDWLYHO\\RXFDQUXQWKHEDWFKƬOHDQGGLVSOD\
LWRQWKHXVHUoVGHVNWRSDVDWH[WƬOH
@echo off
echo Hello, %USERNAME%. > c:%HOMEPATH%\user.txt
67(3 Variables stored with Set can be called with the
echo. >> c:%HOMEPATH%\user.txt
9$5,$%/(1$0(V\QWD[,QWKHEDWFKƬOHZH
HFKR7KDQNVIRUORJJLQJLQ&XUUHQWO\WKHQHWZRUN
XVHGWKHQHZO\FUHDWHGQDPHV\QWD[WRFDOOXSRQWKHFRQWHQWVRI
LVRSHUDWLQJDWHI¿FLHQF\!!F+20(3$7+?
WKHYDULDEOHFDOOHGQDPH<RXUXVHUQDPHIRUH[DPSOHLVVWRUHGDVD
user.txt
YDULDEOH7U\WKLVLQDEDWFKƬOH
echo. >> c:%HOMEPATH%\user.txt
HFKR+HOOR86(51$0(:KDWDUH\RXGRLQJ" echo Your Home directory is located at: %HOMEPATH%
>> c:%HOMEPATH%\user.txt
HFKR7KHFRPSXWHUQDPH\RX¶UHORJJHGLQWRLV
&20387(51$0(!!F+20(3$7+?XVHUW[W
echo. >> c:%HOMEPATH%\user.txt
notepad c:%HOMEPATH%\user.txt
7KH!RXWSXWVWRDQHZƬOHFDOOHGXVHUW[WZKLOHWKH!!DGGVWKH
OLQHVZLWKLQWKHƬOH

&RGLQJ 3URJUDPPLQJ 


Coding with Windows 10 Batch Files

Playing with Variables


7KHUHoVDORW\RXFDQDFFRPSOLVKZLWKERWKWKHV\VWHPDQGHQYLURQPHQWDOYDULDEOHV
DORQJVLGH\RXURZQ0L[LQJWKHWZRFDQPDNHIRUDSRZHUIXODQGH[WUHPHO\XVHIXO
EDWFKƬOHDQGZKHQFRPELQHGZLWKRWKHUFRPPDQGVWKHHƪHFWLVUHDOO\LPSUHVVLYH

86,1*025(9$5,$%/(6
+HUHoVDJRRGH[DPSOHRIPL[LQJV\VWHPDQGHQYLURQPHQWDOYDULDEOHVZLWKVRPHRI\RXURZQFUHDWLRQDORQJZLWKDQXPEHURI
H[WHUQDO:LQGRZVFRPPDQGV

67(3 &UHDWHDQHZEDWFKƬOHFDOOHGOLVWEDWDQGVWDUWLWRƪ 67(3 1RZFUHDWHDEDWFKƬOHWKDWGLVSOD\VWKHFRQWHQWV


with the @echo off command. Begin by clearing RIDQ\GLUHFWRU\DQGSRVWLWDVDWH[WƬOHWRWKHXVHUoV
WKHFRPPDQGSURPSWVFUHHQDQGGLVSOD\LQJDOLVWRIWKHFXUUHQW VFUHHQ$GGWKHIROORZLQJWRWKHOLVWEDWEDWFKƬOH
GLUHFWRULHVRQWKHFRPSXWHU
echo Hello, %USERNAME%.
cls HFKR)URPWKHOLVWZKLFKIROGHUZRXOG\RXOLNHWR
dir “c:\” > list.txt view?
type list.txt set /p view= (enter as c:\folder)
echo. dir “%view%” > view.txt
notepad.exe view.txt

67(3 6DYHDQGH[HFXWHWKHEDWFKƬOH:LWKLQWKH 67(3 :KDWoVKDSSHQLQJKHUHLVWKHEDWFKƬOHDVNVWKHXVHU


FRPPDQGSURPSW\RXFDQVHHWKHFRQWHQWVRIDOO WRHQWHUDQ\RIWKHGLUHFWRULHVGLVSOD\HGLQWKHOLVWLW
WKHƬOHVDQGGLUHFWRULHVIURPWKHURRWRIWKH&?GULYHDQGDVDQ\ JHQHUDWHGLQWKHIRUPRInc:\directoryo3URYLGLQJWKHXVHUHQWHUVD
XVHUXQGHU:LQGRZVKDVSHUPLVVLRQWRVHHWKLVWKHUHoVQR8$& YDOLGGLUHFWRU\LWVFRQWHQWVDUHGLVSOD\HGDVDWH[WƬOH:HFUHDWHG
HOHYDWHGSULYLOHJHVUHTXLUHG WKHYLHZYDULDEOHKHUHDORQJZLWK+20(3$7+WRVWRUHWKHLQSXW
DQGWKHWH[WƬOH

 &RGLQJ 3URJUDPPLQJ


3OD\LQJZLWK9DULDEOHV

67(3 ,WoVDOZD\VDJRRGLGHDZKHQFUHDWLQJWH[WƬOHV 67(3 ,QVWHDGRIOHIWFOLFNLQJRQWKH&RPPDQG3URPSW


IRUWKHXVHUWRWHPSRUDULO\YLHZWRFOHDQXSDIWHU UHVXOWDV\RXGLGWKHƬUVWWLPH\RXRSHQHGLW
\RXUVHOI7KHUHoVQRWKLQJZRUVHWKDQKDYLQJFRXQWOHVVUDQGRP ULJKWFOLFNLWDQGIURPWKHPHQXFKRRVH5XQDV$GPLQLVWUDWRU7KHUH
WH[WƬOHVFOXWWHULQJXSWKHƬOHV\VWHP7KDWEHLQJWKHFDVHOHWoV LVDULVNWKDW\RXFRXOGGDPDJHV\VWHPƬOHVDVWKH$GPLQLVWUDWRU
FOHDUXSZLWK EXWDVORQJDV\RXoUHFDUHIXODQGGRQoWGRDQ\WKLQJEH\RQGYLHZLQJ
GLUHFWRULHV\RXZLOOEHRND\
cls
del /Q view.txt
del /Q list.txt
HFKR$OO¿OHVGHOHWHG6\VWHPFOHDQ

67(3 7KHDGGLWLRQVWRWKHEDWFKƬOHVLPSO\FOHDUWKH
FRPPDQGSURPSWZLQGRZ XVLQJWKHFOVFRPPDQG 
DQGGHOHWHERWKWKHYLHZW[WDQGOLVWW[WƬOHVWKDWZHUHFUHDWHGE\
WKHEDWFKƬOH7KH4ƮDJLQWKHGHOFRPPDQGPHDQVLWGHOHWHV
WKHƬOHVZLWKRXWDQ\XVHULQSXWRUQRWLƬFDWLRQ7KHƬQDOPHVVDJH
67(3 7KLVDFWLRQWULJJHUVWKH8$&ZDUQLQJPHVVDJH
LQIRUPVWKHXVHUWKDWWKHƬOHVDUHUHPRYHG
DVNLQJ\RXLI\RXoUHVXUH\RXZDQWWRUXQWKH
:LQGRZVFRPPDQGSURPSWZLWKWKHHOHYDWHG$GPLQLVWUDWRU
SULYLOHJHV0RVWRIWKHWLPHZHZRXOGQoWUHFRPPHQGWKLVFRXUVH
RIDFWLRQWKH8$&LVWKHUHWRSURWHFW\RXUV\VWHP,QWKLVFDVH
KRZHYHUFOLFN<HV

67(3 Depending
on how
\RXUV\VWHPLVFRQƬJXUHG
you may not get any
GLUHFWRU\LQIRUPDWLRQ
at all or a message
stating Access Denied.
This is because the UAC 67(3 :LWKWKH8$&DFWLYHWKHFRPPDQGSURPSWORRNV
LVEORFNLQJDFFHVVWR DOLWWOHGLƪHUHQW)RUVWDUWHUVLWoVQRZGHIDXOWLQJ
SURWHFWHGDUHDVRIWKH WRWKH&?:,1'2:6?V\VWHPIROGHUDQGWKHWRSRIWKHZLQGRZVLV
V\VWHPOLNHF?:LQGRZV ODEHOOHG$GPLQLVWUDWRU7RUXQWKHEDWFKƬOH\RXQHHGWRQDYLJDWHWR
RU&?3URJUDP)LOHV WKH%DWFK)LOHVGLUHFWRU\ZLWKFG?8VHUV?86(51$0(?'RFXPHQWV?
7KHUHIRUH\RXQHHGWR %DWFK)LOHV7RKHOSSUHVVWKH7DENH\WRDXWRFRPSOHWHWKH
UXQWKHEDWFKƬOHDVDQ directory names.
$GPLQLVWUDWRU&OLFNWKH
Windows Start button and
enter &0' again.

&RGLQJ 3URJUDPPLQJ 


Coding with Windows 10 Batch Files

Batch File Programming


,WoVWKHOLWWOHDGGLWLRQVZHFDQPDNHWRDEDWFKƬOHWKDWKHOSLWVWDQGRXWDQGXOWLPDWHO\
EHFRPHPRUHXVHIXO:KLOHWKH:LQGRZVJUDSKLFDOLQWHUIDFHLVVWLOONLQJWKHFRPPDQG
OLQHFDQGRMXVWDVPXFKDQGWKLVLVZKHUHEDWFKƬOHVFRPHLQWRWKHLURZQ

6($5&+,1*)25),/(6
+HUHoVDQLQWHUHVWLQJOLWWOHEDWFKƬOHWKDW\RXFDQHDVLO\H[WHQGIRU\RXURZQXVH,WDVNVWKHXVHUIRUDƬOHW\SHWRVHDUFKIRU
and displays the results.

67(3 :HDUHLQWURGXFLQJDFRXSOHRIQHZFRPPDQGV 67(3 1RZOHWoVH[WHQGWKHVHHNEDWEDWFKƬOH


LQWRWKHPL[KHUHEXWZHWKLQNWKH\oUHUHDOO\XVHIXO
&UHDWHDQHZEDWFKƬOHFDOOHGVHHNEDWDQGLQLWSXW @echo off
cls
@echo off
color 2
cls
HFKR3OHDVHHQWHUWKHW\SHRI¿OH\RXZDQWWR
color 2
VHDUFKIRU 03'2&-3*IRUH[DPSOH
HFKR3OHDVHHQWHUWKHW\SHRI¿OH\RXZDQWWR
echo.
VHDUFKIRU 03'2&-3*IRUH[DPSOH
set /p ext=
echo.
where /R c:\ *.%ext% > found.txt
notepad.exe found.txt
cls
color
del /Q found.txt

67(3 The new command in this instance is color 67(3 $QRWKHUQHZFRPPDQG:KHUHORRNVIRUDVSHFLƬF


$PHULFDQLVHGVSHOOLQJ &RORUDV\RXDOUHDG\ ƬOHRUGLUHFWRU\EDVHGRQWKHXVHUoVUHTXLUHPHQWV
DVVXPHFKDQJHVWKHFRORXURIWKHFRPPDQGSURPSWGLVSOD\7KH ,QWKLVFDVHZHKDYHFUHDWHGDEODQNYDULDEOHFDOOHGH[WWKDWWKHXVHU
FRORUDWWULEXWHVDUHVSHFLƬHGE\WZRKH[GLJLWVWKHƬUVWFRUUHVSRQGV FDQHQWHUWKHƬOHW\SHLQZKLFKWKHQVHDUFKHVXVLQJ:KHUHDQG
WRWKHEDFNJURXQGFRORXURIWKH&RPPDQGFRQVROHDQGWKHVHFRQG GXPSVWKHUHVXOWVLQDWH[WƬOHFDOOHGIRXQGW[W6DYHDQGUXQWKH
WRWKHIRUHJURXQGDQGFDQEHDQ\RIWKHIROORZLQJYDOXHV EDWFKƬOH

 &RGLQJ 3URJUDPPLQJ


%DWFK)LOH3URJUDPPLQJ

&+2,&(0(186
&UHDWLQJDPHQXRIFKRLFHVLVDFODVVLFEDWFKƬOHXVHDQGDJRRGH[DPSOHWRKHOSH[SDQG\RXUEDWFKƬOHSURJUDPPLQJVNLOOV
+HUHoVVRPHFRGHWRKHOS\RXXQGHUVWDQGKRZLWDOOZRUNV

67(3 5DWKHUWKDQXVLQJDYDULDEOHWRSURFHVVDXVHUoV 67(3 (UURU/HYHOVDUHHVVHQWLDOO\YDULDEOHVDQGWKH0


UHVSRQVHEDWFKƬOHVFDQLQVWHDGXVHWKH&KRLFH VZLWFKRI&KRLFHDOORZVDGHVFULSWLYHPHVVDJHVWULQJ
FRPPDQGLQFRQMXQFWLRQZLWKDQ(UURU/HYHOSDUDPHWHUWRPDNHD WREHGLVSOD\HG([WHQGWKLVPHQXZLWKVRPHWKLQJQHZ
PHQX&UHDWHDQHZƬOHFDOOHGPHQXEDWDQGHQWHUWKHIROORZLQJ
@echo off
@echo off cls
cls echo.
choice /M “Do you want to continue? Y/N” echo ---------------------------------------------
LIHUURUOHYHOJRWR1 echo.
LIHUURUOHYHOJRWR< echo Please choose a directory.
JRWR(QG echo.
HFKR3UHVVIRUF?0XVLF
echo.
echo Press 2 for c:\Documents
echo.
echo Press 3 for c:\Pictures
echo.
echo Press 4 for c:\Videos
echo.
echo ---------------------------------------------
67(3 5XQQLQJWKHFRGHSURGXFHVDQHUURUDVZHoYHFDOOHG FKRLFH&
D*RWRFRPPDQGZLWKRXWDQ\UHIHUHQFHWRLWLQWKH LIHUURUOHYHOJRWR9LGHRV
ƬOH*RWRGRHVH[DFWO\WKDWJRHVWRDVSHFLƬFOLQHLQWKHEDWFKƬOH LIHUURUOHYHOJRWR3LFWXUHV
)LQLVKWKHƬOHZLWKWKHIROORZLQJDQGUXQLWDJDLQ LIHUURUOHYHOJRWR'RFXPHQWV
LIHUURUOHYHOJRWR0XVLF
:N
echo.
HFKR<RXFKRVH1R*RRGE\H 67(3 1RZDGGWKH*RWRVHFWLRQV
JRWR(QG
:Y :Videos
echo. cls
echo You chose Yes. Hello &'+20(3$7+?9LGHRV
echo You are now in the Videos directory.
:End
JRWR(QG
:Pictures
cls
&'+20(3$7+?3LFWXUHV
echo You are now in the Pictures directory.
JRWR(QG
:Documents
cls
&'+20(3$7+?'RFXPHQWV
echo You are now in the Documents directory.
67(3 7KHRXWSXWIURP\RXUFKRLFHLVGLƪHUHQWGHSHQGLQJRQ
JRWR(QG
ZKHWKHU\RXSLFN<RU17KH(QGSDUWVLPSO\VLJQLƬHV
WKHHQGRIWKHƬOH DOVRNQRZQDV(2) :LWKRXWLWWKHEDWFKƬOHUXQV :Music
WKURXJKHDFKOLQHDQGGLVSOD\WKH<UHVSRQVHHYHQLI\RXHQWHU1VRLWoV cls
LPSRUWDQWWRUHPHPEHUWRIROORZ\RXU*RWRFRPPDQGV &'+20(3$7+?0XVLF
echo you are now in the Music directory.
JRWR(QG
:End

67(3 :KHQH[HFXWHGWKHEDWFKƬOHGLVSOD\VDPHQXDQGZLWK
each choice the code changes directory to the one the
XVHUHQWHUHG7KH+20(3$7+V\VWHPYDULDEOHZLOOHQWHUWKHFXUUHQWO\
ORJJHGLQXVHUoV0XVLF3LFWXUHVDQGVRGLUHFWRULHVDQGQRWDQ\RQHHOVHoV

&RGLQJ 3URJUDPPLQJ 


Coding with Windows 10 Batch Files

Loops and Repetition


/RRSLQJDQGUHSHDWLQJFRPPDQGVDUHWKHVWDSOHGLHWRIHYHU\SURJUDPPLQJODQJXDJH
LQFOXGLQJEDWFKƬOHSURJUDPPLQJ)RUH[DPSOH\RXFDQFUHDWHDVLPSOHFRXQWGRZQRU
HYHQPDNHQXPEHUHGƬOHVRUGLUHFWRULHVLQWKHV\VWHP

&2817(56
&UHDWLQJFRGHWKDWFRXQWVLQLQFUHDVLQJRUGHFUHDVLQJQXPEHUVHWVLVJUHDWIRUGHPRQVWUDWLQJORRSV:LWKWKDWLQPLQGOHWoVORRN
DWWKH,IVWDWHPHQWDOLWWOHPRUHDORQJVLGHPRUHYDULDEOHVDQGLQWURGXFHWKH(OVH7LPHRXWDQGHRI (QGRI)LOH FRPPDQGV

67(3 6WDUWE\FUHDWLQJDQHZEDWFKƬOHFDOOHGFRXQWEDW 67(3 7KHFRXQWEDWLVDURXJKZD\RIGHPRQVWUDWLQJD


(QWHUWKHIROORZLQJVDYHLWDQGUXQ ORRSDEHWWHUDSSURDFKZRXOGEHWRXVHDIRUORRS
7U\WKLVH[DPSOHLQVWHDG
@echo off
cls @echo off
VHWDFRXQWHU  IRU/QLQ  GRHFKRQ
QXPEHUV
VHWDFRXQWHU FRXQWHU
LIFRXQWHU  JRWRHRI HOVH HFKR
%counter%)
WLPHRXW7QREUHDN!QXO
JRWRQXPEHUV

67(3 %UHDNLQJLW
GRZQWKHUHoV
)RUWKHQWKH/VZLWFKZKLFK
KDQGOHVDUDQJHRIQXPEHUV
Then the parameter labelled as
67(3 The count.
%%n to denote a number. Then
bat code
WKHLQ  SDUWZKLFKWHOOV
starts at number one and
WKHVWDWHPHQWKRZWRFRXQW
FRXQWVVFUROOLQJGRZQWKH
DVLQ VWDUWQXPEHU  VWHSV
VFUHHQXQWLOLWUHDFKHV
WRWDNH  WKHHQGQXPEHU 
The Timeout command
7KHQH[WSDUWLVGRPHDQLQJ'2
OHDYHVDRQHVHFRQGJDS
ZKDWHYHUFRPPDQGLVDIWHU
between numbers and the
(OVHVWDWHPHQWFRQWLQXHV
XQWLOWKHFRXQWHUYDULDEOH
HTXDOVEHIRUHJRLQJWR
WKHHRI (QG2I)LOH WKXV
closing the loop.

 &RGLQJ 3URJUDPPLQJ


/RRSVDQG5HSHWLWLRQ

67(3 You can include the pause between the numbers 67(3 7KHUHDUHGLƪHUHQWZD\VRIXVLQJWKH)RUORRS,Q
HDVLO\HQRXJKZLWKLQWKHIDUVLPSOHU)RUORRSE\ WKLVH[DPSOHWKHFRGHFUHDWHVGLUHFWRULHVRQH
DGGLQJPXOWLSOHFRPPDQGVDIWHUWKH'R)RUORRS7KHEUDFNHWVDQG IRUHDFKOHWWHURIWKHDOSKDEHWZLWKLQWKHGLUHFWRU\F?WHVWZKLFKWKH
DPSHUVDQG VHSDUDWHWKHGLƪHUHQWFRPPDQGV7U\WKLV EDWFKƬOHPDNHVXVLQJWKH0'FRPPDQG
@echo off @echo off
IRU/QLQ  GR HFKRQ WLPHRXW7 )25),1 DEFGHIJKLMNOPQRSTU
QREUHDN!QXO  VWXYZ[\] '2 PG&?WHVW?))

67(3 2QHRIWKHJUHDWWLPHVDYLQJXVHVRIEDWFKƬOHVLVWR 67(3 /RRSVFDQEHSRZHUIXODQGH[WUHPHO\XVHIXO


FUHDWHPXOWLSOHQXPEHUHGƬOHV$VVXPHWKDW\RX HOHPHQWVLQDEDWFKƬOH:KLOHFUHDWLQJ
ZDQWWZHQW\ƬYHWH[WƬOHVZLWKLQDGLUHFWRU\DOOQXPEHUHGIURPWR GLUHFWRULHVPD\QRWVRXQGWRRKHOSIXOLPDJLQHKDYLQJWRFUHDWH
$)RUORRSPXFKOLNHWKHSUHYLRXVH[DPSOHGRHVWKHWULFN XVHUVRQDQHWZRUNDQGDVVLJQHDFKRQHWKHLURZQVHWRI
XQLTXHGLUHFWRULHV7KLVLVZKHUHDEDWFKƬOHVDYHVDQLPPHQVH
@echo off
DPRXQWRIWLPH
IRU/QLQ  GRFRS\QXOQW[W

67(3 ,I\RXRSHQ:LQGRZV([SORUHUDQGQDYLJDWHWRWKH 67(3 6KRXOG\RXHYHUJHWVWXFNZKHQXVLQJWKHYDULRXV


%DWFK)LOHVGLUHFWRU\ZKHUH\RXoUHZRUNLQJIURP FRPPDQGVZLWKLQDEDWFKƬOHGURSLQWRWKH
\RXFDQQRZVHHWH[WƬOHVDOOQHDWO\QXPEHUHG2IFRXUVH\RX FRPPDQGSURPSWDQGHQWHUWKHFRPPDQGIROORZHGE\DTXHVWLRQ
FDQDSSHQGWKHƬOHQDPHZLWKVRPHWKLQJOLNHXVHUW[WDQGVRRQE\ VZLWFK)RUH[DPSOHIRU"RULI"<RXJHWDQRQVFUHHQKHOSƬOH
DOWHULQJWKHFRGHWRUHDG GHWDLOLQJWKHFRPPDQGVoXVH)RUHDVLHUUHDGLQJSLSHLWWRDWH[WƬOH
@echo off For /? > forhelp.txt
IRU/QLQ  GRFRS\QXO8VHUQW[W

&RGLQJ 3URJUDPPLQJ 


Coding with Windows 10 Batch Files

Creating a Batch File Game


@echo off
%DVHGRQZKDW\RXoYHORRNHGDW Cls
VRIDUZLWKEDWFKƬOHV\RXFDQ :start
set /a score=0
SUREDEO\FRPHXSZLWK\RXURZQ set /a question=0
cls
VLPSOHWH[WDGYHQWXUHRUPXOWLSOH set /p name= What is your name?
FKRLFHJDPH+HUHoVRQHWKDWZH
:menu
created, with which you’re free to cls
echo.
HGLWDQGPDNH\RXURZQ echo ****************************************************
**
echo.
echo Welcome %name% to the super-cool trivia game.
0DNHXS\RXURZQTXHVWLRQVEXWKRZDERXWDOVR echo.
LQFOXGLQJDQLQWURGXFWRU\RUORDGLQJVFUHHQ"0DNH\RXU echo Press 1 to get started
ORDGLQJVFUHHQLQDVHSDUDWHEDWFKƬOHDQGVDYHLWDV echo.
VFUHHQVEDW IRUH[DPSOH 7KHQIURPWKHPDLQJDPH echo Press 2 for instructions
EDWFKƬOH\RXFDQORDGLWDWWKHEHJLQQLQJRIWKHƬOH echo.
ZLWKWKHnFDOOoFRPPDQGIROORZHGE\FRORXUWRUHVHW echo Press Q to quit
echo.
WKHJDPHoVFRORXUV
echo ****************************************************
**
@echo off
choice /C 12Q
Cls
if errorlevel 3 goto :eof
Call screens.bat
if errorlevel 2 goto Instructions
color
if errorlevel 1 goto Game
:start
set /a score=0
:Instructions
set /a question=0
cls
cls
echo.
set /p name= What is your name?
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
cls
echo.
echo ******************************
echo.

 &RGLQJ 3URJUDPPLQJ


&UHDWLQJD%DWFK)LOH*DPH

echo Your current score is %score% if errorlevel 3 goto wrong


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

&RGLQJ 3URJUDPPLQJ 


Coding on Linux

Linux is such a versatile operating


system that’s both malleable
DQGSRZHUIXOZKLOHRƪHULQJWKH
programmer a perfect foundation on
which to build their skills. While all the
popular and mainstream programming
languages are available on Linux, as
they are on Windows and macOS,
Linux also utilises its own coding
language, called scripting.

Bash scripting on Linux can be used to


create a wealth of useful, real-world
programs that interact with the user,
or simply work in the background
EDVHGRQDSUHGHƬQHGVFKHGXOH
Scripting is a powerful interface to the
Linux system, so we’ve crafted this
section to help you get to grips with
KRZHYHU\WKLQJƬWVWRJHWKHUDQGKRZ
to make some amazing Linux scripts.

112 Why Linux?


114 The Best Linux Distributions
116 Equipment You Will Need
118 Creating a Linux Installer on Windows
120 Installing Linux on a PC
122 Installing a Virtual Environment
124 Installing Linux in a Virtual Environment
126 Getting Ready to Code in Linux
128 Creating Bash Scripts – Part 1
130 Creating Bash Scripts – Part 2
132 Creating Bash Scripts – Part 3
134 Creating Bash Scripts – Part 4
136 Creating Bash Scripts – Part 5
138 Command Line Quick Reference

110 &RGLQJ 3URJUDPPLQJ


Index

&RGLQJ 3URJUDPPLQJ 111


Coding on Linux

Why Linux?
For many of its users, Linux means freedom. Freedom from the walled-gardened
approach of other operating systems, freedom to change and use the OS as you please
and freedom from any form of licensing or payment. There’s a lot more to Linux than
you may think.

FREE AND OPEN


/LQX[LVDIDQWDVWLFƬWIRUWKRVHZKRZDQWVRPHWKLQJGLƪHUHQWWKHHƯFLHQF\RIWKHV\VWHPWKHDYDLODELOLW\RIDSSOLFDWLRQVDQG
its stability, are just a few reasons why.

7KHƬUVWWKLQJZHQHHGWRDGGUHVVLVWKDWWKHUHLVQREDVLFRSHUDWLQJ /LQX[ZRUNVYHU\GLƪHUHQWO\WR:LQGRZVRUPDF26)RUDVWDUWLWoV
system called Linux. Fundamentally, Linux is the operating system free to download, free to install on as many computers as you like,
kernel, the core component of an OS. When talking about Linux we free to use for an unlimited amount of time and free to upgrade
are, in fact, referring to one of the many distributions, or distros, and extend with equally free programs and applications. This free to
that use the Linux kernel. No doubt you’ve heard of at least one of use element is one of the biggest draws for the developer. While a
the current popular distros: Ubuntu, Linux Mint, Fedora, openSUSE, Windows license can cost up to £100 and a Mac considerably more,
'HELDQ5DVSELDQfWKHOLVWJRHVRQ(DFKRQHRIWKHVHGLVWURVRƪHUV a user, be they a developer, gamer, or someone who wants to put an
WKHXVHUVRPHWKLQJDOLWWOHGLƪHUHQW:KLOHHDFKKDVWKH/LQX[NHUQHODW older computer to use, can quickly download a distro and get to work
LWVFRUHWKH\RƪHUDGLƪHUHQWORRNLQJGHVNWRSHQYLURQPHQWGLƪHUHQW in a matter of minutes.
SUHORDGHGDSSOLFDWLRQVGLƪHUHQWZD\VLQZKLFKWRXSGDWHWKHV\VWHP
DQGJHWPRUHDSSVLQVWDOOHGDQGDVOLJKWO\GLƪHUHQWORRNDQGIHHO Alongside the free to use aspect comes a level of freedom to customise
throughout the entire system. However, at the centre lies Linux, which and mould the system to your own uses. Each of the distros available on
is why we say, Linux. WKH,QWHUQHWKDYHDFHUWDLQnVSLQoVRPHRƪHULQFUHDVHGVHFXULW\DIDQF\

Linux is a great operating system in


which to start coding.

112 &RGLQJ 3URJUDPPLQJ


Why Linux?

ORRNLQJGHVNWRSDJDPLQJVSHFLƬFVSLQRUVRPHWKLQJGLUHFWHGWRZDUG
students. This extensibility makes Linux a more desirable platform to
use, as you can quickly mould the system into a development base,
LQFOXGLQJPDQ\GLƪHUHQWNLQGVRI,'(VIRUXVHZLWK3\WKRQZHE
development, C++, Java and so on, or even a base for online anonymity,
perhaps as a Minecraft server, media centre and much more.

Another remarkable advantage for those looking to learn how to code


is that Linux comes with most of the popular coding environments
built-in. Both Python and C++ are pre-installed in a high percentage of
Linux distros, which means you can start to program almost as soon as
\RXLQVWDOOWKHV\VWHPDQGERRWLWXSIRUWKHƬUVWWLPH

Generally speaking, Linux doesn’t take up as many system resources


as Windows or macOS, (by system resources, we mean memory,
(DFKGLVWURRƪHUVVRPHWKLQJXQLTXHWRWKH
hard drive space and CPU load), as the Linux code has been
user but all have Linux at the core.
streamlined and is free from third-party ‘bloatware’, which hogs
WKRVHV\VWHPVUHVRXUFHV$PRUHHƯFLHQWV\VWHPPHDQVPRUH
available resources for the coding and testing environment and the So rather than throwing away an old computer, it can be reused with
programs you will eventually create. Less resource use also means a Linux distro.
you can use Linux on older hardware that would normally struggle,
or even refuse to run, the latest versions of Windows or macOS. However, it’s not all about C++, Python, or any of the other more
popular programming languages. Using the command line of Linux
(also called the Terminal), you’re able to create Shell scripts, which are
programs made up of scripting languages and designed to run from
WKHFRPPDQGOLQH7KH\DUHXVHGPDLQO\WRDXWRPDWHWDVNVRURƪHUWKH
user some form of input and output for a certain operation.

There are many more advantages we could list, for example, there
are thousands and thousands of free programs and apps available
that cover practically every aspect of computing. Known as packages,
WKHUHDUH DWWKHWLPHRIZULWLQJ RYHUVSHFLƬFSURJUDPPLQJ
applications on Linux Mint alone and an incredible 62,000+ overall
packages, catering from Amateur Radio to WWW tools.

In conclusion, Linux is a great resource and environment in which


to program. It’s perfectly suited for developers, while continually
improving and evolving. If you’re serious about getting into coding, or
There are thousands of free packages
you just want to explore something new, then give Linux a try and see
available for programmers under Linux.
how it works for you.

A Linux programming environment can be


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

&RGLQJ 3URJUDPPLQJ 113


Coding on Linux

The Best Linux


Distributions
There are numerous versions of Linux available, known as “Distributions”. Each has a
GLƪHUHQWHWKRVDQGDSSURDFK+HUHDUHƬYHJUHDWGLVWULEXWLRQVWRWU\DQGZKHUH\RX
can get them.

/,18;0,17ǟ/,18;0,17&20
By far the most popular Linux distro (distribution) is Linux Mint. In fact, it’s recommended that you spend at least some time trying
Mint began life back in 2006, as an alternative to the then, most GLƪHUHQWHQYLURQPHQWVDQGHYHQGLƪHUHQWGLVWURVWRVHHZKLFK
popular distro, Ubuntu. Although based on Ubuntu’s Long Term suits you and your computer best.
6XSSRUWEXLOG/LQX[0LQWWRRNDGLƪHUHQWGLUHFWLRQWRRƪHUWKH
user a better overall experience.

Linux Mint has three main desktop versions available with each
new version of the core OS it releases. This may sound confusing
DWƬUVWEXWLWoVTXLWHVLPSOH&XUUHQWO\/LQX[0LQWXVHVWKH
&LQQDPRQ'HVNWRS(QYLURQPHQWDVLWVƮDJVKLSPRGHODOWKRXJK
MATE and Xfce models are also available.

Cinnamon is a graphically rich desktop environment, while MATE


uses less fancy graphics but is more stable on a wider variety of
GHVNWRSV\VWHPVDQGƬQDOO\;IFHLVDQH[WUHPHO\VWUHDPOLQHG
desktop environment that is built for speed and ultimate stability.

Throughout this title, we’ll be using the Cinnamon version,


however, you can try out any of the other desktop environments.

8%8178ǟ8%8178&20
The second most popular distro available is Ubuntu: an ancient
African word meaning ‘humanity to others’. Ubuntu’s popularity
KDVƮXFWXDWHGRYHULWVIRXUWHHQ\HDUOLIH$WRQHWLPHLWZDV
easily the most used, Linux-based operating system in the
world, sadly, some wrong choices along the way with regards
to its presentation, along with some unfavourable and
controversial elements involving privacy, saw it topple from the
number one spot. and it’s a little heavy on system resources (especially if you plan
to install it on an older computer).
That said; Ubuntu has since made amends and is slowing crawling
its way back up the Linux leader board. The latest versions of Ubuntu, for all its faults, is a good Linux distro to start
the OS use the GNOME 3 desktop environment, it’s impressive experimenting with. It’s a clean interface, easy to use and install
although it can be a little confusing for former Windows users DQGRƪHUVWKHXVHUWKHFRPSOHWH/LQX[H[SHULHQFH

114 &RGLQJ 3URJUDPPLQJ


The Best Linux Distributions

$5&+ǟ$5&+/,18;25* 23(1686(ǟ23(1686(25*
Arch is one of the longest running Linux distributions and Most Linux distributions fall into two camps: those with the
forms the basis of many other versions of Linux. So why latest features and technology like Ubuntu and Mint and those
install Mint, or Ubuntu when you can install Arch? Many users with fewer new features, but rock-solid reliability, like Debian.
do exactly that, but it’s not ideal for beginners. Ubuntu and
0LQWERWKRƪHUDQHDVLHULQVWDOODWLRQSDWKDQGFRPHZLWK Meanwhile, openSUSE attempts to cover both bases.
software packages that will help you get started. OpenSUSE Leap is a rock-solid system. It’s developed openly
by a community, along with SUSE employees. They develop
$UFKRQWKHRWKHUKDQGLVDPRUHnEDUHERQHVoDƪDLU,WLV an enterprise-level operating system: SUSE, which powers the
committed to free software and its repositories contain over London Stock Exchange, amongst other things. It is designed
50,000 apps to install. You can also install multiple Desktop for mission critical environments where ‘there is no scope
environments and use them as you would with any other distro. IRULQVWDELOLW\o,I\RXƬQGDOOWKDWWRRVHQVLEOHRSHQ686(
Tumbleweed is a rolling release with all the latest features and
Arch is a distro for when you’re more experienced with Linux. the occasional crash.
You start with nothing more than the command line and from
there: you manually partition your hard drive, set where the openSUSE is a highly respected Linux distribution and many
LQVWDOODWLRQƬOHVZLOOJRFUHDWHDXVHUVHWWKH26ORFDOHDQG RILWVFRUHFRQWULEXWRUVZRUNRQWKH/LQX[.HUQHO/LEUH2ƯFH
install a desktop environment, along with the apps you want. Gnome and other key Linux areas. In short: openSUSE is where
\RXoOOƬQGWKHSURVKDQJLQJRXW
The advantage, for all this hard work, is a distro that you’ve
created. This means your Arch distro won’t come with all
WKHXQQHFHVVDU\ƬOHVDQGDSSVWKDWRWKHUGLVWURVKDYHSUH
installed; it’s custom made for you, by you.

5$63%(55<3,'(6.723ǟ5$63%(55<3,25*ǖ'2:1/2$'6ǖ5$63%(55<Ǖ3,Ǖ'(6.723
No doubt you’ve heard of the GLƪHUHQWSURJUDPPLQJODQJXDJHVDQG
Raspberry Pi? It’s hard not to have, as educational resources.
this remarkable, tiny computer has
taken the technology world by storm Originally, Raspbian was exclusive to
since it was introduced six years ago. the Pi hardware, as the Raspberry Pi
uses an ARM processor to power it.
There are several aspects to the +RZHYHUWKH5DVSEHUU\3L)RXQGDWLRQ
Raspberry Pi that make it such a has since released a PC version of
sought-after piece of the computing Raspbian: Raspberry Pi Desktop.
world. For one, it’s cheap, costing
around £25 for, what is essentially, As with the Pi version, Raspberry Pi
a fully working computer. It’s small, Desktop comes with the all the coding,
measuring not much bigger than a credit card. You can employ HGXFDWLRQDODQGRWKHUDSSV\RXZLOOHYHUQHHG,WoVTXLFNVWDEOH
it to build electronics, using a fully programmable interface and and works superbly. If you’re interested in stretching your
it comes with Raspbian, its own custom-made, Debian-based /LQX[H[SHULHQFHWKHQWKLVLVGHƬQLWHO\RQHRIWKHWRSGLVWURV
RSHUDWLQJV\VWHPWKDWLQFOXGHVDQRƯFHVXLWHDORQJVLGHPDQ\ to consider.

&RGLQJ 3URJUDPPLQJ 115


Coding on Linux

Equipment You
Will Need
7KHV\VWHPUHTXLUHPHQWVIRUVXFFHVVIXOO\LQVWDOOLQJ/LQX[0LQWRQWRD3&DUH
surprisingly low, so even a computer that’s several years old will happily run this distro.
+RZHYHULWoVZRUWKFKHFNLQJ\RXKDYHHYHU\WKLQJLQSODFHEHIRUHSURFHHGLQJ

0,17<,1*5(',(176
+HUHoVZKDW\RXoOOQHHGWRLQVWDOODQGUXQ/LQX[0LQWDVZHZRUNWKURXJKWKLVERRN<RXKDYHVHYHUDOFKRLFHVDYDLODEOHVRWDNH
your time and see which works best for you.

SYSTEM REQUIREMENTS
The minimum system requirements for Linux Mint are as follows:

&38 700MHz

RAM 512MB

+DUG'ULYH6SDFH 9GB (20GB recommended)

Monitor 1024 x 768 resolution

Obviously the better the system you have, the better and quicker
the experience will be.

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’ll need), then you’re going to
QHHGDPLQLPXP*%86%ƮDVKGULYHVWLFNWRFRQWDLQWKH
Linux Mint ISO.

116 &RGLQJ 3URJUDPPLQJ


(TXLSPHQW<RX:LOO1HHG

DVD INSTALLATION ,17(51(7&211(&7,21


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

0$&+$5':$5(
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 looking
to breathe new life into an older Mac, make sure it’s an Intel
CPU model and not the Power-PC models. However, be aware,
it’s not as pain-free as installing on to a PC.

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.
7KHUHDUHPDQ\GLƪHUHQWYLUWXDOHQYLURQPHQWDSSVDYDLODEOH
however VirtualBox, from Oracle, is one of the easiest. You can
get the latest version from www.virtualbox.org.

&RGLQJ 3URJUDPPLQJ 117


Coding on Linux

Creating a Linux Installer


on Windows
You need to transfer the downloaded Linux ISO to either a DVD or a USB key before
you can install it to a computer. This will be a live environment, which will allow you to
WHVWWKH26SULRUWRLQVWDOODWLRQEXWƬUVW\RXQHHGWRFUHDWHWKHERRWDEOHPHGLD

DVD BOOTABLE MEDIA


:HoUHXVLQJD:LQGRZV3&KHUHWRWUDQVIHUWKH,62WRD'9'$VORQJDV\RXoUHXVLQJDYHUVLRQRI:LQGRZVIURPRQZDUG
the process is extremely easy.

STEP 1 First locate the ISO image of Linux you’ve already STEP 3 Right-click the Linux ISO and from the menu select
downloaded. In Windows 7, 8.1 and 10 computers, Burn Disc Image. Depending on the speed of the PC,
\RXoOOXVXDOO\ƬQGWKLVLQWKH'RZQORDGVIROGHUXQOHVVZKHQVDYLQJ it may take a few seconds before anything happens. Don’t worry too
LW\RXoYHVSHFLƬHGDGLƪHUHQWORFDWLRQ 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 With the Windows Disc Image Burner dialogue box
computer’s optical drive. After a few seconds, while open, click on the ‘Verify disc after burning’ tick
the disc is read, Windows will display a pop-up message asking you box, followed by the Burn button. The process should take a few
what to do with the newly inserted disc, ignore this as we’re going minutes, depending on the speed of your PC’s optical drive. Once
to use the built-in image burning function. LWoVFRPSOHWHLWZLOOUXQWKURXJKWKHYHULƬFDWLRQVWDJHDQGZKHQ
done, the optical drive should auto-eject the disc for you.

118 &RGLQJ 3URJUDPPLQJ


Creating a Linux Installer on Windows

USB BOOTABLE MEDIA


86%PHGLDLVIDVWHUWKDQD'9'DQGLWoVRIWHQPRUHFRQYHQLHQWDVPRVWPRGHUQ3&VGRQoWKDYHDQRSWLFDOGULYHLQVWDOOHG7KH
SURFHVVRIWUDQVIHUULQJWKHLPDJHLVHDV\EXW\RXoOOQHHGDWKLUGSDUW\DSSƬUVWDQGD86%ƮDVKGULYHRI*%RUPRUH

STEP 1 STEP 4 When you’re ready, click on the Start button at


the bottom of the Rufus app. This may open up
First, open up a web another dialogue box asking you to download and use a new version
browser and go to of SysLinux. SysLinux is a selection of boot loaders used to allow a
https://rufus.akeo. PRGHUQ3&WRDFFHVVDQGERRWIURPD86%ƮDVKGULYH,WLVQHFHVVDU\
ie/. Scroll down the so if asked, click on ‘Yes’ to continue.
page a little and you’ll
come to a Download
heading, under which
you’ll see the latest
version of Rufus.
Left-click on the link to
start the download.

STEP 2 STEP 5 The next step asks in which image mode do you
ZDQWWKH/LQX[,62WREHZULWWHQWRWKH86%ƮDVK
Double-click the GULYH%RWKPHWKRGVZRUNIRUGLƪHUHQWVLWXDWLRQVEXWJHQHUDOO\WKH
downloaded Rufus recommended ISO Image Mode is the more popular. Make sure this
executable; you can mode is pre-selected and click ‘OK’ to continue, followed by ‘OK’
click ‘Yes’ to the DJDLQWRFRQƬUPWKHDFWLRQ
Windows security
question and ‘Yes’
to checking for
updates. With Rufus
launched, it should
KDYHDOUHDG\LGHQWLƬHG
your inserted USB
ƮDVKGULYH LIQRWMXVW
remove and reinsert).

STEP 3 $WƬUVWJODQFHWKH5XIXVLQWHUIDFHFDQORRNDOLWWOH STEP 6


confusing, don’t worry though, it’s really quite
simple. To begin with, click on the SELECT button next to the ‘Disk The Linux ISO is now
or ISO Image (Please select)’ pull-down menu. This will launch a being transferred to
Windows Explorer window from where you can locate and select WKH86%ƮDVKGULYH7KH
the Linux ISO. process shouldn’t take
too long, depending on
the speed of the USB
device and the PC. During
WKHSURFHVV\RXPD\ƬQG
Rufus will auto-open the
USB drive in Windows
Explorer, don’t worry you
can minimise or close it
if you want. Click on the
Close button once the
process is complete.

&RGLQJ 3URJUDPPLQJ 119


Coding on Linux

Installing Linux on a PC
Most Linux distros come as a Live Environment. This means you can boot into an actual,
fully working distro straight from the DVD or USB you’ve just created. Let’s see how
that works and how you go about installing Linux from there.

UEFI BIOS
7KH8QLƬHG([WHQVLEOH)LUPZDUH,QWHUIDFH 8(), LVXVHGWRLGHQWLI\KDUGZDUHDQGSURWHFWD3&GXULQJLWVERRWXSSURFHVV,W
replaces the traditional BIOS, but can cause issues when installing Linux.

STEP 1 ,QVHUW\RXU'9'RU86%ƮDVKGULYHLQWR\RXU3&DQG STEP 3 With UEFI turned to Legacy mode, there are now
if you haven’t already, shutdown Windows. In this two ways of booting into the Live Environment. The
instance, we’re using the USB boot media but the process is virtually ƬUVWLVYLDWKH%,26\RXoUHDOUHDG\LQ/RFDWHWKH%RRW6HTXHQFH and
identical. Start the PC and when prompted press the appropriate FKDQJHWKHƬUVWERRWGHYLFHIURPLWVRULJLQDOVHWWLQJXVXDOO\,QWHUQDO
keys to enter the BIOS or SETUP; these could be, for example, F2, HDD or similar, to: USB Storage Device for the USB media option; or
Del or even F12. DVD Drive, for the DVD media option.

STEP 2 7KHUHDUHGLƪHUHQWYHUVLRQVRID8(),%,26VR 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 %RRW6HTXHQFH or Boot to display a list of boot media options; from there, you can choose
Mode+HUH\RXoOOKDYHWKHRSWLRQWRWXUQRƪ8(),DQGFKRRVH the appropriate boot media. Either way, you can now Save and Exit
Legacy, or disable Secure Booting. Most distros work with UEFI but the BIOS by navigating to the Save & Exit option and choosing Save
it can be a tricky process to enable it to boot. &KDQJHVDQG([LW.

120 &RGLQJ 3URJUDPPLQJ


Installing Linux on a PC

,167$//,1*/,18;
2QFHWKH/LYH(QYLURQPHQWKDVERRWHG\RXZLOOVHHWKHRSWLRQWRLQVWDOOWKHGLVWURWR\RXUFRPSXWHU+DYHDORRNDURXQGDQG
when you’re ready, look for the Install option on the desktop.

STEP 1 Providing you’re connected to the Internet (if not, STEP 4 Before the installation process begins, you’re asked
then do so now) and you’re in the Live Environment, if the choice you made regarding the erasure of the
start the installation process by double-clicking on the Install Linux hard drive is correct. This is your last chance to back out. If you’re
Mint icon on the desktop. Other distros will display their own name, of certain you don’t mind wiping everything and starting again with
course, but the process is the same. Click &RQWLQXH when you’re ready. Linux Mint, click &RQWLQXH,I\RXQHHGWREDFNXS\RXUƬOHVUHPRYH
WKH/LQX[GLVF86%UHERRWEDFNXSDQGVWDUWDJDLQ

STEP 2 While the installation process is very similar across STEP 5 Eventually you will be asked to set up your Linux
PRVW/LQX[GLVWURVVRPHRƪHUGLƪHUHQWTXHVWLRQV username and password. Enter your Name to begin
GXULQJWKHLQVWDOODWLRQ*HQHUDOO\WKHTXHVWLRQVDUHQoWWRRGLƯFXOWRU with, then &RPSXWHU1DPH – which is the name used to identify
technical, but some such as ‘Installing third-party software…’ can be it on the network. Next, choose a Username, followed by a good
confusing. In this case, you can click &RQWLQXH, but if you’re unsure, Password. You can tick the Login Automatically option, but leave
have an Internet-connected device available to ask any questions. the Encrypt Home Folder option for now.

STEP 3 When installing a new operating system it’s STEP 6 The installation process can be quick and there may
recommended that you wipe the old OS, replacing it be more questions to answer, or it may simply start
with the new. When you reach this stage of the installation process, installing Linux based on your previous answers. Either way, you will
ensure the ‘Erase disk and install Linux…’ option is selected. NOTE: end up being asked to Continue Testing the Live Environment, or
7KLVZLOOFRPSOHWHO\ZLSH:LQGRZVIURP\RXUFRPSXWHUPDNH Restarting to use the newly installed OS. If you’re ready to use Linux,
VXUH\RXKDYHEDFNXSVRIDOO\RXUSHUVRQDOƬOHVDQGGDWD then click Restart Now.

&RGLQJ 3URJUDPPLQJ 121


Coding on Linux

Installing a Virtual
Environment
A Virtual Environment is a simulated computer system. Using a Virtual Machine, you
FDQPLPLFDVWDQGDUG3&DQGLQVWDOODQHQWLUHRSHUDWLQJV\VWHPRQLWZLWKRXWDƪHFWLQJ
the one installed on your computer. It’s a great way to test and use Linux, while still
having Windows 10 as your main OS.

*2,1*9,578$/
8VLQJD9LUWXDO0DFKLQH 90 ZLOOWDNHUHVRXUFHVIURP\RXUFRPSXWHUPHPRU\KDUGGULYHVSDFHSURFHVVRUXVDJHDQGVRRQ
So make sure you’ve got enough of each before commencing.

STEP 1 We’re using VirtualBox in this instance, as it’s one of STEP 3 With the correct packages downloaded, before
the easiest virtual environments to get to grips with. we install anything, we need to make sure that the
Enter www.virtualbox.org and click on ‘Download VirtualBox’. This computer you’re using is able to host a VM. To do this, reboot the
will take you to the main download page. Locate the correct host computer and enter the BIOS. As the computer starts up, press the
for your system: Windows or Mac – the Host is the current installed Del, F2, or whichever key is necessary to Enter Setup.
operating system and click the link to begin the download.

STEP 2 Next, while still at the VirtualBox download page, STEP 4 $VHDFK%,26LVODLGRXWGLƪHUHQWO\LWoVYHU\GLƯFXOW
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, 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.

122 &RGLQJ 3URJUDPPLQJ


Installing a Virtual Environment

STEP 5 With the computer back up and running, locate STEP 8 When installing VirtualBox, your network
the downloaded main VirtualBox application and connection will be disabled for a very brief
double-click to begin the installation process. Click Next to continue, period. This is due to VirtualBox creating a linked, virtual network
when you’re ready. connection so that 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’ll probably be asked by Windows to accept a
should satisfy most users, but if you have any special VHFXULW\QRWLƬFDWLRQFOLFN<HVIRUWKLVDQGQH[W
location requirements, click on the ‘Browse’ button and change the you may encounter a dialogue box asking you to trust the
install folder. Also, make sure that all the icons in the VirtualBox installation from Oracle, again, click yes and accept the installation
feature tree are selected and none of them have a red X next to RIWKH9LUWXDO%R[DSSOLFDWLRQ:KHQLWoVFRPSOHWHFOLFNƬQLVKWR
them. Click Next to move on. start VirtualBox.

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

&RGLQJ 3URJUDPPLQJ 123


Coding on Linux

Installing Linux in a
Virtual Environment
With Oracle’s VirtualBox now up and running, the next task is to create the Virtual
0DFKLQH 90 HQYLURQPHQWLQWRZKLFK\RXZLOOLQVWDOO/LQX[7KLVSURFHVVZRQoWDƪHFW
your currently installed operating system, which is why a VM is a great choice.

&5($7,1*7+(90
7KHUHDUHSOHQW\RIRSWLRQVWRFKRRVHIURPZKHQFUHDWLQJD90)RUQRZWKRXJKZHoOOVHWXSD90DGHTXDWHWRUXQWKH
excellent Linux Mint, and perform well.

STEP 1 With VirtualBox open, click on the New icon in the STEP 3 7KHQH[WVHFWLRQZLOOGHƬQHWKHDPRXQWRIV\VWHP
top-middle of the right-hand panel of the app. This memory, or RAM, the VM has allocated. Remember
will open the new 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 (2048MB) 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’ll start to create the virtual
VirtualBox should automatically choose Linux as hard disk that the VM will use to install Mint on to.
the Type and Ubuntu (64-bit) as the Version, if not then use the The default option, ‘Create a virtual hard disk now’, is the one we’re
drop-down boxes to select the correct settings (remember Mint using. Click &UHDWH to move on.
mainstream is based on Ubuntu). Click Next when you’re ready
to proceed.

124 &RGLQJ 3URJUDPPLQJ


Installing Linux in a Virtual Environment

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

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

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. button in the ‘Select Start-up Disk’ window; the
Ensure the location of the virtual hard disk, on your computer, has explorer button is a folder with a green arrow. Click Add in the new
enough free space available. For example, we’ve used a bigger pop-up window, to locate the downloaded ISO of Mint; and click
storage option on our D:\ drive, named it Linux Mint, and allocated Open to select the ISO. Now click the Start button to boot the VM
25.50GB of space to the virtual hard disk. with the Linux Mint Live Environment. You can now install Linux as per
the standard PC installation requirements.

&RGLQJ 3URJUDPPLQJ 125


Coding on Linux

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

7$.,1*&200$1'
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 QDPHGLWZKHQ\RXƬUVWLQVWDOOHGWKH26RQWRWKHFRPSXWHU7KH
the Menu followed by the Terminal icon in the panel, or entering OLQHWKHQHQGVZLWKWKHFXUUHQWIROGHUQDPHDWƬUVWWKLVLVMXVWDWLOGH
‘Terminal’ into the search bar. (~), which means your Home folder.

STEP 2 The Terminal will give you access to the Linux STEP 4 7KHƮDVKLQJFXUVRUDWWKHYHU\HQGRIWKHOLQHLV
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.

126 &RGLQJ 3URJUDPPLQJ


Getting Ready to Code in Linux

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

+(5(%('5$*216
There’s an urban myth on the Internet that an employee at Disney Pixar nearly ruined the animated movie Toy Story by
LQDGYHUWHQWO\HQWHULQJWKHZURQJ/LQX[FRPPDQGDQGGHOHWLQJWKHHQWLUHV\VWHPWKHƬOPZDVVWRUHGRQ

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.
GHOHWHGƬOHV

STEP 2 +RZHYHUWKH7HUPLQDOGRHVQoWRƪHUWKDWOX[XU\,I STEP 4 Second, research before blindly entering a


\RXZHUHWRDFFHVVDIROGHUZLWKƬOHVZLWKLQYLDWKH command you’ve seen on the Internet. If you see the
Terminal and then enter the command: rm *.*DOOWKHƬOHVLQWKDW 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. ZLOOZLSHWKHHQWLUHKDUGGULYHDQGƬOOLWZLWKUDQGRPGDWD7DNHD
moment to Google the command and see what it does.

&RGLQJ 3URJUDPPLQJ 127


Coding on Linux

Creating Bash Scripts


– Part 1
Eventually, as you advance with Linux Mint, you’ll want to start creating your own
automated tasks and programs. These are essentially scripts, Bash Shell scripts
WREHH[DFWDQGWKH\ZRUNLQWKHVDPHZD\DVD'26%DWFKƬOHGRHVRUDQ\RWKHU
programming language.

*(76&5,37,1*
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 EDWFKƬOHWRZRUNDVLQEHH[HFXWHGDQGIROORZWKH
so on. In the end it all comes down to personal preference. Our SURJUDPPLQJZLWKLQLWLWQHHGVWRKDYHD%$7ƬOHH[WHQVLRQ/LQX[
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.

128 &RGLQJ 3URJUDPPLQJ


Creating Bash Scripts – Part 1

STEP 5 Let’s start with a simple script to output something STEP 8 When you enter ls again, you can see that the
to the Terminal. Enter xed helloworld.sh. helloworld.sh script has now turned from being
7KLVZLOOODXQFK;HGDQGFUHDWHDƬOHFDOOHGKHOORZRUOGVK,Q;HG ZKLWHWRJUHHQPHDQLQJWKDWLWoVQRZDQH[HFXWDEOHƬOH7RUXQ
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 <RXFDQVDYHWKLVƬOHFOLFNLQJ)LOH!6DYHDQGH[LW 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.

&RGLQJ 3URJUDPPLQJ 129


Coding on Linux

Creating Bash Scripts


– Part 2
3UHYLRXVO\ZHORRNHGDWFUHDWLQJ\RXUƬUVW%DVKVFULSW+HOOR:RUOGDQGDGGLQJD
system variable. Now you can expand these and see what you can do when you start
WRSOD\DURXQGZLWKFUHDWLQJ\RXURZQXQLTXHYDULDEOHV

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 $16DYHWKHƬOHDQGH[LW;HG%DFNLQWKH7HUPLQDO 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
VRPHWKLQJGLƪHUHQW./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: ¿UVWQDPH 
‘Hello’ is displayed in the Terminal. However, if you then issue the VXUQDPH HFKR+HOOR¿UVWQDPHVXUQDPH. 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.

130 &RGLQJ 3URJUDPPLQJ


Creating Bash Scripts – Part 2

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

STEP 6 Create a new script called addition.sh, using STEP 9 We’ve added a –n to the echo command here
the same format as the hello.sh script, but which will leave the cursor on the same line as the
changing the variable names. Here we’ve added ¿UVWQXPEHU and question, instead of a new line. The read command stores the
secondnumber, and used the echo command to output some XVHUVoLQSXWDVWKHYDULDEOHVƬUVWQDPHDQGVXUQDPHWRWKHQUHDG
simple arithmetic by placing an integer expression, echo The sum back later in the last echo line. And the clear command clears
LV ¿UVWQXPEHUVHFRQGQXPEHU . 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 $VDƬQDODGGLWLRQOHWoVLQFOXGHWKHGDWHYDULDEOH
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: HFKR+HOOR¿UVWQDPHVXUQDPHKRZ
LVo7U\LWZLWKDIHZGLƪHUHQWQXPEHUVDQGVHHZKDWKDSSHQV DUH\RXRQWKLV¿QH GDWH$ ". 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.

&RGLQJ 3URJUDPPLQJ 131


Coding on Linux

Creating Bash Scripts


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

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

STEP 1 Let’s look at the If, Then and Else statements now, STEP 3 The next line, ELSE, is what happens if the variable
which when executed correctly, compare a set of doesn’t equal ‘David’. In this case it simply outputs
instructions and simply work out that IF something is present, THEN to the screen the now familiar ‘Hello…’. The last line, the FI
GRVRPHWKLQJ(/6(GRVRPHWKLQJGLƪHUHQW&UHDWHDQHZVFULSW 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
VOLJKWGLƪHUHQFH+HUHZHoYHDGGHGDORRSVWDUWLQJ little, changing the name variable that triggers a
at the if statement. This means, IF the variable entered is equal to UHVSRQVHRUPD\EHHYHQLVVXLQJDUHVSRQVHZKHUHWKHƬUVWQDPH
David the next line, THEN, is the reaction to what happens, in this DQGVXUQDPHYDULDEOHVPDWFKDVSHFLƬFYDULDEOH
case it will output to the screen ‘Awesome name,’ followed by the
variable (which is David).

132 &RGLQJ 3URJUDPPLQJ


Creating Bash Scripts – Part 3

025(/223,1*
<RXFDQORRSRYHUGDWDXVLQJWKH)25:+,/(DQG817,/VWDWHPHQWV7KHVHFDQEHKDQG\LI\RXoUHEDWFKQDPLQJFRS\LQJRU
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 817,/ZRXOGEHXQWLO
of the script equals zero. Then start the WHILE loop, which WHILE [ $count -gt 100 ]; do7KHGLƪHUHQFHEHLQJ817,/FRXQWLV
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 WKHORRSWRUXQIRU5HQDPLQJDPLOOLRQƬOHVFUHDWLQJƬIW\IROGHUV
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.

&RGLQJ 3URJUDPPLQJ 133


Coding on Linux

Creating Bash Scripts


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

&+2,&(6$1'/2236
/HWoVEULQJLQDQRWKHUFRPPDQG&+2,&(DORQJZLWKVRPHQHVWHG,)DQG(/6(VWDWHPHQWV6WDUWE\FUHDWLQJDQHZVFULSWFDOOHG
mychoice.sh.

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


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

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

STEP 4 You can use the


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

134 &RGLQJ 3URJUDPPLQJ


Creating Bash Scripts – Part 4

&5($7,1*$%$&.837$6.6&5,37
One of the most well used examples of Bash scripting is the creation of a backup routine, one that automates the task as well
as adding some customisations along the way.

STEP 1 A very basic backup script would look something STEP 4 2QFHWKHaEDFNXSVIROGHULVFUHDWHGZHFDQQRZ
along the lines of: ELQEDVKWKHQ 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
ZLOOFUHDWHDFRPSUHVVHGƬOHEDFNXSRIWKHa'RFXPHQWVIROGHU $dest/”$day $month $year”. It’s in here that you put the
ZLWKHYHU\WKLQJLQLWDQGSXWLWLQDIROGHUFDOOHGEDFNXSVZLWKWKH EDFNXSƬOHUHOHYDQWWRWKDWGD\PRQWK\HDU
name my-backup.tgz.

STEP 2 :KLOHSHUIHFWO\ƬQHZHFDQPDNHWKHVLPSOHVFULSW STEP 5 With everything in place, you can now enter the
DORWPRUHLQWHUDFWLYH/HWoVEHJLQZLWKGHƬQLQJ 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...”
GLƪHUHQWVSHOOLQJRQRXUSDUW 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
WKHEDFNXSƬOHZLOOEHFUHDWHG aEDFNXSV <RXFDQQRZDGGD customised to include any folder within your Home area, as well as
VHFWLRQRIFRGHWRƬUVWFKHFNLIWKHaEDFNXSVIROGHUH[LWVLIQRW the entire Home area itself.
then it creates one.

&RGLQJ 3URJUDPPLQJ 135


Coding on Linux

Creating Bash Scripts


– Part 5
The backup script we looked at previously can be further amended to incorporate
FKRLFHVRULQRWKHUZRUGVXVHULQWHUDFWLRQZLWKUHJDUGVWRZKHUHWKHEDFNXSƬOHZLOO
EHFRSLHGWRDQGVRRQ$XWRPDWLQJWDVNVLVRQHRIWKHPDLQEHQHƬWVRI%DVKVFULSWLQJ
a simple script can help you out in many ways.

($6<$8720$7,21$1'+$1'<6&5,376
$UH\RXHQWHULQJOLQHDIWHUOLQHRIFRPPDQGVWRUHWULHYHV\VWHPLQIRUPDWLRQƬQGDƬOHRUUHQDPHDEDWFKRIƬOHV"$VFULSWLVD
EHWWHU{DQVZHU

STEP 1 Let’s start by creating a script to help display the STEP 3 (DFKRIWKHVHFWLRQVUXQVDGLƪHUHQW7HUPLQDO
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
ƬOHUHDG\WREHYLHZHGLQDEURZVHU

STEP 4 Although there are simple Terminal commands to


KHOS\RXORRNIRUDSDUWLFXODUƬOHRUIROGHULWoVRIWHQ
more fun to create a script to help you. Plus, you can use that script
for other non-technical users. Create a new script called look4.sh,
entering the content from the screenshot below.

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


WKLVVFULSW7KHƬUVWLVWKHHH[WHQVLRQIRUHFKR
this means it’ll enable echo interpretation of additional instances
of a new line, as well as other special characters. The proceeding
‘31;43m’ element enables colour for foreground and background.

136 &RGLQJ 3URJUDPPLQJ


Creating Bash Scripts – Part 5

STEP 5 When executed the script waits for input from the STEP 8 The output from colours.sh can, of course, be
XVHULQWKLVFDVHWKHƬOHH[WHQVLRQVXFKDVMSJ PL[HGWRJHWKHUEULQJLQJGLƪHUHQWHƪHFWV
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 ZKLWHWH[WLQDUHGEDFNJURXQGƮDVKLQJ RUEOLQNLQJ 6DGO\WKH
H[WHQVLRQRIWKH¿OH\RX¶UHORRNLQJIRU³, just EOLQNLQJHƪHFWGRHVQoWZRUNRQDOO7HUPLQDOVVR\RXPD\QHHGWR
before the read command. FKDQJHWRDGLƪHUHQW7HUPLQDO

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


app espeak. Install espeak with sudo apt-get
install espeak, then enter the text below into a new script called
speak.sh$V\RXFDQVHHLWoVDUHKDVKRIWKHƬUVWJUHHWLQJVFULSW
we ran. Only this time, it uses the variables in the espeak output.

STEP 7 :HEULHƮ\ORRNHGDWSXWWLQJVRPHFRORXUVLQWKH
output for our scripts. Whilst it’s too long to dig a STEP 9 Whilst we’re on making fancy scripts, how about
little deeper into the colour options, here’s a script that outputs using Zenity to output a graphical interface?
what’s available. Create a new script called colours.sh and enter Enter what you see below into a new script, mmenu.sh. Make it
the text (see below) into it. executable and then run it. You should have a couple of dialogue
ER[HVDSSHDUIROORZHGE\DƬQDOPHVVDJH

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


that’s often touched upon, it is entirely possible,
DOEHLWDOLWWOHEDVLF0RYHPHQWEDVHGJDPHVDUHGLƯXFOWDQG
sometimes buggy, however a good text adventure, or Fighting
Fantasy type game is a perfect choice for gaming in the Terminal.
give it a go, and let us know how you get on.

&RGLQJ 3URJUDPPLQJ 137


Coding on Linux

Command Line
Quick Reference
:KHQ\RXVWDUWXVLQJ/LQX[IXOOWLPH\RXZLOOTXLFNO\UHDOLVHWKDWWKHJUDSKLFDO
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
FRPPDQGOLQHTXLFNUHIHUHQFHJXLGHLVGHVLJQHGWRKHOS\RXPDVWHU/LQX[TXLFNHU

723&200$1'6
7KHVHPD\QRWEHWKHPRVWFRPPRQFRPPDQGVXVHGE\HYHU\RQHEXWWKH\ZLOOFHUWDLQO\IHDWXUHIUHTXHQWO\IRUPDQ\XVHUVRI
Linux and the command line.

The cd command is one of the commands you The mvFRPPDQGPRYHVDƬOHWRDGLƪHUHQW


will use the most at the command line in Linux. It ORFDWLRQRUUHQDPHVDƬOH)RUH[DPSOHPY¿OH
cd allows you to change your working directory. You mv subUHQDPHVWKHRULJLQDOƬOHWRsub. mv sub
use it to move around within the hierarchy of your ~/DesktopPRYHVWKHƬOHnVXEoWR\RXUGHVNWRS
ƬOHV\VWHP<RXFDQDOVRXVHFKGLU directory but does not rename it. You must specify
DQHZƬOHQDPHWRUHQDPHDƬOH

The lsFRPPDQGVKRZV\RXWKHƬOHVLQ\RXU The chownFRPPDQGFKDQJHVWKHXVHUDQG


current directory. Used with certain options, it lets RUJURXSRZQHUVKLSRIHDFKJLYHQƬOH,IRQO\DQ
ls \RXVHHƬOHVL]HVZKHQƬOHVZKHUHFUHDWHGDQGƬOH chown owner (a user name or numeric user ID) is given,
permissions. For example, ls ~VKRZV\RXWKHƬOHV WKDWXVHULVPDGHWKHRZQHURIHDFKJLYHQƬOHDQG
WKDWDUHLQ\RXUKRPH{GLUHFWRU\ WKHƬOHVoJURXSLVQRWFKDQJHG

The cpFRPPDQGLVXVHGWRPDNHFRSLHVRIƬOHV The chmod command changes the permissions on


and directories. For example, FS¿OHVXE makes WKHƬOHVOLVWHG3HUPLVVLRQVDUHEDVHGRQDIDLUO\
cp DQH[DFWFRS\RIWKHƬOHZKRVHQDPH\RXHQWHUHG cmod simple model. You can set permissions for user,
DQGQDPHVWKHFRS\VXEEXWWKHƬUVWƬOHZLOOVWLOO group and world and you can set whether each can
H[LVWZLWKLWVRULJLQDO{QDPH UHDGZULWHDQGRUH[HFXWHWKHƬOH

The pwd command prints the full pathname of The rmFRPPDQGUHPRYHV GHOHWHV ƬOHVRU
the current working directory (pwd stands for GLUHFWRULHV7KHUHPRYDOSURFHVVXQOLQNVDƬOHQDPH
pwd “print working directory”). Note that the GNOME rm LQDƬOHV\VWHPIURPGDWDRQWKHVWRUDJHGHYLFH
terminal also displays this information in the title and marks that space as usable by future writes. In
bar of its window. RWKHUZRUGVUHPRYLQJƬOHVLQFUHDVHVWKHDPRXQW
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 FUHDWHGLUHFWRULHVRQDƬOHV\VWHPLIWKHVSHFLƬHG
clear terminal type and then in the terminfo database mkdir directory does not already exist. For example,
WRƬJXUHRXWKRZWRFOHDUWKHVFUHHQ7KLVLV mkdir work creates a work directory. More than
equivalent to typing Control-L when using the RQHGLUHFWRU\PD\EHVSHFLƬHGZKHQFDOOLQJPNGLU
bash shell.

138 &RGLQJ 3URJUDPPLQJ


Command Line Quick Reference

&?&RPPRQO\B8VHGB&RPPDQGV

86()8/+(/3ǖ,1)2&200$1'6
The following commands are useful for when
you are trying to learn more about the system or
program you are working with in Linux. You might
not need them every day, but when you do, they
will be invaluable.

The free command displays the total amount The sed command opens a stream editor.
of free and used physical and swap memory in A stream editor is used to perform text
free the system. For example, free -m gives the sed WUDQVIRUPDWLRQVRQDQLQSXWVWUHDPDƬOHRULQSXW
information using megabytes. from a pipeline.

The df FRPPDQGGLVSOD\VƬOHV\VWHPGLVNVSDFH
The adduser command adds a new user to the
usage for all partitions. The command df-h
df is probably the most useful (the -h means adduser system. Similarly, the addgroup command adds a
QHZJURXSWRWKH{V\VWHP
human-readable).

The top program provides a dynamic real-time The deluser command removes a user from
view of a running system. It can display WKHV\VWHP7RUHPRYHWKHXVHUoVƬOHVDQG
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
uname-a all system information, including machine name, delgroup the system. You cannot remove a group that is the
kernel name, version and a few other details. primary group of any users.

The ps command allows you to view all the


The man man command brings up the manual
processes running on the machine. Every
ps operating system’s version of ps is slightly man man entry for the man command, which is a great place
to start when using it.
GLƪHUHQWEXWDOOGRWKHVDPHWKLQJ

The grep command allows you to search inside a The man intro command is especially useful.
QXPEHURIƬOHVIRUDSDUWLFXODUVHDUFKSDWWHUQDQG It displays the Introduction to User Commands,
grep then print matching lines. An example would be: man intro which is a well written, fairly brief introduction to
JUHSEODK¿OH. the Linux command line.

&RGLQJ 3URJUDPPLQJ 139


Code Projects and Ideas

To help you on your way to becoming


a better coder, we’ve included some
great coding projects and ideas that
you can apply to your own code, use
as a demo for those who are starting
to code, or improve and send out into
the coding community. Want to learn
how to craft some retro code? How
about learning how to code a text
adventure? These and more are all
IRXQGLQWKLVƬQDOVHFWLRQ

No matter where you go next in


coding, whether it’s on to learning
more languages, creating amazing
apps and games, or helping out and
teaching new coders to avoid the
pitfalls you made, remember the
basics, and have fun!

From here, it’s down to you and your


imagination. So dream it, and code it.

142 Planning your Code


144 Finding Resources
146 Creating a Loading Screen
148 Planning a Text Adventure
150 Text Adventure Script
152 Retro Coding
156 Common Coding Mistakes
158 Python Beginner’s Mistakes
160 C++ Beginner’s Mistakes

140 &RGLQJ 3URJUDPPLQJ


Index

&RGLQJ 3URJUDPPLQJ 141


Code Projects and Ideas

Planning Your
Code
Knowing how to code is great, but it’s not going to get you very far if you don’t know
what it is you’re supposed to be coding. Small samples of code don’t need much
planning, but bigger projects do, so here are some tips on planning your code.

<RXZLOOƬQGWKDWQHDUO\DOOWKHSURIHVVLRQDOGHYHORSHUVRXWWKHUHZLOO
VHWDVLGHVRPHWLPHWRSODQRXWKRZWKHLUFRGHLVJRLQJWRƬWLQWRWKH
wider project on which they’re working. Regardless of whether they’re
ZRUNLQJDVSDUWRIDWHDPRQWKHODWHVWJDPHGHYHORSLQJDZRUNƮRZ
user interface for the company, or creating a set of automated
WDVNVWKDWFDQEHXVHGDFURVVDQXPEHURIGLƪHUHQWSODWIRUPVHDFK
developer will set out their code in a plan.

The planning stages can be unique to the developer, unique to the


company for which they’re working, or the project on which they’re
working. Planning meetings will often sketch out a rough plan of how
the end product will function, with each developer team then working
on their element within the project. Lone developers will sometimes
go back to basics, grab paper and a pencil and start getting their ideas
down. The end result is always the same, though, a plan of action that
enables the developer to plan without worrying about the actual code
at this early stage.

PSEUDOCODE
Code Example:

If “1”
Print response
“I am result 1”

If “2”
Print response
“I am result 2”

One of the more popular methods of planning to code is using It’s very simplistic, but from
pseudocode. It’s terms used in programming circles that allows the there the developer can
developer to represent the implementation of code, the sequence continue to plan the remainder
of the actions, using plain English and a mixture of code examples of the code needed without
WRJHWKHUZLWKDƮRZFKDUWRUWZRWRKHOSnSLFWXUHoORRSVZLWKLQWKH taking up too much valuable
coding project. time – but while also having a
readable plan of action for how
For example, a developer who is planning to write a program that will the code is going to be formed.
check user input for odd or even numbers will probably begin with a
basic statement of pseudocode: The actual writing of the code,
therefore, takes place later on
A program to allow a user to check if the number is odd or even. in the project. Once there’s
Then the basic statement can be expanded: a plan of action in place, the

142 &RGLQJ 3URJUDPPLQJ


Planning Your Code

developer can share the plan with their colleagues, lead developers,
managers, and so on. Then the plan can be further tweaked to include
other aspects that the original developer may have missed or may
have been removed due to being being classed as unnecessary.

7KLVSURFHVVZLOOQRWRQO\WULPWKHIDWRƪWKHFRGHEHIRUHLWoVHYHQ
written but will also help plug any gaps in the project before the hard
work of entering the code begins.

GRAPH PAPER
If you’re planning to include graphics in your project, such as a
platform game, then one of the best resources you can use – and
one that has been used since the early days of coding games – is
graph paper.

Super Mario Bros., launched for the Nintendo Entertainment


System in 1985, was nearly exclusively drawn out – both characters
and levels – on graph paper before being applied to code. Entire Once the graphical planning stage is complete, it’s then down to
game maps were often created this way, especially on the \RXDVWKHGHYHORSHUWRƬOOLQWKHEODQNVDVLWZHUH7KLVPHDQV
older 8-bit machines such as the Commodore 64 and Sinclair ZX creating the code that will place and animate your characters
Spectrum home computers. 8-Bit graphics were ideal for graph within the game, as well as developing interactions, collision
paper since the sprites used then were made up of eight or sixteen detection, number of lives, and so on. With the help of some
blocks; the developer could then visualise the layout of the sprite pseudocode, you could easily plan out what modules you’d use or
using the drawing on the graph paper and apply that to the code. create, the number of variables needed, and the various endgame
The end result, of course, is the character appearing on the screen. states that will arise when someone plays your game.

GET PLANNING
The whole point of planning is to create something easy to follow that
will help you write the code for your project. Planning isn’t supposed
to be a chore; it’s there to aid you when you get stuck trying to work
out which variables you’ve used, where you are in the game, with what
you’re left and how the game will eventually pan out and end.

When planning, begin with small steps. Coding a Hangman game, for
example, begins with the plan to get the player’s name, then includes
the word bank, drawing out the stages of the Hangman, asking the
ULJKWTXHVWLRQVDQGƬQLVKLQJWKHJDPHLQRQHRIWZRVWDWHVsDZLQRU
a lose – then asking if the player wants another go.

2QFH\RXoUHXVHGWRSODQQLQJLWoOOFRPHQDWXUDOO\DQG\RXoOOƬQG
yourself thankful for all those post-it notes stuck to a sheet of A3
paper, as well as the reams of graph paper that detail your characters
and level designs.

3VHXGRFRGHƮRZFKDUWVFDQEHVLPSOHRUDVFRPSOH[
as necessary

Writing pseudocode will help


you visualise the actual code

&RGLQJ 3URJUDPPLQJ 143


Code Projects and Ideas

Finding
Resources
The Python community is huge and spans countless websites and forums on the
,QWHUQHWVRƬQGLQJH[WUDKHOSKHUHDQGWKHUHLVQoWWRRPXFKRIDSUREOHP+RZHYHU
ƬQGLQJJRRG3\WKRQUHVRXUFHVFDQEHVRKHUHDUHVRPHLGHDVIRU\RXWRWU\

You will reach a point in your Python coding experience when you need to rely
on some external resources to help you through a sticky patch in your project
or give you a bit of inspiration. Python resources are available throughout
the Internet, but not all of them are any good. If you spend any time looking
up code for a particular project, then you’re likely to come across copious
examples, yet not all of them seem to work.

That’s one of the main issues with resources for Python. With the language
EHLQJWZHQW\QLQH\HDUVROGDQGPDQ\GLƪHUHQWYHUVLRQVXQGHUWKHEULGJH
WKHUHoVDVLJQLƬFDQWDPRXQWRIFRQWHQWRXWWKHUHWKDWoVVLPSO\RXWRIGDWHsRU
just wrong for the version you’re using. Newer versions, even by one number
RXWFDQKDYHGLƪHUHQWRXWSXWVIRU\RXUFRGHIURPDSUHYLRXVYHUVLRQsLWoV
QRWDOZD\VWKDWFDVHEXWLWFDQKDSSHQ7KHUHIRUH\RXQHHGWRƬQG\RXUVHOI
some trusted Python resources that work, or at least 90% would work, with the
version you’re using and the code within.

THE HITCHHIKER’S GUIDE TO PYTHON


2QHRIWKHƬUVWSODFHVWKDWoVZRUWKWXUQLQJWRLVIUHH&RGH&DPSRUJ7KLVZHEVLWH
features a wealth of code that covers most aspects of the learning experience,
HYHQIRUWKRVHZKRDUHH[SHUWVDW3\WKRQ<RXoOOƬQGFRQWHQWWKDWZLOOWDNH\RXU
Python journey to new heights; with code snippets to help you access networking
HOHPHQWVPLOLWDU\VW\OHHQFU\SWLRQDQGPRUHDQG\RXFDQHYHQJDLQFHUWLƬFDWLRQ
through the site.

Programiz is another useful resource that features Python code examples


covering a wide range of concepts. There’s everything in here from the original
p+HOORZRUOGqFRGHWKURXJKWRFRGHWKDWZLOOWUDQVSRVHDPDWUL[RUƬQGWKHKDVK
RIDƬOH7KHUHoVDOVRDQRQOLQHFRPSLOHUDQGLQGHSWKORRNVLQWRIXUWKHUUHDGLQJ
for aspiring data scientists.

If you’re looking for resources about using graphics in Python, then


ProgramArcadeGames.com is a good place to start. This site has plenty of code for
the Pygame module, including moving an object around the screen using a mouse
or game controller, creating fractals, moving sprites, and an example of a classic
Pong game for you to try out.

GitHub is always worth a look. However, the code featured here isn’t always up
WRGDWHDQG\RXPD\ƬQG\RXUVHOIKDYLQJWRFRQYHUW3\WKRQFRGHLQWR3\WKRQ
3. Nevertheless, you do come across some gems from time to time, especially if
you look up the Pygame examples that users have uploaded. We recommend the
excellent Solarwolf, by Pete Shinners.

144 &RGLQJ 3URJUDPPLQJ


Finding Resources

67521**22*/(Ǖ)8
7KHUHoVQRWULFNWRƬQGLQJJRRG3\WKRQUHVRXUFHVRQOLQHPRVW
of the time, it’s a case of trial and error. You’ll need to make sure
you’re searching for the right content, though, just to save you
VRPHWLPH,ILWoVD3\JDPHVSHFLƬFVHWRIUHVRXUFHV\RXoUHORRNLQJ
for then you’ll need to specify the Python version you’re using;
include Pygame, and include what it is you’re looking for – it may
VRXQGOLNHZHoUHWHDFKLQJ\RXWRVXFNHJJVEXWHƪHFWLYHVHDUFKLQJ
is often overlooked.

Again, it’s also worth looking up working examples of a type of


game if you’re looking for Pygame content. If you want to learn
how to engineer sprites moving from one side of the screen
to the other, then look up some examples of Space Invaders,
which feature such movements. The same goes if you’re making
a platform game, examine some classic games that involved
platforming, like Mario and so on.

One last resource is our very own code portal. Log in to https://
SFOpublications.com/H[FOXVLYHV/DQG\RXoOOILQGDFRQWLQXDOO\
growing list of Python code and resources that you can freely add
to your own code, then chop, change, and use for whatever
projects you have in mind.

&RGLQJ 3URJUDPPLQJ 145


Code Projects and Ideas

Creating a Loading Screen


If you’re looking to add a little something extra to your Python code, then consider
including a loading screen. The loading screen is a short introduction, or piece of art,
that appears before the main part of your code.

LOAD”” THE CODE


Back in the 80s, in the 8-bit Launch Python and enter the following code to a New File:
home computing era, loading
import os
screens were often used to
import time
display the cover of a game
as it loaded from tape. The def loading_screen(seconds):
image would load itself in, screens=open(“screens.txt”, ‘r’)
usually one-line-at-a-time, for lines in screens:
then proceed to colour print(lines, end=’’)
itself in while the loading time.sleep(seconds)
raster bars danced screens.close()
around in the borders of
#Main Code Start
WKH{VFUHHQ
os.system(‘cls’ if os.name == ‘nt’ else
Loading screens were a part of the ‘clear’)
package and often the buy-in for loading_screen(.5)
the whole game as an experience. Some
print (“\nYour code begins here...”)
loading screens featured animations, or a countdown for time
remaining as the game loads, while others even went so far as to
include some kind of playable game. The point being: a loading
screen is not just an artistic part of computing history, but an
introduction to the program that’s about to be run.
While these days loading screens may no longer be with us, in
terms of modern gaming we can still include them in our own
Python content. Either just for fun, or to add a little retro-themed
VSLFHWRWKH{PL[

SCREEN$
Creating a loading screen in Python is remarkably easy. You have
several options to hand: you can create a tkinter window and
display an image, followed by a brief pause, before starting your
main code, or you could opt for a console-based ASCII art version
that loads one-line-at-a-time. Let’s look at the latter and see how
it works.
The code is quite simple: import the OS and Time modules and
First you’ll need some ASCII art, you can look up plenty of examples
then create a Python function called loading_screen with a
online, or use an image to ASCII Art converter to transform any
VHFRQGV RSWLRQ:LWKLQWKHIXQFWLRQRSHQWKHWH[WƬOHZLWKWKH
images you have to ASCII. When you have your ASCII art, drop it into
ASCII art as read-only and create a For loop that’ll read the text
DQHZO\FUHDWHGIROGHULQVLGHDQRUPDOWH[WƬOH
ƬOHRQHOLQHDWDWLPH1H[WSULQWWKHOLQHVsLQFLGHQWDOO\WKH
lines, end=’’ element will strip the newline from the text
document, without it you’ll end up with a double-line spaced
GLVSOD\,QFOXGHWKHWLPLQJLQVHFRQGVDQGFORVHWKHWH[WƬOHEXƪHU
7KHƬQDOSDUWRIWKHFRGH #Main Code Start, is where you’ll
clear the screen (CLS for Windows, Clear for Linux (Raspberry
Pi) and macOS) and call the function, together with the output
number of seconds to wait for each line to be written to the screen
– in this case, .5 of a second.

146 &RGLQJ 3URJUDPPLQJ


Creating a Loading Screen

print (“\nYour code begins here...”)


The code works in much the same way as the previous, except,
LQVWHDGRIUHDGLQJIURPDWH[WƬOHLWoVUXQQLQJWKURXJKD)RUORRS
that prints Loading… followed by an animation of sorts, along with a
percentage counter; clearing the screen every second and displaying
WKHQHZUHVXOWV,WoVVLPSOH\HVEXWTXLWHHƪHFWLYHLQLWVGHVLJQ

Save the code as screens.py, drop into a Command Prompt or COMBINING THE TWO
Terminal and execute it. The screen will clear and your ASCII art
How about combining the two elements we’ve looked at? Let’s
LQVLGHWKHWH[WƬOHZLOOORDGLQOLQHE\OLQHFUHDWLQJDORDGLQJ
begin with a Loading… progress bar, followed by the loading
VFUHHQ{HƪHFW
screen. After that, you can include your own code and continue
your program. Here’s the code:
LOADING…
import os
import time
def loading_bar(seconds):
for loading in range(0,seconds+1):
percent = (loading * 100) // seconds
print(“\n”)
print(“Loading...”)
print(“<” + (“-” * loading) + (“ “ * (seconds-
Another favourite introduction screen is that of a simple loading
loading)) + “> “ + str(percent) + “%”)
animation, where the word loading is displayed, followed by
print(“\n”)
some characters, and a percentage of the program loaded. While
time.sleep(1)
LWPD\QRWWDNHORQJIRU\RXU3\WKRQFRGHWRORDGWKHHƪHFWFDQ
os.system(‘cls’ if os.name == ‘nt’ else
EH{LQWHUHVWLQJ
‘clear’)
Create a New File in Python and enter the following code:
def loading_screen(seconds):
import os screens=open(“screens.txt”, ‘r’)
import time for lines in screens:
print(lines, end=’’)
def loading_bar(seconds):
time.sleep(seconds)
for loading in range(0,seconds+1):
screens.close()
percent = (loading * 100) // seconds
print(“\n”) #Main Code Start
print(“Loading...”) loading_bar(10)
print(“<” + (“-” * loading) + (“ “ * (seconds- os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
loading)) + “> “ + str(percent) + “%”) loading_screen(.5)
print(“\n”)
print (“\nYour code begins here...”)
time.sleep(1)
os.system(‘cls’ if os.name == ‘nt’ else You can, of course, pull those functions up wherever and whenever
‘clear’) you want in your code and they’ll display, as they should, at the
EHJLQQLQJ5HPHPEHUWRKDYHWKH$6&,,WH[WƬOHLQWKHVDPHIROGHU
#Main Code Start
DVWKH3\WKRQFRGHRUDWWKHVFUHHQV RSHQ pVFUHHQVW[WqnUo SDUW
loading_bar(10)
RIWKHFRGHSRLQWWRZKHUHWKHWH[WƬOHLVORFDWHG

ADVENTURE TIME
A good example of using loading screen, ASCII art
text images is when coding a text adventure. Once
you’ve established your story, created the characters,
events and so on, you could easily incorporate some
excellently designed ASCII art to your game.
Imagine coming across a dragon, in game, and
displaying its representation as ASCII. You can then
load up the image lines, one-by-one, and continue with
the rest of the adventure code. It’s certainly worth
KDYLQJDSOD\DURXQGZLWKDQGLWoOOGHƬQLWHO\DGGDOLWWOH
something else extra.

&RGLQJ 3URJUDPPLQJ 147


Code Projects and Ideas

Planning a Text Adventure


Planning a text adventure is one of the best ways of teaching yourself some new
Python tricks and essential code. A good text adventure contains many aspects, all of
which will need to be carefully planned and structured, to get the best from the code.

If you can think back to some of the classic text adventures you
may have played in the past, consider the amount of work that was
needed to get them up and running. If you’re not familiar with a text
adventure, then open a browser and go to http://textadventures.
FRXNJDPHVSOD\]\RTUVXJHRSHOƪK]BYT. This is an online version
of the classic text adventure Zork. Zork was created for the DEC PDP-
10 workstations, using the MDL programming language back in the
late seventies. Despite its age, it’s still considered one of the best text
adventures to play. The second crucial element is choice. Without that, the player may as
well read the story from a book. It’s the choice presented to the player
that makes the game an adventure. If the player chooses something
wrong, they could be punished, whereas a correct choice could gain
them gold or some other form of reward. However, it doesn’t always
need to be a positive or negative choice; after all, most common real-
life decisions we make aren’t life or death, they merely result in one
thing happening or another.

Locations are similarly important. Text Adventures rely on good the


locations featured in the game can draw a picture in the mind of the
player. Whether they’re on a wooden ship in the middle of the sea or
trying to escape a haunted mansion, each location has to stand out.

Items are also a vital requirement for a good adventure game. A


Zork, or any other text adventure game, features several elements player will need to be able to pick up, examine, take, and use, an item
necessary to make the game both interesting and playable. IURPLWVORFDWLRQLQWKHJDPH)RUH[DPSOH\RXUFKDUDFWHUFRXOGƬQGD
NH\LQWKHƬUVWORFDWLRQSRFNHWLWDQGWKHQXVHLWODWHURQLQWKHJDPH
to unlock a door. You’ll need to factor in the list of possible items, and
INGREDIENTS FOR A you’ll also need to factor in the real-world physics of each item too. If
COMPELLING ADVENTURE you have your adventurer enter a room with an anvil, then allowing
7KHƬUVWLQJUHGLHQWLVDVWRU\DSORWWKDWZLOOWDNHWKHSOD\HURQDULGH them to pick up the anvil and put it in their pocket isn’t particularly
through their own imagination. It doesn’t necessarily have to include realistic. One of the major drawbacks of some text adventures, and
dragons, barbarians, spaceships, or other such things, but it needs to even modern graphical games, is the unrealistic carrying capability of
be engaging. Perhaps it could follow the theme of a murder mystery, the player.
much in the same vein as an Agatha Christie novel, or it could be
something that explores the base fears of people.

148 &RGLQJ 3URJUDPPLQJ


Planning a Text Adventure

Although not always necessary, puzzles do form an interesting aspect Lists, tuples and dictionaries will be needed to store the
of a text adventure. These puzzles can test the player’s abilities various elements of the game. These can be descriptions of
DQGH[SDQGWKHJDPHEH\RQGVLPSO\ƬQGLQJDQREMHFWDQGXVLQJ characters whom you’ll meet, either friend or foe. Locations, with
it. Puzzles can range from using these objects correctly to achieve descriptions, throughout the game; items you’ll come across that
VRPHWKLQJWRƬQGLQJWKHFRUUHFWURXWHWKURXJKDPD]HZLWKVRPH can be used, along with a player inventory, which will grow or
being vital to the plot while others are simply there to give the player lessen depending on what the player has used/dropped/picked up.
something interesting to do. Ideally, puzzles should be easy near the
beginning of the game and get progressively harder as your character Variables will be needed to hold vital statistics during gameplay,
advances through the game. the player’s name, amount of strength, endurance, skill and health,
for example. You’ll also need variables to hold the current score
or number of moves used so far, plus any statistics regarding the
other characters you’ll meet.

Randomly generated numbers are vital for those who want to


include an element of combat. Within such examples, a virtual dice
UROOZLOOGHWHUPLQHWKHZLQQHURUORVHUHLWKHULQDƬJKWRUZKHQ
using luck to win through something.

Strings can be used to keep non-moving elements of the game,


in other words the names of the rooms you may enter. These
components are static throughout the game, each and every time you
play, so they can be called upon when the player interacts with them.

Functions are the lifeblood of a text adventure, as they will form


Hints and help along the way can make the adventure seem less the backbone of the locations, interactions, events and anything
daunting. Of course, if you’re particularly mean-spirited, then you can else that happens within the game.
opt to exclude any form of help along the way altogether. However,
most text adventures do include some form of a hint. If you’ve /RRSVZLOONHHSDSURFHVVJRLQJVXFKDVDƬJKWZLWKDQRUFXQWLODQ
created a great set of puzzles for the player to beat, and they’re stuck event occurs – either the death of the orc or your player. In addition,
in their progression of the game, then allowing them to enter the you’ll need to include a loop, if and else components to help out
word: help, or hint, into the system, will reveal a small clue as to what with choices made: do you take the green door or the red door?
to do next. It’s not cheating, just keeping the story moving along.

3DFLQJLVWKHƬQDODVSHFWRIWKHDGYHQWXUHJDPHWKDWQHHGVWREH
planned correctly. Good pacing within the story is vital to keeping
your player’s attention, as well as keeping them entertained and
engaged with what’s going on. It’s not an easy egg to crack, however.
Too much pace and the player can get lost. Too slow, and they’ll get
bored and move on to something else.

THE CODE
It’s impossible to list the code you’ll need for your adventure
JDPHVLQFHLWoOOEHGLƪHUHQWIURPHDFKUHDGHUWRWKHQH[WEXWKHUH
are some pointers to help you out.

GOOD LUCK, ADVENTURER


There’s a lot to take in and plan, so our advice is to start small and
SODQRXW\RXUVWRU\ƬUVW2QFH\RXoYHJRWWKHEDVLFVWRU\EXLOGRQ
the settings and locations, then puzzles and other elements. From
there, you can begin to expand the game world and add things like
combat.

It won’t be easy, but it’ll be great fun and will help you become a
better Python coder.

&RGLQJ 3URJUDPPLQJ 149


Code Projects and Ideas

Text Adventure Script


Text adventures are an excellent way to build your Python coding skills and have
some fun at the same time. This example that we created will start you on the path to
making a classic text adventure; where it will end is up to you.

ADVENTURE.PY import time


The Adventure game uses just the Time module to begin
with, creating pauses between print functions. There’s a help print(“\n” * 200)
print(“>>>>>>>>>>Awesome Adventure<<<<<<<<<<\n”)
system in place to expand upon, as well as the story itself.
print(“\n” * 3)
time.sleep(3)
print(“\nA long time ago, a warrior strode forth from
the frozen north.”)
time.sleep(1)
print(“Does this warrior have a name?”)
name=input(“> “)
print(name, “the barbarian, sword in hand and looking
for adventure!”)
time.sleep(1)
print(“However, evil is lurking nearby....”)
time.sleep(1)
print(“A pair of bulbous eyes regards the hero...”)
time.sleep(1)
print(“Will”, name, “prevail, and win great fortune...”)
time.sleep(1)
print(“Or die by the hands of great evil...?”)
time.sleep(1)
print(“\n” *3)
print(“Only time will tell...”)
time.sleep(1)
print(‘...’)
time.sleep(1)
print(‘...’)
time.sleep(1)
print(‘...’)
time.sleep(1)
print(‘...’)
time.sleep(5)
print(“\n” *200)

SULQW µ¶¶<RX¿QG\RXUVHOIDWDVPDOOLQQ7KHUH¶V
little gold in your purse but your sword is sharp,
and you’re ready for adventure.
With you are three other customers.
A ragged looking man, and a pair of dangerous
looking guards.’’’)

def start():
print(“\n ----------”)
print(“Do you approach the...”)
print(“\n”)
print(“1. Ragged looking man”)
print(“2. Dangerous looking guards”)

cmdlist=[“1”, “2”]
cmd=getcmd(cmdlist)

150 &RGLQJ 3URJUDPPLQJ


Text Adventure Script

if cmd == “1”: def getcmd(cmdlist):


ragged() cmd = input(name+”>”)
elif cmd == “2”: if cmd in cmdlist:
guards() return cmd
elif cmd == “help”:
def ragged(): print(“\nEnter your choices as detailed in
print(“\n” * 200) the game.”)
print(‘’’You walk up to the ragged looking man and print(“or enter ‘quit’ to leave the game”)
greet him. return getcmd(cmdlist)
He smiles a toothless grin and, with a strange elif cmd == “quit”:
accent, says. print(“\n-----------”)
“Buy me a cup of wine, and I’ll tell you of time.sleep(1)
great treasure...’’’) print(“Sadly you return to your homeland without
time.sleep(2) fame or fortune...”)
time.sleep(5)
def guards(): exit()
print(“\n” *200)
print(‘’’You walk up to the dangerous looking guards
and greet them. if _ _ name _ _ ==” _ _ main _ _ ”:
7KHJXDUGVORRNXSIURPWKHLUGULQNVDQG start()
snarl at you.
“What do you want, barbarian?” One guard reaches
for the hilt of his sword...’’’)
time.sleep(2)

Adventure Time
This, as you can see, is just the beginning of the adventure and
takes up a fair few lines of code. When you expand it, and weave
WKHVWRU\DORQJ\RXoOOƬQGWKDW\RXFDQUHSHDWFHUWDLQLQVWDQFHV
such as a chance meeting with an enemy or the like.

:HoYHFUHDWHGHDFKRIWKHWZRHQFRXQWHUVDVDGHƬQHGVHW
of functions, along with a list of possible choices under the
FPGOLVWOLVWDQGFPGYDULDEOHRIZKLFKLVDOVRDGHƬQHGIXQFWLRQ
Expanding on this is quite easy, just map out each encounter and
FKRLFHDQGFUHDWHDGHƬQHGIXQFWLRQDURXQGLW3URYLGLQJWKHXVHU
doesn’t enter quit into the adventure, they can keep playing.

There’s also room in the adventure for a set of variables designed


for combat, luck, health, endurance and even an inventory or
amount of gold earned. Each successful combat situation can
reduce the main character’s health but increase their combat skills
or endurance. Plus, they could loot the body and gain gold, or earn
gold through quests.

Finally, how about introducing the Random module. This will


enable you to include an element of chance in the game. For
example, in combat, when you strike an enemy you will do a
random amount of damage as will they. You could even work out
the maths behind improving the chance of a better hit based on
your or your opponent’s combat skills, current health, strength and
endurance. You could create a game of dice in the inn, to see if you
win or lose gold (again, improve the chances of winning by working
out your luck factor into the equation).

Needless to say, your text adventure can grow exponentially


and prove to be a work of wonder. Good luck, and have fun with
your adventure.

&RGLQJ 3URJUDPPLQJ 151


Code Projects and Ideas

Retro Coding
There’s a school of thought, that to master the foundations of good coding skills you
need to have some experience of how code was written in the past. In the past is a bit
of a loose term, but mostly, it means coding from the 80s.

UHFRJQLVHGWKDWRQHRIWKHnEHVWoDQGSRVVLEO\PRVWXWLOLVHGIRUPRI
BASIC from the 80s was that of BBC BASIC.
BBC BASIC was used on the Acorn BBC Micro range of computers,
XWLOLVLQJWKH026EDVHGSURFHVVRUWHFKQRORJLHV,WZDVRQHRI
the quickest examples of BASIC and, thanks to an inline assembler, it
was also capable of allowing the developers of the time to write code
IRUGLƪHUHQWSURFHVVRUW\SHVVXFKDVWKH=LORJ=sD&38SUHVHQWLQ
THE GOLDEN ERA OF CODE the ZX Spectrum, as well as many arcade machines.
While it may seem a little counterproductive to learn how to code in a The BBC Micro was designed and built by Acorn Computers – a
ODQJXDJHWKDWoVYLUWXDOO\REVROHWHWKHUHDUHVRPHVXUSULVLQJEHQHƬWV company that is historically responsible for the creation of the ARM
to getting your hands dirty with a bit of retro coding. Firstly, learning &38WKHSURFHVVRUWKDWoVXVHGLQYLUWXDOO\HYHU\$QGURLGSKRQHDQG
old code will help you build the structure of code as, regardless of tablet, smart TV, set top box and so on, as well as the Raspberry Pi –
whether it is a language that was developed yesterday, or forty years so essentially, the BBC Micro is the grandfather of the Raspberry Pi.
ago, code still demands strict discipline to work correctly. Secondly,
7KH%%&0LFURZDVERUQLQDWLPHZKHQWKH8.JRYHUQPHQWZDV
everyday coding elements, such as loops, sub routines and so on, are
looking for a countrywide computer platform to be used throughout
a great visual aid to learn in older code, especially BASIC. Lastly, it’s
HGXFDWLRQ'LƪHUHQWFRPSDQLHVELGEXWLWZDVWKH%%&oV&RPSXWHU
simply good fun.
Literacy Project (the BBC Micro) that was chosen, due to its
ruggedness, upgradability, and potential for education. As a result,
WKH%%&0LFURRUWKH%HHEDVLWoVDƪHFWLRQDWHO\NQRZQEHFDPHWKH
dominant educational computer throughout the 80s.

BEEBEM
Naturally, you could scour eBay and look for a working BBC Micro to
GOING BASIC play around on, and it’ll be a lot of fun. However, for the sake of just
getting hands-on with some retro code, we’ll use one of the best BBC
The easiest retro language to play around with is, without doubt,
Micro emulators available: BeebEm.
BASIC. Developed back in the mid-sixties, BASIC (Beginner’s All-
Purpose Symbolic Instruction Code) is a high-level programming %HHE(PZDVRULJLQDOO\GHYHORSHGIRU81,;LQE\'DYH*LOEHUWDQG
language whose design was geared toward ease of use. In a time later ported to Windows. It is now developed by Mike Wyatt and Jon
when computers were beginning to become more accessible, Welch, who maintain the Mac port of the emulator, and is therefore
designers John Kemeny and Thomas Kurtz needed a language that available for Windows 10, Linux and macOS, as well as other platforms.
students could get to grips with, quickly and easily. Think of BASIC as a
If you’re using Windows 10, simply navigate to http://www.mkw.
distant relation to Python.
me.uk/beebem/index.html, and download the BeebEM414.exe
that’s displayed in the main screen.
THE BEEB
7KHSUREOHPZLWK%$6,&LVWKDWWKHUHZHUHVRPDQ\GLƪHUHQWYHUVLRQV
available, across multiple 8-bit platforms, with
each having its own unique elements
on top of the core BASIC
functions. The BASIC that
was packaged with the
&RPPRGRUHZDVGLƪHUHQW
to that on the ZX Spectrum,
or the Atari home computers, Once downloaded, launch the executable and follow the on-screen
GXHWRWKHGLƪHULQJKDUGZDUHRI instructions to install it. MacOS users can get everything they need
each system. However, it’s widely from: http://www.g7jjf.com/. However, Raspberry Pi and Linux users

152 &RGLQJ 3URJUDPPLQJ


Retro Coding

will have to do a little nifty keyboard work before they can enjoy the clears the screen; although the Pi uses Clear instead of CLS. We’re also
EHQHƬWVRIWKH%HHERQWKHLUVFUHHQV+HUHoVKRZWRJHWLWZRUNLQJ able to do some maths work, and play around with variables too:
under Linux:
1 CLS
First, drop to a Terminal and enter:
10 input “how old are you? “ a
20 print
sudo apt-get update && upgrade
30 if a > 40 print “You’re over 40 years old.”
wget http://beebem-unix.bbcmicro.com/download/
40 if a < 40 print “You’re under 40 years old.”
beebem-0.0.13.tar.gz
50 print
7KHQH[WUDFWWKHFRPSUHVVHGƬOHVZLWK
BBC BASIC also has some interesting built-in features, such as the
value of PI:
tar zxvf beebem-0.0.13.tar.gz, then enter the newly
created Beebem folder with: cd beebem-0.0.13/.
1 REM Area of a circle
2 CLS
Now enter the following lines, hitting Enter and answering Y to accept
20 Input “Enter the radius: “ r
any changes:
30 let area = PI*r*r
SULQW³7KHDUHDRI\RXUFLUFOHLV³DUHD
sudo apt-get install libgtk2.0-dev libsdl1.2-dev
50 print ‘’’
FRQ¿JXUH
make
sudo make install

This may take some time, but when it’s all done, simply enter: beebem,
to start the BBC Micro emulator.

BBC BASIC
Once installed and powered up, BeebEm will display the default As you’ll notice, variables with a dollar ($) represent strings, nothing
BBC system start-up, along with a couple of beeps. Those of you DIWHUWKHYDULDEOHRUDKDVK  UHSUHVHQWƮRDWLQJSRLQWGHFLPDOVD
ROGHQRXJKWRKDYHEHHQLQD8.VFKRROLQWKHVZLOOFHUWDLQO\ whole integer has a % character, and a byte has an ampersand (&).
recall this setup. The single quotes after the Print on line 50 indicate a blank line, one
for each tick, while REM on line 1 is a comment, and thus ignored by
In BASIC, we use line numbers to determine which lines of code run in
the BASIC compiler.
sequence. For example, to print something to screen we’d enter:
Needless to say, there’s a lot you can learn, as well as having fun, with
10 print “hello” BBC BASIC. It’s a rainy day project and something that’s interesting to
show the kids – this is how we rolled back in the 80s, kids!
Once you’ve typed the above in, press
There are a number of sites you can visit to learn BBC BASIC, such
Enter and then type:
as http://archive.retro-kit.co.uk/bbc.nvg.org/docs.php3.html.
See what you can come up with using BBC BASIC, or other BASIC
run
W\SHVIRUGLƪHUHQWV\VWHPVDQGOHWXVNQRZZKDW\RXoYHFUHDWHG
We can of course expand the code to
include variables, multi-line print statements, and so on:
OTHER SYSTEMS
Naturally, you don’t have
1 CLS to look to the BBC Micro
10 Input “Hello, what’s your name? “ n$ to play around with some
20 print retro code. If you grew up
30 print “Hi, “ n$ “ I hope you’re well today.” with a Commodore 64, then
you can always try VICE, the
C64 emulator. Likewise, the
ZX Spectrum has a slew of
great emulators available for
every modern system to play
around on. In fact, you can
SUREDEO\ƬQGDQHPXODWRUIRU
virtually every 8-bit or 16-bit
machine that was produced
7\SH581WRH[HFXWHWKHFRGH\RXFDQDOVRW\SH/,67WRYLHZWKH
over the years. Each has their
code you’ve entered.
own unique perspective and
As you can see, variables are handled in much the same way as FRGLQJQXDQFHVVRƬQGDIHZ
Python, a print statement on its own displays a blank line, and CLS and see what you can create.

&RGLQJ 3URJUDPPLQJ 153


Code Projects and Ideas

Text Animations
There’s a remarkable amount you can do with some simple text and a little Python
know-how. Combining what you’ve already learned, we can create some interesting
DQLPDWLRQHƪHFWVIURPWKHFRPPDQGOLQH

print(message)
THE FINAL COUNTDOWN print(“< >”)
Let’s begin with some example code that will display a large print(“v^v^v^v^v^v^v^v^v^v^v^v^v^v^v”)
countdown from ten, then clear the screen and display a message. print(“\n\n\n”)
The code itself is quite simple, but lengthy. You will need to start by
importing the OS and Time modules, then start creating functions The code in its entirety can be viewed
that display the numbers (see image below) and so on to 10. It’ll take from within our Code Repository: https://
some time, but it’s worth it in the end. Of course, you can always take SFOpublications.com/H[FOXVLYHV, where you’re
DGLƪHUHQWDSSURDFKDQGGHVLJQWKHQXPEHUV\RXUVHOI free to copy it to your own Python IDLE DQGXVH
LWDV\RXVHHILW7KHHQGHIIHFWLVTXLWHgood
The next step of the process is to initialise the code settings and start
and it’ll be worth adding to your own games, or
the countdown:
presentations, in Python.
#Initialise settings To extend the code, or make it easier to use,
start = 10 you can always create the number functions
PHVVDJH ³!%/$672)) in their own Python code, call it Count.py for
<” example, then import Count at the beginning of
DQHZ3\WKRQƬOHFDOOHGCountdown.py, along with the OS and Time
#Start the countdown
modules:
for counter in range(start, 0, -1):
if counter == 10:
import os
ten()
import time
elif counter == 9:
import count
nine()
elif counter == 8:
From there, you will need to specify the imported code in the
eight()
Countdown section:
elif counter == 7:
seven()
#Start the countdown
elif counter == 6:
for counter in range(start, 0, -1):
six()
if counter == 10:
elif counter == 5:
count.ten()
¿YH
elif counter == 9:
elif counter == 4:
count.nine()
four()
elif counter == 8:
elif counter == 3:
count.eight()
three()
elif counter == 7:
elif counter == 2:
count.seven()
two()
elif counter == 6:
elif counter == 1:
count.six()
one()
elif counter == 5:
time.sleep(1)
FRXQW¿YH
os.system(‘cls’ if os.name ==
elif counter == 4:
‘nt’ else ‘clear’)
count.four()
elif counter == 3:
$QGƬQDOO\ZHFDQDGGDGLVSOD\IRUWKHPHVVDJH
count.three()
elif counter == 2:
#Display the message
count.two()
print(“v^v^v^v^v^v^v^v^v^v^v^v^v^v^v”)
elif counter == 1:
print(“< >”)
count.one()

154 &RGLQJ 3URJUDPPLQJ


Text Animations

ROCKET LAUNCH ROLLING DIE


Building on the previous Aside from the rocket animation, together
countdown example, we can with its countdown, another fun bit of text-
create an animated rocket that’ll based animation is that of a rolling dice.
ODXQFKDIWHUWKH%ODVW2ƪ
A rolling dice can be a great animation
message has been printed. The
to include in an adventure game, where
code would look something like:
the player rolls to see what their score
is compared to that of an enemy. The
def Rocket():
highest roller wins the round and the losers’ health drops as a result.
GLVWDQFH)URP7RS 
It’s an age-old combat sequence, used mainly in the Dungeon and
ZKLOH7UXH
Dragons board games and Fighting Fantasy novels, but it works well.
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
SULQW ³?Q´ GLVWDQFH)URP7RS The code you’ll need to animate a dice roll is:
print(“ /\ “)
print(“ || “) import os
print(“ || “) import time
print(“ /||\ “) from random import randint
time.sleep(0.2)
die = [“ \n O \n “] #1
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
die.append(“ O\n \nO “) #2
GLVWDQFH)URP7RS 
die.append(“O \n O \n O”) #3
LIGLVWDQFH)URP7RS
die.append(“O O\n \nO O”) #4
GLVWDQFH)URP7RS 
die.append(“O O\n O \nO O”) #5
#Launch Rocket die.append(“O O\nO O\nO O”) #6
Rocket()
def dice():
for roll in range(0,15):
Here, we’ve created a new function called Rocket, which produces
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
WKHHƪHFWRIDQ$6&,,OLNHURFNHWWDNLQJRƪDQGVFUROOLQJXSZDUGV
print(“\n”)
using the distanceFromTop variable.
number = randint(0,5)
To use this, add it to the end of the previous countdown code and, print(die[number])
DWWKHHQGRIWKH%ODVW2ƪPHVVDJHDGGWKHIROORZLQJOLQHV time.sleep(0.2)
#Main Code Begins
print(“\n\n\n\n”)
dice()
input(“Press Enter to launch rocket...”

You may need to tweak the O entries, to line up the dots on the
This will allow your message to be displayed and then, when the
virtual dice. Once it’s done, though, you’ll be able to add this
user has hit the Enter button, the rocket will launch.
function to your adventure game code and call it up whenever your
Again, the code in its entirety can be found in the Code character, or the situation, requires some element of luck, combat,
Repository at: https://SFOpublications.com/H[FOXVLYHV. or chance roll of the dice.

DISCOVER ANIMATIONS
The great thing about Python code is that it’s so accessible. These <RXoOOƬQGWKDWPDQ\SURIHVVLRQDOVZLOORIWHQWDNHWRWKH,QWHUQHW
IHZH[DPSOHVZLOOKHOS\RXDGGVRPHIXQRUVRPHWKLQJGLƪHUHQW WRƬQGFRQWHQWWKH\oUHDIWHU7UXHWKH\oUHDEOHWRFRGHLW
to your programs, but they’re just the tip of the proverbial iceberg. themselves, but even experts get stuck sometimes, so don’t worry
If there’s something you want to include in your code, and you’re about hunting code snippets down; you’re in good company.
DWDVWLFNLQJSRLQWWKHQFRQVLGHUKHDGLQJRYHUWR6WDFN2YHUƮRZ
and search for Python 3 content.
6WDFN2YHUƮRZLVDJUHDWRQOLQHKHOSDQGUHVRXUFHSRUWDOZKHUH
you can ask questions and experts will try and help you. It doesn’t
DOZD\VZRUNRXWEXWPRVWRIWKHWLPH\RXoOOƬQGZKDW\RXoUH
looking for within this great resource.
Also, if you’re after a simple animation then take to Google and
VSHQGVRPHWLPHVHDUFKLQJIRULW:KLOH\RXPD\QRWƬQGH[DFWO\
what it is you’re after, you’re bound to come across something
YHU\OLNHWKHGHVLUHGHƪHFWDOO\RXQHHGWRGRLVPRGLI\LWVOLJKWO\
to accomplish your own goals.

&RGLQJ 3URJUDPPLQJ 155


Code Projects and Ideas

Common Coding Mistakes


When you start something new you’re inevitably going to make mistakes, this is purely
down to inexperience and those mistakes are great teachers in themselves. However,
even experts make the occasional mishap. Thing is, to learn from them as best you can.

X=MISTAKE, PRINT Y
There are many pitfalls for the programmer to be aware of, far too many to be listed here. Being able
WRUHFRJQLVHDPLVWDNHDQGƬ[LWLVZKHQ\RXVWDUWWRPRYHLQWRPRUHDGYDQFHGWHUULWRU\

SMALL CHUNKS EASY VARIABLES


It would be wonderful to be able to Meaningful naming for variables is a must to eliminate
work like Neo from The Matrix movies. common coding mistakes. Having letters of the alphabet
Simply ask, your operator loads it into LVƬQHEXWZKDWKDSSHQVZKHQWKHFRGHVWDWHVWKHUHoV
your memory and you instantly know DSUREOHPZLWK[YDULDEOH,WoVQRWWRRGLƯFXOWWRQDPH
everything about the subject. Sadly variables lives, money, player1 and so on.
WKRXJKZHFDQoWGRWKDW7KHƬUVW
major pitfall is someone trying to learn
too much, too quickly. So take coding in
small pieces and take your time.

//COMMENTS
8VHFRPPHQWV,WoVDVLPSOHFRQFHSWEXWFRPPHQWLQJRQ
your code saves so many problems when you next come to
look over it. Inserting comment lines helps you quickly sift
through the sections of code that are causing problems;
PLAN AHEAD
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.

156 &RGLQJ 3URJUDPPLQJ


Common Coding Mistakes
USER ERROR
8VHULQSXWLVRIWHQDSDUDO\VLQJPLVWDNHLQFRGH)RU
example, when the user is supposed to enter a number for
their age and instead they enter it in letters. Often a user
FDQHQWHUVRPXFKLQWRDQLQSXWWKDWLWRYHUƮRZVVRPH
LQWHUQDOEXƪHUWKXVVHQGLQJWKHFRGHFUDVKLQJ:DWFKWKRVH
BACKUPS
user inputs and clearly state what’s needed from them.
Always make a backup of your work, with a secondary
backup for any changes you’ve made. Mistakes can be
UHFWLƬHGLIWKHUHoVDJRRGEDFNXSLQSODFHWRUHYHUWWRIRU
those times when something goes wrong. It’s much easier
WRVWDUWZKHUH\RXOHIWRƪUDWKHUWKDQVWDUWLQJIURPWKH
beginning again.

RE-INVENTING WHEELS
You can easily spend days trying to fathom out a section SECURE DATA
of code to achieve a given result and it’s frustrating and
often time-wasting. While it’s equally rewarding to solve If you’re writing code
the problem yourself, often the same code is out there on to deal with usernames
the Internet somewhere. Don’t try and re-invent the wheel, and passwords, or
ORRNWRVHHLIVRPHHOVHKDVGRQHLWƬUVW other 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 WKRXVDQGVRILQVWDQFHVZKHUHSURJUDPVKDYHRƪHUHG
VRPHRQHWRVXƪHULQVLOHQFH+RZHYHUDVORQJDV\RXDVN incorrect data based on poor mathematical coding, which
the query in the correct manner, obey any forum rules and FDQKDYHGLVDVWURXVHƪHFWVGHSHQGLQJRQZKDWWKHFRGHLV
be polite, then your question isn’t silly. set to do. In short, double check your code equations.

&RGLQJ 3URJUDPPLQJ 157


Code Projects and Ideas

Python Beginner’s Mistakes


Python is a relatively easy language to get started in where there’s plenty of room for
WKHEHJLQQHUWRƬQGWKHLUSURJUDPPLQJIHHW+RZHYHUDVZLWKDQ\RWKHUSURJUDPPLQJ
language, it can be easy to make common mistakes that’ll stop your code from running.

'()%(*,11(5Ǔ0,67$.(6 ǔ
+HUHDUHWHQFRPPRQ3\WKRQSURJUDPPLQJPLVWDNHVPRVWEHJLQQHUVƬQGWKHPVHOYHVPDNLQJ%HLQJDEOHWRLGHQWLI\WKHVH
mistakes will save you headaches in the future.

VERSIONS INDENTS, TABS AND SPACES


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

THE INTERNET COMMENTING


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

158 &RGLQJ 3URJUDPPLQJ


Python Beginner’s Mistakes

COUNTING LOOPS COLONS


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

CASE SENSITIVE
Python is a case sensitive programming language, so you will need
to check any variables you assign. For example, Lives=10 is a
GLƪHUHQWYDULDEOHWROLYHV FDOOLQJWKHZURQJYDULDEOHLQ\RXUFRGH
can have unexpected results.

OPERATORS
Using the wrong operator is also a common mistake to make. When
you’re performing a comparison between two values, for example,
\RXQHHGWRXVHWKHHTXDOLW\RSHUDWRU DGRXEOHHTXDOV 8VLQJ
DVLQJOHHTXDO LVDQDVVLJQPHQWRSHUDWRUWKDWSODFHVDYDOXHWRD
YDULDEOH VXFKDVOLYHV  

BRACKETS
Everyone forgets to include that extra bracket they should have
added to the end of the statement. Python relies on the routine OPERATING SYSTEMS
having an equal amount of closed brackets to open brackets, so any
:ULWLQJFRGHIRUPXOWLSOHSODWIRUPVLVGLƯFXOWHVSHFLDOO\ZKHQ\RX
errors in your code could be due to you forgetting to count your
start to utilise the external commands of the operating system. For
brackets; including square brackets.
example, if your code calls for the screen to be cleared, then for
Windows you would use cls. Whereas, for Linux you need to use
clear. You need to solve this by capturing the error and issuing it
with an alternative command.

&RGLQJ 3URJUDPPLQJ 159


Code Projects and Ideas

C++ Beginner’s Mistakes


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

92,'Ǔ&0,67$.(6ǔ
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 STD NAMESPACE


A common C++ mistake, and to be honest a common mistake with Referencing the Standard Library is common for beginners
most programming languages, is when you try and output a variable throughout their code, but if you miss the std:: element of a
WKDWGRHVQoWH[LVW'LVSOD\LQJWKHYDOXHRI[RQVFUHHQLVƬQHEXWQRW statement, your code errors out when compiling. You can combat
if you haven’t told the compiler what the value of x is to begin with. this by adding:
XVLQJQDPHVSDFHVWG
Under the #include part and simply using cout, cin and so on from
then on.

SEMICOLONS GCC OR G++


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

160 &RGLQJ 3URJUDPPLQJ


C++ Beginner’s Mistakes

&200(176Ǔ$*$,1ǔ TOO MANY BRACES


Indeed the mistake of never making any comments on code is back The braces, or curly brackets, are beginning and ending markers
once more. As we’ve previously bemoaned, the lack of readable around blocks of code. So for every { you must have a }. Often it’s
LGHQWLƬHUVWKURXJKRXWWKHFRGHPDNHVLWYHU\GLƯFXOWWRORRNEDFNDW easy to include or miss out one or the other facing brace when
how it worked, for both you and someone else. Use more comments. writing code; usually when writing in a text editor, as an IDE adds
them for you.

QUOTES
Missing quotes is a common mistake to make, for every level of user.
Remember that quotes need to encase strings and anything that’s
JRLQJWREHRXWSXWWHGWRWKHVFUHHQRULQWRDƬOHIRUH[DPSOH0RVW
compilers errors are due to missing quotes in the code.
INITIALISE VARIABLES
In C++ variables aren’t initialised to zero by default. This means if
you create a variable called x then, potentially, it is given a random
number from 0 to 18,446,744,073,709,551,616, which can be
GLƯFXOWWRLQFOXGHLQDQHTXDWLRQ:KHQFUHDWLQJDYDULDEOHJLYHLW
the value of zero to begin with: x=0.

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

&RGLQJ 3URJUDPPLQJ 161


Want to master your Coding?
Then don’t miss our NEW Programming
magazine on digital platforms NOW!

Visit us at: www.pclpublications.com


$5BC?47:B@BC>=6>:C%B<AB;# 8B-A9B,C"@C<B4>A=;C@5BC76<95>;B<;C;?:BC<B;7?=;A2A:A@1C@?C8B@B<4A=B >9+=?0:B8.B8,C B:B->=@C.<>75A9CA4>.B<1C<B7<?869B8C0A@5C
@5BC;6A@>2A:A@1C?3C@5A;C2??+C>=8CA@;C9?=@B=@C3?<C05>@B-B<C76<7?;B, 9?6<@B;1C?3C)B=?-?/CB0:B@@'C(>9+><8/CB::/CA9<?;?3@/C%>4;6=./
     *=1C>77CA4>.B;C<B7<?869B8C?=C@5BC3<?=@C>=8C2>9+C9?-B<C><BC )A=6CA=@/C&*%*/C>=8C*77:B,C*88A@A?=>:CA4>.B;C9?=@>A=B8C0A@5A=
!CC"% &#C ''!!!' ' ;?:B:1C3?<C8B;A.=C76<7?;B;C>=8C><BC=?@C<B7<B;B=@>@A-BC?3C9?=@B=@, @5A;C762:A9>@A?=C><BC<B7<?869B8C6=8B<C:A9B=9BC3<?4C%56@@B<;@?9+,
(62:A;5B8C21#C(>7B<96@C)A4A@B8C BC>8-A;BC>::C7?@B=@A>:C261B<;C@?C95B9+C:A;@A=.C7<A?<C@?C76<95>;B (<A9B;/CA=@B<=>@A?=>:C>->A:>2A:A@1/C<>@A=.;/C@A@:B;C>=8C9?=@B=@C><BC
A.A@>:C8A;@<A26@A?=C21#C(?9+B@4>.;CA=A?CCCCC 3?<C9?=3A<4>@A?=C?3C>9@6>:C9?=@B=@,C*::CB8A@?<A>:C?7A=A?=C5B<BA=CA;
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ;62B9@C@?C95>=.B,
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C!C(>7B<96@C)A4A@B8C*::C<A.5@;C<B;B<-B8,C&?C7><@C?3C@5A;C @5>@C?3C@5BC<B-AB0B<C'C>;C>=CA=8A-A86>:C'C>=8CA;C=?@C<B7<B;B=@>@A-BC?3 *::CA=3?<4>@A?=C0>;C9?<<B9@C>@C@A4BC?3C762:A9>@A?=,C%?4BC9?=@B=@
762:A9>@A?=C4>1C2BC<B7<?869B8CA=C>=1C3?<4/C;@?<B8CA=C>C<B@<AB->: @5BC762:A;5B<C?<C>=1C?3CA@;C>33A:A>@B;,C$5B<B3?<BC@5BC762:A;5B<C5?:8; 4>1C5>-BC2BB=C7<B-A?6;:1C762:A;5B8CA=C?@5B<C-?:64B;C?<C@A@:B;,
;1;@B4C?<CA=@B.<>@B8CA=@?C>=1C?@5B<C762:A9>@A?=/C8>@>2>;BC?<C =?C<B;7?=;A2A:A@1CA=C<B.><8C@?CB8A@?<A>:C?7A=A?=C>=8C9?=@B=@,   
9?44B<9A>:C7<?.<>4;C0A@5?6@C@5BCB7<B;;C0<A@@B=C7B<4A;;A?=C?3 $5A;CA;C>=CA=8B7B=8B=@C762:A9>@A?=C>=8C>;C;695C8?B;C=?@C B.A;@B<B8CA=C=.:>=8CC>:B;C&?#C!
@5BC762:A;5B<,C=8B<C=?C9A<964;@>=9B;C;5?6:8C@5A;C762:A9>@A?=C>=8 =B9B;;><A:1C<B3:B9@C@5BC-AB0;C?<C?7A=A?=;C?3C@5BC4>=63>9@6<B<;C?<
A@;C9?=@B=@;C2BC<B;?:8/C:?>=B8C?6@C?<C6;B8CA=C>=1C3?<4C21C0>1C?3 5><80><BC>=8C;?3@0><B/C>77:A9>@A?=;C?<C7<?869@;C9?=@>A=B8C0A@5A=, * $"%"& CC?<C?6<C:>@B;@C4B8A>C7>9+;C7:B>;BC9?=@>9@#C
@<>8BC0A@5?6@C@5BC762:A;5B<;C0<A@@B=C7B<4A;;A?=,C5A:BC0BC7<A8BC $5A;C762:A9>@A?=CA;C=?@CB=8?<;B8C?<C>;;?9A>@B8CA=C>=1C0>1C0A@5C <>8C<>=9A;C'CB4>A:#C2<>8 7>7B<96@:@8,9?,6+
?6<;B:-B;C?=C@5BC6>:A@1C?3C@5BCA=3?<4>@A?=C0BC7<?-A8B/C(>7B<96@ $5BC)A=6C?6=8>@A?=/C$5BC >;72B<<1C(AC?6=8>@A?=/C* C?:8A=./ B2C'C000,79:762:A9>@A?=;,9?4
)A4A@B8C<B;B<-B;C@5BC<A.5@C=?@C@?C2BC5B:8C<B;7?=;A2:BC3?<C>=1C >=?=A9>:C)@8/C(1@5?=/CB2A>=C(<?B9@/C)A=6CA=@/CA9<?;?3@/
4A;@>+B;C?<CA=>996<>9AB;C3?6=8C0A@5A=C@5BC@B@C?3C@5A;C762:A9>@A?=, )B=?-?/CB::/CB0:B@@'(>9+><8/C*77:BC>=8C%>4;6=.C?<C>=1C "&$ &*$"&*)C)"&%"& CC(>7B<96@C)A4A@B8C5>;C4>=1C.<B>@
6BC@?C@5BC=>@6<BC?3C@5BC@B95CA=86;@<1/C@5BC762:A;5B<C9>==?@C >;;?9A>@BC?<C>33A:A>@BC9?47>=1,C*::C9?71<A.5@;/C@<>8B4><+;C>=8C 762:A9>@A?=;C>=8C>::C><BC>->A:>2:BC3?<C:A9B=;A=.C0?<:80A8B,C
.6><>=@BBC@5>@C>::C>77;C>=8C;?3@0><BC0A::C0?<+C?=CB-B<1C-B<;A?=C?3 <B.A;@B<B8C@<>8B4><+;C3?<C@5BC<B;7B9@A-BC9?47>=AB;C><BC ?<C4?<BCA=3?<4>@A?=CB4>A:#C.>:B 79:762:A9>@A?=;,9?4

You might also like