The Complete Coding Manual - Issue 4 - February 2024
The Complete Coding Manual - Issue 4 - February 2024
Manual OVER
Master programming and 920
GUIDES
improve your Python, &TIPS
Linux & C++ skills
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
4 &RGLQJ 3URJUDPPLQJ
Contents
&RGLQJ 3URJUDPPLQJ 5
Welcome, Future Coder
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
“It’s up to you
creating something from a few lines of BASIC code was achievable and so
WKHƬUVWJHQHUDWLRQRIKRPHEUHGSURJUDPPHUZDVERUQ
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.
%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.
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
,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.
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.
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.
&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.
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
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++
&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.
18 &RGLQJ 3URJUDPPLQJ
Why 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.
&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++.
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++.
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.
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.
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++
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 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 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++
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 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++
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++
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++
&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.
34 &RGLQJ 3URJUDPPLQJ
Index
&RGLQJ 3URJUDPPLQJ 35
Coding with C++
+(//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++
*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.
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.
&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;
&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´
}
&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”;
}
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´
}
&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.
&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
&RGLQJ 3URJUDPPLQJ 51
Introducing Python
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.
Java is a powerful
language that’s used in
web pages, set-top boxes,
TVs and even cars.
&RGLQJ 3URJUDPPLQJ 55
Introducing Python
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(YHQF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HFRGHQHHGVWROHDUQ
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.
&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.
in PYTHON AND
LINUX SKILLS
N UMBERS
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.
£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
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.
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
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.
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.
<RXQHHGWREHFDUHIXOZ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DQGLWoVXVLQJDIRUPRI$,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
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.
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
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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RUVSDFHDQGPRQH\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.
,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.
70 &RGLQJ 3URJUDPPLQJ
Index
&RGLQJ 3URJUDPPLQJ 71
Coding with Python
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
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.
&RGLQJ 3URJUDPPLQJ 75
Coding with Python
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.
&RGLQJ 3URJUDPPLQJ 77
Coding with Python
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)
&RGLQJ 3URJUDPPLQJ 79
Coding with Python
,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)
80 &RGLQJ 3URJUDPPLQJ
Numbers and Expressions
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
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.
&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
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
%DWFKƬOHSURJUDPPLQJLVDVNLOO
WKDWV\VWHPDGPLQLVWUDWRUVVWLOOXVH
VRLWoVZRUWKVSHQGLQJDELWRIWLPH
learning how they work, and what
\RXFDQGRZLWKWKHP7KLVVHFWLRQ
LQWURGXFHVEDWFKƬOHVDQGFRYHUVXVHU
LQWHUDFWLRQVYDULDEOHVORRSVDQGHYHQ
DEDWFKƬOHTXL]JDPHWRLQMHFWDQ
HOHPHQWRIIXQ
94 &RGLQJ 3URJUDPPLQJ
Index
&RGLQJ 3URJUDPPLQJ 95
Coding with Windows 10 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HVDPHZD\
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
$1(:%$7&+
7KURXJKRXWWKLVVHFWLRQRQEDWFKƬOHVZHoUHJRLQJWREHZRUNLQJZLWK1RWHSDGWKHFRPPDQGSURPSWDQGZLWKLQDIROGHU
FDOOHGn%DWFK)LOHVo7REHJLQZLWKOHWoVVHHKRZ\RXJHWWRWKH:LQGRZVFRPPDQGSURPSW
98 &R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WFK)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.
287387:,7+9$5,$%/(6
9DULDEOHVRƪHUDPRUHLQWHUHVWLQJZD\RIRXWSXWWLQJVRPHWKLQJWRWKHVFUHHQDQGFUHDWHDKLJKHUOHYHORILQWHUDFWLRQEHWZHHQ
WKHXVHUDQGWKHEDWFKƬOH7U\WKLVH[DPSOHEHORZ
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
86,1*025(9$5,$%/(6
+HUHoVDJRRGH[DPSOHRIPL[LQJV\VWHPDQGHQYLURQPHQWDOYDULDEOHVZLWKVRPHRI\RXURZQFUHDWLRQDORQJZLWKDQXPEHURI
H[WHUQDO:LQGRZVFRPPDQGV
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.
6($5&+,1*)25),/(6
+HUHoVDQLQWHUHVWLQJOLWWOHEDWFKƬOHWKDW\RXFDQHDVLO\H[WHQGIRU\RXURZQXVH,WDVNVWKHXVHUIRUDƬOHW\SHWRVHDUFKIRU
and displays the results.
&+2,&(0(186
&UHDWLQJDPHQXRIFKRLFHVLVDFODVVLFEDWFKƬOHXVHDQGDJRRGH[DPSOHWRKHOSH[SDQG\RXUEDWFKƬOHSURJUDPPLQJVNLOOV
+HUHoVVRPHFRGHWRKHOS\RXXQGHUVWDQGKRZLWDOOZRUNV
67(3 :KHQH[HFXWHGWKHEDWFKƬOHGLVSOD\VDPHQXDQGZLWK
each choice the code changes directory to the one the
XVHUHQWHUHG7KH+20(3$7+V\VWHPYDULDEOHZLOOHQWHUWKHFXUUHQWO\
ORJJHGLQXVHUoV0XVLF3LFWXUHVDQGVRGLUHFWRULHVDQGQRWDQ\RQHHOVHoV
&2817(56
&UHDWLQJFRGHWKDWFRXQWVLQLQFUHDVLQJRUGHFUHDVLQJQXPEHUVHWVLVJUHDWIRUGHPRQVWUDWLQJORRSV:LWKWKDWLQPLQGOHWoVORRN
DWWKH,IVWDWHPHQWDOLWWOHPRUHDORQJVLGHPRUHYDULDEOHVDQGLQWURGXFHWKH(OVH7LPHRXWDQGHRI (QGRI)LOH FRPPDQGV
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.
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?))
: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.
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.
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\
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.
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.
/,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.
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
$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.
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
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.
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.
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.
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).
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.
,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.
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.
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’.
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.
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.
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.
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
*(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.
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.
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.
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.
,)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).
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.
&+2,&(6$1'/2236
/HWoVEULQJLQDQRWKHUFRPPDQG&+2,&(DORQJZLWKVRPHQHVWHG,)DQG(/6(VWDWHPHQWV6WDUWE\FUHDWLQJDQHZVFULSWFDOOHG
mychoice.sh.
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.
&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.
($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 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 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
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 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.
&?&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 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.
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.
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
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
It won’t be easy, but it’ll be great fun and will help you become a
better Python coder.
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)
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.
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
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.
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()
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.
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\
//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.
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.
'()%(*,11(5Ǔ0,67$.(6 ǔ
+HUHDUHWHQFRPPRQ3\WKRQSURJUDPPLQJPLVWDNHVPRVWEHJLQQHUVƬQGWKHPVHOYHVPDNLQJ%HLQJDEOHWRLGHQWLI\WKHVH
mistakes will save you headaches in the future.
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.
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.
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