You are on page 1of 164

PROGRAM UNUX, PYTHON & C ++

The Complete

|||{» |
Manual
Master programming and
improve your i,
9)5
guides
\& t ip s y
Linux & C++skills

www.pclpublications.com Papercut 100% INDEPENDENT


The Com plete
M anual Series
A vaitable on ■a Readlg
.A FOR APPLE WATCH & watchOS 10 ^ ^ UPDATEDFORmatOSSONOMA ^
, The Com plete The C o m plete The Com plete * The C o m plete Sr The Com plete

iPhone MacBook
User Manual
iPad
& iO S £ The essential step-by-step guide to
MacBook and macOS Sonoma User Manual &iPadOSE
User Manual
•essential step-by-
User Manual

The Com plete The C o m plete The C o m plete The C o m plete The C o m plete

W in d o w s 11
User Manual Galaxy
Samsung Google Chromebook
User Manual
W h a ts A p p
Manual
The essential step-by-step manual User Manual Master your Chromebook and
Google's Chrome OS
The essential step-by-step
to mastering Microsoft's Windows 11
Manual " Googles amailng tree apps /owwX
720
manual to mastering
your WhatsApp
1essential step-by-step manual ta using your
\ GOIDtS j

wow.pdpubtaTionscom Cj Popercut >00%INDEPENDENT n«..|*lpvlill'0(Enutm <>Popercut >00%INDEPENDENT

^ MASTERPYTHONPROGRAMMING LINUX,PYTHON&C++CODING < ,■$ LEARNPYTHON&C++CODING </> ^ PROGRAMUNUX,PYTHON&C++ <j > RASPBERRYPi5, Pi4,400&PICO gj
* The C o m plete i S' The Co m plete [ The Com plete The Co m plete * The C o m plete
V

C++ Codina R a sp b e rry


Coding Manual
Coding Manual Manual * D l Coding
The essential step-by-step
& P y th o n
Linux programming skills H i Manual
m b

The Com plete The Complete The Com plete The Complete The C o m plete
In s t a g r a m Internet [W in d o w s 1 0 1 Home Cloud
User Manual
essential step-by-step manual to mastering
Security User Manual
The essential step-by-step guide
Networking Computing
K A *■>■■A'l I ■ to mastering Microsoft's Windows 10
,— operating system Manual Manual
89Oi The essential step-by-step manual to using cloud
\ 'EES? Qjg-„
Keep yourself
secure and
your data
safe onl'ne

i essential siep-Oy-step guide to


’your home network and smart dr

3 Popercut
For a full list of titles available please visit:
w w w .pclpublications.com
The Complete

C o d in g is everyw here. From yo u r TV th ro u g h to the


International S p a c e Station, you'll find m illions of lines of
c o d e controlling a n d delivering the se rv ic e s that w e take for
granted. Behind all this c o d e are the p r o g r a m m e rs w h o
d e v e lo p our digital world, u sin g a m ultitude of different
la n g u a g e s to w e a v e the fabric of the Internet, o p e ra tin g
sy ste m s, g a m e s a n d m o d e rn entertainm ent. W h e th e r it's
in side the w o rld 's m o st pow erful su p e rc o m p u te r or
a u to m a tin g ta sk s a b o a r d the ISS, scrip ting is the key to
effective interaction be tw e e n s y s t e m s a n d people.

The C o m p le te C o d in g M a n u a l Series a im s to help yo u ge t


the m o st from yo u r c o d in g experience. Insid e this book, yo u
will find ideas, c o n c e p ts, tutorials, hints a n d projects that
will take y o u from b e in g a b e g in n e r to a n a d v a n c e d
p ro g r a m m e r w h o u n d e rsta n d s several la n g u a g e s a n d how
to form y o u r o w n code.

SJPopercut
w w w .p clp ub licatio n s.com
6 ) Coding Foundations * 3 4 ) Coding with C++
8 Being a Programmer 36 Your First C++Program
10 A Brief History of Coding 38 Compile and Execute
12 Choosing a Programming Language 40 Using Comments
14 Creating a Coding Platform 42 Variables
44 Data Types
[ 1 6 ) Introducing C++ 46 Strings
48 C++ Maths
18 Why C++?
50 User Interaction
20 C++ Facts & Figures
22 Equipment You Will Need
24 Structure of C++ Code 5 2 ) Introducing Python
26 How to Set Up C++ in Windows
54 Why Python?
28 How to Set Up C++ on a Mac
56 What Can You Do with Python?
30 How to Set Up C++ in Linux
58 Python in Numbers
32 Other C++ IDEs to Install
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

70 ) Coding with Python


72 Starting Python for the First Time
74 Your First Code
76 Saving and Executing Your Code
78 Executing Code from the Command Line
80 Numbers and Expressions
82 Using Comments
FREE CODE
m3 DOWNLOAD
Contents G

50 Complete Programs
Over 20,000 lines of code
Visit: www.pclpublications.com/exclusive
Please note: Sign up is required to download

84 Working with Variables 120 Installing Linux on a PC


86 User Input 122 Installing a Virtual Environment
88 Creating Functions 124 Installing Linux in a Virtual Environment
90 Conditions and Loops 126 Getting Ready to Code in Linux
92 Python Modules 128 Creating Bash Scripts-Part 1
130 Creating Bash Scripts - Part 2
132 Creating Bash S crip ts-P a rt3
134 Creating Bash Scripts —Part 4
136 Creating Bash Scripts-Part 5
96 What is a Batch File?
138 Command Line Quick Reference
98 Getting Started with Batch Files
100 Getting an Output
102 Playing with Variables
104 Batch File Programming
106 Loops and Repetition 142 Planning your Code
108 Creating a Batch File Game 144 Finding Resources
146 Creating a Loading Screen
148 Planning a Text Adventure
150 Text Adventure Script
112 Why Linux? 152 Retro Coding
114 The Best Linux Distributions 156 Common Coding Mistakes
116 Equipment You Will Need 158 Python Beginner's Mistakes
118 Creating a Linux Installer on Windows 160 C++Beginner's Mistakes

Coding & Programming 5


W elcom e, Fu tu re C o d er

Everything you do online, every time


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

We cover C++, Python, and Linux


Scripting within these pages. There's
a huge section oF project ideas, type-
in listings, and in-depth looks at how
code works. But First, let's begin with a
good Foundation.

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

Coding & Programming


Index

Coding & Programming


W elcom e, Fu tu re C o d er

Being a Programmer
Programmer, developer, coder, they're all titles For the sam e occupation, som eone w ho
creates code. W hat they're creating the code For can be anything From a video gam e
to a critical element on board the International Space Station. H ow do you become a
program m er though?

Coding & Programming


Being a Programmer

M ORE THAN CODE


For those of you old enough to remember the '80s, the golden era of home
computing, the world of computing was a very different scene to how it is
today. 8-bit computers that you could purchase as a whole, as opposed to
being in kit form and you having to solder the parts together, were the stuff
of dreams; and getting your hands on one was sheer bliss contained within
a large plastic box. Flowever, it wasn't so much the new technology that
computers then offered, moreover it was the fact that For the first time
ever, you could control what was being viewed on the 'television'.

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


Times have changed since programming in the '80s, time, many users decided they wanted to create their own content, their
but the core values still remain. own games; or simply something that could help them with their homework
or home finances. The simplicity of the 8-bit home computer meant that
creating something from a few lines of BASIC code was achievable and so

It's up to you the first generation of home-bred programmer was born.

From that point on, programming expanded exponentially. It wasn't long

how Far to take before the bedroom coder was a thing of the past and huge teams of
designers, coders, artists and musicians were involved in making a single
game. This of course led to the programmer becoming more than simply

your coding 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.
Flowever, the fundamentals of programming remain the same; but what
exactly does it take to be a programmer?
# in c lu d e < s t d io . h >
# i n c lu d e < d o s . h > The single most common trait of any programmer, regardless of what
# in c lu d e < s t d lib . h >
# i n c lu d e < c o n i o . h>
v o id g e tu p ()
they're doing, is the ability to see a logical pattern. By this we mean
{ someone who can logically follow something from start to finish and
t e x t c o l o r ( B L A C K );
te x tb a c k g ro u n d (1 5 ); envisage the intended outcome. While you may not feelyou’re such a
c lr s c r ();
w in d o w (1 0 , 2 , 7 0 j 3 ) ; person, it is possible to train your brain into this way of thinking. Yes, it
c p r in t f ("P re s s X to E x it , P r e s s S p a c e t o D u m p ");
w in d o w (6 2 ,2 ,8 0 j3 ); takes time but once you start to think in this particular way you will be able
c p r i n t f ("S C O R E : " ) ;
w in d o w (1 , 2 5 , 8 0 , 2 5 ) j to construct and follow code.
f o r ( i n t x = 0 ;x < 7 9 ;x + + )
c p r in t f ( " n " ) ;
t e x t c o l o r ( 0);
} Second to logic is an understanding of mathematics. You don't have to be
i n t t,sp e e d = 4 0 ; at a genius level but you do need to understand the rudiments of maths.
v o i d d s ( i n t jum p=0)
Maths is all about being able to solve a problem and code mostly falls under
s t a t ic in t a = l;
the umbrella of mathematics.
i f (ju m p = = 9 )
t=9;
e l s e if(ju m p = = 2 )
Being able to see the big picture is certainly beneficial for the modern
e ls e t+ + ;
window(2i 1 5 - t J18J25 ); programmer. Undoubtedly, as a programmer, you will be part of a team
c p r in t f( ”
c p r in t f( " M AO n /l/l/lM ") j of other programmers, and more than likely part of an even bigger team
c p r in t f( " nnn n n n n n
c p r in t f( ” juin/i/irinn of designers, all of whom are creating a final product. While you may only
c p r i n t f C /i Mjum/innn
c p r i n t f ( “ J1/1M MJUUU1J1J1MMM be expected to create a small element of that Final product, being able to
c p r i n t f ( " n/iJiJi/iJiJwiJiJiJi n
c p r in t f ( “ rw iuuuum n understand what everyone else is doing will help you create something
i f (jump==l || jump==2){
c p r in t f(" /l/in rui ") j that’s ultimately better than simply being locked in your own coding cubicle.
c p r in t f( ” JIM JIM ”)j
} e ls e i f ( a — 1)
s
\
c p r in t f(" n/utn nnn Finally, there's also a level of creativity needed to be a good programmer.
c p r in t f( ” JIM
a=2; Again though, you don't need to be a creative genius, just have the
>
e ls e i f ( a = = 2 )
s
imagination to be able to see the end product and how the user will interact
\
c p r in t f( ” ruiM nji with it.
c p r in t f(" •);
a = l;
}
c p r in t f ( " "); There is of course a lot more involved in being a programmer, including
d e la y (s p e e d );
;5 > learning the actual code itself. Flowever, with time, patience and the
57 v o id o b j ( )
58 C 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!

Coding & Programming


Welcome, Future Coder
A

A Brief History of Coding


It's easy to think that programming a machine to automate a process or calculate a value
is a m odern concept that's only really happened in the last Fifty years or so. However,
that assum ption is quite wrong, coding has actually been around For quite som e time.

01000011 01101111 0110010001100101


Essentially all Forms oF coding are made up oF ones and zeros, on or oFF states. This works For a modern computer
and even the oldest known computational device.

It's diFFicult to pinpoint an exact


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
the First 'coded' arteFact. It’s
programmable loom, which used cards with
dated to about 87 BC and is an
punched holes to create the textile design.
ancient Creek analogue computer
However, it is thought that he based his
and orrery used to predict
design on a previous automated weaving
astronomical positions.
process From 1725, by Basile Bouchon.

Ada Lovelace translated


the memoirs oF the Italian
mathematician, Francis
Maneclang, regarding
Charles Babbage's
Analytical Engine. She
made copious notes
within her writing,
detailing a method oF
The Banu Musa brothers, three Persian calculating Bernoulli
scholars who worked in the House oF Numbers using the
Wisdom in Baghdad, published the engine. This is recognised
Book oF Ingenious Devices in around as the First computer
850 AD. Among the inventions listed program. Not bad,
was a mechanical musical instrument, considering there were
a hydro-powered organ that played no computers available at
interchangeable cylinders automatically. the time.

10 Coding & Programming


A Brief History of Coding

During the Second World War, From the 1970s, the development of the likes of C, SQL, C with
there significant advances Classes (C++), MATLAB, Common Lisp and more came to the
were made in programmable fore. The '80s was undoubtedly the golden age of the home
machines. Most notably, the computer, a time when silicon processors were cheap enough
cryptographic machines used for ordinary folk to buy. This led to a boom in home/bedroom
to decipher military codes coders with the rise of 8-bit machines.
used by the Nazis. The Enigma
was invented by the German
engineer Arth ur Scherbius
but was made famous by Alan
Turing at Bletchley Park's
codebreaking centre.

1990s-Pre se n t Day

ora ROM*-50000 BEGIN MONITOR


Computer programming was
mainly utilised by universities,
the military and big
corporations during the '60s |p #
Erlang q # D $ ML
Visual Basic I
^ Tra n sa ct-S Q L o
" ~ * '
Clarion
»00010011
*00010001 and the '70s. A notable step JavaScript Python o.p~ 2 * b fpusQL
toward a more user-friendly, Sch em e ; 0 " * " V O ' f i a P /
q

or home user language, was Haskell qp| ,9>SgtoVSi


3 3i pup 1 l ? l i t< x
the development of BASIC 1"S Pascal0 Dclphi 2
INPUT: non*
OUTPUT; chu
(Beginners All-purpose
DESTROYS: «c
CALLS: none
DESCRIPTION:
Symbolic Instruction Code) in
the mid-sixties.

COIB 7E CO 79

FUNCTION: INHEX - INPUT HEX DIGIT


INPUT: none
The Internet age brought a wealth
OUTPUT: Diqit in sec A
CALLS: INCH
DESTROYS: «ee A
of new programming languages and
40 FOR I = 1 TO N
50 S$ = 3« + allowed people access to the tools and
55 NEXT I
60 PRINT S$ knowledge needed to learn coding in a
65 REM
70 INPUT "Do you want more stars? A$ better way. Not only could a user learn
80 I F LEN(Aif) = 0 THEN GOTO 70
90 A$ = LEFTS(A$ , 1) how to code but they could freely share
100 IF (AS = "Y") OR (AS = "Y") THEN GOTO 30
• SOF 110 PRINT "Goodbye their code and source other code to
120 FOR I = 1 TO 200
130
140
PRINT US; "
NEXT I
improve their own.
150 PRINT

The first true computer code was


Assembly Language (ASM) or
Regional Assembly Language. Admiral Grace Flopper was part of
ASM was specific to the 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
languages such as IPL, FORTRAN Language), a computer language that's
and ALGOL 58 were developed. still in use today.

Coding & Programming 11


W elcom e, Fu tu re C o d er
w

Choosing a
Programming
Language
It would be impossible to properly
explain every program m ing 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 alm ost daily; and with the
onset oF quantum computing, even more
complex m ethods are being born. Here
is a list oF the more com m on languages
along with their key Features.

12 Coding & Programming


Choosing a Programming Language

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

J AVASCRIPT JavaScript (oFten shortened to JS) is a lightweight,


W F interpreted, object-oriented language with first class
Functions. JavaScript runs on the clientside oF the web, that can be used to design
or program how the web pages behave on the occurrence oF an event. JavaScript is
an easy to learn and also powerful scripting language, widely used For controlling
web page behaviour.

JAVA ~*ava *s foundation For virtually every type of networked


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

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


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

igi python python Python is a widely used high level programming language used
for general purpose programming, created by Guido van
Rossum and first released in 1991. An interpreted language, Python has a design
philosophy that emphasises code readability and a syntax that allows programmers
to express concepts in Fewer lines of code. This can make it easier For new
programmers to learn.

£ ^ .|, C++ (pronounced cee plus plus) is a general purpose programming


language. It has imperative, object-oriented and generic programming

C Features. It was designed with a bias toward system programming and embedded,
resource-constrained and large systems, with performance, efficiency and Flexibility
oF use as its design highlights.

RUBY Ruby 'sa language of careful balance. Its creator, Yukihiro "Matz"
W Matsumoto, blended parts of his Favourite languages (Perl, Smalltalk,
a Eiffel, Ada and Lisp) to Form anew language. From its release in 1995, Ruby has
drawn devoted coders worldwide. Ruby is seen as a Flexible language; essential
parts of Ruby can be removed or redefined, at will. Existing parts can be added to.

p £ p |_ Perl is a general purpose programming language, used for a wide


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

SWIFT Sw ift is a powerful and intuitive programming language for macOS,


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

Coding & Programming 13


W elcom e, Fu tu re C o d er

Creating a Coding
Platform
The term 'Coding Platform' can signify: a type of hardware on which you can code,
a particular operating system, or even a custom environm ent that's pre-built and
designed for easy gam e 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 program m ing
language you intend to code in and w hat your end goals are.

f rom d}ango.contrlb.auXE.decorator* Coding can be one of those experiences that sounds fantastic,
from <i}ango.cotVtrib.admin.vims.decorator* >
but is often confusing to tackle. A fter all, there's a plethora
from django.core.exceptions Ob^ectboerHi
of languages to choose from, countless apps that will enable
from diaogo.http import KttpResponseforbiddea
from d}ango.cootrip.autP import authenticate, you to code in a specific, or range, of languages and an equally
from d}ango.contrib.auth.mode\* tmport User huge amount of third-party software to consider. In addition, by
accessing the Internet, you will discover that there are countless
from diango.core.paqinator import Paginator coding tutorials available for the language in which you've decided
from diango.core.urVresoVvers import reverse you want to program, alongside even more examples of code. It's
from diango.conf import settings all a little too much at first.
from diango.db.models import Q, Sum. Win, Couo

The trick is to slow down and, to begin with, not look too deeply
from diango.contrib import messages
from datetime import date, timedetta into coding. Like all good projects, you need a solid foundation
on which to build your skillset and to have all the necessary tools
import re
available to enable you to complete the basic steps. This is where
from .modets import * creating a coding platform comes in, as it will be your learning
foundation while you begin to take your first tentative steps into
the wider world of coding.
"There are some errors, p\ease
one MCC.Cli.GE

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
Commodore 64 then you may have some difficulty following a 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 Over time, you may find yourself progressing from the
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
and you will find that most code resources are written with experienced, you will start to use different tools to get the
one, or all, of these in mind. job done.

Coding & Programming


Creating a Coding Platform

OPERATING SYSTEMS VIRTUAL MACHINES

Windows 10 is the most widely used operating system in the A virtual machine is a pieceoFsoFtware that allows you to install a
world, so it's natural that the vast majority oF coding tools are Fully working operating system within the conFines oF the soFtware
written For MicrosoFt’s leading operating system. However, itselF. The installed OSwillallocateuser-deFined resources From the
don't discount macOS and especially Linux, host computer, providing memory, hard drive space etc., as well as
sharing the host computer's Internet connection.
macOS users enjoy an equal number oF coding tools to their
Windows counterparts. In Fact, you will probably Find that a The advantage oF a virtual machine is that you can work with
lot oFproFessional coders use a Mac over a PC, simply because Linux, For example, without it aFFecting your currently installed
oF the Fact that the Mac operating system is built on top oF host OS. This means that you can have Windows 10 running and
Unix (the command-line OS that powers much oF the world's launch your virtual machine client, boot into Linux and use all
Filesystems and servers). This Unix layer lets you test programs the Functionality oF Linux, while still being able to use Windows.
in almostany language without using a specialised IDE.

This, oF course, makes it a Fantastic coding platForm, asyou can


However, Linux is, by Far and away, one oF the most popular have diFFerent installations oF operating systems running From
and important coding operating systems available. Not only the host computer while using diFFerent coding languages.
does it have a Unix-like backbone, it's also Free to download, You can test your code without Fear oF breaking your host OS
install and use and comes with most oF the tools necessary to and it's easy to return to a previous conFiguration without the
start learning how to code. Linux powers most oF the servers need to reinstall everything again.
that make up the Internet. It's used on nearly all oF the top
supercomputers, as well as speciFically in organisations such Virtualisation is the key to most big companies now. You
as NASA, CERN and the military, it also Forms the base oF will probably Find, rather than having a single server with an
Android-powered devices, smart TVsand in-car systems. Linux, installation oF Windows Server, For example, the IT team have
as a coding platForm, is an excellent idea and it can be installed instead opted Fora virtualised environment whereby each
inside a virtual machine without everaFFecting the installation Windows Server instance is a virtual machine running From
oF Windows or macOS. several powerful machines. This cuts down on the number
oF physical machines, allows the team to better manage
resources and enables them to deploy an entire server
dedicated to a particular task in a Fraction oF the time.

THE RASPBERRY PI

iFyou 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, asyou 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
diFFerent hardware, in
the Form oF robotics and
electronics projects, as well
as oFFering a complete desktop
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.

Coding & Programming 5


Introducing C++

C++ is an amazing programming


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

C++ is an efficient and powerful


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

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

Coding & Programming


Index

Coding & Programming


Introducing C++

Why C++?
C++ is one of the m ost popular program m ing languages available today. Originally
called C with Classes, the language w as renamed to C++ in 1983. It's an extension of
the original C language, and is a general purpose object-oriented (OOP) environment.

C E V E R Y T H IN G
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 majorapplications, such as
computing, C++, or rather C with Classes, was the brainchild of Photoshop, InDesign and so on, are developed in C++. You will find
Danish computerscientist 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 well as Windows 10, Microsoft Office, and the backbone to Google's
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 easieraddition to the core C language, C++ is
regular people who didn't have access to the mainframes and large also extremely efficient and performs well across the board. This
computing data centres could use it. higher level of performance overother languages, such as Python,
BASICand such, makes itan 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.
Why C++?

Installing - Visual Studio Community 2017 (15.026223.1) X

Workloads Individual components Language packs

W indows (3)
Summary
U niversal W indows Platform developm ent .N ET desktop developm ent
v D esktop developm ent with C...
■ m Create applications fo r the Universal Windows Platform with C *. Build WPF, Windows Forms and console applications using the
VB, JavaScript o r optionally C++. .N ET Framework. Included

V Visual C++ core desktop features

Desktop development w ith C++ □ Optional

'a Build classic Windows-based applications using the power of the H VC++ 2 0 1 7 v141 toolset (x86,x64)
Visual C++ toolset, A TI, and optional features like MFC and... n C++ profiling tools
Q Windows 10 SDK (10.0.14393.0)
Q Visual C++ tools for CMake
Q Visual C + + ATL support
Web & Cloud (4)
□ Windows 8.1 SDK and UCRT SDK
/ 'T \ \ ASP.NET and web developm ent Azure developm ent f l Windows X P support for C++
V j Bui l d web applications using ASP.NET, ASP.NET Core, HTML, Azure SDK, tools, and projects for developing cloud apps and l~l MFC and ATL support (x&6 and x64)
JavaScript, and CSS. creating resources.
□ C++/CU support
M Clang/C2 (experimental)
l~| Standard Library Modules
Node.js developm ent Data storage and processing
Q By continuing, you agree to die license for the
LP ^ J Build scalable network applications using Node.js, an asynchronous r —j Connect, develop and test data solutions using SQL Server, Azure
Visual Studio edition you selected. We also offer the
event-driven JavaScript runtime. Data Lake, Hadoop or Azure ML.
ability to download other software with Visual
Studio. This software is licensed separately, as set
out in the 3rd Party Notices or in its accompanying
license. By continuing, you also agree to those
M obile & Gam ing (5) licenses.

Microsoft’s Visual Studio is a great, free


environment in which to learn C++.

C++ puts the developer in a much wider world oF coding. By improvements to the engine, or when creating a new game, if
mastering C++, you will find yourself being able to develop code for the developers want to add something that the engine can't do,
the likes of Microsoft, Apple and so on. Generally, C++ developers they will use C++ to create the new content or link between two
enjoy a higher salary than programmers of some other languages, different engines. The end result, of course, is a game that contains
and, due to its versatility, the C++ programmer can move between the latest graphical technology, while being seamlessly bound
jobs and companies without the need to re-learn anything specific. together with some pretty clever C++ coding.

You will discover, as you become a more advanced coder, that many Getting to use C++ is quite easy, all you need is the right set of tools
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, andjustabout everything else you'd see in the game. The
engine itself has been modified to make the most of the current So, to answer the question of Why C++, the answer is because it’s fast,
graphics card hardware, and computer or console processing efficient, and developed by mostoF the applications you regularly
power. These engines are mostly written in C++, and when making use. It's cutting edge, and a Fantastic language to have mastered.

Coding & Programming 9


Introducing C++

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

one of the s
predominant
programming
languages for the
development of all
kinds of technical
NASA, CERN, and commercial
MICROSOFT,
software.
ORACLE, PAYPAL,
LINKEDIN, AMAZON AND
THE MILITARY USE C++.

C++ IS U SED FR EQ U EN T LY
IN ANIM ATION P R O C ESS ES .
3D ANIMATION,
MODELLING,
ANDSIMULATIONS
A LL UTILISE C++.

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

SUPERCOMPUTING USES C++ CODE • *-u


More than 70% of all
TO CALCULATE VAST AMOUNTS OF trading is known as
High Frequency Trading
DATA, INCLUDING THE NASA-BASED (HFT), and the software
SUPERCOMPUTING FARM THAT RUNS responsible is written in
C++ to make use of its
SIMULATIONS OF THE UNIVERSE.
high speed.

2 Coding & Programming


Sources: ITJobsWatch,
Google, Quora, Stack C++ Facts & Figures
Exchange, eduCBA,
StackOverflow,
stackShare,
AppDynamics operating system i
uses C++ as its
backbone.

Gaming is one oF the


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

THE
C++ is
used in computer
networking as the
main code behind the
Programmable Logic Most of Adobe’s
PERCENTILE SALARY stable of products
Controller, connecting FOR A UK-BASED C++ are developed
servers, processors, other DEVELOPER IS using C++. ^

£120,000

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++,
Microsoft Office, use C++ the enhanced imagery is used For hundreds
as the backbone programming produced by these oF games, including
language of choice.
systems. Fortnite.

PROCESSING ^
TECHNOLOGIES
U s e 'c + M s
WEL^AS
ADVANCED
m is s il e

SV5TEMS
FLIGHT CONTROL SYSTEMS IN
MODERN AIRCRAFT, INCLUDING
MILITARY AIRCRAFT, USE C++.

Coding & Programming


Introducing C++

EquipmentYou
Will Need
You don't need to invest a huge am ount of m oney in order to learn C++, and you
don't need an entire computing lab at your disposal either. Providing you have a fairly
m odern computer, everything else is freely available.

C + + SETU PS
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.

_J COM PUTER
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.

_ J A N ID E
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.

_ J C O M P IL E R
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 partoF the
package. More on this later.

□ T E X T E D IT O R
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.

_ J IN T E R N E T A C C E S S
While it’s entirely possible to learn how to code on a computer that's not attached
to the Internet, it's extraordinarily difficult. You will need to install the relevant
soFtware, keep it up to date, install any extras or extensions, and look For help when
coding. All of which require access to the Internet.

_ J T IM E A N D P A T IE N C E
You’re going to need to set aside significant time to spend on learning how to code
in C++. Sadly, unless you're a genius, it's not going to happen overnight, or even in a
week. A good C++ coder has spent many years honing their craFt, so be patient, start
small and keep learning.

Coding & Programming


Equipment You Will Need

OS SPECIFIC NEEDS
C++ will work in any operating system; however, getting all the necessary pieces together can be conFusing to a newcomer. Here's
some OS speciFics For C++.

LINUX WINDOWS

Linux users are lucky in that they already have a compiler and As we've mentioned previously, 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
enter their code in Notepad++ then compile it with MinGW -
which Code::Blocks uses.

<4 p -v*
S H l ► C«*~. • .4 . -6

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.

Coding & Programming


introducing C++

Structure of C++ Code


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

# IN C L U D E < C + + IS A C E !>
As you learn the basics of programming, you will begin to understand the structure oFa program. The commands may be
diFFerent, butyou will start to see how the code works.

C++ # IN C L U D E
The structure of a C++ program
File Edit View Search Tools Documents Help
Danish student Bjarne can look complex, but once you
Stroustrup invented C++ in get Familiar with ityou'll begin to
D © Pi IT*- W y. ip e
1979, as a part of his Ph.D. see how it flows. Every C++ code
thesis. Initially C++ was called begins with a directive, #include
C with Classes, which added <>. The directive instructs the |C**| *newcode,cpp X
features to the already popular pre-processor to include a
C programming language section of the standard C++ #include <iostream>
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++.

IN T M A IN () *newcode.cpp (~/D
V
int main() initiates the File Edit View Search Tools Documents Help
declaration of a function, which
is a group of code statements
under the name 'main'. All
£1 © < lP 6
5 Q
,
C++ code begins at the main
function, regardless of where 10 * * 1 +newcode.cpp X
it lies within the main body oF
the code. #include <iostream>
int main()

BRACES *newcode.cpp (-/Documents)


The open brace is File Edit View Search Tools Documents Help
something that you may
not have come across
+1 C D» ^ ^ Y. IP e o, &
before, especially iF
you're used to other
coding languages.The (clj *newcode.cpp x
open brace indicates the
beginning of the main ^include <iostream>
function, and contains
all the code belonging to i n t m ainO
that function. <

2 Coding & Programming


Structure of C++ Code

COMM ENTS <<


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 atyour 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.
*r>ewcode.cpp (-/Documents)
*newcode.cpp (-/Documents) File Edit View Search Tools Documents Help
File Edit View Search Tools Documents Help

£) © K l S B 0 .5 .
[cfj *newcode.cpp X
Ic"i *newcode.cpp X
# in c lu d e <iostream>
#include <iostream>
int mainO
i n t m a in O {
{ / / My f i r s t C++ program!
// My f i r s t C++ program! s t d ::c o u t « (" H e llo W orld!\n")

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
in C++, which covers a number of different statements and the screen when the code is executed. You can enter whateveryou
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.
▼ *neweode.cpp (-/Documents)
File Edit View Search Tools Documents Help

+n © □j jr. w< y ip e ^ &

Ic’i *newcode.cpp X

# in c lu d e <iostream>
// My first C++ program!
using namespace s t d ; std::cout « ("Hello World!\n")|
int mainO
{
/ / My f i r s t C++ program!

COUT ; AND}
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
Namespace - hence why it's there, as you're asking C++ to use it from (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.

T *newcode.cpp (-/Documents) Rle Edit vtew search Tods Documents Help

File Edit View Search Tools Documents Help P © Di X G B Q.9.

c" rvewcode.epp X
* i i i elude <iosi least*
£1 © Di *■* «* (□ C <1 9: 'in t mainO
(
// My f i r s t C li program!
std::cout « ( "Hello world’Vn"):
ItTI *newcode,cpp X
# in e lu d e <iostream >

i n t m a in O
{
/ / My f i r s t C++ program!
s t d : rcout |

Coding & Programming


Introducing C++

How to Set Up
C++ in Windows
W indow s users have a wealth of choice when it com es to program m ing in C++. There
are loads oP IDEs and compilers available, including Visual Studio Prom MicrosoPt.
However, in our opinion, the best C++ IDE to begin with is Code::Blocks.

C O D E ::B L O C K S
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.

Start by visiting the Code::Biocks download site, at When you've located the File, click on the
www.codeblocks.org/downloads. From there, click SourceForge.net link at the end oF the line and a
on the 'Download the binary releases' link to be taken to the latest download notiFication window appears; click on Save File to start
downloadable version For Windows. the download and save the executable to your PC. Locate the
downloaded Code::Blocks installer and double-click to start. Follow
the on-screen instructions to begin the installation.

^ C o d e ::B lo c k s Installa tio n

Welcome to CodeBlocks Setup

Setup will guide you through the installation o f CodeBlocks,

I t is recommended that you dose all other applications


before starting Setup. This will make it possible to update
relevant system files without having to reboot your
computer.

Click N ext to continue.

There you can see, there are several Windows 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 oFthe components but we
the time oF writing this is: codeblocks-17.12mingw-setup.exe. The recommend that you opt For the Full option, as deFault.
diFFerence is that the mingw-setup version includes a C++ compiler
I C o d e ::B lo clcs Installatio n
and debugger From TDM-GCC (a compiler suite).
C h o o s e C o m p o n e n ts
Windows XP / Vista / 7 18.x /10: Choose which features o f CodeBlocks you w ant to install.
1

File
codeblocks-17 12-setup.exe 30 Dec! Check the components you w ant to install and uncheck the components you don't w ant to
codeblocks-17 12-setup-nonadmin exe 30 Dec: install. Click N ext to continue.

codeblocks-17.12-nosetup.zip 30 Dec:
Select the type o f install: Full: All plugins, all tools, ju st everything V
codeblocks-17 12mingw-setupexe 30 Dec;
O r, select the optional ] - 0 D e fa u lt in s t a ll
codeblocks-17 12mingw-nosetup zip 30 Dec:
components you wish to
- ] - 0 Contrib Plugins
codeblocks-17 12mingw_fbrtran-setup exe 30 Dec: install:
0 C ::B C B P 2 M a k e
NOTE: The codeblocks-17 12-setup.exe file includes Code Blocks with all plugins. The codeblocks-17 12-setup-nonadmin.ex file is provided for conven •0 C ::B C C T e s t
NOTE The codeblocks-17.12mingw-setup.exe file includes additionally the GCC/G++ compiler and GDB debugger from TDM-GCC (version 5.1.0. 32 bit. 0 C ::B Share Config
(TDM-GCC)
0 C ::B Launcher
V
NOTE: The codeblocks-17.12(mingw)-fl’osetup zip files are provided for convenience to users that are allergic against installer1 However, it will not allow I m .- „ ... ^ .. „ ..
Description
If unsure, please use codeblocks-17 12mingw-setup.exe! Space required: 2 53.4 MB Position your mouse over a component to see its

Coding & Programming


How to Set Up C++ in Windows

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

C reate shortcut: C:VJsersVdavid\AppData fo a m in g V^icrosoft\Windows\S tart Menu p rogram s \

E xtra ct: gdbinit, •_


w CodeiBlocks Installation
Output folder: C
E xtra ct: fsf-fun)
E xtra ct: g fd l.7 .,
E xtra ct: g p l.7 ...
Output folder: C
o Do you want to run Code::Blocks now?

Output folder: C
Created uninsta
Output folder: C ________. _ _ __ enuV^ro...
C reate shortcut: C:VJsersyiavid\AppData fo a m in g ydicrosoft\WindowsVStart M e n u ^ ...

Nullsoft Install System V 3 .Q 2 .1 -

The first time Code::Blocks loads it runs an In the new window, enter the following:
autodetect for any C++ compilers you may already
have installed on your system. If you don't have any, click on the tinclude <iostream>
first detected option: GNU GCC Compilerand click the Default
Int main ()
button to set it as the system's C++ compiler. Click OK when you're
ready to continue.
{
//My first C++ program
Compilers a u to -d etectio n □ X
Std::cout « "Hello World!\n";
Note: After auto-detection, a t least one compiler's master path is still empty and therefore invalid.
!
Inspect the list below and change the compiler's master path later in the compiler options.
Select you favourite default compiler here: Notice how Code::Blocks auto-inserts the braces and speech quotes.
Compiler Status A Set as default
N 1cit■ ^.fcdb 17.12
GNU GCC Compiler Detected Pile Edit Vwv. Scorch Propel Md Debuj fortran loots Toot- PIujvb OrvyBecb Sdtajs Help
i a 0 * * 4 «*;# ► ii D i^ a r
f * f » » M 1* ‘
Starthire ‘ UnWcdJ
• Projects biflidcJs rtes 1 1 Unelude viescjew'
Q Workspace
; c -o r ,
5 {
6 //My fin e Co-o peojram

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

Release 1712rev 1125612017-12-28104-441>occ5 10Wndowsfriicodc -32M

feuan etaeysdunaeassMUtora hamtheen-.v<


xw*m utves later.

O MO,leaveeverylhmgasit«
O No. leeveevtrytfmg*Jit8 (butaskme»gannexttime)
O fes, esssMteCode wthC/C+*He types
(5)fes. associateCodeiiBocksKithevery snowted tyce(ndudngGroiectAlesfromotter IDEs}

Coding & Programming


Introducing C++

How to Set Up C++


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

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

Start by opening the AppStore on your Mac, Apple When you're ready, click on the Get or cloud icon
Menu > App Store. In the Search box enter Xcode, bu tton which wi ll insta ll the Xcod e a pp. En ter your
and press Return. There will be many suggestions filling the App Apple ID, and Xcode will begin to download and install. It may take
Store window, but it's First option, Xcode, that you need to dick on. some time depending on the speed oFyour Internet connection, as
Xcode is in excess oF 11GB.

Take a moment to browse through the app's 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 enteryour 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.

Coding & Programming


How to Set Up C++ on a Mac

With everything now installed, including the The next step asks where to create a Git Repository
additional components, Xcode will launch displaying For all your Future code. Choose a location on your
the version number along with three choices and any recent projects Mac, o ra network location, and click the Create button. When
that you've worked on-although fora Fresh install, this will be blank. you've done all that, you can start to code. The leFt-hand pane
details the Files used in the C++ program you're coding. Click on the
main.cpp File in the list.

Start by clicking on Create New Xcode Project, this 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 The differences here are that the int main () Function now contains
Command LineTool option. Click Next to continue. multiple Functions and the layout is slightly different. This is just
Xcode utilising the content that’s available to your Mac.

Choose a template for your new project:

Mulliplatfcim iOS ra«OS vatehOS tvOS Other ©


Application

© ffi □
App Document App Same m c ... ui „
H ‘e I I I %

Framework * Library

( 0 ] (S) Jit/ (j*f) ( X )

DriverKit Framework Library Metal Library XPC Service


Framework

Bundle

Cancel

Fill in all the fields, but ensure that the Language 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
it from the drop-down list. When you've Filled in the Fields, and 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.

Coding & Programming


Introducing C++

How to Set Up C++


in Linux
Linux is a great C++ coding environment. M o st Linux distros already have the essential
com ponents preinstalled, such as a compiler and the text editors are excellent For
entering code into, including colour coding; there's also tons of extra software
available to help you out.

L IN U X + +
There are many different versions of Linux available, for this example we're using one of the more popular distributions: Linux
Mint. However, these steps will work in any Debian-based Linux.

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

ir---------
File Edit View Search Terminal
david@mint-mate - S sudo apt-get update
Help

[sudo] password for david: ||

Most Linux distros come preinstalled with all the 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
iinclude <iostream>
build-essential and press Return. If you have the right
components, nothing is installed but if you're missing some then int m a i n ()
they are installed by the command.
{

david@ m int-m ate - //My first C++ program


File Edit View Search Terminal Help
d a v i d @ m i n t - m a t e $ sudo apt-get install build-essential sLd::oouL « "Hello World!\n";
(Reading package lists... Done
Building dependency tree
(Reading state information... Done I__| *Unsaved Document 1 x
build-essential is already the newest version (12.Iubuntu2).
tbuild-essential set to manually installed. # in c lu d e <iostream >
|o to upgrade, 0 to newly install, G to remove and 6 not to upgrade.
idavid@mint-mate S | 1i n t m ain()
{

//My f i r s t C++ Program


s t d ::c o u t « " H e llo W o rld !\n ” ;

3i Coding & Programming


How to Set Up C++ in Linux

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

david@mii
File Edit View Search Terminal Help
david@mint-mate -/Documents g++ helloworld.cpp
david@mint-mate -/Documents

Name, helkworldipd

S3 desktop

pfrfnrte py
GUlTest.py

a* Pictures
L a Videos

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

w davidt?
File Edit View Search Terminal Help
david@mint-mate '/Documents $ g++ helloworld.cpp
david@mint-mate -/Documents S Is
a.out helloworld.cpp
david@mint-mate -/Documents $

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

david@mint-mate ~7Doci
File Edit View Search Terminal Help

File Edit View Search Terminal Help david@ m int-m ate -/Documents S ./ a .o u t
H e llo W orld!
david<Bmint-mate ~ s cd Documents david@ m int-m ate -/Documents S g-w- h e llo w o rld .c p p -o h e llo w o rld
david@ m int-m ate -/Documents S ./ h e llo w o r ld
david@mint-mate ~/Documents s § H e llo W orld!
david@ m int-m ate -/Documents S

Coding & Programming


Introducing C++

Other C++ IDEs to Install


IF you w ant to try a different approach to working with your C++ code, then there are
plenty of options available to you. W indow s is the m ost prolific platform for C++ IDEs
but there are plenty for M ac and Linux users too.

DEVELOPING C++
Here are ten great C++ IDEs that are worth looking into. You can install one or all oF them iFyou like, but Find the one that
works best For you.

Eclipse is a hugely popular C++ IDE thatoFfers CodeLite isa Free and open source IDE that's
the programmer a wealth oF Features. It has a regularly updated and available For Windows,
great, clean interface, is easy to use and available For Windows, Linux and macOS. It’s lightweight, uncomplicated and extremely
Linux and Mac. Head over to www.eclipse.org/downloads/to powerful. You can Find out more information as well as how to
download the latest version. IF you're stuck, click the Need Help link download and install it at www.codelite.org/.
For more inFormation.

£ C/C++ - Hello World C++ Project/src/Hdlo World C++ Projectcpp - Eclipse


File Edit Source Refactor Navigate Search Project Run Window Help

rt- A ll * - e - i f - e - ■%-»- 0 - 0 - 4 - am
: § | . {, I - ■ •

The GNAT Programming Studio (GPS) is a powerful Another popular choice is NetBeans. This
and intuitive IDE that supports testing, debugging is another excellent IDE that's packed with
and code analysis. The Community Edition is free, whereas the Features and a pleasure to use. NetBeans IDE includes project based
Pro version costs; however, the Community Edition is available For templates For C++ that give you the ability to build applications with
Windows, Mac, Linux and even the Raspberry Pi. You can Find it at dynamic and static libraries. Find out more a twww.netbeans.org/
www.adacore.com/download. Features/cpp/index.html.

Coding & Programming


Other C++ IDEs to Install

MicrosoFt's Visual Studio is a R W n fT S S The Anjuta DevStudio is a Linux-only IDE that


VISUAL STUDIO
mammoth C++ IDE thatallowsyou Features some oF the more advanced Features you
to create applications for Windows, Android, iOSand the web. The would normally Find in a paid software development studio. There's
Community version is Free to download and install but the other a GUI designer, source editor, app wizard, interactive debugger and
versions allow a free trial period. Go to www.visualstudio.com/to much more. Go to www.anjuta.org/ For more information.
see what it can do For you.
£<ie Edit yiew Eroiect guild gun Bebug Qocuments Help
Lb - £ -
O■ a ■f U J* 9 - CM»4 - M - ► ■ , * fa n .i s B • ’* Q „
<http;ffwww.gnaorgflicefi**es/>.

_■ Makefile
B Makefile
config.h
conflg.log
config.log
• config.status
Makefile
stamp-til
i-i+1:
Makefile.am
Makefiie.am.ix
Mukefite.in

Files " Project Symbols Starter Documents " TbikS

Build S5: Debug Q Build 54. Debug Build S3.


Entering: /nome/torrest/tigure/Debug
make! 11: tntenng directory /nome/forrest/flgure/uetwq'

This cross-platform IDE is designed to This excellent IDE allows developers


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

Bloodshed Dev C++, despite its colourful name, Ultimate++ is a cross-platform C++ IDE that boatsa 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 m oreatwww.ultimatepp.org/index.html.
something different: www.bloodshed.net/devcpp.htmL

Coding & Programming


Coding w ith C++

This section contains the building


block of C++, from learning how to
compile and execute your first C++
code, through to developing user
interaction. There's a lot to learn with
C++, but these tutorials, tips and tricks
will lead you in the right direction.

C++ is different to the other


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

36 Your First C++Program


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

Coding & Programming


Index

Coding & Programming


Coding w ith C++

Your First C++ Program


You may have Followed the M ac and Linux examples previously but you're going to be
working exclusively in W indow s and Code::Blocks From here on. Let's begin by writing
your First C++- program and taking the First small step into a larger coding world.

HELLO, W O R L D !
It's traditional in programming For the First code to be entered to output the words 'Hello, World!' to the screen. Interestingly,
this dates back to 1968 using a language called BCPL.

We're going to use Windows 10 and the excellent 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, in due course. Now click on File >Save File As. Create or Find a
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
it helloworld.cpp. Click the Save as type box and select C/C++ Files.
Click the Save button.
H **.«*•' -ofcibrhl-V

jftlfl a■■■■■■a!»►f*": 11ois

PigeSIVMirFte

O Owpbm BT

' ‘ J, iaaiwk Scut ' C u t ) > rMJmnugn ’l (OtMAlM ' CnO«J,V.!. .« « « «. '.dm* ■ ClCtl

Now you can see a blank screen, with the tab You can see that Code::Blocks has now changed
labelled *Untitled1, and the number one in the top the colour coding, recognising that the File is now
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.
tinclude <iostream>
H I *helloworld.cpp - Code::Blocks 17.12
Ml -U ntitled l - C od tu Blo cks 17.12 File Edit View Search Project Build Debug Fortran wxSm ith Tools Tools-*- Plugins DoxySloi:
File Edit View Search Project Build Debug Fortran w xSm ith Tools Tools+ Plugins DoxyE
c s ( a . H 9 i ^ = * | s s » » i a ®i|i □ - E3 i ►
> =»| R> B S B I -t + /“ *< -] v| | • k
- * f* R* F5 » /•**<! IS «+ -H • k » Management
* h ellow orld.cpp X |
Management

P r o je c ts Symbols

Q W orkspace

1 0 0
0
0 1 1 1
10 1
111 0 0
0 1 0 0
0 0 1 0 0 0 0 1 1 0 1
D 1 o 1 1 0 0
Coding & Programming
1 0 1 0 o o
0 111 o ooo l 0 o0 0 0 0 11 1 0 0 1 0 0 1
Your First C++ Program

Auto-selection oF commands is extremely handy and 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 raain()
1 IS ft ft I Q , f t ; ® B
Note: there's no space between the brackets.
\ » * i /** * < i a m i ^ : *H • K ; & |v | o
,* X
Start here X *helk>workl.cpp X |
__
r * |/** *< |M [f] |^> * k : iles ►
1 #include <iostream>
X 2
Start here X * h e llo w o rld .c p p X
3 i n t m a i n ()
► 1 #in c lu d e < io s tr e a m > 4 EM
2 5

3 in t m a in () 6 s td ::c o n t « "H e llo , w o r l d ! \ n '';|


7
4
S
5
5
6

On the next line below int main{), enter a curly bracket: A


Ju st as beFore, Code::Blocksauto-completes the
code you’re entering, including placing a closing
{
speech mark as soon as you enter the First. Don't Forget the
This can be done by pressing ShiFt and the key to the right oF P on an semicolon at the end oF the line; this is one oF the most important
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.

Notice that Code::Blocks has automatically created 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 to look at how a C++ program is structured First; then you can build
Now enter: and run the code. For now, click on Save, the single Floppy disc icon.

//My first C++ program H 'helloworld.cpp - Code::Blocks T7.12

File Edit View Search Project Build Debug Fortran wxSmith Tools Tools* Plugins DoxyBlocks Settii
nr ! q a a t i o. | m * a I a ®i|; @ + :1
« * | r * *< | @ |$] | ^ ; H * k
Management X
X *helk>world.cpp X Start here X “ helloworld.cpp X
Projects Symbols Files ►
#include <iostreaoa> ( J Workspace 2
3 i n t m a in l)

!
i n t m a in () 4 R (
5 /,m- n » t c « program
1 {
6
7
std::c o n t « " H e llo , w o r ld !\ n ” ; 0 0
L>
8 0
0 1 1 l
0 1
1 1 1
0 1
0 0 0 10 1 0 1 c oo o0 0 1 0 10 1 o 1 0 0 0 0
0 0 0 i o () 1 1 0 1 o Oil 1 1 o o 1 1 1 1 l 1 o 1
Coding & Programming
0 1 0 0 1 0 0 i )0 0 1 0 1 111 0 0
Ollio 0 0 0 0 1 0 l 0 o 0 0 1 0 0 1 1 1 1 1 0 O i l 1 0
Coding with C++

Compile and Execute


You've created your first C++ program and you now understand the basics behind the
structure of one. Let's actually get things m oving and compile and execute, or run if
you prefer, the program and see how it looks.

G R E E T IN G S F R O M C++
Compiling and executing C++ code From Code::Blocks is extraordinarily easy; it's just a matter oF clicking an icon and seeing
the result. Here's how it's done.

Open Code::Blocks, iFyou haven't already, and 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 compilerand checked Forany errors. You can see
semicolons at the end oF the stdccout line. the results oF the Build by looking to the bottom window pane. Any
messages regarding the quality oF the code are displayed here.
m ’ helloworld.cpp - Code;;Blocks 17,12
File Edit View Search Project Build Debug Fortran wxSmith Toots Tools* Plugins DoxyBlocks Settings

- * h> * w * **/••*< -I -,| | h & ~I > .


Management X
Start here X *helloworld.cpp X|
Projects Symbols Files ► 1 #in c l u d e < io 3 tre a m >
Q Workspace 2
3 i n t m a in ()

a at
5
6 s t d ::c o u t « " H e llo , w o r ld !\ n " ;
7
8 Lj
9
10
11

iFyour code is looking similar to the one in our 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 pressa key to continue. Well
button together. These are Build, Run, Build and Run Functions. done, you just compiled and executed your First C++ program.

ocks 17.12

roject Build Debug Fortran wxSmith Tools Tools+ Plugins DoxyBloi

££ * a I # ► % O Q

» * /** *< I 0 IS] ^ j M • k


x
Start here X * helioworld.cpp X
::S ►
^ in c lu d e < io s tr e a m >

i n t m a in ( )

s t d ::c o ir t « " H e llo , w o r ld !\ n " ;

Coding & Programming


Compile and Execute

Pressing any key in the command line box closes it, 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"
using namespace std;
Start here X * helloworld.cpp X
Then, delete the std:: part oF the Cout line; like so:
1 ^include <iostream>
cout << "Hello, world\n";
2 using namespace std;
3
4 int m a i n ()
5 Fpit
6 //My first C++ p r o g r a m
7 c o u t << "Hello, world!\n"
3
9
10
11
12

In order to apply the new changes to the code, you 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:
Expected before token, indicating the missing semicolon.
Buna Deeug Fonrin iwstwm Toon took* piugmt DMyBJoiB smmgt H«p
2i i t ; © ► 4 -0 g g ; ► 4= c: V u a ! SJ ■ i V matnOrht
1r •< -J vl : • h !» ~ * 2 + to \ - .1 - - - ■ ! ° K ^ I s C II
Starthere hcHoworld.cpp

>*P*a« «td;

Ju st as we mentioned in the previous pages, you Replace the semicolon and under the cout line,
don't need to have stdccout if you already declare enter a new line to your code:
using namespace std; at the beginning oF the code. We could have
Cout << "And greetings from C++!\n";
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.
running, the file has been saved. Build and Run the code, to display your handiwork.

Hi helloworld.cpp - Code::Blocks 17.12


f ile Edit View Search Project Build Debug Fortran vvxSmith Tools Tools+ Plugins DoxyBlocks Settin

B a a m I •*. + I 2S * * |Q, 64 : # ► % •©■ Q U \ > '•


;®| lrl!»
lanagement X
Start here X helloworld.cpp X
Projects Symbols Files ► 1 # i n c l u d e < io s t re a m >
^ Workspace 2 u s i n g n a m e sp a c e s t d ;
3
4 i n t m a in ()
5 El
6
7 | cout « " H e llo , w o rld !\ n " ;
8
9 L|
10
11
12

Coding & Programming


Coding w ith C++

Using Comments
While com m ents 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 Pact
they're probably one oP the m ost important Factors.

T H E IM P O R T A N C E O F C O M M E N T IN G
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
effectively describe the purpose of a line, section, or individual wasyou 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.
DEFB 26h, 30h,32h,26h,30h,32h,0,0 , 32h,72h,73h,32h,72h, 73h,32h
In a professional environment, comments are vital to the success DEFB
DEFB
60h, 61h, 32h, 4Ch, <5DA, 32h, 4Ch, 99h, 32h, 4Ch, 4Dh, 32h, 4Ch, 4Dh
32h,4Ch,99h,32h,5Bh,5Ch,32h,56h,57h,32h,33h,OCDh, 3 2 h , 3 3 h
of the code and ultimately, the company. In an organisation, many DEFB 34h , 3 2 h f33h,34h,32h,33h,OCDh,32h,40h,41h,32h,66h, 6 7 h , 6 4 h
DEFB 66h,67h,32h,72h,73h,64h,4Ch,4Dh,32h,56h,57h,32h,8 0 h , O C B h
programmers work in teams alongside engineers, other developers, DEFB 19h,80h,0 , 1 9h,80h,81h,32h,SOh,OCBh,OFFh
TS58C:
hardware analysts and so on. If you're a part of the team that's DEFB 80h,72h,66h,60h,56h,66h,56h,56h,51h,60h,51h,51h,5 6 h , 6 6 h
DEFB 56h,56h, SOh, ?2h, 66h, 60h, S6h, 66h, 56h, 56h, 51h, 60h, Slh, Slh
writing a bespoke piece of software for the company, then your DEFB 56h, 56h,56h,56h,80h,72h,66h,60h,56h,66h,56h,56h,5 1 h , € 0 h
DEFB Slh,51h,56h,66h,5€h,56h,SOh,72h,66h,60h,56h,66h,5 6 h , 4 0 h
comments help save a lot of time should something go wrong, and DEFB 56h, 66h,SOh,66h,56h,56h,56h,56h

another team member has to pick up and follow the trail to pinpoint ; Game restart point
the issue. START: XOR A
LD (SHEET),A
LD (KEMP) ,A
Place yourself in the shoes of someone whosejob it is to find out LD (DEMO),A
LD (B845B),A
what's wrong with a program. The program has in excess of 800,000 LD (BB458),A
LD A, 2 ;Initial lives count
lines of code, spread across several different modules. You can soon LD (NOMEN),A
LD HL,T845C
appreciate the need fora little help from the original programmers SET O, (HL)
LD HL,SCREEN
in the form of a good comment. LD DE,SCREEN+1
LD BC,17FFh ;Clear screen image
LD (HL),0
The best comments are always concise LDIR
LD HL,OAOOOh ;Title screen bitmap
and link the code logically, detailing what LD DE,SCREEN
LD BC,4096
happens when the program hits this line LDIR
LD HL,SCREEN + 8Q0h + 1*32 + 29
or section. You don’t need to comment on LD DE,MANDAT+64
LD C,0
every line. Something along the lines of: if CALL DRWFIX
LD HL,0FCQOh ;A t t ributes fox the last room
x==0 doesn't require you to comment that if x LD DE,ATTR ; (top third)
LD BC,256
equals zero then do something; that's going LDIR
LD HL,09E00h ;Attributes for title screen
to be obvious to the reader. However, if x LD BC,512 ; (bottom two-thirds)
LDIR
LD BC, 31
DI
XOR A
R8621!
IN E, (C)
OR E
DJNZ R8621 ??-03
AND 20h
JR NZ,R 8 6 2 F ;$+07
LD A, 1
LD (KEMP) ,A
R862F:
LD IY,T846E
CALL C92DC
JP NZ,L8684
XOR A
LD (EUGHGT),A

Coding & Programming


Using Comments

C++ COMM ENTS


Commenting in C++ involves using a double Forward sla sh '/', or a Forward slash and an asterisk, You've already seen some
brieF examples but this is how they work.

Using the Hello World code as an example, you can Be careful when commenting, especially with block
easily comment on different sections of the code comments. It’svery 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.
//My first C++ program
cout « "Hello, world!\n"; - Start here X ‘helk»world.cpp X
1 ^include <iostream>
2 using namespace std;
1 # i n c l u d e <iostreain> 3
4 int main()
2 using namespace s t d ; 5 E3 i
6
3
7 cout « "Hello, world!\n";
4 int m a i n f ) 8 cout « "And greetings from C++";
9
/• T h i t rnm m pnr r~*n
5
6
^ 10
11
12 without the need to add more slashes
7 coat « "Hello, worl d ! \ n " ; 13
14 Sm & « "This line is now being ignored by the compiler!";
8 15
16
9 17
10 18
19
11 20

12
_1 _

However, you can also add comments to the end 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: bracket'}' to finish off the block of code. If you've made the
error a few times, then it can be time consuming to go back and
cout << "Hello, world!\n"; //This line outputs the
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.

You can comment out several lines by using the 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
comment block off before continuing with the code:
cover several lines
without the need to add more slashes */ /* This comment can
* cover several lines
Ju st remember to finish the block comment with the opposite
* without the need to add morS slashes */
asterisk and forward slash.

4 int m a i n ()
5 Hi
5
6
^
cout. « "Hello, world!\n";
7 coat « "Hello, world!\n"; 3 cout c< "And greetings from C++\n";
8 coat « "And greetings from C++"; 9
10
9
11 cover several lines
10 /* This comment can 12
11 cover several lines 13
12 wit ho it the need to add. more slashes 14
15 cout « "This line is now being ignored by the compiler!\n";
13
16
14 17
15 18

Coding & Programming


Coding w ith C++

Variables
Variables differ slightly w hen using C++ as opposed to Python. In Python, you can
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.

T H E D E C L A R A T IO N O F V A R IA B L E S
You can declare a C++ variable by using statements within the code. There are several distinct types of variables you can
declare. Here's how it works.

Open up a new, blank C++ file and enter the usual You can build and run the code but it won't do
code headers: much, other than store the values 10 and S to the
integers a and b. To output the contents of the variables, add:
#inclucte <iostream>
using namespace std; cout « a;
Starthere X V a r ia b le s ,t p p X |
cout « "\n";
int main() 1 ♦include ciostreano
cout << b; using namespace std;
{ 2
3
The c o u t « "\n"; part
4 int m a i n ()
simply places a new line 5
between the output of 6 E3<
7 int a;
10 and 5.
8 int b;
9
10 a = 10;
11 b = 5;
12
13 cout << a;
14 cout << "\n” ;
15 cout << b;
16
17 >
18

Start simple by creating two variables, a and b, with 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:
result = a + b;
int a;
Start here X *Variables.cpp X cout << result;
int b;
1 ♦include <iostream> Insert the above into the code as per the screenshot.
a = 10 2 u s ing n a m espace std;
b = 5; 3
Start here X Variables.cpp X |___
4 int m a i n ()
#include ciostreano
5 □sing namespace std;

€ Be int main ()
F l C:M)sers\david\Documents\C» *\Variables.e

7 int a;
Pc •ocess returned 0 (0x0) execution time ; 0.045 :
3 int b; •ess any key to continue.

int b;
9
infc result;
10 a = 10;
a = 10;
11 b = 5; b =5;
12
13 cout « result;
14

Coding & Programming


Variables

You can assign a value to a variable as soon as you 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.
int result = a + b;

cout « result; ■ C:\Users\david\Document5\C++\Variables.exe

Process returned 9 (0x9) execution time : 0.040 5


Press any key to continue.

The modern C++ compiler is Far more intelligent


than most programmers give it credit. While there
are numerous data types you can declare for variables, you can in
fact use the auto Feature:

#include <iostream>
using namespace std;
auto pi = 3.141593;

Specific to C++, you can also use the following int raainf)
to assign values toa variable as soon as you
{
declare them:
double area, radius = 1.5;
int a (io;
area = pi * radius * radius;
int b (5) ,
cout « area;
Then, from the C++ 2011 standard, using curly brackets:
}
int result (a+b);
• 1 -- — • ‘ i' -- 1
— r —
Start here X Variables, cpp X 1 Start here X Variables.cpp X
1 ♦ I n c l u d e < io s t r e a m >
2 u s i n g n a m e sp a ce s t d ;
1 ♦include <iostreara>
l i l C:\Users\dsvicf\Documeirts\C-n-\Vanables.exe
3 2 u s in g n am espace s t d ;
4 i n t m a in ( ) 15
}r o c e s s re tu rn e d 0 (0 x 0 ) e x e c u t i o n t im e : 6 .0 3 8 s
3 a u to pi = 3.141593;
5
6 P r e s s a n y ke y t o c o n t in u e . 4
7 i n t a (10) ; 5 i n t m a i n ()
8 i n t b (5),-
9 i n t r e s u l t C a + b ); 6
10 7 E3<
11 cout « r e s u lt ;
12
S d o u b le area, radius = 1.5;
13 } 9
14
10 area = pi * radius * radius;
11
12 cout « area;
13
14 >

You can create global variables, which are variables


that are declared outside any function and used in
A couple of new elements here: first, auto won't
any function within the entire code. What you've used so far are
work unless you go to Settings > Compiler and
local variables: variables used inside the function. For example:
tick the box labelled 'Have C++ follow the C++11 ISO C++ Language
#include <iostream> Standard [-std=c++1]'. Then, the new data type, double, which
using namespace std; means double-precision floating point value. Enable C++11, then
int StartLives = 3; build and run the code.The resultshould be 7.06858.

Coding & Programming 3


Coding w ith C++

Data Types
Variables, as w e've seen, store information that the program m er can then later call up,
and manipulate if required. Variables are simply reserved m em ory locations that store
the values the program m er assigns, depending on the data type used.

THE VALU E O F DATA


There are many different data types available for the programmer incredibly accurate numbers but those numbers are only accurate
in C++, such as an integer, floating point, Boolean, character and so up to the fifteenth decimal place. There's also the problem when
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
called Primitive Built-in Types; however, you can create your own by default only outputs the first five decimal places. You can combat
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>
using namespace std;
double PI = 3.141592653589793238463;

int m a i n ()
{
cout « PI;
i

Start here X DataTypes.cpp X

1 #inclnde ciostrearrD-
2 using namespace s td;

3 1 double PI = 3.141592653589793233463;
4
5 int icainQ

6 ^
7 cout << PI;
8
These basic types can also be extended using the following modifiers:
9 }
Long, Short, Signed and Unsigned. Basically this means the modifiers
10 Ll
can expand the minimum and maximum range values for each data
type. For example, the intdata type has a default value range of
-2147483648 to 2147483647, a fair value, you would agree. ■ C:\Users\david\DocumentsVC++\DataTypes,exe

Now, if you were to use one of the modifiers, the range alters: 3.14159
Process returned 0 (0x0) execution time 0.054 s
Unsigned int = 0 to 4294967295 Press any key to continue.
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 getaway with using the basic type without the
#include <iostream>
modifier, as there's plenty of range provided with each data type.
using namespace std;
Flowever, it's considered good C++ programming practise to use the
double PI = 3.141592653589793238463;
modifiers when possible.
int m a i n ()
There are issues when using the modifiers though. Double
{
represents a double-floating point value, which you can use for

Coding & Programming


Data Types

cout.precision(22);
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
oFdata, oFwhich 52-bitsare dedicated to the signiFicant(the
signiFicant digits in a Floating-point number) and roughly 3.5-bits
are taken holding the values 0 to 9. IFyou divide 53 by 3.5, then you
Start here X DataTypes.cpp X arrive at 15.142857 recurring, which is 15-digits oF precision.

1 ♦include <iostreara> To be honest, if you're creating code that needs to be accurate to


2 using namespace std; more than FiFteen decimal places, then you wouldn't be using C++,
3 double PI = 3.141592653589793233463; you would use some scientiFic speciFic language with C++ as the
4 connective tissue between the two languages.
5 int main()
You can create your own data types, using an alias-like system called
6 ^3 ( typedeF. For example:
7 cout.p r e c i s i o n (22);
s cout << PI;
s
10 >
11
1

SI C:\Users\david\D ocuments\C++\DataTypes,exe
B . 141592653589793115998
Process returned 0 (0x0) execution time : 0.047 s
Press any key to continue.

Again, build and run the code; as you can see From the command
line window, the number represented by the variable PI isdiFFerent
to the number you've told C++ to use in the variable. The output
reads the value oF PI as 3.141592653589793115998, with the
numbers going awry From the FiFteenth decimal place.

Calculator — □ X
#include <iostream>
using namespace std;
= Sc ie n tific s> typedef int metres;

int main()

15.142857142857142857142857142857 metres distance;


distance = 15;
cout « "distance in metres is: " « distance;

DEG HYP F-£


E 3 C:\User5\david\Documents\C++\DataTypes.exe
MC MR M+ M- MS M~
distance in metres is: 15
Process returned 0 (0x0) execution time : 0.041 s
X* s in COS ta n Press any key to continue.

y 10* lo g Exp M od

t CE C <3 —

TT 7 8 9 X
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,
n! — which is an integer; so you're basically telling the compiler that
4 5 6
there's another name Forint. We assigned the value 15 to distance
± and displayed the output: distance in metres is 15.
1 2 3 +
It might sound a little conFusing to begin with but the more you use
— C++ and create your own code, the easier it becomes.
c ) 0 -

Coding & Programming ■5


Coding w ith C++

Strings
Strings are objects that represent and hold sequences of characters. For example, you
could have a universal greeting in your code 'W elcom e' and assign that as a string to be
called up w herever you like in the program.

ST R IN G T H E O R Y
There are different ways in which you can create a string of characters, which historically are all carried over from the original
C language, and are still supported by C++.

To create a string you use the char function. Open a Build and run the code, and 'Welcome' appears
new C++ file and begin with the usual header: on the screen. While this is perfectly fine, it's
not a string. A string is a class, which defines objects that can be
#include <iostream>
represented as a stream of characters and doesn't need to be
using namespace std;
terminated like an array. The code can therefore be represented as:
int main ()
#include <iostream>
{ using namespace std;

} int main ()

{
char greet[] = "Welcome";
cout « greet « "\n";

it's easy to confuse a string with an array. Here's an 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>
using namespace std; #include <iostream>
using namespace std;
int main ()
int main ()
{
char greet [8] = { 'W' , 'e' , '1', 'c' , 'o', 'm',
V' , ' \ 0' } ; string greet = "Welcome";
cout « greet « "\n"; cout « greet « "\n";

finclude <io3tream>
n s i n g n a m e s p a c e std;

int main ()

string greet = "Welcome"


coot << greet « "Vn";

Coding & Programming


Strings

There are also many different operations that you Ju st as you mightexpect, 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>
using namespace std; #include <iostEeam>
using namespace std;
int main ()
int main ()
{
string greet = "Welcome"; {
cout « "The length of the string is: int length;
cout « greet.size() « "\n"; string greetl = "Hello";
string greet2 = ", world!";
string greet3 = greetl + greet2;
1 #include <iostreara> length = greet'3 .siz.ej );
2 using namespace std;
3
4 int main ()
cout « "The length Of the combined Strings
5 is: " << length « "\n";
6 EEH
7 string greet = "Welcome”;
}
8 cont « "The length of the string is:
S cout << greet.size(> << "\n";
10
11 >
12 Using the available operations that come with the
string Function, you can manipulate the contents oF a
string. For example, to remove characters from a string you could use:
You can see that we used greet.size() to output the
#include <iostream>
length, the number of characters there are, of the
using namespace std;
contents of the string. Naturally, if you call your string something
other than greet, then you need to change the command to reflect int main ()
this. It's always string name.operation. Build and run the code to see
{
the results.
string strg ("Here is a long sentence in a
* C:\Users\david\Documents\C++\Strings,ece
string.");
The length of the string is: 7
cout « strg « '\n';

Process returned 0 (0x0) execution time : 0.044 s strg.erase (10,5);


Press any key to continue. cout « strg « '\n';

strg.erase (strg.begin ()+8);


cout « strg « '\n';
You can of course add strings together, or rather
strg.erase (strg.begin ()+9, strg.end()-9);
combine them to form longer strings:
cout « strg « '\n';
tinclude <iostream>
}
using namespace std;

int main ()
It's worth spending some time playing around with
{
the numbers, which are the character positions
string greetl = "Hello";
in the string. Occasionally, it can be hit and miss whether you get it
string greet2 = ", world!";
right, so practice makes perfect. Take a look at the screenshot to see
string greet3 — greetl + greet2;
the result of the code.
cout << greet3 « "\n";
H j C:\User5\david \D ocu menls\C-t-+\Strin gs. exe
}
Here i s a long sentence in a s tr in g .
X
Start here X Strings.cpp X
Here i s a sentence in a s tr in g .
Files ► Here i s sentence in a s tr in g .
2 a s in g namespace std; Here i s a s tr in g .
3
4 Int m a i n ()
5
Process returned 0 (0x0) execution time : 0.0S1 s
e FEH Press any key to continue.
7 string greetl = "Hello";
8 string greet2 = ", world!";
S string greet3 = greetl + greet2;
10
11 coat « greet3 « "\n";
12
13 >
14

Coding & Programming


Coding w ith C++

C++ Maths
Program m ing is mathematical in nature and as you m ight expect, there's plenty oF
built-in scope For som e quite intense maths. C++ has a lot to oFFer som eone w h o's
implementing mathematical m odels into their code. It can be extremely complex or
relatively simple.

C++ = MC2
The basic mathematical symbols apply in C++ as they do in most other programming languages. However, by using the C++
Math Library, you can also calculate square roots, powers, trig and more.

C++'s mathematical operations follow the Multiplication and division can be applied as such:
same patterns as those taught in school, in that
#include <iostream>
multiplication and division take precedence overaddition and
using namespace std;
subtraction. You can alter that though. For now, create a new File
and enter: int main ()
{
#includs <iostream>
float numbers = 100;
using namespace std;
numbers = numbers * 10; // This multiplies 100
int main ()
by 10
{
float numbers = 100; cout « numbers « "\n";

numbers = numbers + 10; // This adds 10 to the numbers = numbers / 10; // And this divides
initial 100 1000 by 10

cout « numbers « "\n"; cout « numbers « ”\n";

numbers — numbers - 10; // This subtracts 10 )


from the new 110

cout << numbers « "\n";

While simple, it does get the old maths muscle


warmed up. Note that we used a Float for the
numbers variable. While you can happily use an integer, iFyou Again, execute the simple code and see the results.
suddenly started to use decimals, you would need to change to a While not particularly interesting, it's a start into C++
Float ora double, depending on the accuracy needed. Run the code maths. We used a Float here, so you can play around with the code
and see the results. and multiply by decimal places, as well as divide, add and subtract.

i l l C:\U5ers\david\Documents\C++\Maths.exe i l l CAUsers\david\Document5\C++\Maths,exe

110 1000
100 100

Process returned 0 (0x0) execution time : 0.043 s Process returned 9 (0x0) execution time : 0.050 s
Press any key to continue. Press any key to continue.

Coding & Programming


C + + Maths

The interesting maths content comes when you call 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 <iostxeam>
Everything from computing cosine to arc tangent with two #include <cmath>
parameters, to the value of PI. You can call the header with: using namespace std;

#include <iostream> int main ()


#include <cmath> {
using namespace std; float number = 12;

int main () cout « number « " to the power of 2 is " «


{ pow(number. 2) « '’\n";
cout « number « 1' to the power of 3 is '' «
pow(number. 3) « ''\n ";
X
cout « number « " to the power of .08 is
S ta r t h ere X *Maths.cpp X
« pow(number, 0.8) << "\n";
Files ►
1
2 #in c lu d e < c m a th >
3 using namespace std;
♦ in c lu d e < io 3cream >
-3 ♦ in c lu d e <cmach>
u sing namespace std;
5 int m a i n ()
in t main ()
6 E3 f
7 flo a t number = 1 2 ;

8 coat « number << " to the power o f 2 i s ' « pow(number, 2 ) « "\n";


10 cout « number « “ to the power o f 3 i s " « pow(number, 3) « "\n";
9 } 11 eout « number « " to the power o f .08 i s ■ « pow (number, 0.8) "\n";
12
10
13

Start by getting the square root of a number: Here we created a float called number with the
value of 12, and the pow(variable, power) is where
the calculation happens. Ofcourse, you can calculate powersand
#include <iostream>
square roots without using variables. For example, pow (12, 2)
tinclude <cmath>
outputs the same value as the first cout line in the code.
using namespace std;

int main 0 113 C;\Users\ddvidVDocum ents\C-++VM aths,exe


12 to the power of 2 is 144
{ 12 to the power of 3 is 1728
float number = 134; 12 to the power of .08 is 7.30037

Process returned 0 (0x0) execution time : 0.049 s


cout < < "The sgi:are root of '' < < number « "
Press any key to continue.
i s : " « sqrt(number) « "\n";

X *Maths.cpp X |____ The value of Pi is also stored in the cmath header


♦ in c lu d e < iostream >
♦ in c lu d e xeaach>
library. It can be called up with the M_PI function.
u s i n g namespace s t d ; Enter co u t« M_PI; into the code and you get 3.14159; oryou can
int main () use it to calculate:
Eli
f l o a t number — 134;
#include <iostream>
9 cont « "The square root of " « number « "is: " « sqrt(number) « "\n";
10 #include <cmath>
11
12 using namespace std;

int main ()
{
double area, radius = 1.5;

area = M_PI * radius * radius;


Here we created a new float called number and
used the sqrt(number) function to display the cout « area << "\n";
square root of 134, the value of the variable, number. Build and run
the code, and your answer reads 11.5758.

I l l C :\U sers\d avid \D o cu m en ts\C + + \M aths.exe

Fhe square root of 134 is: 11.5758

Process returned 0 (0 x 0 ) execution time : 0.046 s


Press any key to continue.

Coding & Programming 19


Coding w ith 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 m ost taught aspects of any language and with it
you're able to do much more than simply greet the user by name.

HELLO, D A V E
You have already used cout, the standard output stream, throughout our code. Now you're going to be using cin, the standard
input stream, to prompt a user response.

Anything that you want the user to input into the The cin command works in the opposite way from
program needs to be stored somewhere in the the cout command. With the first cout line you're
system memory, so it can be retrieved and used. Therefore, any outputting ’What is your age' to the screen, as indicated with the
input must first be declared as a variable, so it's ready to be used by chevrons. Cin uses opposite facing chevrons, indicating an input. The
the user. Start by creating a blank C++ file with headers. input is put into the integer age and called up in the second cout
command. Build and run the code.

I C:\Users\david\Documents\C++\userinteraction.exe

what i s your age: 45

you are 45 years old.

Process returned 0 (0x0) execution time : 4.870 s


Press any key to continue.

If you're asking a question, you need to store the


input as a string; to ask the user their name, you
would use:

tinclude <iostream>
■ j The data type of the variable must also match the using namespace std;
type of input you want from the user. For example,
int main ()
to ask a user their age, you would use an integer like this:
{
tinclude <iostream> string name;
using namespace std; cout « "what is your name: ";
cin » name;
int main ()
{ cout « "\nHello, " << name « ". I hope you're
int age; well today?\n";
cout « "what is your age: ";
}
cin » age;

cout « " \ n Y o u are " « age « " years old.\n";

Starthere X *userinteraction.cpp X |
1 #include <iostream>
2 using namespace std;
3
4 Int main ()
5 EpH
6 int age;
7 cout << "what is your age:
8 cin » age;
5
10 cout <<"\nYou are " << age « " years old.\n";
11
12 }
13

51 Coding & Programming


User Interaction

The principal works the same as the previous code. 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 Forjust single words not multiple words.
cout line. As long as the variable 'name' doesn't change, then you Flowever, getline takes cin as the First argument and the variable as
can recall it whereveryou like in your code. the second:

B j C:\Llsers\david\Documents\C--Auserinteraction.exe #include <iostream>


what is y our name: David using namespace std;
Hello, David. I hope y o u're w ell today?

Process returned 0 (0x0) execution time : 2.153 s


int main ()
Press any key t o continue.
{
string mystr;
cout « "Enter a sentence: \n";
You can chain input requests to the user but just
getline(cin, mystr);
make sure you have a valid variable to store the
input to begin with. Let's assume you want the user to enter two cout « "Your sentence is: " « mystr.size() «
whole numbers: " characters long.\n";

#include <iostream> i
using namespace std;

int main ()
{
int numl, num2;

cout' « "Enter two whole numbers:


cin » numl » num2;

cout « "you entered " « numl << " and " <<
num2 « "\n"; Build and execute the code, then enter a sentence
with spaces. When you're done the code reads the
number oF characters. IFyou remove the getline line and replace it
with cin » mystr and try again, the result displays the number oF
characters up to the First space.

• C:\UsersVdavid\DocumentsVC++\userinteraction.oe

Enter a sentence:
BDM Publications Python and C++ fo r Beginners
/our sentence is : 45 characters long.

Process returned 0 (9x0) execution time : 27.054 s


Press any key to continue.

Likewise, inputted data can be manipulated once


you have itstored in a variable. For instance, ask the Getline is usually a command that new C++
user For two numbersand do some maths on them: programmers Forget to include. The terminating
white space is annoying when you can't Figure out why your code
tinclude <iostream>
isn't working. In short, it’s best to use getline(cin, variable) in Future:
using namespace std;
#include <iostream>
int main ()
using namespace std;
{
float numl, num2; int main ()
{
cout « "Enter two numbers: \n";
cin » numl » num2; string name;
cout « "Enter your full name: \n";
'' is: " «
V
V

cout « numl '« num2 «


+

getline (cin, name);


numl + num2 « "\n";
cout « "\nHello, " << name « "\n";
)

r -
2
#include <iostxeam>
using namespace std:
3 1 ^include <iostream>
4 int main () 2 nsing namespace std;
5 E ll 3
6 float numl, num2; 4 int main ()
7 5 E 3<
8 cout « "Enter two numbers: \n"; 6
5 cin » numl >> num2; 7 string name;
10 8 cout « "Enter your full name: \n";
11 coat « numl « " + " « num2 « " is: " << numl + num2 << "\n"; 9 getline(cin, name);
12 10
13 > 11 cout « "\nHello, " « name « "\n";|
14 1 Ll

Coding & Programming


introducing Python

Python is one of the most respected


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

You don't need to look too far to


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

In this section, we will look at what


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

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

Coding & Programming


Index

m n m iin j n M I l|F|
W vQ I
V
m % 1 \ % m m m m\ \ m\ S

H I lllllilllU !M lu H II

Coding & Programming


introducing Python

Why Python?
There are many different program m ing languages available for the modern computer,
and som e still available for older 8 and 16-bit com puters too. Som e of these languages
are designed for scientific work, others for mobile platforms and such. So w hy choose
Python out o f all the rest?

PYTHON POW ER
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 o ra thousand other connected and 'smart'
that's used to ultra high-deFinition graphics and open world, multi­ appliances, behind them all is programming.
player online gaming. However, Forty-something years ago it was
blindingly brilliant. All those aForementioned digital devices need instructions to tell
them what to do, and allow them to be interacted with. These
Naturally these bedroom coders helped Form the Foundations For instructions Form the programming core oF the device and that core
every piece oF digital technology we use today. Some went on to can be built using a variety oF programming languages.
become chieF developers For top soFtware companies, whereas
others pushed the available hardware to its limits and Founded the The languages in use today diFFer depending on the situation, the
billion pound gaming empire that continually amazes us. platForm, the device's use and how the device will interact with its

!• Bombs - GUI - ThelDE - [d:\uppsic\CtilLibVAi iciyCtil.cpp windows-1252J { examples }


1 File Edit Macro Project Buid Debug Assist Setup Ln639. Cd «
$ % B GUI___ v vnscriatoA uB- ® ^ t , a r e t iy □ ®
® Bombs ©plugin/bmp SetC u rso r(p .y);
® Ctrlib ®plugin\j C t r l: : ChiIdGotFccus(5; .11
® Or Coro ®plugin\png }
®RichText SB <prj-aux>
©PdfDravi ■ <ide-aux> void A r r a y C t r l:: ChildLostFocusO
©Draw B <temp-aux> {
©Core if (c u r s o r >= 0)
RefreshRow(cursor);
Ctrl::ChildLostFocus();
# EdtCtrt.h £ AKeys.cpp >
fi EdtField.cpp # RichText.h
# TextEdits £ RichTextView.cpp void ArrayCtrl::Paint(Draws w) {
£ Text.cpp £ Prompt.cpp LTIMINGC“P a i n f ) ;
C LineEdft.cpp £ Help.cpp Size size = GetSizeO;
£ DocEdR.cpp # DateTimeCtrl.h Rect r;
# ScrcJBer.h £ DateTimeCtrJ.cpp r.bottom = 0;
bool hasfocus = HasFocusDeep();
C ScroJBar.cpp £>Bar
int i = GetLineAt(sb);
# He.aderCtH.J-i # Bar.h
int xs - header.GetScrollO;
£ HeaderCtH.cpp £ Bar.cpp
int js;
# ArrayCtrl, h £ MenuBar.cpp fortjs = 0 ; js < column.GetCount(); js++) {
£ ArrayCtrl. cpp £ ToolBar.cpp int cw = header.GetTabWidth(js);
# DropChoice.h £ ToolTip.cpp if ( ( xs + cw - v e r t g n d + (js == column.GetCount() - 1)) s- o)
£ DropBox.ccc # StatusBar h break;
fi Droplist.cDP £ StatusBar.cpp xs + = cw;
£ DropPusher.cpp 0-T *bC trl }
£ DropCboice.cpp # TabCtrl.h Color fc = Blend(SColorDisabled, SColorPaper);
# StaticCtrl.h £ Tabari,cpp i f (IIsNull(i))
£ Static, cpp (J> TreeCtrl w h i l e d < G e tCountO) {
# Splitter.h # TreeCW.h r.top = GetLineY(i) sb;
£ Spltter.cpp £ TreeCtrl.cpp if(r.top > size.cy) break;
£ FrameSpttter.cpp U>Dlt|Lolor r.bottom = r.top + GetLineCy (i);
int x = xs;
# SfcderCtrl.h # DlgColor.h
for(int j = js; j < oolumn.CetCountO; j-H-) {
£ SllderCtrl.rpp £ DlgColor.cpp
int cw = header.GetTabwidth(jJ;
# Cotumntist.il £ CoJorPopup.cpp
int cm = column!j].margin;
£ CokmnLisl.cpp £ ColorPusFier.cpp if(cm < 0)
# Proyess.h O -F ilrSH cm = header.Tab(j) .CetMarginO ;
£ Progress.cpp # FifeSel.h if(x > size.cx) break;
# AKeys.h £ RksUst.cpp r.left = x;
# key_hcader.h £ FileSel.ccp r. right = x + cw • vertgrid + (j = column.GetCountO ■ 1
# key.source,h O Utilities
________:( _______________________
Color bg = i & 1 ? evenpaper : oddpaper;

Coding & Programming


Why Python?

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

Python is what's known asa 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 ofarrays, learn, exceptionally powerful, universally accepted, effective and a
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
stacks and registers, its beneFit is that it's universally accessible 4.0 L E T p y = 15
7 0 FO R W=1 T O 1 0
and easy to learn. 71 CLS
7 5 L E T b y = XN T IR N D * 2 3 )
8 0 L E T b x =0
I//file: Invoke.java 9 0 F O R d =1 T O £ 0
import java.lang.reflect.*; 1 0 0 P R IN T R T p x , p y ; " U ”
1 1 0 P R I N T R T bx , by j " o "
1 £ 0 I F I N K E Y $ = " p " T H E N L E T p y = P
y + 1
1 3 0 I F I N K E Y $ = ” Q ‘‘ T H E N L E T p y = P
class Invoke { y - 1 U
public static void main( String [] args ) { 1 3 5 F O R n =1 T O 1 0 0 : N E X T n
try { 1 4 0 I F p y <£ T H E N L E T p y =£
Class c = Class.forNameC args[0] ); 1 5 0 I F p y > 27 T H E N L E T p y = 2 7
Method m = c.getMethodC args[l], new class 1 S 0 L E T b x = bx +1
[] { } ) ; 1 8 5 P R IN T R T b X - l , b y ; " "
object ret = m.invokef null, null ); 1 9 0 N E X T d
System.out.pri ntln( 2 0 0 I F ( b M - 1 ) =p y T H E N L E T £ = S + 1
"Invoked static method: " + args[l] 2 1 0 P R IN T R T I 0 , l 0 ; " s c o r e = " ; s
2 2 0 F O R V =1 T O 1 0 0 0 : N E X T V
+ " of class: " + args[0] 3 0 0 N E X T W
+ " with no args\nResults: " + ret );
} catch ( ClassNotFoundException e ) { 0 O K , 0 : 1
// Class.forNameC ) can’t find the class
} catch ( NosuchMethodException e 2 ) {
// that method doesn't exist BASIC was once the starter language that early
} catch ( illeaalAccessException e 3 ) {
// we don't nave permission to invoke that 8-bit home computer users learned.
method
} catch ( invocationTargetException e4 ) {
// an exception ocurred while invoking that p r i n t (H A N G M A N [0])

method attempts = len(HANGMAN) - 1

System.out.pri ntln(
"Method threw an: " + e4 . while (attempts != 0 and in w o r d _ g uessed):

getTargetExceptionC ) ); pr i n t ( ("\nYou have {} attempts remaining").format(attempts))


joined_i*ord = join(word_guessed)
print(join e d _word)

Java is a powerful try:


player guess = str(input("\nPlease select a letter between A-Z" + ”\n> ")}.
language that's used in except: # check valid input
print("That is not valid input. Please try again.")
web pages, set-top boxes, continue

TVs and even cars. else:


if not p l ayer_guess.isalpha(): # check the input is a letter. Also checks a
print("That is not a letter. Please try again.")
continue
elif len(player_guess) > 1: # check the input is only one letter
print("That is more than one letter. Please try again.")
continue
elif player_guess in guessed_letters: # check it letter hasn't been guessed
print("You have already guessed that letter. Please t r y again.")
continue
else:
pass

guessedletters.append(playerguess)

for letter in range(len(chosen_word)):


if player_guess == c h o sen_word[l e t t e r ] :
w°rd_guessed[letter] = player guess # replace all letters in the chosen

if player_guess not in chosen_word:

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


and makes For an ideal beginner’s programming language.

Coding & Programming


</>] Introducing Python

What Can You Do


with Python?
Python is an open-source, object-oriented program m ing language that's simple to
understand and write with, yet also powerful and extremely malleable. It's these
characteristics that help make it such an important language to learn.

Python's ability to create highly readable code, within a small set You'll find lots of examples of this, where Python is acting behind
of instructions, has a considerable impact on our modern digital the scenes. This is why it's such an important language to learn,
world. From being an ideal first programmers' choice through to
being able to create interactive stories and games; from scientific
applications through to artificial Intelligence and web-based Beautiful is b etter th a n ugly.


Explicit is better than implicit.
applications, the only limit to Python is the imagination of the Sim p le is b etter than com plex.
Com plex is b etter tha n com plicated.
person coding in it. Flat Is better than nested,
S p a rse is b etter than dense.
Readability co un ts.
It's Python's malleable design that makes it an ideal language for Sp ecial c a s e s a re n ’t special enough to b reak the rules.
Although p racticality b eats purity.
many different situations and roles. Even certain aspects of the E rro rs should n e v e r p a ss silently.
U nless exp licitly silenced .
coding world that require more efficient code still use Python. For In the face o f am biguity, refu se th e tem ptation to g ue ss.
example, NASA utilises Python both as a stand-alone language Th ere should be o n e - and preferab ly only one -o b v io u s w ay to do it.
Although th a t w ay m ay not be o bvious a t first u n le ss yo u 're Dutch.
and as a bridge between other programming languages. This way, Now is b etter than n ever.
Although n e v e r is often b etter tha n “ rig h t* now.
NASA scientists and engineers are able to get to the data they I f the im plem entation is h ard to exp la in , it's a bad idea.
need without having to cross multiple language barriers; Python I f the im plem entation is e a s y to e xp la in , it m ay be a good idea.
N am espaces are one honking g reat id ea — le t's do m ore o f those?
fills the gaps and provides the means to get the job done.

BIG DATA
« T o ,.
Big data is a buzzword you're likely to have come across in the last couple of years.
• ir r o r
Basically, it means extremely large data sets that are available for analysis to reveal
patterns, trends and interactions between humans, society and technology. Of course,
it’s not just limited to those areas, big data is currently being used in a variety of
industries, from social media to health and welfare, engineering to space exploration = False
HIRRORjp
and beyond. x * F a ls e
= F a ls e
L_* - T ru e
Python plays a substantial role in the world of big data. It's extensively used to analyse
huge chunks of the available big data and extract specific information based on what
the user/company requires from the wealth of numbers present. Thanks to an
impressive set of data processing libraries, Python makes the act of getting to the data,
in amongst the numbers, that counts and presenting it in a fashion that's readable and
useable for humans.

There are countless libraries and freely available modules that enable fast, secure and
more importantly, accurate processing of data from the likes of supercomputing clusters.
For example, CERN uses a custom Python module to help analyse the 600 million collisions
per second that the Large Pladron Collider (LHC) produces. A different language handles
the raw data, but Python is present to help sift through the data so scientists can get to the
content they want without the need to learn a far more complex programming language.

56 Coding & Programming


What Can You Do with Python?

4 0 Minecraft Launcher

ARTIFICIAL INTELLIGENCE Q ER TIC E60 2T H ELP

Artificial Intelligence and Machine Learning are two of the


M IH E C R R F t
most groundbreaking aspects of modern computing. Al is the N ew s S k in s S e ttin g s L a u n ch o p tio n s
umbrella term used for any computing process wherein the
machine is doing something intelligent, working and reacting
in similar ways to humans. Machine Learning is a subset of Al
and provides the overall Al system with the ability to learn
from its experiences.

However, Al isn't simply the creation of autonomous robots


intent on wiping out human civilisation. Indeed, Al can be
found in a variety of day-to-day computing applications where
the 'machine', or more accurately the code, needs to learn
from the actions of some form of input and anticipate what iliil %^ a .. ‘
the input is likely to require, or do, next.

This model can be applied to Facebook, Google, Twitter,


Instagram and so on. Have you ever looked up a celebrity
on Instagram and then discovered that your searches within
other social media platforms are now specifically targeted
toward similar celebrities? This is a prime example of using Al
in targeted advertising and behind the code and algorithms
GAMING
that predict what you're looking for, is Python.

Although you won’t find too many triple-A rated games coded
Spotify, for example, uses Python based code,
using Python, you may be surprised to learn that Python is used as
among other things, to analyse your musical
an extra on many of the high-ranking modem games.
habits and offer playlists based on what you've
listened to in the past. It’s all clever stuff and
The main use of Python in gaming comes in the form of scripting,
moving forward, Python is at the forefront of
where a Python script can add customisations to the core game
the way the Internet will work in the future.
engine. Many map editors are Python compatible and you wilt also
come across it if you build any mods for games, such as The Sims.

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


Playing Game) games available utilise Python as a companion
WEB DEVELOPMENT language for the server-side elements. These include: code to
search for potential cheating, load balancing across the game's
Web development has moved on considerably since the early servers, player skill matchmaking and to check whether the player's
days of HTML scripting in a limited text editor. The many client-side game matches the server's versions. There's also a
frameworks and web management services available now Python module that can be included in a Minecraft server, enabling
means that building a page has become increasingly complex. theserveradmin to add blocks, send messagesand automate a lot
of the background complexities of the game.
With Python, the web developer has the ability to create
dynamic and highly secure web apps, enabling interaction with
other web services and apps such as Instag ram and Pinterest.
Python also allows the collection of data from other websites
and even apps built within other websites.
PYTHON EVERYWHERE

As you can see, Python is quite a versatile


programming language. By learning Python,
you are creating a well-rounded skiilset that's
able to take you into the next generation of
computing, either professionally or simply
as a hobbyist.

Whatever route you decide to take on your


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

r i <d
«
«
Coding & Programming
Introducing Python

There’s a
lot to like ab o u t
Python, but don’t ju st
take our word for it. Here are
som e amazing facts and figures
surrounding one of the most popular
programming languages of recent years.

Alexa, Amazon’s Virtual 1 r Data analysis and


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

PYTH O N AND
LIN UX S K ILLS
A R E TH E THIRD
As of the end of 2023, Disney Pixar uses Python
Python was the most M OST P O P U LA R in its Renderman software
discussed language on I.T. S K IL L S IN to operate between other
the Internet. graphics packages.
TH E UK.

1
*
7 5 % )
^
# % 9 0 f 7 5 %)
OVER 75% OF 90% OF ALL IT’S ESTIMATED
RECOMMENDED FACEBOOK POSTS THAT OVER 75% OF
CONTENT FROM NETFLIX ARE FILTERED NASA'S WORKFLOW
IS GENERATED FROM THROUGH PYTHON- AUTOMATION
MACHINE LEARNING - CODED MACHINE SYSTEMS ON BOARD
CODED BY PYTHON. LEARNING. THE I.S.S. USE PYTHON.

Coding & Programming


Python in Numbers

PYTHON SKILL-BASED
16,000 POSITIONS ARE THE

ftfffttt
m tm i MOST SOUGHT-AFTER
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.

95% OF A LL 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.

Coding & Programming


introducing Python

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

W H A T W E 'R E U SIN G
ThankFully, Python is a multi-platForm programming language available For Windows, macOS, Linux, Raspberry Pi and more. IF
you have one oF those systems, then you can easily start using Python.

□ COM PUTER
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 eithera 32
or 64-bit processor, an Apple Mac or Linux installed PC.

_ J A N ID E
An IDE (Integrated Developer Environment) is used to enter and execute Python
code. It enables you to inspect your program code and the values within the code, as
well as offering advanced features. There are many different IDEs available, so find
the one that works for you and gives the best results.

_ J PYTHO N SO FTW ARE


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.

□ T E X T E D IT O R
Whilst a text editor is an ideal environment to enter code into, it's not an absolute
necessity. You can enter and execute code directly from the IDLE but a text editor,
such as Sublime Text or Notepad++, offers more advanced features and colour coding
when entering code.

_ J IN T E R N E T A C C E S S
Python is an ever evolving environment and as such new versions often introduce
new concepts or change existing commands and code structure to make it a more
efficient language. Having access to the Internet will keep you up-to-date, help you
out when you get stuck and give access to Python's immense number of modules.

_ J T IM E A N D P A T IE N C E
Despite what other books may lead you to believe, you won’t become a programmer
in 24-hours. Learning to code in Python takes time, and patience. You may become
stuck at timesand other times the code will Flow like water. Understand you're learning
something entirely new, and you will get there.

61 Coding & Programming


Equipment You Will Need

THE RASPBERRY PI
Why use a Raspberry Pi? The Raspberry Pi is a tiny computer that's very cheap to purchase, but oFFers the user a Fantastic learning
platForm. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many modules and extras.

RASPBERRY PI

The Raspberry Pi 5 Model is the latest version,


incorporating a more powerful CPU, a choice of 4CB or
8GB memory versions and Wi-Fi and Bluetooth support.
You can pick up a Pi 5 from around £59, increasing up to
£79 for the 8GB memory version, or as part of a kit
depending on the Pi model you're interested in.

FUZE PROJECT

The FUZE is a learning environment built on the latest model


of the Raspberry Pi. You can purchase the workstations that
come with an electronics kit and even a robot arm for you
to build and program. You can find more information on the
FUZE at www.Fuze.co.uk.

BOOKS

We have several great Raspberry Pi titles available via www.


pclpublications.com. Our Pi books cover how to buy your
first Raspberry Pi, y
set it up and use
RASPBIAN
it; there are some great step- ■
by-step project examples and - F \ m
The Raspberry Pi's main operating system is a Debian-based
guides to get the most from ■ y
Linux distribution that comes with everything you need in
the Raspberry Pi too. ' O f B p C T lD
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. x s s a I started
s o d in g

n 2 r * l* * ~ '*
Col°ur Guides

'MPublia,;on!.
3 Popercut t-
’"timremcl,
Coding & Programming
</>] Introducing Python

Getting to Know Python


Python is one o f the m ost used and popular program m ing languages. It's a great
language on which to learn how to code, but it's also powerFul enough to be used by
companies w hen trawling through petabytes oF raw data.

PYTHON POW ER
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.

The Python Software Foundation, a non-profit organisation devoted Made up from over 5 Petabytes of data, spread across a
to both furthering and improving Python, currently develops the ton of hard drives, Python helped science to unveil the first
language. The foundation's purpose is to "promote, protect, and image of a black hole.
advance the Python programming language, and to support and
facilitate the growth of a diverse and international community of
Python programmers." As a side note, it’s not just the likes of the Stock Exchange that
use Python to study large quantities of data; in April 2019 the first
The structure of Python code has been designed to flow easily, image of a black hole was released, the supermassive black hole in
allowing those who are just beginning to code to follow it without the galaxy called M87, located roughly 55 million light years away.
too much difficulty. Yet, despite its ease of use, Python is regularly Thanks to the collaboration of over 200 scientists, using an array of
used throughout a number of industries in real-world scenarios. telescopes spanning the world (called the Event Horizon Telescope
Project), the combined power of the telescopes formed an
Big Data and Al are the two fastest growing Python-backed impressive five petabytes of data, spread across tens of hard drives
technologies at the moment. Big Data is simply a modern term weighing in at nearly one ton. Five petabytes, by the way, equates
used to describe huge to around 5,000 years’ worth of MP3 files. Once all those hard drives
amounts of data, were gathered together and shipped to a central supercomputer
such as sequences cluster, the team then used Python to painstakingly stitch together
of numbers collated all the fragments of data from the five petabytes to finally form the
during a day's worth of most talked about astronomic event of the decade.
trading on the Stock
Exchange. Python Al, if you're not familiar with the term, stands for Artificial
code is used to dig Intelligence. Although we're still a long way off from the visionary
into the voluminous stories of Arthur C. Clarke, Al is fast becoming one of the most
collection of numbers, influential technologies of our modern age. Rather than controlling
and then feed back robots, the Al that Python drives is designed to create autonomous
with reports on the ways of interacting with people online. For example, when you
highs and lows, what's search for something on the Amazon website you will usually notice
trending, and so on. that similar products start to appear, whether within Amazon itself,

62 Coding & Programming


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.

You need to be careful when you look up Python code online, although
jgi python there are countless websites that offer quick tutorials, code snippets
About Downloads DocunterVlotion Community Success Stones News fventS and support-and 99% of these site are a great help to those starting
out with Python - a lot of the sites haven't been updated for some
ngfunctions. time, and as such use Python 2. If you enter Python 2 code into the
Python 3 IDLE, the chances are it won't work due to incompatibilities
between the older version and the newer. Python 2 is good, but
6 9 Python 3 is better. You can obviously spend time converting the
Python 2 code into version 3, but, to begin with, it's best to make sure
that the code you're looking at is for the Python 3 libraries. Don’t
Python 3 is the best option to
worry, though, all the code in this book is designed for Python 3, and
download, or update to.
that includes all the sub versions from Python 3.1 to the latest 3.x.
Python 3 is the newest release of the programming language.
However, if you dig a little deeper into the Python site and investigate Python 3's growing popularity has meant that it's now prudent to start
Python code online, you will undoubtedly come across Python 2. learning to develop with the new features and begin to phase out the
Crucially, although you can run Python 3 and Python 2 alongside previous version. Many development companies, such as SpaceX and
each other, it's not recommended. Always opt for the latest stable NASA, use Python 3 for snippets of important code.
release, as posted by the Python website. You will find, when using
macOS or Linux, that Python 2 is already installed. This is because However, support for Python 2 is set to end on January 1st 2020, but
both these operating systems utilise elements of code necessary to this doesn't mean it’ll be the last you see of it. Many Linux distros use
the core functionality of the OS. Linux users tend to be better off, Python 2 libraries, as does macOS, and to be fair, for the developers
as most distributions package the latest version of Python 3 out-of- to transfer the existing Python 2 content to Python 3 may take more
the-box, whereas macOS often has Python 3, it's usually an older time than they have available, i.e. before the start of 2020. It's likely
version. Microsoft doesn't use any Python code for its core Windows then, that we will still be seeing Python 2 long after it has had the Final
systems, which is why you won’t find Python inherent to Windows and nail hammered into its coffin-in fact, expect to see that cut-off date
therefore need to install it from scratch. extend further into the future.

or from a search engine, or even Facebook. The code behind


these targeted snippets is Python, and it's using a form of Al to
help determine what it is you would likely search for. ZEN OF PYTHON

Despite the fact that many people find the targeting of Python lets you access
advertising intrusive, or even an invasion of privacy, you have to all the power of a
admit that the code technology behind it all is rather impressive. computer in a language
With some very clever techniques, a Python developer is able that humans can
to create a machine thinking script that not only displays items, understand. Behind all
news stories, books, other websites and ideas relating to what this is an ethos called
you've searched for, but it can also predict what you may be "The Zen of Python".
interested in looking for in the future. Another element to This is a collection of 20
consider, with regards to Al, is that Python code can be used to software principles that

$
help a computer learn how to do something more efficiently. In influences the design of
the case of neural networks in Al, the Python code is designed the language. Principles The Zen of Python, as
to return a result, then, as the code is run over and over again, include "Beautiful is seen when entering:
the Al portion will begin to learn how to obtain a more accurate better than ugly" and import this, into the
result, or do the maths behind the code quicker. It all depends on "Simple is better than Python IDLE.
what the developer wants from their Al Python code. comnlex." Tvne: WIBWM
| into Python and it will display all the principles.

An example of Python Al 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
. jpot random
im p o rt numpy a s np games, tools, and maybe even something in Al. The only limit
c l a s s N e tw o rk (o b j e c t ) :
d e f _init__[ s e l f , s i z e s ) : with Python is your own imagination.
se l f . n u m _ la y e rs le n ( s iz e s )
se l f . s iz e s s iz e s
se l f . b ia s e s [n p .r a n d o m .r a n d n (y f 1 ) y in s i z e s [ l : ] ]
se l f . w e ig h t s [n p .r a n d o m .r a n d n (y , x )
fo i x , y z ip (s iz e s [ :- 1 ] , s i z e s [ l:J ) ]
d e f fe e d fo rw a rd ( s e l f , a ) :
for* b , w z ip ( s e Z f .b ia s e s , s e l f .w e ig h t s ):
a s ig m o id (n p .d o t (w , a ) b) Coding & Programming 63
re tu rn a
d e f SGD(self, t r a i n i n g _ d a t a , e p o c h s , m i n i _ b a t c h _ s i z e , e t a ,
t e s t data-Mone):
introducing Python

How to Set Up
Python in Windows
W indow s users can easily install the Python programming language via the main Python
Downloads page. While most seasoned Python developers may shun W indow s as the
platform of choice for building their code, it's still an ideal starting point for beginners.

IN ST A L L IN G P Y T H O N 3.X
MicrosoFt Windows doesn’t come with Python pre-installed as standard, so you're going to have to install it yourselF manually.
ThankFully, it's an easy process to follow.

Start by opening your web browser to www.python, 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 deFaultsit's a good habit to adopt as sometimes (not
the last digit For each bug Fix and update. ThereFore, don't worry iF 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 Features. On the First screen available, ensure all boxes are ticked
this book will work Fine. and click the Next button.

e* python
Optional Features
About Downloads Documentation Community Success Stories News E'l 0 Documentation
Installs the Python documentation file.

D o w n lo a d t h e la t e s t v e r s io n f o r W in d o w s 0 pip
Installs pip. which can download and install other Python packages.
W w \ ! J! 0 td/tk and IDLE
Looking for Python with a different OS? Python for Windows,
Installs tkinter and the IDLE development environment
Unux/UNIX, Mac OS X, Other
Want to help test development versions of Python? Prereleases, 0 Python test suite
Docker images Installs the standard library test suite.
Looking for Python 2.7? See below for specific releases
Ji 0 py launcher 0 for all users (requires elevation)

1 Installs the global 'py‘ launcher to make it easier to start Python.

nuthnn

Click the download button For version 3.x, and save The next page oF options include some interesting
the File to your Downloads Folder. When the File is additions to Python. Ensure the Associate File with
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 Nowand 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.

& Python 3.9.0 (64-bit) Setup & Python 3.9.0 (64-bit) Setup X

Install Python 3.9.0 (64-bit) Advanced Options


Select Install Now to install Python with default settings, or choose 0 Install for all users
Customize to enable or disable features.
0 Associate files with Python (requires the py launcher)


0 Create shortcuts for installed applications
^ Install Now
C:\Users\dav idVAppDataVLocaf\Prograrm\Python\Python39 0 Add Python to environment variables

Includes IDLE, pip and documentation


0 Precompile standard library
Creates shortcuts and file associations O Download debugging symbols
□ Download debug binaries (requires V S 2017 or later)

Custom ize installation


Choose location and features
Customize install location
| C:\Program Files\Python39 Browse
nuthnn i ith n n

6. Coding & Programming


H ow to S e t Up P ython in W ind ow s

You may need to confirm the installation with the If you now click on the Windows Start button again,
Windows authentication notification. Simply click and this time typeCMDyou'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
the final Python wizard page will allow you to view the latest release command line environment. To enter Python within the command
notes, and follow some online tutorials. line, you need to type: python and press Enter.

5* Python 3.9.0 (64 bit) Setup

Setup w as successful

New to Python? Start with the online tutorial and


d o cum entation. At vour terminal, tvpe 'p v" to launch Pvthon.
or search for Python in your Start menu.

See what’s new in this release, or find more info about u sin a
r * Python on Windows.

p y th o n
for

w in d o w s Close

Windows 10 users will now find the installed 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 inStep 7; note the
section. The first link, Python 3.x (64-bit) - or 32-Bit (more on that three left-facing arrows (»>). While it's a perfectly fine environment,
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.
I Command Prompt
Microsoft Windows [Version 10.0.19041,610]
Best match (c) 2020 Microsoft Corporation. All rights reserved.

IDLE (Python 3.9 64-bit) C:\Users\david>python


App
4 Python 3.9.0 <tags/v3.9.0:9cf67S2, Oct 5 2020, 15:34:46> [MSC v.1927 64 bit (AMD64)] on Win32
Type "help", ’’copyright'’, "credits" or "license" for more information.
» > exit()
p ,dle n~ > ID L E (P v th o n 3 .9 6 4 - b it)
' Integrated Development Envir,, ■ App
C:\Users\david>

Apps

^ idle.bat > ! Open


Search the web 16 Run as administrator

P idle See web results > IL Open file location

Documents (12+) Pin to Start

Folders (2+) "f3 Pin to taskbar

Jb Uninstall

Clicking on the IDLE (Python 3.x 64-bit) link will 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 4CB 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.
[ £ Python 3.9.0 Shell - □ X
File Edit Shell Debug Options Window Help
Python 3.9.0 tcags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on Win32
Type "help", "copyright", "credits” or "licensed" for more information.

Coding & Programming


introducing Python

How to Set Up
Python in Linux
While the Raspberry Pi's operating system contains the latest, stable version of Python,
other Linux distros don't come with Python 3 pre-installed. IP you're not going down
the Pi route, then here's how to check and install Python Por Linux.

P Y T H O N P E N G U IN
Linux is such a versatile operating system that it's oFten diFficult to nail down just one-way of doing something. DiFFerent
distributions go about installing software in different ways, so For this particular tutorial we will stick to Linux Mint.

First you need to ascertain which version of Python Once the update and upgrade completes, enter:
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,
david@david-Mint: - but they can contain vital new elements.

File Edit View Search Terminal Help I FL[e Edit View Search Terminal Help

d a v id @ d a v id -M in t:-$ | Need to ge t 1,4 09 kB o f a r c h iv e s .


A f t e r t h i s o p e r a t io n , 2 3 .6 kB o f a d d it i o n a l d is k sp a ce w i l l be used.
Do you want t o c o n t in u e ? [Y/n] y
G e t : l h ttp :/ / a rc h iv e .u b u n tu .c o m / u b u n tu b io n ic -u p d a t e s / m a in amd64 lib a s o u n d 2 amd6
4 1 . I. 3 - 5 u b u n t u 0 .2 [359 kB]
G e t : 2 h ttp :/ / a rc h iv e .u b u n tu .c o m / u b u n tu b io n ic -u p d a t e s / m a in amd64 lib a s o u n d 2 - d a ta
Next, enter: python --version into the Terminal a l l 1 .1 .3 -5 u b u n tu 0 .2 [3 6 .5 kB]
G e t :3 h ttp :/ / a rc h iv e .u b u n tu .c o m / u b u n tu b io n ic -u p d a t e s / m a in amd64 l i n u x - l i b c - d e v
screen. You should have the output relating to amd64 4 . 1 5 . 0 - 4 4 . 4 7 [1 ,0 1 3 kB]
version 2.x of Python in the display. Most Linux distro come with Fetched 1 ,4 0 9 kB i n 9 s ( 3 , 6 2 3 kB /s)
(R ea d in g d a ta b a se . . . 290768 f i l e s and d i r e c t o r i e s c u r r e n t ly i n s t a l l e d . )
both Python 2 and 3 by default, as there's plenty of code out there P r e p a r in g t o unpack .. . / lib a s o u n d 2 _ l. 1.3-5uburvtu0.2_am d64.deb ...
U np ackin g lib a so u n d 2 :a m d 6 4 ( 1 . 1 .3 -5 u b u n t u 0 .2 ) o v e r ( 1 . 1 .3 -5 u b u n t u 0 .1 ) . ..
still available for Python 2. Now enter: python3 — version. P r e p a r in g t o unpack . . ./ Iib a s o u n d 2 - d a t a _ 1 . 1 .3 -5 u b u n t u 0 . 2 a ll . d e b . ..
U np ackin g lib a s o u n d 2 - d a ta ( 1 . 1 .3 -5 u b u n t u 0 .2 ) o v e r (1 . 1 . 3 - 5 u b u n t u 0 . 1 ) . ..
P r e p a r in g t o unpack . . . / l in u x - l ib c - d e v 4 . 1 5 . 0 - 4 4 . 47_amd64.deb ...
U np ackin g lin u x - lib c - d e v : a m d 6 4 ( 4 . 1 5 .0 - 4 4 .4 7 ) o v e r ( 4 . 1 5 .0 - 4 3 .4 6 ) . . .
david@david-Mint: S e t t in g up lib a s o u n d 2 - d a t a ( 1 . 1 .3 -5 u b u n tu 0 .2 ) . . .

File Edit View Search Terminal Help


david@ david-M int: $ python -v e rsio n
However, if you want the latest, cutting edge
Python 2 . 7 . 1 5 r c l
version, you'll need to build Python from source.
david@ david-M int: $ python3 - v e r s i o n
Start by entering these commands into the Terminal:
Python 3 . 6 . 7
david@ david-M int:~$ | sudo apt-get install build-essential checkinstall
sudo apt-get install libreadline-gplv2-dev
libncursesw5-dev libssl-dev libsqlite3-dev tk-dev
In our case we have both Python 2 and 3 installed. libgdbm-dev libc6-dev libbz2-dev
As long as Python 3.x.x is installed, then the code in
our tutorials will work. It's always worth checking to see if the distro david<adavid-Mint: -

has been updated with the latest versions, enter: sudo apt-get File Edit View Search Terminal Help
d a v id @ d a v id -M in t : S sudo a p t -g e t i n s t a l l b u i l d - e s s e n t i a l c h e c k in s t a l l
update && sudo apL-geL upgrade to update the system. Reading package l i s t s . . . Done
B u ild in g dependency tre e
Reading s t a t e in f o r m a t io n . . . Done
d a v id e d a v id - M in t : - b u i l d - e s s e n t i a l i s a lre a d y th e newest v e r s io n ( 1 2 .4 u b u n t u l) .
The fo llo w in g NEW packages w i l l be i n s t a l l e d
File Edit View Search Terminal Help c h e c k in s t a l l
0 to upgrade, 1 to new ly i n s t a l l , 0 to remove and 3 not to upgrade.
david@david-Mint:-$ python --version Need to ge t 9 7 .1 kB o f a r c h iv e s .
Python 2.7.15rcl A f t e r t h i s o p e ra t io n , 438 kB o f a d d it io n a l d is k space w i l l be used.
david@david-Mint:-$ python3 --version Do you want to c o n tin u e ? [Y/n] y
Python 3.6.7
david@david-Mint:-$ sudo apt-get update && sudo apt-get upgrade
[sudo] password for david: |_____________________________________

6i Coding & Programming


How to Set Up Python in Linux

Open up your Linux web browser and go to the For the GUI IDLE, you'll need to enter the following
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
IDLE runs a different version to the one you installed from source.

37.2
da vid @ d a vid -M in t: -/ D o w n lo a d s/ P yth o n - .

File Edit View Search Terminal Help

david@david-Mint:-/Downloads/Python-3.7.2$ sudo apt-get install idle3


Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
bit idle idle-python3.6 python3-tk tk8.6-blt2.5
Suggested packages:
blt-demo tix python3-tk-dbg
The following NEW packages will be installed
bit idle idle-python3.6 idle3 python3-tk tk8.6-blt2.5
0 to upgrade, 6 to newly install, 0 to remove and 3 not to upgrade.
Need to get 938 kB of archives.
After this operation, 4,221 kB of additional disk space will be used.
Do you want to continue? [Y/n] |

In the Terminal, go to the Downloads folder


by entering: cd Downloads/. Then unzip the
contents of the downloaded Python source code with: tar -xvf
Python-3.Y. Y. tar .xz (replace the Y's with the version numbers
you've downloaded). Now enter the newly unzipped folder with: cd
Python-3 .Y .Y/. You'll also need PIP (Pip Installs Packages), which is
a tool to help you install more modules and extras.
Python - 3 . 7 . 2/Obj e c t s / c l in ic / f l o a t o b j e c t .c .h
Python - 3 . 7 . 2 / O b j e c ts / c lin ic / fu n c o b j e c t .c .h Enter: sudo apt-get install python3-pip
Python - 3 . 7 . 2/Obj e c t s / c lin ic / lo n g o b j e c t .c .h
Python - 3 . 7 . 2/Obj e c t s / c lin ic / d ic t o b j e c t .c .h Once PIP is installed, check for the latest update with:
P ytho n ■ 3 . 7 . 2/Obj e c t s / c l in ic / s t r u c t s e q .c .h
Python - 3 . 7 . 2 / O b j e c t s / c lin ic / t u p le o b j e c t .c .h
Python - 3 . 7 . 2 / O b je c ts / c lin ic / m o d u le o b je c t.c .h pip3 install --upgrade pip
Python - 3 . 7 . 2/Obj e c t s / c lin ic / o d ic t o b j e c t .c .h
Python - 3 . 7 . 2/Obj e c ts/ b y te a rra y o b j e c t . c
Python - 3 . 7 . 2/ O b je c ts/ ty p e o b je c t.c
When complete, close the Terminal and Python 3.x will be available
Python - 3 . 7 . 2/Obj e c t s/ ln o t a b n o t e s . t x t via the Programming section in your distro's menu.
Python - 3 . 7 . 2/Objects/methodobj e c t . c
Python - 3 . 7 . 2/Obj e c t s / t u p le o b j e c t . c
Python - 3 . 7 . 2/Obj e c ts/ o b m a llo c . c davidi&david-Mint: -/Downloads/Python-3.7.2
Python - 3 . 7 . 2/Obj e cts/ o b j e c t .c
Python - 3 . 7 . 2 / O b je c ts / a b st r a c t . c File Edit View Search Terminal Help
Python - 3 . 7 . 2 / O b j e c ts / lis to b j e c t .c
P y th o n -3 . 7 . 2/O bjects/bytes_m ethods.c
david@david-Mint:~/Downloads/Python-3.7.2$ sudo apt-get install python3-pip
Python - 3 . 7 . 2 / O b je c ts / d ic t n o t e s.t x t Reading package lists... Done
Python - 3 . 7 . 2 / O b j e c ts / t y p e s lo t s . in c Building dependency tree
david@ david -M in t:~/D o w n loads$ cd P ytho n -3 .7 .2 / Reading state information... Done
d avid< 3d a vid -M in t: -/D o w nloa d s/ Pyth o n-3. 7 . 2$ The following additional packages will be installed:
python-pip-whl python3-distutils python3-lib2to3
Recommended packages:
pythons-dev python3-setuptools python3-wheel
The following NEW packages will be installed
Within the Python folder, enter: python-pip-whl python3-distutils python3-lib2to3 python3-pip
0 to upgrade, 4 to newly install, 0 to remove and 3 not to upgrade.
. /configure Need to get 1,984 kB of archives.
After this operation, 4,569 kB of additional disk space will be used.
sudo make altinstall Do you want to continue? [Y/n] |

This could take a while, depending on the speed of your computer.


Once finished, enter: python3.7 — version to check the latest
installed version. You now have Python 3.7 installed, alongside older
Python 3.x.x and Python 2.
UietMliy WneTTrei CUmpTTZTig dIJU rrTTKTTTg dydlllbl UpUIISSL BDTrSTTT to
c h e ck in g f o r - - w i t h - s s l - d e f a u l t - s u i t e s . .. python
c o n fig u r e : c r e a t in g . / c o n f ig . s t a t u s
c o n f ig . s t a t u s : c r e a t in g M a k e file . p r e PYTHON ON macOS
c o n f ig . s t a t u s : c r e a t in g M isc/ p ytho n .p c
c o n f ig . s t a t u s : c r e a t in g M is c / p y t h o n -c o n fig .s h
c o n f ig . s t a t u s : c r e a t in g M o d u l e s / l d s o a i x
c o n f ig . s t a t u s : c r e a t in g p y c o n fig .h
Installation of Python on macOS can be done in much the
c r e a t in g M odules/Setup same way as the Windows installation. Simply go to the Python
c r e a t in g M o d u le s/ S e tu p .lo c a l
c r e a t in g M a k e file webpage, hoveryour mouse pointer over the Downloads
link and select Mac OS X from the options. You will then be
I f you want a re le a se b u ild w ith a l l s t a b le o p t im iz a t io n s a c t iv e (PGO, e t c ),
p le a s e run ./ c o n fig u r e --e n a b le - o p t im iz a t io n s
guided to the Python releases for Mac versions, along with the
necessary installers for macOS 64-bit for OS X 10.9 and later.
d a vid @ d a vid -M in t:~ / D o w n lo a d s/ P yth o n -3 .7 .2 $ sudo make a l t i n s t a l l

Coding & Programming


Introducing Python

Python on the Pi
IF you're considering on which platForm to install and use Python, then give som e
thought to one oF the best coding bases available: the Raspberry Pi. The Pi has many
advantages For the coder: it's cheap, easy to use, and extraordinarily Flexible.

THE POW ER O F PI
While having a Far more powerful coding platForm on which to write and test your code is ideal, it's notoFten Feasible. Most oF
us are unable to jump into a several hundred-pound investment when we're starting oFF and this is where the Raspberry Pi can
help out.

While having a Far more powerful coding platForm on which to kits available will provide the Pi with a pre-loaded SD card (with the
write and test your code is ideal, it's not often feasible. Most of us latest Raspbian OS), a case, power socket and cables, this is a good
are unable to jump into a several hundred-pound investment when idea as you could, with very little effort, leave the Pi plugged into the
we're starting oFF and this is where the Raspberry Pi can help out. wall under a desk, while still being able to connect to it and code.

The Raspberry Pi is a fantastic piece of modern hardware that The main advantage is, of course, the extra content that the
has created, or rather re-created, the Fascination we once all had Raspberry Pi Foundation has included out of the box. The reason
about computers, how they work, how to code and Foundation for this is that the Raspberry Pi's goal is to help educate the
level electronics. Thanks to its unique mix of hardware and custom user, whether that’s coding, electronics, or some other aspect of
software, it has proved itself to be an amazing platform on which to computing. To achieve that goal the Pi Foundation includes different
learn how to code; specifically, using Python. IDEs for the user to compile Python code on; as well as both Python
2 and Python 3, there's even a Python library that allows you to
While you're able, with ease, to use the Raspberry Pi to learn to communicate with Minecraft.
code with other programming languages, it's Python that has been
firmly pushed to the Forefront. The Raspberry Pi uses Raspbian as There are other advantages, such as being able to combine Python
its recommended, default operating system. Raspbian is a Linux code with Scratch (an Object-Oriented programming language
OS, or to be more accurate, it's a Debian-based distribution of developed by MIT, For children to understand how coding works) and
Linux. This means that there's already a built-in element of Python being able to code the GPIO connection on the Pi to further control
programming, as opposed to a Fresh installation of Windows 10, any attached robotics or electronics projects. Raspbian also includes
which has no Python-specific base. However, the Raspberry Pi a Sense HAT Emulator (a HAT is a hardware attached piece of
Foundation has gone the extra mile to include a vast range of circuitry that offers different electronics, robotics and motorisation
Python modules, extensions and even examples, out of the box. projects to the Pi), which can be accessed via Python code.
So, essentially, all you need to do is buy a Raspberry Pi, follow the
instructions on how to set one up (by using one of our excellent Consequently, the Raspberry Pi is an excellent coding base, as well
Raspberry Pi guides found at www.bdmpublications.com) and you as a superb project foundation. It is for these, and many other,
can start coding with Python as soon as the desktop has loaded. reasons we've used the Raspberry Pi as our main Python codebase
throughout this title. While the code is written and performed on a
Significantly, there's a lot more to the Raspberry Pi, which makes Pi, you're also able to use it in Windows, other versions of Linux and
it an excellent choice for someone who is starting to learn how to macOS. If the code requires a specific operating system, then, don't
code in Python. The Pi is remarkably easy to set up as a headless worry; we will let you know in the text.
node. This means that, with a few tweaks here and there, you're able
to remotely connect to the Raspberry Pi From any other computer,
Everything you need to learn to code with Python is
or device, on your home network. For example, once you've set up
included with the OS!
the remote connectivity options, you can simply plug the Pi into the
power socket anywhere in your house within range of your wireless IP ^ B ^ Q ^[Se"MHATEmul»lotl ^ :v- 'ir-r-.:- ^ [PylhoiJ53SMI)
HE I
router. As long as the Pi is connected, you will be able to remotely Cdu:si'<>r > t y vr.-tuwa-ra

access the desktop from Windows or macOS as easily as if you were ^ off*# I r* rynon3<iDiQ
(y) Scratch
sitting in front of the Pi with a keyboard and mouse. 5 Graphics • Scratch2
f A«*JS5TV« > mSeos#K4TEmulator
Using this method saves a lot of money, as you don’t need another
keyboard, mouse and monitor, plus, you won't need to allocate
sufficient space to accommodate those extras either. If you're pushed
for space and money, then for around £60, buying one of the many

68 Coding & Programming


Python on the Pi

PI 4-EVER!

Introduced on 24th June 2019, the Raspberry Pi 4 Model B was


a significant leap in terms of Pi performance and hardware
specifications. It was also one of the quickest models, aside from the
original Pi, to sell out. You'll also f ind a pair of USB 3.0 ports, Bluetooth 5.0, and a GPU
that's capable of handing 4K resolutions and OpenGL ES 3.0 graphics
With a new 1,5GHz, 64-bit, quad-core ARM Cortex-A72 processor, In short, the Pi 4 is the most powerful of the current Raspberry Pi
and a choice of 2GB, 4GB, or 8GB memory versions, the Pi 4 is models. However, the different memory versions have an increased
onestep closer to becoming a true desktop computer. In addition, cost. The 2GB version costs £34,4GB is £54, and the 8GB Pi 4 will set
the Pi 4 was launched with the startling decision to include dual- you back £74. Remember to also factor in one or two micro-HDMI
monitor support, in the form of a pair of two micro-HDMI ports. cables with your order.

RASPBIAN BUSTER

In addition to releasing the Pi 4, the Raspberry Pi team also compiled


a new version of the Raspbian operating system, codenamed Buster.

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


offer a few updates. Although on the whole it's very similar in
appearance and operation to the previous version of Raspbian. The
updates are mainly in-line with the 4K's display and playback, giving the
Pi 4 a new set of graphical drivers and performance enhancements.

In short, what you see in this book will work with the Raspberry Pi
4,5 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.

* - a » r j i S e n s e | i - senses py-/home/p' | ,• •l*ylhon35iSM


Coding w ith Python

It's a long way from creating your Fist


Python code to controlling a robot
on Mars, but it's not impossible.
Every advanced and proFessional
Python coder started with the
base Fundamentals, tips and Fixes
mentioned in this section.

With these Foundation Python


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

72 Starting Python for the First Time


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

Coding & Programming


Coding w ith Python

Starting Python for


the First Time
W e're using Python 3 under W indow s 10 for these Following examples. D on't w orry iF
your version oF Python is 3.4.2, or som ething lesser than the current version, as long as
you're using Python 3, the code will work.

ST A R T IN G P Y T H O N
As when learning anything new, you need to start slow. You can pick up the pace as your experience grows, but For now, let’s
just get something appearing on the screen. Don’t worry, you'll soon be coding like a pro!

■ S H j Click on the Windows Start button, and start typing 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.
Li Python 3.7.0 Shell □ X
File Edit Shell Debug Options Window Help
Python 3.7.0 (v3.7.0:lbfScc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bi t (Intel)]
“ "1” 32

>»l

The Shell is where you can enter code and see the 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, iFyou will, where you're able interactions with the system. Integers, which are the inFinite
to try out some simple code and processes. sequence oF whole numbers, can easily be added, subtracted,
multiplied, and so on.
Python 3.7,0Shell - □ X
File Edit Shell Debug Options Window Help
Qfc Python 3.7.0Shell — O X
Python 3.7.0 (v3.7.0:lbfScc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on Win32
Type "copyright", "credits" or "licensed" for more information. File Edit Shell Debug Options Window Help
i Python 3,7,0 <v3.7,0;lbf9cc50S3, Jun 27 2018, 04:0«7TT) [MSC v7l914 32 "bit (Intel)] on Win32
Type "copyright", "credits" or "licensed" for more information.
2+2
» > 8+6
234S3+645545522
645568975
» > 98778642342-12343
98778629999
» > 1287437*43534
56047282358

Coding & Programming


Starting Python for th e F irst Tim e

While that's very interesting, it's not particularly The Python IDLE is a configurable environment. IF
exciting. Instead, try this: you don't like the way the colours are represented,
then you can always change them via Options > Configure IDLE, 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.

L# Python 3.7.0Shell - □
File Edit Shell Debug Options Window Help File Edit Shell Debug Options Window Help
Python 3.7.0 (v3.7.0:Ibf9ec5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)) on Win32 Python 3.7.0 (v3.7.0:Ibf9cc5093, Jun 27 2018, 04:06:47) (MSC v.1914 32 bit (Intel)] i
Type "copyright", "credits" or "license()" for more information. Type "copyright", "credits" or "licensee)" for n : information.

14 14
23453+645545522 » > 23453+645545522
645568975 645568975 bfc Settings
» > 98778642342-12343 > » 98778642342-12343
98778629999 98778629999 Fonts/Tabs Highlights Keys Generi
» > 1287437*43534 » > 12 87437" 43534 Custom Highlighting Highlighting Theme
56047282358 56047282358
» > print("Hello everyone:’ » > print ("Hello every* Select:
Hello everyone! Choose Color for: ® a Built-in Theme
I
Normal Text

(•) Foreground O Background


io custom themes - ■

This is a little more like it, since you've just produced As with most programs available, regardless of the
your First bit oF code. The Print command is Fairly 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 > Configure IDLE and under the Keys tab, you'll see a list of the
case the 'Hello everyone!' bit. current bindings.

» > p r i n t C ’H e llo e ve ryon e :")


H e llo e v e ry o n e !
»> I

You'll have noticed the colour coding within the The Python IDLE is a power interface, and one
Python IDLE. The colours represent different 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 B lu e -U se r 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
O rang e- Commands

IDLE Colour Coding


Colour Use for Examples
Black Data &variables 23.6 area

Green Strings "Hello World"

Purple Functions len() print ()

Orange Commands if for else


Blue User functions get_area()

Dark red Comments #Remember VAT

Light red Error messages S y n t axError:

Coding & Programming


Coding w ith Python

Your First Code


Essentially, you've already written your first piece of code with the print("Hello
everyone!") function from the previous tutorial. However, let's expand that and look at
entering your code and playing around with som e other Python examples.

P LA Y IN G W IT H P Y T H O N
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.

Ifyou've dosed Python 3 IDLE, re-open it as you 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: screen. The quotation marks are defining what's being outputted
to the IDLE Shell, to print the total of 2+2 you’ll need to remove
print("Hello")
the quotes:

Gfc Python 3.7.0 Shell print (2+2)


File Edit Shell Debug Optio
Python 3.7.0 (v3.7.0;lbfScc50S3, Jun 27 2018, 04:06:47) [MSC v.lS-14 32 bit (Intel)]
Win32
l # Python 3.7.0Shell
Type "copyright", "credits" ox "license ()" Tux mure information.
> » print ("Hello") File Edit Shell Debug Options Window Help
Hello Python 3.7.0 (v3.7.0:Ibf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)) >
»>
Type "copyright", "credits" or "license()" for more information.
» > print ("Hello")
Hello
» > print ("2+2")
2+2
> » print (2+2)

As predicted, the word Hello appears in the Shell 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
[jjt 1hc-n SheI
File Edit Shell Debug Options Window Help
lift Python 3,7.0 Shell
Python 3.7.0 (v3.7.0:lbf9ccS093, Jun 27 2018, 04:06:47) [MSC v.1514 32 bit (Intel)]
Win32 File Edit Shell Debug Options Window Help
Type "copyright", "credits” or "license ()" for more information. Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)]
» > print ("Hello") W in32
Hello Type "copyright", "credits" or "license ()" for more information.
» > print ("2+2") » > print ("Hello")
2+2 Hello
»> » > print ("2+2 ")
2+2
» > print (2+2)
0
1
1 0 0
0
0 1 1 1
10 1 ) )
111 0 0
0 1 0 0 1 0
0 0 1 0 1 0 0 0 1 0 1 0 1 » 10 0 0 0 1 1 1 0 1
0 0 1 1 1 1 i 1 ° 10 1 o 0 0
goding & Programming
0 o 0 1 0 1 11 0 0 1 0 1 0 1 1 0 0
0 1 1 1 o ooo o 0 0 0 1 o 0 1 11 l1 oo 0 1 1 0 1
Your First Code

What you have done here is assign the letters a 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:
We now have two variables containing both a first name and a
print(a)
surname, and we can print them independently.
print(b)

[£ Python 3.7.0 Shell - □ X

File Edit Shell Debug Options Window Help


Python 3.7.0 (v3.7.0:Ibf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
1)] on Win32
Type "copyright", "credits" or "license ()" for more information.
> » name="D a v id "
» > print (name)
David
» > surname="Haywaxd"
> » print (surname)
Hayward
»>

The output oF the last step displays the current IF we were to apply the same routine as beFore,
values oFa and b individually, as essentially you've using the + symbol, the name wouldn't appear
asked them to be printed separately. iFyou 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)
We need a space between the two, deFining them as two separate
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.

Python 3.7_0 Shell — □ X

File Edit Shell Debug Options Window Help


Python 3.7.0 (v3.7.0:lbf5cc5Q93, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on
Win32
Type "copyright", "credits" or "licensed" for more information.
> » print ("Hello”)
Hello
» > print ("2+2")
2+2
> » print (2+2)
4
> » a=2
»> b=2
» > print (a)
2
> » print (b)
2
> » print (a+b)
4
»>___________________________________________________________________________

You can play around with diFFerent kinds oF variables In Python 3 we can separate the two variables
together with the Print Function. For example, we with a space by using a comma:
could assign variables For someone's name:
print(name, surname)
name= " David"
Alternatively, you can add the space yourselF:
print(name)
print(name+" "isurname)
G | Python 3.7,0Shell
As you can see, the use oF the comma is much neater.
File Edit Shell Debug Options Window Help
Pychon 3.7.0 (v3.7. 0:lbf9cc5053, Jun 27 2018, 04:06:47) [MSC v.1514 32 bit (Intel)) Congratulations, you've just taken your First steps into the wide
Win32
Type "copyright", ’credits" or "licensed" ^or more information. world oF Python.
» > print ("Hello")
Hello
» > print ("2+2")
0 2+2 [<& Python 3.7.0 Shell
> » print (2+2)
4 File Edit Shell Debug Options Window Help
» > a=2 Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
» > b=2 1)] on Win32
» > print (a)
Type "copyright", "credits" or " l i censed" f°r more information.
2 >>> name="David"
»> print (b)
1 2 >>> p r i n t (name)
» > print (a+b) David

_ 1 4
» > name=" David.”
» > surname*"Hayward"
>>> p r i n t (surname)

11 » > print (name)


David
»>
Hayward
>>> p r i n t (name+surname)

0 1 DavidHayward

0 0 0 1 0 1 0 1 0 o o o 0 0 0 1 i 0 1 » 1 0 0 0 0 0 0 1
0 0 0 l o () 1 1 0 1 0 0 1 1 1 o 0 i 1 1 1 1
Coding & Programming
0 1 0 0 1 0 0 1 i 0 0 0 () o o 1 0 1
O i i i o 0 0 0 0 1 0 1 0 o 0 0 1 0 0 ii o 0 0 1 l 10 10
Coding w ith Python

Saving and Executing


Your Code
While working in the IDLE Shell is perfectly fine for snippets of code, it's not designed
for entering longer program listings. In this section, w e ’ll introduce you to the IDLE
Editor, where m ost of our code will be entered from now on.

E D IT IN G C O D E
You will eventually reach a point where you have to move on From inputting single lines oF code into the Shell. Instead, the
IDLE Editor will allow you to save and execute your Python code.

First, open the Python IDLE Shell. When it's up, dick 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. code, however, you need to first save it. Press F5 and you'll have a
Save...Check box open.
u ti --

Type “copyright", "cieaiss" or "licensed • for more information.

The IDLE Editor is, for all intents and purposes, a 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 foldercalled Python, oryou can
taking an example from the previous tutorial, enter: just dump it wherever you like. Remember to keep a tidy file system,
though, it'll help you out in the future.
print("Hello everyone!")

Coding & Programming


Saving and Executing Yo ur C o d e

Enter a name foryourcode, 'print hello' For 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)

IFyou press F5 now, you'll be asked to save the File again, as it's been
modiFied From beFore.

This is how the vast majority oF your Python code T H IFyou click the OK button the File will be overwritten
j l
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
will diFFer, depending on whether you've requested a separate if you were to edita larger File overwriting can become an issue.
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.
(jf!r "print hello.py - C:/Python Code/print hello.py (5.7.0)*
U Python 3.7.0 Shell □ X File Edit Format Run Options Window Help
File Edit Shell Debug Option Window Help New File Ctrl+N
Python 3.7.0 (v3.7.0:lbf9eeS093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte Open... Ctrl+O
1)] on Win32
Type "copyright", "credits" or "license()" for more information.
Open Module... Alt+M
»> Recent Files ►
= ============= = = RESTART: C:/Python Code/print hello.py = =========== = = = Module Browser Alt+C
Hello everyone!
»> Path Browser

Save Ctrl+S
Save As... Ctrl-*-Shift-*- S
Save Copy As... Alt+Shift+S

Print Window Ctrl+P

Close Alt+ F4
Exit Ctrl+Q

iFyou open the File location oF the saved Python Now create a new File. Close the Editor, and open
code, you'll notice that it ends in a .py extension. a new instance (File > New File From the Shell).
This is the deFault Python filename, any code you create will be Enter the Following, and save it as hello.py:
whatever.py, and any code downloaded From the many Internet
a="Python"
Python resource sites will be .py. Just ensure that the code is written
b="is"
For Python 3.
c="cool!"
print(a, b, c)

We will use this code in the next tutorial.

[& hello.py- C:/Python Code/hello.py (5.7.0) — □ X

File Edit Format Run Options Window Help


a="Python"
b="is"
c="cool"
print (a, t>, c)|

Coding & Programming


Coding w ith Python

Executing Code from


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

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

When you first installed Python, the installation 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.

As you did when launching the Python IDLE, 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 launcha newwindow, w itha 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.

Microsoft Windows [Version 10.0,17763.529] I Microsoft WimJuws [Version 16.0.17763.529]


(c) 2018 Microsoft Corporation. All rights reserved.
<c) 2018 Microsoft Corporation. All rights reserved.
C:\Users\david> C :MJscrs\david>python
Python 3.7.0 (v3.7.0:lbf9ccS093, 3un 27 2918, 94 ;06M7> [MSC v.1911 32 bit (Int«l)] on Win32

» > print(a)

Coding & Programming


Executing Code Prom the Command Line

Now enter exit () to leave the command line 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
previous tutorial, and list the available files within; you should see
the hello.py file. This will execute the code we created, which to remind you is:

Microsoft Windows [Version 10.0.17763.529]


i(c) 2018 Microsoft Corporation. All rights reserved.

ic:\Users\david>python
Python 3.7.0 (v3.7.0:lbf9ccS093, 3un 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] (
Type "help", "copyright", "credits" or "license” for more information.
» > a=2
i»> print(a)
2 j Com mand Prompt
>» e*it()
C :\Users\david>ed\ C:\Python Code>python hello.py
Python is cool!
jc:\>cd "Python Code"

t:\Python Code>dir/w C:\Python Code>


Volume in drive C has no label,
volume Serial Number is 8E47-ABFF

Directory of C:\Python Code

hello.py print hello.py


2 File(s) 73 bytes
2 Dir(s) 76,514,8 !9,728 bytes free

C:\Python Code>

DIFFERENT VERSIONS OF PYTHON

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

C3B Comm and Prompt — □ X

[Microsoft Windows [Version 10.0.17763.529]


(c) 2018 Microsoft Corporation. All rights reserved.

C :\Users\david>path
P A T H=C:\ProgramData\Oracle\lava\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C
:\Windows\system32;C :\Windows;C :\Windows\System32\Wbemj C :\Windows\System32\WindowsPowerShell\vl.0 \ ; C :\Program Files (x86
)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DALjC:\Pr
pgram Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Comp
onents\IPT;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\WINDOWS\system32;C:\WINtX)WS;C:\WINDOWS\System32\Wbe
mjC:\WINDOWS\System32\WindowsPowerShell\vl.0\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files\PuTTY\;C:\WIND
bws\System32\OpenSSH\;C:\Program Files\NVIDIA Corporation\NVIDIA N vDLISR;C:\Users\david\AppData\Local\Programs\Python\Py
phon37-32\Scripts\;C:\Users\david\AppData\Local\Programs\Python\Python37-32\;"C:\Users\david\AppData\Local\Microsoft\Win
dowsApps; C:\Users\david\AppData\local\Programs\Python\Python36-32w; ; C :\Users\david\AppData\Local\Microsoft\WindowsApps

C :\Users\david>

Coding & Programming


Coding w ith Python

Numbers and Expressions


W e've seen som e basic mathematical expressions with Python, simple addition and the
like. N ow let's expand on that, and see just how powerful Python is as a calculator. You
can w ork within the IDLE Shell, or in the Editor, whichever you like.

IT'S A LL MATHS, MAN


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.

Open up the GUI version of Python 3, as mentioned You can use all [ + Python 3.7,0 Shell

you can use either the Shell or the Editor. For the the customary File Edit Shell Debug Options W indow
Python 3.7.0 (v 3 .7.O :lbf9cc5093,
time being, we're going to use the Shell. If you've opted to use a Mathematical operations: divide, 1)] on Win32
third-party text editor, note thatyou need to get to the IDLE Shell multiply, brackets and so on. Type "copyright", "credits" or "I
> » 2+2
for this part of the tutorial. Practise with a few, for example: 4
» > 54356+34553245
|_^r Python 3.7,0 Shell — □ X 1/2 34607601
» > 99867344*27344434221
File Edit Shell Debug Options Window Help 6/2
2730821012201179024
Python 3.7.0 (v3.7.0:Ibf9cc5093, Jun 27 2018, 0-4:06:47) [MSC v.1914 32 bit (Inte
1 )] o n W in 3 2
2+2*3 > » 1/2
0.5
Type "copyright", "credits" or "license()" for more information. (1+2)+(3*4)
>» >» 6/2
3.0
> » 2+2*3
8
>» (l+2>+(3*4>
15
»>

In the Shell enter the following: As you've no Python 3.7.0 Shell

doubt noticed, File Edit Shell Debug O p tio n s Windci*4


8
2+2 Python 3.7.0 (v3.7.0: lbf 9cc509:i
division produces a decimal
54356+34553245 1) ] on wxn.32
number. In Python, these are Ty p e "copyright", "credits" or
99867344*27344484221
called floats, or floating point » > 2+2
4
As you can see, Python can handle some quite large numbers. arithmetic. If however, you » > 54356+34 5 5 3 2 4 5
need an integer as opposed to a 34607601
U |r Python 3.7.0 Shell — □ X » > 9 9 8 6 7 3 4 4*27344484221
decimal answer, then you can use
File Edit Shell Debug Options Window Help 2 7 3 0 8 2 1012201179024
["Python 3.7.0 (v3.7.0:Ibf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
a double slash: » > 1/2
1)] on Win32 0.5
Type "copyright", "credits" or "license()" for more information. 1//2 > » 6/2
> » 2+2
4 6//2 3.0
» > 54356+34553245 » > 2+2*3
34607601 8
» > 99867344*27344484221 and so on.
> » (1+2) + (3*4)
2730821012201179024
»> 15
»> 1//2
0
» > 6//2
3

81 Coding & Programming


Numbers and Expressions

File Edit Shell Debug Options Window Help


You can also use L I Python 3.7.0 Shell
R R T b This will be Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27
an operation to File Edit Shell Debug Options Window 1)] on Win32
E i l i i l i F displayed as Type "copyright", "credits" or "license)
Python 3.7.0 (v3.7.0 :Ibf9cc5093, .
see the remainder left over from 1 )] on Win32 '0b11', converting the integer > » 2+2
4
division. For example: Type "copyright", "credits" or "1: into binary, and adding the preFix » > 54356+34553245
» > 2+2 34607601
4 Ob to the front. If you want to » > 99867344*27344484221
10/3 » > 54356+34553245
2730821012201175024
remove the Ob preFix, then you »> 1/2
34607601 0.5
will display 3.333333333, which » > 59867344*27344484221 can use: > » 6/2
2730821012201179024 3.0
is, of course, 3.3-recurring. If you > » 2+2*3
» > 1/2 format(3, 'b') 8
now enter: 0.5
>» (1+2) +(3*4)
» > 6/2
The Format command converts 15
1 o%:> 3.0 » > 1//2
» > 2+2 *3 a value, the number 3, to a 0
8 »> 6 //2
This will display 1, which is the »> (l+2}+ (3*4) Formatted representation 3
» > 10/3
remainder left over from dividing 15 as controlled by the format 3.3333333333333335
» > 1//2 > » 1Q%3
10 by 3. 0 specification, the ‘b’ part. 1
»> 6//2 » > 2**3
8
3
» > 10**10
»> 10/3 10000000000
3.3333333333333335 » > bin (3)
» > 10%3 ■Obll1
1 » > format(3,’b ■)
'll*
»> \ »>

File Edit Shell Debug Options Window H*3


8
Next up we Python 3.7.0 (v3.7.0:lbf9cc5093, Jx
A Boolean Expression is a logical statement that will
have the power 1)] o n W i n 3 2 either be true or False. We can use these to compare
Type "copyright", " c r e d i t s " or "lie
operator, or exponentiation »> 2+2 data, and test to see if it's equal to, less than, or greater than. Try
if you want to be technical. 4 this in a New File:
» > 54356+34553245
To work out the power of 34607601 [_jjf F-.tr ■n 1 ~ If ? -r tv - - -

» > 99867344*27344484221 a = 6 file Edit Format Run Options Window


something you can use a 2730821012201179024 a - 6
b = 7 b = 7
double multiplication symbol, »> 1/2 print<1, a = 6)
0.5 print(1, a == 6) print<2 , a “ 7)
or double-staron the keyboard: »> 6 /2
3.0
print (2, a == 7) print <4'
print<5,
a — 7 ar.d b — 7)
r.or a — 7 a t:! b == 7)
print <6, a “ 7 o r b " 7)
2**3 » > 2+2*3 print(3, a == 6 and b = = 7) print <7, a = 7 o r b = 6)
8 print(8, not (a == 7 and b = 6)
10**10 » > (1+2} + (3*4) print(4, a == 7 and b = = 7) print<S, a ” 7 and b “ 6)
15
»>
print (5, not a s e a l 7 and b 7)
Essentially, it's 2x2x2, but we're 1//2
0 print(6, a == 7 or b S * s ± 7)
sure you already know the »> 6 //2
3 print (7, a == 7 or Sf ^ *6)
basics behind maths operators. » > 10/3 print (8, not (a 3"= 7 and b == 6) )
This is how you would work it 3.3333333333333335
» > 10%3 print (9, not a == 7 and b H M 61
out in Python. 1
» > 2* *3
8
» > 10**10
10000000000
»>l

P y t h o n 3.7.0 ( v 3.7.0:lbf9cc5093, Jun


Numbers and 1)] o n W i n32 Execute the code from Step 9, and you'll see a
Typ e "copyright", "credits" or "licer
expressions don't » > 2+2 series of True or False statements depending on
4
stop there. Python has numerous the result of the two defining values: 6 and 7. It's an extension of
» > 54356 + 3 4 5 5 3 2 4 5
built-in functions to work out 34607601 what we've looked at, and an important part oF programming.
> » 99867344*27344484221
sets of numbers, absolute values, 273 0 8 2 1 0 1 2 2 0 1 1 7 9 0 2 4
> » 1 /2 L A Python 3.7.0 Shell □
complex numbers, and a host of 0.5
File Edit Shell Debug Options Window Help
Mathematical expressions and > » 6 /2
3.0 Python 3.7.0 (v 3 .7.0:l b f 9 c c 5 0 9 3 , Jun 27 2018, 04:06:47) [MSC v .191 4 32 bit
Pythogarian tongue-twisters. For » > 2 + 2*3 1)] on Win32
8 Type "copyright", "credits" or " l i c e n s e ()" for mor e information.
example, to convert a number to » > (1+2) + (3*4) »>
=== = = = = == = ====== === RESTART: C:/Py t h o n C o d e / B o o leantest.py
binary, use: 15
1 True
> » 1//2
2 False
0
bin (3) > » 6//2
3 True
4 False
3
5 True
» > 10/3
6 True
3.3333333333333335
7 False
» > 1Q%3
8 True
1 9 False
» > 2**3
» >
8
» > 1 0 ** 1 0
10000000000
» > b i n (3)
■Obll'
»>l

Coding & Programming


Coding w ith Python

Using Comments
W hen writing your code, the Plow, what each variable does, how the overall program
will operate and so on, is all inside your head. Another program m er could Follow the
code line by line, but w hen the code starts to hit thousands oP lines, things get a little
diPPicult to read.

#CO M M EN TS!
A method used by most programmers for keeping their code readable, is by commenting on certain sections. For example, if a
variable is used, the programmer comments on what it’s supposed to do. It’s just good practise.

We'll start by creating a new instance of the IDLE 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=lO
and others of what's going on, without the user being aware.
print("The value of A is,", a)
Python 3.7.0 Shell — □ X
Save the Pile, and execute the code.
File Edit Shell Debug Options Window Help
Python 3.7.0 (v3.7.0:lbfScc5093, Jun 27 2018, 04:06:47) [MSC v.1514 32 bic (Inte
[j|r Comm ents.py - C:/Python Code/Com m ents.py (3.7.0) 1)] on Win32
Type "copyright", "credits" or "license()" for more information.
File Edit Format Run Options W indow Help >»
==================== RESTART: C:/Python Code/Comment3 .py ====================
a=10 The value of A is, 10
p r i n t ( "The value of A is,", a) >»
==================== RESTART: C:/Python Code/Comments.py ====================
The value of A is, 10

Running the code will return the line: The value of Let's assume that the variable A we've created is
A is, 10 into the IDLE Shell w indow-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-l


a=10 print("You've just lost a life I'')
# Print the current value of A print("You now have", a, "lives left!")
print("The value of A is,", a)
ii *Comments.py - C:/Python Code/Comments.py (3.7.0)*
l * *Comments.py - C:/Python Code/Comments.py (3.7.0)* File Edit Format Run Options Window Help

File Edit Format Run Options W indow Help # Set the start value of A to 1C
# Set the start value of A to 10 a=10
a=10
# Print the current value of A
iprint("The value of A is,”, a )
0 # Print the current value of A
p r i n t ("The value of A is,", a )
a=a-l
p r i n t ("You*ve just lost a l i f e !r
p r i n t ("You n ow have", a , "lives left!") 0 0
0
0 1 1 1
10 1 ) 0
1 1 1 0 0
0 1 o |_____________ 0
0 0 1 0 1 0 « 0 0 1 o~ io o 10 0 0 0 1 1 1
110 1 o ii o 1 1 1 1 0 1 0 1 o 0 0
goding & Programming
0 0 1 0 1 0 10 1 0 0 0 1 1 0
0 111 o ooo i o 0 0 0 1 0 0 111 1 o o 0 1 1 1
Using Comments

While we know that the variable A denotes number Inline Comments are comments that follow a
of lives and the player hasjust lost one, a casual section of code. Take our examples from above,
viewer, or someone checking the code, may not know. Imagine fora 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 a re.
print("The value of A is,", a) # Print the current
L& Python 3.7.0 Shell - □ X value of A
File Edit Shell Debug Options Window Help a=a-l # Player lost a life!
Python 3.7.0 <v3.7.0:Ibf5cc5053, Jun 27 2018, 04:06:47) [MSC v.1514 32 bit (Inte
1)] on Win32
print("You've just lost a life!")
Typ e "copyright", "credits" or "license()" for more information. print("You now have", a, "lives left!") # Inform

= = = = = = = = = = = = = = RESTART: C:/Python Code/Comments.py = = = = = = = = = = = = = = = = player, and display current value of A (lives)
The value of A is, 10
»>
============= = = = = = = RESTART: C:/Python Code/Comments.py ============ = = ====== [_£ "Comments.py - C:/Python Code/Gomments.py (3.7.0)' — □ X
The value of A is, 10 File Edit Format Run Options Window Help
»> a=10 t Sec che scare value of A co 10
==== = = = = = = == = == RESTART: C:/Python Code/Comments.py == = = = = = = = = =
print("The value of A is,", a) t Print the current value of A
T he value of A is, 10 a=a-l it Player lose a life E
You've just lost a life! print("You've just lost a life!")
You n ow have 9 lives left! print("You now have", a, "lives left!") ♦ Inform player, and display current of A (lives)]
»>l

Essentially, the new code together with comments 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
the First print statement, you would use:
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! |j^f *C o m m e n ts.p y - C:/Pyth on C o de./Com m en ts.py (3.7.0)*
a=a-l File Edit Form at Run O p tio n s W in d o w Help
# Inform player, and display current value of A # Set the start value of A to 10
(lives) 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)|
# Player lost a life!
a=a-l
[A -Comm.nB.py-. C:/Python Codc/Conun'rb.py (3.7®* — □ X
File Edit Format Run Options Window Help
# Inform player, and display current of A (lives)
t Sec che start value of A to 10 print("You1ve just lost a life!")
a=10
# Print che current value of A
print("You now have", a, "lives left!")
print("The value of A is,”, a)
# Player lost a life!
a=a-l
t Inform player, and display current of A (lives)|
print("You1ve just lost a life!")
print("You now have", a, "lives left!")

You can use comments in different ways. For 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
M 1 1 1 1 1 ft i n . 1 1 n ( works really well. '' '
14 'Comments,py - C:/Python Code/Commerits,py (3.7.0)*
— ______________________________________________ _______ d_ _____ n n
0 File Edit Format Run Options Window Help 'Comments.py • C:/Python Code/Comments.py (3.7.0)*
# This is che besc game ever, and has been developed by a crack squad of Python experts
# who haven't slept or washed in weeks. Despite being very smelly, the code at least
File Edit Format Run Options Window Help
0
t works really well. |
rack squad cf Python experts
U 0
# Set the start value of A to 10
a=10
it Print the current value cf A t Set the > 10
0 1 1 print("The value of A is,”, a) 1»10
t Print the current value of A
10 1 # Player lost a life!
a=a-l
print("The value of A is,”, a)
4 Player lost a life!

1 1 # Inform player, and display current of A (lives)


print ("You" ve just lost a life.'")
print ("You now have"1, a , "lives left!")
a=a-l
t Inform player, and display current of A (lives)
print("You”ve just lost a life!")
0
print(“You now have", a, "lives left!") 0
10 1 o 10
1

0 0 0 10 10 1 1 oi oooooo i
0

1
o
o

0 0 0 l o () 1 1 0 1 o 0 ' 11 o 0 i 111 1 1 Coding & Programming


1 0 0 1o 0 i * 00 10 1 11 0
O

0
o
o

Ol l i o 0 0 0 0 10 1 o00 0 1 00 1111 i o o 0 1 i 10 0 0 1
Coding w ith Python

Working with Variables


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

V A R IO U S V A R IA B L E S
We'll be working with the Python 3 IDLE Shell in this tutorial. IFyou haven't already, open Python 3 or close down the previous
IDLE Shell to clear up any old code.

In some programming languages, you're required 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 asa 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" (useyourown 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.

[*|f Python 3.7.0 Shell — O X [_& Python 3.7.0 Shell — □ X

File Edit Shell Debug Options Window Help File Edit Shell Debug Options Window Help
Python 3.7.0 (v3.7.0:Ibf9cc5093, Jun 27 201S, 04:06:47) [MSC v.1914 32 bit (Inte Python 3.7.0 (V3.7.0:lbfScc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)
1)] on Win32 ] on Win32
Type "copyright", "credits" or " l i c e n s e O " for more information. Type "copyright", "credits" or "license()" for more information.
> » name=" David Hayward" » > name*"David Hayward"
> » print (name) » > print (name)
D a vid Hayward David Hayward
> » type (name)
l <class 1str*>
» > title="Descended from Celts"
>>> p r i n t (name + ": " + title)
David Hayward: Descended from Celts
»>

on 3.7,0 Shell
You can check the type of variable in use by issuing We can also
File Edit Shell Debug Options Window Help
the type () command, placing the name of the combine variables Python 3.7.0 (v3.7.0: lbf9cc50S3, Jun ;l
variable inside the brackets. In our example, this would be: within another variable. For ] on Win32
Type "copyright", "credits" or "licen:
type (name). Add a new string variable: title="Descended example, to combine both name > » n a m e="David Hayward"
» > print (name)
from Celts". and title variables into a new D avid Hayward
» > type (name)
variable, we use: Cclass ’s t r ^
[j& Python 3.7.3 Shell
» > tit!e="Descended from Celts"
File Edit Shell Debug Options Window Help character=name + » > p r int (name + " + title)
Python 3.7.0 (v3.7.0:Ibf5cc5093 Jun 27 2018, 04:06:47) [MSC ’ ,1914 32 bit (Intel) D avid Hayward: Descended f r o m Celts
] on Win32 title >>> character=narae + ■: " + title
Type "copyright", "credits" or "license()" for more infoxmati( » > print (character)
» > name="David Hayward" D avid Hayward: Descended fro m Celts
> » print (name)
Then output the content of the » > age=46
David Hayward new variable as: » > type (age)
» > type (name) cclass ’int'>
cclass 1str'> I »>
> » title="Descended from Celt print (character)
»>

Numbers are stored as different


variables:

age=44
Type (age)
0 1 1
10 1 Which, as we know, are integers.

111 0 u
0 0

A A A
0 0 1 0 1 0 1 0 o 1 0 0 10 0 0 0 0 1 1
o 1 1 1 0 10 1 0 0 0
Coding & Programming
o 0 1 0 o1 0 C 1 0 1 1
0 111 o ooo 1 0 00 1 0 111 1
1 oo 0 1 l 1 0 0 1
Working with Variables

However, you can't combine both strings and 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
] on Win32
Type "copyright", "credits" or "license()" for more information.
worked with.
» > name="David Hayward"
» > print (name)
L # Python 3.7.0 Shell - □ ~ ~ xl
David Hayward
» > type (name) File Edit Shell Debug Options Window Help
<class 'str’> Python 3.7.0 (v3.7.0:Ibf5cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
» > title="Descended from Celts" 1)] on Win32
> » print (name + ": " + title) Type "copyright", "credits" or "license()" for more information.
David Hayward: Descended from Celts > » age=input ("How old are you? ")
» > character=name + ": " + title
How old are you? 46
» > print (character)
> » type (age)
David Hayward: Descended from Celts <class 'str’>
» > age=46
» > age + 10
» > type (age)
Traceback (most recent call l a s t ) :
<class •i n t ‘>
File "<pyshell#2>", line 1, in <module>
» > print (name+age)
age + 1 0
Traceback (most recent call l a st):
TypeError: can only concatenate str (not "int") to str
File "<pyshell#S>", line l r in <module>
> » int (age) + 10
print (name+age)
56
TypeError: can only concatenate str (not "int") to str
>» »>

This is a process known as Typecasting. The Python The use of Typecasting is also important when
code is: dealing with floating pointarithmetic; remember:
numbers that have a decimal point in them. For example, enter:
print (character + " is " + str(age) + " years
old.") shirt=l9.99

Alternatively, you can use: Now enter: type (shirt) and you'll see that Python has allocated
the number as a 'float', because the value contains a decimal point.
print (character, "is", age, "years old.")
L i Python 3.7.0 Shell
Notice again that in the last example, you don't need the spaces
i File Edit Shell Debug Options Window Help
between the words in quotes, as the commas treat each argument Python 3.7.0 (v3.7.0:lbf9cc5053, Jun 27 2018, 04:06:47) [MSC v.1514 32 bit (Inte
to print separately. 1)] on Win32
Type "copyright", "credits" or "license()" for more information.
» > shirt=19.99
David Hayward: Descended fro m Celts » > type (shirt)
>>> age=46 <class 'float'>
>>> type(age) >»
<class ’i n t 1>
> » print (name+age)
Traceback (most recent call l ast):
File "<pyshell#9>", line 1, in <module>
print (name+age)
TypeError: can only concatenate str (not "int") to str
> » print (character + " is " + str (age) + " years old.")
David Hayward: Descended fro m Celts is 46 years old.
>>> print (character, "is", age, "years old.”)
David Hayward: Descended fro m Celts is 46 years old.

Another example of Typecasting is when you ask When combining integers and floats Python
for input from the user, such as a number, for usually converts the integer to a float, but should
example, enter: the reverse ever be applied, it's worth remembering that Python
doesn't return the exact value. When converting a float to an
age= input ("How old are you? ")
integer, Python will always round down to the nearest integer,
All data stored from the Input command is stored as a string variable. called truncating; in ourcase instead of 19.99, it becomes 19.

Python 3.7.0 Shell I j | Python 3.7.0 Shell

File Edit Shell Debug Options Window Help File Edit Shell Debug Options Window Help
Python 3.7.0 (v3.7.0:lbf9cc5Q93, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte Python 3.7.0 (v3.7.0:lbfScc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
1)] on Win32 1)] on Win32
Type "copyright", "credits" or "license()" for more information. Type "copyright", "credits" or "license))" for more information.
» > age=input ("How o ld are you? ") > » shirt=19.99
H o w old are you? 46 > » type (shirt)
> » type (age) cclass 1float'>
<class 'str‘> > » int (shirt)
»> 19
>» 0 0
0
i

1 1 1 0 0
J 4 0 1 0
10 1 oToooood l
O

" 0 1 0 1 0 1 0 1 o
o
o

0 0 1
000 1 0 1 o 0 1 1 1 o 0 i 1 1 1 1
Coding & Programming
0 0 1 0 0 i 1 0 0 0 0 o 0 1 0 1 1 1
0 1 1 1 0 000 1 o0 0 0 1 o 0 1 i oo 0 1 i
i 10
Coding with Python

User Input
W e've seen som e 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.

U S E R F R IE N D L Y
The type of input you want From the user will depend greatly on the type oF program you're coding. A game, For example, may
ask For a character's name, whereas a database can ask For personal details.

K C R S I IF it's not already, open the Python 3 IDLE Shell, Now that we have the user's name stored in a
■ U S a n d 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") print ("Welcome", firstname, surname, ". I hope


firstname=input ("What is your first name? ") you're well today.")
print("Thanks .")
[ 'Userlnputpy - G/Python Code/Userlnput-py (3.7.0)' — □
surname=input("And what is your surname? ")
File Edit Format Run Options Window Help
p r i n t (" H e l l o .")
[jfc "Untitled" firstn a m e = i n p u t ("What is youx first name? ")
p r i n t ("Th a n k s .")
sur n a m e = i n p u t ("And what is your surname? ")
File Edit Form at Run Options W in d ow Help
p r i n t ("Welcome", firstname, surname,". I hope you're well today.")
print("Hello.")
firstname=input("What is your first name? ")
print("Thanks.">
surname=input("And what is your surname? ">

Save and execute the code, and, as you no doubt 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.
Foryour First name, storing it as the variable firstname, 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:

\ Jft Python 3.7.0 Shell


print("Welcome", firstname, surname+". I hope
File Edit Shell Debug Options Window Help you're well today.")
Python 3.7.0 <v3.7.0:Ibff9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
1)] on Win32
I * *Userlnput.py - Cr/Python Code/Userlnput.py (3.7.0)*
Type "copyright", "credits" or "license()" for more information.
»> File Edit Format Run Options Window Help
= ========= = ===== ==== RESTART: C:/Python Code/UserInput.py ====================
p r i n t ("Hello.")
Hello. firstname=input("What is your first name? ")
What is your first name? David p r i n t ("Thanks.")
Thanks.
surname=input("And what is your surname? ")
A n d what is your surname? Hayward
print ("Welcome", firstname, surname-tj". I hope you're well today.")
»>

1 0 0
0
0 1 1 1
10 1
11 0 0
o 0 0

A A A «
0 1 0 1 0 1 0 O lo 1 0 o 1 0 0 0 0 1 1 1
o 1 1 1 1 0 0
goding & Programming
0 01 0 1 0 0 0
0 111 o ooo 1 o o0 0 1 0 0 111 0 0 11 1 0 0 1
User Input

You don't always have to include quoted text within Whatyou'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
print("Hello. What's your name?")
unhindered. If, however, they entera name other than David, the
name=input ()
guard challenges them to a fight.
(_■& *Userlnput.py - C:/Python Code/Userlnput,py (3.7.0)* — □ X
li^hon 3.7.0Shell - □ X
File Edit Format Run Options Window Help File Edit Shell Debug Options Window Help

p r i n t ("Hello. What is your name?") 1)1 nn hins?


type "copyright", "ereaits" or "license!)" lor Bore lnfonucien.
name=input ()| r l, . .....,

The code from the previous step is often regarded 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
print("Halt! Who goes there?") print ('"'Input a rate and a distance")
name=input() rate = float (input ("Rate : ") )

(jjr *Userlnput.py - C:/Python Code/Userlnput.py (3.7.0)* — O X \Jjfr ’ Userlnput.py - C:/Python Code/Userlnput.py (3.7.0)* — □ X

File Edit Format Run Options Window Help File Edit Format Run Options Window Help
p r i n t ("Halt! Who goes there?”) # Code to calculate rate and distance
n a m e = i n p u t () p r i n t ("Input a rate and a distance")
rate = f l o at(input("Rate: "))|

It's a good start to a text adventure game, perhaps? And to finalise the rate and distance code, we can add:
Now we can expand on it, and use the raw input
distance = float (input ("Distance: ") )
from the user to flesh out the game a little:
p r i n t ( " T i m e , (distance / rate))
if name=="David":
Save and execute the code, and enter some numbers. Using the
print("Welcome, good sir. You may pass.")
float(input element, we've told Python that anything entered is a
else:
Toating point number rather than a string.
print("I know you not. Prepare for battle!")

[<|f ’ Userlnput.py - C:/Pythorv Code/Userlnput.py (3.7.0)*


[ i Python3.7.0Shell - □ X HUier
File Edit Format Run Options Window Help File Ffto Shell flehug Options Window HHp File Edit F-ottnee Hun Upbons Window Help
print: ("Hale! W ho goes t h ere?”)
n a m e = i n p u t () Type .copyright-, — edit.- or .lic e n ,. (). -o r. » " * « « « « -
0 if n a m e = " D a v i d " : (
p r i n t ("Welcome, good sir. You m a y pass.")
1 print ("I icnow you not. Prepare for battle!”)
l l

) “ 2‘0 0 0
1 )
0
0 1 1 1
10 1
1 1 1
0 1 i> (

0 0 0 1 0 1 0 0 o 0 0 1 1 0 1 o 1 0 0 0 0 0 0 1 1 0 1
000 1 0 110 1 o o i 1 1 i
Coding & Programming
0 0 0 1 0 0 0 1 0 1 1 1
0 1 1 1 0 0 0 0 00 0 0 1 0 M i l l 00 11 o i 0
Coding w ith 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
enables you to define your own function.

FUN KY FUNCTIONS
A Function is a command thatyou 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.

It's not only data that a Function works on. Functions 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 (enFer the text editor For this example):
by brackets. For example, len(), list(), or type().
name=input ("Enter your surname: ")
USr ‘ Python 3.7.0 Shell* - □ X count=len(name)
File Edit Shell Debug Options Window Help print ("Your surname has", count, "letters in
Python 3.7.0 (v3.7.0:lbf9cc50S3, Jun 27 2018, 04:06:47) [MSC v.1514 32 bit (Inte
1)] on Win32 it.")
Type "copyright", "credits" or "license()" for more information.
» > len()| Press F5 and save the code to execute it.

A Function takes data, usually a variable, works on 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 Flowever, to view the list oF built-in Functions available to Python
inside the brackets, so iFyou wanted to know how many letters 3, navigate to https://docs.pytFion.Org/3/library/Functions.html.
are in the word antidisestablishmentarianism, then you'd enter: These are the pre-deFined Functions, but since users have created
len ("antidisestablishmentarianism"), and the num ber28 many more, they're not the only ones available.
would return.
[ j j i Python 3.7.0 Shell — □ X

Python 3.7.0 Shell — □ X File Edit Shell Debug Options Window Help
Python 3.7.0 (v3.7.0:lbf9cc5053, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
| File Edit Shell Debug Options Window Help
1)1 on Win32
Python 3.7.0 (v3.7.0:lbfScc50S3, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte Type "copyright", "credits" or "license()" for more information.
1)] on Win32 >>> l e n ("antidisestablishmentarianism")
Type "copyright", "credits" or "license()" for mo r e information. 28
» > len ("antidisestablishmentarianism") >»
28 ==================== RESTART: C:/Python Code/NameCount.p y == = =========== ======
»> Enter your s urname: Hayward
Your name has 7 letters in it.
> » import math
> »

81 Coding & Programming


Creating Functions

■ T H jJ ' Additional Functions can be added to Python To use a Function From a module, enter the name oF
through modules. Python hasa 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).

life Python 3.7.0 Shell - □ X

| File Edit Shell Debug Options Window Help________________________________________________________________________


2. Built-in Functions
Python 3.7.0 <v3.7.0:lbfScc5093, Jun 27 2018, 04:06:47) [MSC v.1514 32 bit (Inte
1)] on Win32
Type "copyright", "credits" or "lic e n s e ()" for more information.
» > l e n ("antidisestablishmentarianism")
28
»>
=======------ = RES T A R T : C:/Python Code/NameCount .py ~r---- 1
----- — =======
Enter your s urname: Hayward
Your name has 7 letters in it,
» > import math
» > math .sqrt (16)
4.0

FORGING FUNCTIONS
There are many different functions, created by other Python programmers, which you can import and you'll undoubtedly come
across some excellent examples in the future. However, you can also create your own with the def command.

Choose File > New File to enter the editor, let's To modify it further, delete the Hello("David") line,
create a Function called Hello that will greet a the last line in the script, and press Ctrl+S to save
user. Enter: the new script. Close the Editor and create a new file (File > New
File). Enter the following:

■print ("Hello")? |from Hello import Hellol

Press F5 to save and run the script. You'll see Hello in the Shell, Press F5 to save and execute the code.
type in Hello() and it’ll return the new function.

Coding & Programming


Coding w ith Python

Conditions and Loops


Conditions and loops are what make a program interesting, they can be simple or rather
complex. How you use them depends greatly on what the program is trying to achieve,
they could be the number of lives left in a game, or just displaying a countdown.

T R U E C O N D IT IO N S
Keeping conditions simple, to begin with, makes learning to program a more enjoyable experience. Let's start then by
checking if something is TRUE, then doing something else iF it isn’t.

Let's create a new Python program that will ask the 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 printa 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:
print (word, "is a four-letter word. Well done.")

The double equal sign (==) check if something is equal to


something else.

[jjf ’ Untitled* — □ X

File Edit Format Run Options Window Help


w o r d = i n p u t ("Please enter a four-letter word: ")
word_length=len(word)
if word length = 4:
print (word, "is a four-letter word. Well done.")

Now we can create a new variable, then use the len K H B The colon at the end of if tells Python that if this
m
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)
[«|i 'Untitled* — □ X
if word length — 4:
File Edit Format Run Options Window Help
w o r d = i n p u t ("Please enter a four-letter word: ") print (word, "is a four-letter word. Well
word_length=len(word)
done .")
else:
print (word, "is not a four-letter word.")

U|r 'Untitled* — □ X

File Edit Format Run Options Window Help


w o r d = i n p u t ("Please enter a four-letter word: ")
word_length=len (word)
if word_length == 4:
print (word, "is a four-letter word. Well done.")

print (word, "is not a four-letter word.")

91 Coding & Programming


Conditions and Loops

Press F5 and save the code to execute it. Enter Now expand the code to include otherconditions.
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: ")
five-letter word. The Shell will display that it’s not a four-letter word.
word length=len(word)
if word length 4:
print (word, "Is a four-letter word. Well
done.")
elif word_length =— 3:
print (word, "is a three-letter word. Try again.")
else:
print (word, "is not a four-letter word.")

u IA : o«weCoo, *.•
tit. Edit SMI 9*6-49 Option* Window M*lp Edit M M Sen Option, m , Hdp
5>}H! «in32 IV>' J“ * “ *** **■ **■ ’ ’ ** 611 ■ Jits itniTn*l*Mtie*dl
Typ. -copyright", "cr*dlt»" ar for » r * .nfar-arlan. *v,<i_i,„gth. — •;
■ ........................... RESTART; C:/Python r.y ................................ t-ord length — S;
pclet (word. * u V arH>l(IXei n M i Try again. *|
print iwora, *M not • tour letter voro.-|

n r

rieaw enter . four letter word; Em V iU

LOOPS
Although a loop looks quite similar to a condition, they are somewhat different in their operation. A loop will run through the
same block of code a number of times, usually with the support of a condition.

Let's start with a simple while statement. Like if, The for loop, is another example. For is used to
this will check to see if something
's s / y /iss sTRUE,
s s s s s s sthen
s s f/ s run
s s s s jj J i loop over a range of data, usually a list stored as
the indented code: variables inside square brackets. For example:

words=["Cat", "Dog", "Unicorn"]|

for word in words:!

'Untitled' Dcbuij Opliuaiv Window Help nit Hit femm Run Opiipni Window
I Python 3.7,0 (v3.7.0:ibf6ec5053, Jun 27 2013, 04:0fi:47> [MS2 v.ISH 32 bit (Inc
File Edit Format Run Options Window Help 1) ] on Win32

7: /Python r<ia*/ 3nop1. py =

- restart : c:/python code/

•••••••••••••••••••••••••••••••••••••••••••••••••••a*

The difference between if and while is that when 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
than 10. With each loop, it prints the current value of x, then adds
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
creates a list between the first and last numbers used.

- RESTART: 0:/Pyr.hnn Ci-xWlrvnpl .py - File Edrt Shell Debug Option. Window Help_____________

IPython 3.7.0 (V3.7.0;ujt?sc5« 3, 9un 27 2918, 99:9 [M5C y.1919 32 B it (Inte

Type "copyright", "credits" or "licensed" *or reor

■ RESTART: T:/Python CrvWlOft

- RESTART : C:/Python CcxWleopl. p

Coding & Programming


Coding w ith Python

Python Modules
W e've mentioned modules previously, using the Math module as an example, but since
using modules is such a large part of getting the m ost Prom Python it's worth dedicating
a little more time to them.

M A S T E R IN G M O D U L E S
Think oF modules as an extension that's imported into your Python code to enhance and extend its capabilities. There are
countless modules available, and as we've seen, you can even make your own.

Although good, the built-in Functions within Python 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 promptor
Terminal session. At an elevated admin command prompt, enter:
Python 3.7.0 Shell — □ X

File Edit Shell Debug Options Window Help pip install pygame
Python 3."7,0 (v3,7.0:lbfScc5Q93, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit <Inte
1)] on Win32
Type "copyright", "credits" or "license 0 " for more information. S B C o m m a n d P ro m p t
» > impor _ mat h
>»1
C:\Users\david>pip install pygame

Some modules, especially on the Raspberry Pi, are The PIP installation requires an elevated status due
included by deFault; the Math module is a prime to it installing components at diFFerent locations.
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.

Python 3.7.0 Shell - □ X


E&9 Administrator: Command Prompt
File Edit Shell Debug Options Window Help
Python 3.7.0 (v3.7.0:Ibf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
Microsoft Windows [Version 10.0.15063]
1)] on Win32 (c) 2017 Microsoft Corporation. All rights reserved.
Type "copyright", "credits" or "license()" for more information.
» > imp o r math
C :\WINDOWS\system32>pip install pygame
> >> import pygame
Traceback (most recent call l a s t ) : Collecting pygame
File "<pyshell#l>", line 1, in <module> Using cached pygame-1.9.3-cp36-cp36m-win32.whl
import pygame
Installing collected packages: pygame
M o d u l e N o tFoundError: No module named ’p y g a m e ’
Successfully installed pygame-1.9.3

C :\WINDOWS\system32>

Coding & Programming


Python Modules

Close the command prompt orTerminal, and re­ 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
problems. You'll find that most code downloaded, or copied, from
import math
the Internet will contain a module, mainstream or unique, and their
absence is commonly the source oFerrors in execution. for I in range(5):
print (random.randint ( 1 2 5 ) )
[i|r Python 3.7.0 Shell — □ X

File Edit Shell Debug Options Window Help print(math.pi)


Python 3.7.0 (v3.7.0 :lbf 5cc5093, Jun 27 2Q1S, 04:06:47) [MSC v . 151-3 32 bit (Inte
1)] on Win32
[ij|r *rnd number,py - C:/Python Code/rnd number.py (3.7.0)* — □ X
Type "copyright", "credits" or "license()" for more information.
>>> import pygame File Edit Format Run Options Window Help
pygame 1 . S .4 import random
Hello from the pygame community, https://www.pygame.org/contribute.html import math

for i in r a n g e (5):
print(random.randint(1, 25))

print (math.pi)|

The modules contain the extra code needed to 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))
’ ’ id number.py - C:/Python Cade/md numberpy (3.7.0)' — □ X
L # ’ Untitled’ — □ X
File Edit Format Run Options Window Help
File Edit Format Run Options Window Help
from random import randint
import random

for i ir. range (10) : for i in r a n g e (5):


print(ran d o m . r a n d i n t (1, 25)) print(r a n d i n t (1, 25))

This code, when saved and executed, will display ten 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 which will import everything defined within the named module.
range. For example: Flowever, 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.

| j j t ’ rnd num ber.py - C :/Pytho n C od e/m d num ber.p y (3.7.0)’ — □ X

File Edit Format Run Options Window Help


import ma t h as m

print (xn.pi)

Coding & Programming


Coding w ith W in d o w s 10 B atch Files

Did you know that Windows has


its own built-in scripting language?
Batch files have been around since
the early days of Windows, and while
they are overshadowed by the might
of Windows' modern graphical user
interface, they are still there and still
just as capable as they were thirty
years ago.

Batch file programming is a skill


that system administrators still use,
so it's worth spending a bit of time
learning how they work, and what
you can do with them. This section
introduces batch files, and covers user
interactions, variables, loops and even
a batch file quiz game to inject an
element of fun.

96 W h a t is a B a tc h File ?

98 G e t tin g S t a r t e d w it h B a tc h F ile s

100 G e t tin g an O u t p u t

102 P la y in g w it h V a ria b le s

104 B a tc h F ile P ro g ra m m in g

106 L o o p s an d R e p e titio n

108 C re a tin g a B a tc h F ile G a m e

Coding & Programming


(index

Coding & Programming


Coding w ith W in d o w s 10 B atch Files

What is a Batch File?


The W indow s batch file has been around since the early days of DOS, and w as once a
critical element of actually being able to boot into a working system. There's a lot you
can do with a batch file but let's just take a m om ent to see w hat one is.

.BAT M A N
A Windows batch File is simply a script File that runs a series oF commands, one line at a time, much in the same Fashion as a
Linux script. The series oF commands are executed by the command line interpreter and stored in a plain text File with the .BAT
extension; this signiFies to Windows that it's an executable File, in this case, a script.

Batch files have been around since the earliest versions oF Microsoft line in turn, loading programs that would activate the mouse or
DOS. Although not exclusively a Microsoft scripting file, batch files optical drive into the memory areas assigned by the Config.sys file.
are mainly associated with Microsoft's operating systems. In the
early days, when a PC booted into a version of DOS (which produced The DOS user of the day could opt to create different Autoexec,
a simple command prompt when powered up), the batch file was bat files depending on what they wanted to do. For example, if
used in the form of a system file called Autoexec.bat. Autoexec, they wanted to play a game and have as much memory available
bat was a script that automatically executed (hence Autoexec) as possible, they'd create a Config.sys and Autoexec.bat set of files
commands once the operating system had finished dealing with the that loaded the bare minimum of drivers and so on. IF they needed
Config.sys file. access to the network, anAutoexec.bat file could be created to

When a user powered


up their DOS-based
computer, and once the
BIOS had Finished checking
the system memory
and so on, DOS would
look to the Config.sys
file to load any specific
display requirements
and hardware drivers,
allocate them a slot in the
available memory, assign
any memory managers
and tell the system where
the Command.com file,
which is the command line
interpreter For DOS, was.
Once it had done that, then
the Autoexec.bat File took
over and ran through each

TFie Autoexec.bat file was


a PC user’s first experience
with a batch file.

Coding & Programming


What is a Batch File?

BATCH FILE POWER

ettio ..... • HELLO!


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

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

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


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

The Autoexec.bat was the first such file many users came across in
S I Command Prompt - testl
their PC-based computing lives; since many had come from a 16-bit
or even 8-bit background; remember, this was the late eighties
and early nineties. The batch file was the user's primary tool for
************************
automating tasks, creating shortcuts and adventure games and ********* * H ELLO ! *
translating complex processes into something far simpler. ik********** ************************
************* **********
* ***** * ******
Nowadays however, a batch file isn't just For loading in drivers and * ***** * ****
such when the PC boots. You can use a batch file in the same way * ******* «** **
* * ***** * * *
as any other scripting language File, in that you can program it to * * ***** * *
ask for user input and display the results on the screen; or save to ***************
***************
a file and even send it to a locally or network attached printer. You ***************
can create scripts to back up your files to various locations, compare ***************
date stamps and only back up the most recently changed content as ***************
***************
well as program the script to do all this automatically. Batch files are ***************
remarkably powerful and despite them not being as commonly used ***************
**** *** ****
as they were during the older days of DOS, they are still there and *** ** ***
can be utilised even in the latest version oF Windows 10; and can be ** * **
as complex or simple as you want them to be. * *

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


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

Coding & Programming


Coding with Windows 10 Batch Files

Getting Started with


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

A N E W BATCH
Throughout this section on batch Files we're going to be working with Notepad, the command prompt and within a Folder
called 'Batch Files'. To begin with, let's see how you get to the Windows command prompt.

The Windows While at the command prompt window, enter:


command B D @ Filters ' v dir/w. This lists all the Files and directories From
prompt may look a little Best match where you are at the moment in the system. In this case, that’s your
daunting to the newcomer |m Command Prompt Home directory that Windows assigns every user that logs in. You
but it's simply another Desktop app
can navigate by using the CD command (Change Directory). Try:
interface (orShell) used to Search suggestions
cd Documents
access the Filesystem. You P cm d - See web results > 1

can go anywhere you like in Then press Return.


the command prompt, as
you would with the graphical licivsufl HlnJuns [Ve
(c) 2617 M icrosoft Corporation. A l l rig h ts reserved.
interface. To begin, click on
C: \Users\.david>dir/w
the Windows Start button and volume In d rive C has no label.
Volume S e ria l Number i s 8E47-ABFF

enter CMD into the search box. Dire cto ry o f C:\Users\david

[•] [-] [ .android] [ . gdbgui] [.girap-2.8]


[ .id le rc] [ .thumbnails] [ .VirtualBox] [30 Objects]
[Application Data] [Contacts] [Creative Cloud F ile s] [Desktop] [ Documents]
[Downloads] [DropboxJ [Dropbox (Tear* BDM)) LFavorites] [Google Drive]
[ In t e l] [Links] [Music] [OneDrive] [Pictu re s]
[Saved Games] [Scorches] sty lc .d at [Tracing] [Videos]
[V irlualBux VMs]
1 F ile ( s ) 9 bytes
W nir(<0 hytes free

: : \users\davia>cd Documents

t :\Users\david\Documents>
P
1 cmd|
1

Click on the search result labelled Command Prompt The prompt should change and display \
(Desktop App) and a new window pops up. The Documents>; this means you're in the Documents
Command Prompt window isn't much to look at to begin with but directory. Now, create a new directory call Batch Files. Enter:
you can see the MicrosoFt Windows version number and copyright
md "Batch Files"
inFormation Followed by the prompt itselF. The prompt details the
current directory or Folder you're in, together with your username. You need the quotations because without them, Windows creates
two directories: Batch and Files. Now change directory into the
] Command Prompt newly created Batch Files.
M ic r o s o ft Windows [V e r sio n 10.0.1 62 9 9.4 02 ]
( c ) 2017 M ic r o s o f t C o rp o r a t io n . A l l r i g h t s re se rv e d . cd Batch Files
:\U s e r s \ d a v id >
You won't need the quotes to change directories.

I QB ommand Prompt

C : VUsers\david\Docum ents>nid "B atch F i l e s "

:\U se rs\d av id \D o cu m e n ts> cd "B atch F i l e s ”

:\U se rs\d a v id \D o c u m e n ts\B a tc h F ile s >

91 Coding & Programming


Getting Started with Batch Files

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

3 Untitled - Notepad ESI Command Prompt

File Edit Format View Help :\User-s\david\Documents>Bd "Batch F i l e s "

1 t:\Users\d avid \D ocum en tsscd "Batch F i l e s "

:\U se rs\david \Docu m e nts\Batch File s> d ir/ w


Volume i n d riv e C has no l a b e l .
Volume S e r i a l Number i s 8E47-ABFF

D ire c to ry o f C:\U sers\davidYDocum ents\Batch F ile s

.] [..] T e st.bat
1 F ile ( s ) 30 bytes
2 D l r ( s ) 129,865,961,472 bytes fre e

:\U se rs\david \Docu m e nts\Batch F ile s >

To create your First batch File, enter the Following To execute the batch File you've just created, simply
into Notepad: enter its name, Test, in the command prompt
window. You don't need to add the .bat part, as Windows recognises
0echo nff
it as an executable File, and the only one with that particular name in
echo Hello World!
the current directory. Press return and see how you're greeted with
By deFault, a batch File displays all the commands that it runs Hello World! in the command prompt.
through, line by line. What the @echo oFF command does is turn
SB
that Feature oFF For the whole script; with the (at) sign to apply
C:\Users\david\Docuroents>md "Batch Files"
that command to itself.
C:\Users\david\Documents>cd "Batch Files”

C:\Users\david\Docunvents\Batch Files>dir/w
3 Untitled - Notepad Volume in drive C has no label.
Volume Serial Number Is 8E47-ABFF
File Edit Format View Help
@echo o f f Directory of C:\Users\david\Documents\Batch Files
echo H e llo W o rld! [.] [..] T e st.b at
1 File(s) 30 bytes
2 Dir(s) 129,865,961,472 bytes free

C:\Users\david\DocumentsVBatch Files>Test
Hello World!

C:\Users\david\Documents'\Batch Files>

When saving anything in Notepad the deFault


extension is .txt, to denote a text File. However, you
The echo command displays whatever is aFter it
want the extension to be .bat. Click on File > Save As and navigate
to the screen. Right-click theTest.bat File From
to the newly created Batch Files directory in Documents. Click the
Windows Explorer and select Edit to add more echo commands iF
drop-down menu Save as Type, and select All Files from the menu. In
you like. Try this:
File Name, call the FileTest.bat.
Secho off
J Untitled - Notepad
echo Hello World!
File Edit Format View Help
(Secho off echo This is my first batch file
echo Hello World!
echo.
echo With a blank line between!
3 Save As

■f > This PC > Documents > Batch Files Remember to save each new change to the batch File.
Organise » New folder

tm Google D rive* * Name Date modified Type


Amends
No items match your search.
Batch File Basics
Page 106 What i : l
Page 108Gettinc

V Dropbox (Team Bl
Team BDM

A OneDrive

■ This PC
^ 3D Objects
■ Desktop
[HI Documents

Filename: |
Save as type All Files

Hide Folders Encoding: ANSI

Coding & Programming


c
i9
Coding with Windows 10 Batch Files

Getting an O u tp u t
While it's great having the command prom pt w indow display what you're putting after
the echo command in the batch file, it's not very useful at the moment, or interactive
for that matter. Let's change up a gear and get som e output.

INPUT, O U T P U T
Batch Files are capable oF taking a normal Windows command and executing it, while also adding extra options and Flags in to
the equation.

Let’s keep things simple to begin with. Create a new You have no doubt noticed that there is no
batch File called 'dirview.bat', short for Directory indication that the batch file worked as there's
View. Start with the @echo off command and under that add: no meaningful output on the screen. However, if you now open
Explorer and browse to c : \Users\YOURNAME, remembering to
dir "c:\users\YOURNAME\Documents\Batch Files" >
substitute y o u r n a m e with your Windows username, and double­
c :\users\YOURNAME\dirview.txt
click the dirview. t x t file, you can see the batch file's output.
Substitute YOURNAME with your Windows username.

_ j dirview - Notepad

File Edit Format View Help


@echo o f f
d i r "c:\u se rs\d av id \D o c u m e irts\B a tc h F i l e s " > c : \u s e r s \d a v id \ d ir v ie w . t x t

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

2 dirview - Notepad
File Edit Format View Help
@ecFio off
dir "c:\users\david\Documents\Batch Files" > c:\users\david\dirview.txt
notepad.exe c :\users\david\dirview.txt

Coding & Programming


Getting an Output

OUTPUT WITH VARIABLES


Variables oFFer a more interesting way oF outputting something to the screen and create a higher level oF interaction between
the user and the batch File. Try this example below.

Create a new batch File and call it name.bat. Start This is extremely useFul iFyou want to create a
with the 0echo off command, then add the unique, personal batch File that automatically runs
Following lines: when a user logs into Windows, Using the deFault systems variables
that Windows itselF creates, you can make a batch File that greets
set /p name= What is your name?
each user:
echo Hello, %name%
0echo off
Note: there's a space aFter the question mark. This is to make it look
neater on the screen. Save it and run the batch File. echo Hello, %USERNAME%.
echo.
1— — echo Thanks for logging in. Currently the network
1 File Edit Format View Help
giecho o f f
is operating at 100%% efficiency,
s e t /p nam e- What i s y o u r name? echo.
e ch o H e l l o , %name%
echo Your Home directory is located at: %HOMEPATH%
S I Command Prompt echo The computer name you're logged in to is:
: \ U s e r s \ d a v id \ D o c u m e n t s \ B a t c h F ile s> n a m e
%COMPUTERNAME%
What i s y o u r name? D a v id
T e l lo , D a v id echo.
C : \ U s e r s \ d a v id \ D o c u m e n t s \ B a t c h F i l e s >

; 3 nanic-Notepad

feche off

echo Hello, HJSERHAME*.

echo Thanks for logging in. Currently the network i s operating at 10CKC efficiency.
The set/p name creates a variable called name,
echo Your Hone directory i s located at: SHOMEPATHX
with the /p part indicating that an '=prompt string' echo The coaputer name you're logged in to is: JSC0MPUTERNAME5S

is to Follow. The Set command displays, sets or removes system


and environmental variables. For example, while in the command
prompt window enter: Save and execute the batch File changes; you can
overwrite and still use name.bat iFyou want. The
set
batch File takes the current system variables and reports them
To view the current system variables. Note the name= variable we accordingly, depending on the user's login name and the name oF
just created. the computer. Note: the double percent symbol means the percent
sign will be displayed, and is not a variable.

C : \ U s e r s \ d a v i d \ D o c u m e n t s \ B a t c h F ile s > n a m e
H e l lo , d a v id .

T h a n k s f o r l o g g i n g i n . C u r r e n t l y t h e n e t w o rk i s o p e r a t in g a t 130% e f f ic ie n c y .

Y o u r Home d i r e c t o r y i s l o c a t e d a t : \ U s e r s \ d a v i d
The c o m p u te r name y o u 'r e l o g g e d i n t o i s : WINDOWS

C : \U s e rs \d a v id \D o c u m e n t s\B a tc h F ile s >

Alternatively, you can run the batch File and display


it on the user's desktop as a text File:

0echo off

echo Hello, %USERNAME%. > c :%HOMEPATH%\user.txt


Variables stored with Set can be called with the
qcho. >> c :%HOMEPATH%\user.txt
■ ■ ■ F %VARIABLENAM E% syntax. In the batch File, we
echo Thanks for logging in. Currently the network
used the newly created %name% syntax to call upon the contents of
is operating at 100%% efficiency. » c :%HOMEPATH%\
the variable called name. Your username, for example, is stored as a
user.txt
variable. Try this in a batch File:
echo. >> c :%HOMEPATH%\user.txt
echo Hello, %USERNAME%. What are you doing? echo Your Home directory la located at: %HOMEPATH%
» c :%HOMEPATH%\user.txt
echo The computer name you're logged in to is:
%COMPUTERNAME% » c :%HOMEPATH%\user>txt
echo. >> c :%HOMEPATH%\user.txt

notepad c :%HOMEPATH%\user.-txt

The > outputs to a new File called user.txt, while the » adds the
lines within the File.

Coding & Programming


Coding with Windows 10 Batch Files

Playing with Variables


There's a lot you can accomplish with both the system and environmental variables,
alongside your own. Mixing the two can make for a powerful and extremely useful
batch file and w hen combined with other commands, the effect is really impressive.

U SIN G M O R E V A R IA B L E S
Here's a good example of mixing system and environmental variables with some oFyour own creation, along with a number oF
external Windows commands.

Create a new batch File called list.bat and start it oFF Now, create a batch File that displays the contents
with the @echo off command. Begin by clearing oF any directory and post it as a text File to the user's
the command prompt screen and displaying a list oF the current screen. Add the Following to the list.bat batch File:
directories on the computer:
echo Hello, %USERNAME%.
els echo From the list, which folder would you like to
dir "c:\" > list.txt view?
type list.txt set /p view= (enter as c:\folder)
echo. dir "%view%" > view.txt
notepad.exe view.txt
~J list- Notepad
File Edit Format View Help
3 list - Notepad
@echo o f f
File Edit Format View Help
e ls (Secho o ff
d ir " c :\ " > l i s t . t x t
typ e l i s t . t x t | els
echo.
d ir " c : \ " > l i s t . t x t
type l i s t . t x t
echo.
echo Hello, %USERNAME%.
echo From the l i s t , which d irectory would you lik e to view?
se t /p view= (enter as c :\d ire c to ry )
d ir ”%vievi%" > view .txt
notepad.exe view .txt

^
Save and execute the batch File. Within the What’s happening here is the batch File asks the user
command promptyou can see the contents oF all to enter any oF the directories displayed in the list it
the Files and directories From the root oF the C:\ drive; and as any generated, in the Form oF 'c:\directory'. Providing the user enters a
user under Windows has permission to see this, there's no UAC valid directory, its contents are displayed as a text File. We created
elevated privileges required. the view variable here along with %HOMEPATH%, to store the input
and the text File.
Q Command Prompt

Volume in drive C has no label.


Volume Serial Number is 8E47-ABFF

Directory of c :V

26/06/2017 10:37 <DIR> activity


13/07/2017 09:57 <DIR> monitoring
07/12/2017 18:32 <DIR> PerfLogs
25/04/2018 11:51 <DIR> Program Files
27/04/2018 10:52 <DIR> Program Files (x86)
25/08/2017 10:10 <DIR> Python27
26/03/2018 15:38 <DIR> Speccy
27/04/2018 10:52 <DIR> Temp
04/07/2017 16:08 <DIR> Unified_Android_Toolkit
25/10/2017 11:02 <DIR> Users
29/04/2018 11:39 <DIR> Windows
0 File(s) 0 bytes
11 Dir(s) 129,728,413,696 bytes free

k :\Users\david\Documents\Batch Files>

Coding & Programming


Playing with Variables

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

Fite Edit Format View Help Best match


@echo o ff

e ls
dir "e:\" > list.txt
type list.txt Command Prompt
echo H e llo , 3PJ5ERNAMES.
echo From the l i s t , which d ire c to ry would you l ik e to view?
se t /p view - (enter a s c :\d ire c t o ry ) ^ 0 Run as administrator
notepad.exe vie w .txt
els Se
del /Q vie w .txt
del /Q l i s t . t x t
Open file location
echo A l l f i l e s deleted. System clean.
>-
-te Pin to Start

da Pin to taskbar
The additions to the batch file simply clear the
command prompt window (using the els command)
and delete both the view.txt and list.txt Files that were created by
the batch file. The/Q Flag in the del command means it deletes
the files without any user input or notification. The final message
This action triggers the UAC warning message,
informs the user that the Files are removed.
asking you iFyou're sure you want to run the
Windows command prompt with the elevated Administrator
privileges. Most of the time we wouldn't recommend this course
[All files deleted. System clean.
'c:\Users\david\Documents\Batch Files>
of action: the UAC is there to protect your system. In this case,
however, click Yes.

Depending
on how _
B D © Filters N /
your system is configured,
Best match
you may not get any
directory information g || Command Prompt
at all or a message a Desktop app

stating Access Denied. Search suggestions

This is because the UAC yP c m d - See web results > With the UAC active, the command prompt looks
is blocking access to a little different. For starters, it's now defaulting
protected areas of the to the C:\WINDOWS\system32 folderand the top of the windows is
system, like c:\Windows labelled Administrator. To run the batch file, you need to navigate to
or C:\Program Files. the Batch Files directory with: cd \Users\USERNAME\Documents\
Therefore, you need to Batch Files. To help, press the Tab key to auto-complete the
run the batch File as an directory names.
Administrator. Click the
Windows Start button and
enter CMD again. Microsoft Windows [Version 10.0.16299.402]
(c) 2017 Microsoft Corporation. All rights reserved.
©
C :\WINDOWS\system32>cd "\Users\david\Documents\Batch Files

C :\Users\david\Documents\Batch Files>
1
■■ yP cm d

Coding & Programming


c 13
Coding with Windows 10 Batch Files

Batch File Proaram m inq


It's the little additions we can make to a batch file that help it stand out and ultimately
become more useful. While the W indow s graphical interface is still king, the command
line can do just as much, and this is where batch files come into their own.

S E A R C H IN G F O R FILES
Here's an interesting little batch File that you can easily extend For your own use. It asks the user For a File type to search For
and displays the results.

We are introducing a couple oF new commands Now let's extend the seek.bat batch File:
into the mix here but we think they're really useFul.
Create a new batch File called seek.bat and in it put: 0echo off
els
0echo off
color 2
els
echo Please enter the type of file you want to
color 2
search for (MP3, DOC, JPG for example)
echo Please enter the type of file you want to
echo.
search for (MP3, DOC, JPG for example)
set /p ext=
echo.
where /R c:\ *.%ext% > found.txt
3 seek ■ Notepad
notepad.exe found.txt
File Edit Format View Help els
@echo o ff
color
e ls
co lo r 2 del /Q found.txt
echo Please enter the type o f f i l e you want to search fo r (MP3, DOC, DPG fo r example)
echo.
Fit* idri Fvnul Vi*. Mp

The new command in this instance is color Another new command, Where, looks For a speciFic
(Americanised spelling). Color, as you already file or directory based on the user's requirements.
assume, changes the colour oF the command prompt display. The In this case, we have created a blank variable called ext that the user
color attributes are speciFied by two hex digits, the first corresponds can enter the File type in, which then searches using Where and
to the background colour of the Command console and the second dumps the results in a text File called Found.txt. Save and run the
to the Foreground, and can be any oF the Following values: batch File.

0 = Black 8 = Grey
1 = Blue 9 = Light Blue
2 = Green A = Light Green
3 = Aqua B = Light Aqua
4 = Red C = Light Red
5 = Purple D = Light Purple
6 = Yellow E = Light Yellow
7 = White F = Bright White

Coding & Programming


Batch File Programming

CHOICE MENUS
Creating a menu oF choices is a classic batch File use and a good example to help expand your batch File programming skills.
Here's some code to help you understand how it all works.

Rather than using a variable to process a user's ErrorLevels are essentially variables and the /M
response, batch files can instead use the Choice switch of Choice allows a descriptive message string
command in conjunction with an ErrorLevel parameter to make a to be displayed. Extend this menu with something new:
menu. Create a new File called menu.bat and enter the following:
0echo off
@echo off els
els echo.
choice /M "Do you want to continue? Y/N" e c h o ----------------------------------------------
if errorlevel 2 goto N echo.
if: errorlevel 1 goto Y echo Please choose a directory,
goto End: echo.
echo Press 1 for c:\Music
echo.
i f trrorLtvel 1 Y
echo Press 2 for c:\Documents
echo.
echo Press 3 for c:\Pictures
echo.
echo Press 4 for c:\Videos
echo.
e c h o ----------------------------------------------
Running the code produces an error as we've called choice /C 1234
a Goto command without any reference to it in the if errorlevel 4 goto Videos
file. Goto does exactly that, goes to a specific line in the batch file. if errorlevel 3 goto Pictures
Finish the file with the following and run it again: if errorlevel 2 goto Documents
if errorlevel 1 goto Music
:N
echo.
echo You chose N o . Goodbye. Now add the Goto sections:
goto End

:Y :Videos
echo. els
echo You chose Yes,
. Hello CD %HOMEPATH%\Vi decs
echo You are now In the Videos directory,
:End
goto End

:Pictures
els
CD %HOMEPATH%\Pictures
echo You are now in the Pictures directory,
goto End

:Documents
els
CD %HOMEPATH%\Documents
echo You are now in the Documents directory,
The output from your choice is different depending on
goto End
whetheryou pickYorN .The:End part simply signifies
the end of the file (also known as EOF). Without it the batch file runs :Music
through each line and display the Y response even if you enter N;so it’s els
important to remember to follow your Goto commands. CD %HOMEPATH%\Music
echo you are now in the Music directory,
( S i C om m and Prom pt - menu ■ m enu - m enu - menu - menu
goto End
Do you want to continue? Y/N [YJN]?N :End
You chose No. Goodbye.

You chose Yes. Hello When executed, the batch File displays a menu and with
C :\Users\david\Documents\Batch Files>
each choice the code changes directory to the one the
C :\Users\david\Documents\Batch Files>
user entered. The %HOMEPATH% system variable will enter the currently
logged in user's Music, Pictures and so directories, and not anyone else’s.

Coding & Programming


c 15
Coding with Windows 10 Batch Files

Loops and Repetition


Looping and repeating com m ands are the staple diet of every program m ing language,
including batch file programming. For example, you can create a simple countdown or
even make numbered Files or directories in the system.

COUNTERS
Creating code that counts in increasing or decreasing number sets is great For demonstrating loops. With that in mind, let's look
at the IF statement a little more, alongside more variables, and introduce the Else, Timeout and eoF (End oFFile) commands.

Start by creating a new batch File called count.bat. The count.bat is a rough way of demonstrating a
Enter the following, save it and run: loop; a better approach would be to use a For loop.
Try this example instead:
§echo off
els 0echo off
set /a counter=0 for /L %%n in (1,1,99) do echo %%n

:numbers
set /a counter=%counter%+l
if %counter%. -=100 (goto :eof) else (echo
%counter%)
timeout /T 1 /nobreak > nul
goto :numbers

31count - Notepad
File Edit Format View Help
(jSecho o f f
e ls
s e t /a counter=0

: numbers
se t /a counter=%counter%+l
i f %counter% ==100 (go to :e o f) e ls e (echo %counter%)
tim eout /T 1 /nobreak > nul
goto : numbers

Breaking it
down, there's
For, then the/L switch, which
handles a range of numbers.
Then the parameter labelled as
The count, (SB Command Prompt - count
%%n to denote a number. Then
bat code 1 the in (1,1,99) part, which tells
starts at number one and 2
the statement how to count,
counts, scrolling down the
4 as in 1 (start number), 1 (steps
screen, until it reaches 100. 5
to take), 99 (the end number).
The Timeoutcommand 6
7 The next part is do, meaning DO
leaves a one second gap S whatever command is after.
between numbers and the Q
Else statement continues 10
11
until the counter variable 12
equals 100 before going to 13
the eoF (End OF File), thus 14
15
closing the loop. 16
17
18
19
20

Coding & Programming


Loops and Repetition

You can include the pause between the numbers There are different ways of using the For loop. In
easily enough within the Far simpler For loop by this example, the code creates 26 directories, one
adding multiple commands after the Do For loop. The brackets and for each letter of the alphabet, within the directory c:\test which the
ampersand (&) separate the different commands. Try this: batch file makes using the MD command:

@echo off @echo off


for /L %%n in (1,1,99) do (echo %%n & timeout /T 1 FOR %%F IN (a, b, c,d, e, f ,g,h,i,j,k,l,m,n,o,p,q,r,
/nobreak > nul) s,t,u,v,w,x,y,z) DO (md C:\test\%%F)

File Edit Format View Help


i&echo off
FOR %%F IN (a,b,c,d,e,f,g,M,},k,l,m,n,o,pJq,i',s,t,u,v,wJx,y,z) DO (md C:\test\S3tF)

39 Command Prompt

::\Users\david\Docuraents\Batch File s>co u nt


::\Users\david\Docum ents\Batch F ile s >

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

ifyou open Windows Explorer, and navigate to the Should you ever get stuck when using the various
Batch Files directory where you're working from, commands within a batch file, drop into the
you can now see 25 text files all neatly numbered. Of course, you command prompt and enter the command followed by a question
can append the File name with something like userl .txt and so on by switch. For example, for/? or if/?. You get an on-screen help file
altering the code to read: detailing the commands' use. For easier reading, pipe it to a text file:

Coding & Programming


Creating a Batch File Game
@echo off
Based on what you've looked at Cls
so Far with batch files, you can :s tart
set /a score=0
probably come up with your own set /a quest i o n = 0

simple text adventure or multiple- cls


set /p n a m e = W h a t is y o u r name?
choice game. Here's one that we
:menu
created, with which you're free to cls
7 x edit and make your own. echo.
Ca echo *****★★*★*★★★★★★★*★**★*★★★★★★★★★★★★★★★★★★★★★********
★★
W+ echo.
echo W e l c o m e % n a m e % to the s u per-cool trivia game,
Make up your own questions but how about also echo.
including an introductory or loading screen? Make your echo Press 1 to g e t st a r t e d
loading screen in a separate batch file and save it as echo.
screens.bat (For example). Then, from the main game echo Press 2 for instructions
batch File, you can load it at the beginning of the File echo.
echo Press Q to q uit
with the 'call' command Followed by colour to reset
echo.
the game'scolours: echo ********************************************* *******
**
@echo off
choice f C 12Q
Cls
if errorlevel 3 goto :eof
Call screens.bat
if errorlevel 2 goto Instructions
color
if errorlevel 1 goto G a m e
:start
set /a score=0
:Instructions
set /a question=0
cls
cls
echo.
set /p n a m e = What is your name? ho *********************** ********* ******
echo.
echo T h e i n s t r u c t i o n s a re simple. A n s w e r the
q u e s t i o n s correctly,
###($;
##«##«•#.
:toMfn####
jUtnnnmuut- echo.
*»wn«*«SH+ low;® . »*«§>
.##«####«##* gw##########; echo **************************************
JSB .4-SSBBB SSSSSSSBff SSSSSffSSS@ (SI
p ause
; ##(® -HHHHHHHHHHMHt#i tnm§ cls
mt ;#################; .###
@ .###«
;#*##*»#•#**WMHMf#1f#W:.##
########## #####. ; .
i##mni§ goto m e n u
'# * # # . '§>##### «« # # # '
# # # # *# +#####«£ @###### '
(Sififififffsittfuff#• ifffffttttsitiwitif . ififititittttttinifififtttntnntttttttt ifitittfifififititg
:Game
set /a question=%question%+l
cls
if %question% = =5 (goto end) e lse (echo y o u a re on
q u e s t i o n %question%)
echo.
e c h o g et r e a d y for t he question...
echo.
t i m e o u t /T 5 /nobreak > nul
if %question% = =5 (goto end) e lse (goto %question%)

:1
cls
echo.
echo ******************************
echo.
e
P C
*1 v
Creating a Batch File Game

e c h o Y o u r c u r r e n t s core is %score% if errorlevel 3 goto w r o n g


echo. if errorlevel 2 goto w r o n g
e c h o ****************************** if errorlevel 1 goto co r r e c t
echo.
echo. :4
e c h o Q u e s t i o n %question%. els
echo. echo.
e c h o W h i c h o f the f o l l o w i n g v e r s i o n o f W i n d o w s is the echo ******************************
best? echo.
echo. echo Y o u r cu r r e n t score is %score%
e c h o A. W i n d o w s 10 echo.
echo. echo ******************************
e c h o B. W i n d o w s M E echo.
echo. echo.
e c h o C. W i n d o w s V i s t a echo Q u e s t i o n %question%.
echo. echo.
c hoic e /C a b c echo W h i c h of the f ollowing W i n d o w s uses D i r e c t X 12?
if er rorlevel 3 g o t o w r o n g echo.
if er rorlevel 2 g o t o w r o n g echo A. W i n d o w s 10
if erro r l e v e l 1 g o t o c o r r e c t echo.
echo B. W i n d o w s 3.11
:2 echo.
els echo C. W i n d o w s X P
echo. echo.
e c h o ****************************** choice /C a b c
echo. if errorlevel 3 goto w r o n g
e c h o Y o u r c u r r e n t score is %score% if errorlevel 2 goto w r o n g
echo. if errorlevel 1 goto co r r e c t
e c h o ******************************
echo. :Wrong
echo. els
e c h o Q u e s t i o n %question%. echo ******************
echo. echo.
e c h o W h i c h o f the f o l l o w i n g v e r s i o n o f W i n d o w s is the echo WRONG!!!!
m o s t stable? echo.
echo. echo ******************
e c h o A. W i n d o w s 10 set /a score=%score%-l
echo. pause
e c h o B. W i n d o w s 95 goto :g ame
echo.
e c h o C. W i n d o w s M E :c o rrect
echo. els
c hoic e /C a b c echo ******************
if er rorlevel 3 g o t o w r o n g echo.
if er rorlevel 2 g o t o w r o n g echo CORRECT. YIPEE!!!
if er rorlevel 1 g o t o c o r r e c t echo.

:3 set /a score=%score%+l
els pause
echo. goto :g ame
e c h o ******************************
echo. rend
e c h o Y o u r c u r r e n t s core is %score% els
echo. echo ******************************
e c h o ****************************** echo.
echo. echo W e l l done, %name%, y o u h a v e a n s w e r e d all the
echo. que s t i o n s
e c h o Q u e s t i o n %question%. echo.
echo. echo A n d y o u r final score i s __
e c h o W h i c h o f the f o l l o w i n g W i n d o w s v e r s i o n is the echo.
latest? echo %score%
echo. echo.
e c h o A. W i n d o w s 10 echo ********************************
echo. choice /M "play again? Y/N"
e c h o B. W i n d o w s 98 if errorlevel 2 goto reof
echo. if errorlevel 1 goto s tart
e c h o C. W i n d o w s 7
echo.
c hoic e /C a b c

Coding & Programming


€ 19
Coding on Linux

Linux is such a versatile operating


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

Bash scripting on Linux can be used to


create a wealth of useful, real-world
programs that interact with the user,
or simply work in the background
based on a pre-defined schedule.
Scripting is a powerful interface to the
Linux system, so we've crafted this
section to help you get to grips with
how everything fits together, and how
to make some amazing Linux scripts.

112 Why Linux?


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

Coding & Programming


Coding & Programming
Coding on Linux

W h y Linux?
For many of its users, Linux m eans freedom. Freedom from the walled-gardened
approach o f other operating systems, freedom to change and use the O S as you please
and freedom from any form of licensing or payment. There's a lot more to Linux than
you may think.

FREE AND OPEN


Linux is a Fantastic Fit For those who want something diFFerent; the eFFiciency oF the system, the availability oF applications and
its stability, are ju st a Few reasons why.

The First thing we need to address is that there is no basic operating Linux works very diFFerently to Windows or macOS. Fora start, it's
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 oFan 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, ordistros, 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,
Debian, Raspbian... the list goes on. Each one oF these distros oFFers a user, be they a developer, gamer, orsomeone who wants to put an
the user something a little diFFerent. While each has the Linux kernel at older computer to use, can quickly download a distro and get to work
its core, they oFfera different looking desktop environment, diFFerent in a matter of minutes.
pre-loaded applications, different ways in which to update the system
and get moreapps installed and a slightly diFFerent look and Feel Alongside the free to use aspect comes a level of freedom to customise
throughout the entire system. Flowever, 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. the Internet have a certain 'spin', some offer increased security, a fancy-

Linux is a great operating system in


A ____, which to start coding.

File Edit View Search Tools Documents Help

-lie Edit Options Buffers Tools Help

A O B * | - #include--:stdio.
§include <iostream> #include^ :conio.
#include<
wine lude<graphics.h>
int main!) #include<stdlib.h>
#include<
#include<math.h>
#include<dos.h>
//My first C++ program #include^t ime.h»
std::cout « "Hello World!\n' void slinelint,int,int,int,int,int,float,int,int);
void hlinefint,int,int,int,int,int,float,int,int);
void mline(int,int,int,int,int,int,float,int,int);
void grid(int,int,int,int);
void mainO
{
int gd=DETECT,gm,maxx,maxy,midx,midy;
int
sincolor=4,soutcolor=0,hincolor=l,houtcolor=L,mincolor=12,moutcolo
int bakcolor=!.4;
int gcolor=0 ,grad=3;
d a v id @ m irt -m a te -/ D o c u m e n ts
float thita,X,Y,h, File Edit View Search Terminal Help
initg raph(&gd,&gm,
davidgmint-mate Documents s ./helloworla
maxx=getmaxx(); Hello World!
m a x y= g e tm a x y( ) ; davidomint-mate -/Documents S
midx=maxx/2 ;
midy=maxy/2 ;
float phi=3.142 3,deg ree,dh,dm;
int rad=125;
int HX.HY,MX,MY,SX,SY,ML=rad-25.SL=rad-20,H L= rad-25;
char strElO];
helioworld.epp cleardevice();
setfillstylel1 ,bakcolor);
Emacs Tutorial L e a m b a sic keystrc circlelmidx.midy,rad-10 );
Emacs Guided Tour O ve rview of E m a c s floodfill(midx,midy,15);
U :% % - *GNU Em acs* 11% L 3 ( Fun< setfillstylel 1 ,1 );
circle(midx,midy,rad+1 0 );
floodfill(midx+rad+3,midy,15);
for(thita= ’0+45;thita<« !6Q+13S;thita-thita+(18G/( ))

Coding & Programming


Why Linux?

looking desktop, a gaming specific spin, orsomething directed toward


students. This extensibility makes Linux a more desirable platform to
use, as you can quickly mould the system into a development base,
including many different kinds of IDEs for use with Python, web © Q ££
development, C++, Java and so on, or even a base for online anonymity, ubuntu
perhaps as a Minecraft server, media centre and much more.

Another remarkable advantage for those looking to learn how to code (Pdebian Mandriva is la e k w a r e

is that Linux comes with most of the popular coding environments


built-in. Both Python and C++are pre-installed in a high percentage of
Linux distros, which meansyou can start to program almost as soon as
you install the system and boot it up for the first time. C en tO S
Generally speaking, Linux doesn't take up as many system resources
as Windows or macOS, (by system resources, we mean memory,
Each distro offers something unique to the
hard drive space and CPU load), as the Linux code has been
streamlined and is free from third-party 'bloatware', which hogs A _ user but all have Linux at the core.

those systems resources. A more efficient system, means more


available resources for the coding and testing environmentand the So rather than throwing away an old computer, it can be reused with
programs you will eventually create. Less resource use also means a Linux distro.
you can use Linux on older hardware that would normally struggle,
or even refuse to run, the latest versions of Windows or macOS. However, it's not all about C++, Python, or any of the other more
popular programming languages. Using the command line of Linux
rile Edit View (also called the Terminal), you're able to create Shell scripts, which are
Categories programs made up of scripting languages and designed to run from
the command line. They are used mainly to automate tasks, or offer the
user some form of input and output fora certain operation.
Featured All Packages
m
Sound and
m
^ video
There are many more advantages we could list, for example, there
* i, | are thousands and thousands of free programs and apps available
£
--A/*- A | that cover practically every aspect of computing. Known as packages,
**- 1 1m
there are (at the time of writing) over 8,700 specific programming
applications on Linux Mint alone and an incredible 62,000+ overall
JU packages, catering from Amateur Radio to WWW tools.

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


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

nhFolding.tpp + (-/development/projeoli/Uwm/lib/CudeGen) - YAVIDE


e/f/fibonacci.cpp ) 1/C/Allocation0rder.cpp
► GlobaUSel/
. HIRParser/ EnableHoistComnonCodelConmonHoistl, HBBFreqlnfo(Freqlnfo),
MBPIlPioblufu) {
AggrcssivcAntiDcpBrcokcr. ,tch (FlagEnablcTailMcrgc) { 109 LcxiolScopc ‘ LcxicalScopc;; ; findLcxicalScopcIconit DILocation *DL> {
aqgre'.'.iuoSnr inppRrpakor. ■Rnil IIUSFT' Fnabl pTai IMergp = dpfanl tFnahlpTai iKprgp; hrpak: l>TIoralSrnpp •Senpe s= Dl ->gptSrnpe(): » _anonl 1 npip-sparp
AllocationQrder.epp :6011 TRUE: EnableTailHerqe = true; break; i f (!Scope) t BranchFolderPass ; class
Allocationurder.h :BCU_FALSt: tnableiailnerge - false; break; return nullptr; [functions]
Analysis.epp BranchFolderrass|I
AntiDepBreaker.h Inesnbers)
AtomicExpandPass.epp ID
BasicTargetTransfornlnfo. Scope - Scope->getNonLexicalBlockFileScope( );
BranchFolding.cpp
BranchFolding.h void BranchFolder: RemoveDeadBlockiMachineBasieBlock *MBB) ii I auto *IA ■= 0L->getIn UnedAtr) I [ v BranchFolder : class
BuiUiuGCs.cpp asser UHBB-»picd taplyl) d£ 'MBS nu-.l be dead1"); aulo I = InlifiedLexjLdlStopeHap. fii«l(sld; ; t HBPlWiapper : c la n
Cal cSpil Weights, epp DEBUG(dbgs11 -« -SnRcnoving HBB: ' « *HBB); return I I- InlincdLcxicalScopcMap.cndl) 7 (functions]
f al 1i ngfnnvl nwer.rpp getRlnckFreg
CMakeLists.txt MachineFunction *MF = HB8-»qetPare return findLexicalScopelScope); printBlockFreq om
CodeGen.cpp pnntBlockFreq an
codeoenprepare.cpp idiile (!HBB-»succ_enptyll) setBlockFreq ror
CriticalAntiPepOreaker.cp ▼HergePotentialitlt
CriticalAntiOepBreaker.h [functions]
DeadMachinelnstructionEli LexicalScope *LexicalSeopes:;getOrCreateLexicalScope!const OlLocalScope 'Scope. operator < orsi
OetectDeadLanes.epp TriedWerging.erass(MBB); const DILocation 'IA I { (functions)
DFAPacketizer.cpp it HA) i BranchFolder : i de
Dwdi fEHPi epai e.cpp .uwpu It
EarlylfConversion.epp gatOrCreatoAbstractScopelScope); CreateConmonTailOnlyBlocklM
EdgeBundles.cpp FuncletMembership.erase(HBB): HoistComonCodelKarhi neFur c
ExecutionDepsFix,epp i f (MLI) return getOrCreatelnlinedScopelScope, IA ); HoistCownonCodelnSucc s - 1+ 11
ExpandlSelPseudos.epp HLI->renoveBLock(HBBI; MaintainLivelnsIHa chineftasi
ExpandPostRAPseudos.epp OptimlzeBlock; hinefiasi 8
TaultHaps.cpp return getOrCrcateRegularScope(Scope); OptimiaeBranches1 - m
FuiulotLayout.epp f llv n 1■ MaehineLoop ■ OptuizeFunction •r :hmet m
GCMetadata.cpp f void r '-1.......— ' OptimizelmpOefsBlock tec mi
GCHetadataPrinter.epp f void o RemoveBlocksWithHash III sign
uutootLowe ring.epp
GCStrategy.epp copal const DILot ilScope 'Scope) { ReplaceTailWithBranchTo'Ha
GlobalMerge.cpp achineBasicBloc ncodingl" J; SplitMBBAt -i, !■ ...
IfConversion.epp kFileScopei); TailHergeBlocksiHac'u neFu
ImplicitNullChecks.epp * m id addloplavcl LoopUlna: iK k U m Lm p •Haul TryTailMergeBlocks Machine
InlineSpiller.cpp setComnonTa ilEdgetfeights iH
interferencecache.epp cnaogeTcpi.eveli ood chineLoop ’newioop)
IntorfercncoC3che.il * BranchFolderPass class
-rpp
IntrinsicLowerinq.epp seal e.ic runOnMachineFunctionIv
Rich qetAnalysi<tsaqe
Lexicalbcopes,cpp vh;i geti oopuepth icalnlockbase>lbcopel)
LiveOebugValues.epp pe(Block-vgetScopell);
LivoDobugVariables.epp •iMachinolcop • ooara i::MaehineBasicBloek -BB) ipiocowiso construct, * llv« : class
LiveDebugVariables.h ;forward^as_tuple(Scope).
I Iw lm tn.liTrrn ■«nruprd pc vi.nl a! Parent

A Linux programming environment can be


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

Coding & Programming 3


{ { « r l: g lo b
The Best Linux
Distributions
There are num erous versions of Linux available, known as "Distributions". Each has a
different ethos and approach. Here are five great distributions to try and where you
can get them.

LINUXMINT-LINUXMINT.COM
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 different environments and even different distros, to see which
popular distro, Ubuntu. Although based on Ubuntu's Long Term suits you and your computer best.
Support build, Linux Mint took a different direction to offer the
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
at first, but it's quite simple. Currently, Linux Mint uses the
Cinnamon Desktop Environment as its flagship model, although
MATE and Xfce models are also available.

Cinnamon is a graphically rich desktop environment, while MATE


uses less fancy graphics but is more stable on a wider variety of
desktop systems and finally Xfce is an extremely streamlined
desktop environment that is built for speed and ultimate stability.

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


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

UBUNTU-UBUNTU.COM
The second most popular distro available is Ubuntu: an ancient
African word meaning 'humanity to others'. Ubuntu's popularity
has fluctuated over its fourteen-year life. At one time, it was
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 and offers the user the complete Linux experience.

114 | Coding & Programming


Mpirjj.....HTKpgB ;
■ignt") ,$(nb The Best Linux Distributions
r</>
'si.j son upI
ARCH - ARCHLINUX.ORG OPENSUSE - OPENSUSE.ORG
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.

I do exactly that, but it's not ideal for beginners. Ubuntu and
Mint both offer an easier installation path and come with 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
Arch, on the other hand, is a more 'bare bones' affair. It is 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
1 1 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. for instability'. If you find all that too sensible, openSUSE
Tumbleweed is a rolling release with all the latest features and
Arch is a distro for when you're more experienced with Linux. the occasionalcrash.
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
installation files will go, create a user, set the OS locale and of its core contributors work on the Linux Kernel, LibreOffice,
install a desktop environment, along with the apps you want. Gnome and other key Linux areas. In short: openSUSE is where
you’ll find the pros hanging out.
The advantage, For all this hard work, is a distro that you've
created. This means your Arch distro won’t come with all
the unnecessary files and apps that other distros have pre­
installed; it's custom made foryou, by you.

II
. 1 RASPBERRY PI DESKTOP - RASPBERRYPI.ORG/DOWNLOADS/RASPBERRY-PI-DESKTOP
No doubt you've heard of the different programming languages and
Raspberry Pi? It's hard not to have, as li^ ra c p be rry: S neofetch educational resources.

jr
_ ,metSSSSSgg. p i§rasp be rry
this remarkable, tiny computer has .gS5SSSS£5S55«SSP.
,gSSP ........... “Y SS.". OS: Debian GNU/Linux 9 .6 (s tr e t c h ) x86_64
, SSP’ 's s s . Model: V irtu a lB o x 1 .2
taken the technology world by storm ,SSP , ggs.
, SP "1
$Sb:
SSS
Kernel: 4 . 9 ,0-8-amd64
Uptime: 2 minutes
Originally, Raspbian was exclusive to
d S' SSP Packages: 1499
since it was introduced six years ago. Shell: bash 4.4.12 the Pi hardware, as the Raspberry Pi
Resolu tio n : 1280x600
DE: LXDE uses an ARM processor to power it.

ia
VH: Openbox
Theme: Adwaita [GTK3]
There are several aspects to the Ic on s: Adwaita [GTK3] Flowever, the Raspberry Pi Foundation
Term inal: lxte rm in al
Raspberry Pi that make it such a CPU: In t e l 15-660DK (2 ) 0 3.5GHz
GPU: V irtu a lB o x G raphics Adapter has since released a PC version of
Memory: 83MB / 2G04HB
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

ct a fully working computer. It's small,


measuring not much bigger than a credit card. You can employ
it to build electronics, using a fully programmable interface and
it comes with Raspbian, its own custom-made, Debian-based
Desktop comes with the all the coding,
educational and other apps you will ever need. It's quick, stable
and works superbly. If you're interested in stretching your
Linux experience, then this is definitely one of the top distros
operating system that includes an office suite alongside many to consider.

Coding & Programming


Coding on Linux

Equipm entY ou
Will Need
The system requirements for successfully installing Linux M int on to a PC are
surprisingly low, so even a computer that's several years old will happily run this distro.
However, it's worth checking you have everything in place before proceeding.

MINTY INGREDIENTS
Here’s what you'll need to install and run Linux Mint as we work through this book. You have several choices available, so take
your time and see which works best for you.

SYSTEM REQUIREMENTS
The minimum system requirements For Linux Mintare as Follows:

CPU 700MHz

RAM 512MB

Hard Drive Space 9CB (20CB recommended)

Monitor 1 0 2 4 x 7 6 8 resolution

Obviously the better the system you have, the betterand 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
Familiarwith the process (or you're thinking oF USB and just
gathering the hardware you'll need), then you're going to
need a minimum 4GB USB Flash drive/stick to contain the
Linux Mint ISO.

Coding & Programming


Equipment You Will Need

DVD INSTALLATION INTERNET CONNECTION


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

MAC HARDWARE
Although Linux Mint can be installed onto a Mac, there's a
school of thought that recommends Mac owners use a virtual
environment, such as VirtualBox or Parallels; and why not,
macOS is already a splendid operating system. If you're 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.
There are many different virtual environment apps available,
however VirtualBox, from Oracle, is one of the easiest. You can
get the latest version from w ww .virtualbox.org.

Vi rtualBox
Coding & Programming
Coding on Linux

Creating a Linux Installer


on W in d o w s
You need to transfer the downloaded Linux ISO to either a D V D or a U SB key before
you can install it to a computer. This will be a live environment, which will allow you to
test the O S prior to installation, but first you need to create the bootable media.

DVD BOOTABLE MEDIA


We're using a Windows 10 PC here to transFer the ISO to a DVD. As long as you’re using a version of Windows From 7 onward,
the process is extremely easy.

First locate the ISO image of Linux you've already - iT lJ I 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,
you'll usually find this in the Downloads folder unless, when saving it may take a few seconds before anything happens. Don't worry too
it, you've specified a different location. 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
Name Disc Image Burner should launch.
it Quick access
J linuxmint-19.1-cinnamon-64bit
y Dropbox (Team EDM) M o unt

& OneDrive Burn disc image

□ This PC □ Scan with Windows Defender...

& Share
© CD Drive (E:) HiSuite
Open with
Network
Open with WinRAR
Add to archive...
Arlrl + n " 11 r* ii v m i n f - 1 Q 1 - n n n a m n n -foA In 1f~ rar"

Next, inserta recordable DVD disc into your 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. it's complete, it will run through the verification stage and when
done, the optical drive should auto-eject the disc foryou.

<• Windows Disc Image Burner X

Disc imagefile: linuxmint-19.1-cinnamon-64bit.iso

Disc burner

Status
Burning disc image to recordable disc,..

DVD RW Drive (E:)


Tap to choose what happens with blank
DVDs.
Verify disc afterburning

09:45 | Cancel ~|
A® Cl») 18/01/2019

Coding & Programming


Creating a Linux Installer on Windows

USB BOOTABLE MEDIA


USB media is Faster than a DVD and it's oFten more convenient as most modern PCs don't have an optical drive installed. The
process oF transFerring the image is easy, but you'll need a third-party app First and a USB Flash drive oF 4GB or more.

Rufus 3.0.1304 X
When you're ready, click on the Start button at
D riv e P ro p e rtie s ------------------------------ the bottom oF the RuFus app. This may open up
Device
First, open up a web Ubuntu 13.04 ITS amd64 (G:) (3G8]
another dialogue box asking you to download and use a new version
browser and go to Boot selection oFSysLinux. SysLinux is a selection oF boot loaders used to allow a
https://rufus.akeo. ubuntu-18,04-desktop-amd64.iso v (0 SELECT modern PC to access and boot From a USB Flash drive. It is necessary,
ie/. Scroll down the Partition scheme Target system
so if asked, click on 'Yes' to continue.
MBR BlOSorUEFI
page a little and you'll
v Show advanced drive properties
come to a Download
Fo rm at O p tio n s ------------------------------- This image uses Syslinux 6.03/20151222 but this application only
heading, under which Volume label includes the installation files for Syslinux 6.03/2014-10-06.
you'll see the latest [ Ubuntu 18.04 LTS amd&4

version oF RuFus. File system C luster size


As new versions of Syslinux are not compatible with one another, and it
FAT32 (Default) v 4096 bytes (Default)
LeFt-click on the link to wouldn't be possible for Rufus to include them all, two additional files
v Show advanced format options must be downloaded from the Internet (‘Idlinux.sys’ and ’Idlinux.bss'):
start the download.
S tatu s -------------------------------------------- - Select 'Yes' to connect to the Internet and download these files
- Select 'No' to cancel the operation
READY

Note; The files will be downloaded in the current application directory


© (D 2 dH 1 START | CLOSE
and will be reused automatically if present.

1 device found

& Rufus 3,4.1430 X


The next step asks in which image mode do you
Drive Properties ------------------------------- want the Linux ISO to be written to the USB Flash
Double-click the Device
drive. Both methods work for different situations, but generally, the
Linux Mint 19.1 Cinnamon 64-bit (F:) [4.1GB]
downloaded RuFus Boot selection
recommended ISO Image Mode is the more popular. Make sure this
executable; you can Disk or ISO image (PI ease select) v (0 I SELECT mode is pre-selected and click 'OK' to continue, Followed by 'OK'
click 'Yes' to the Partition scheme Target system again to confirm the action.
MBR BIOS (or UEFt-CSM)
Windows security
v Show advanced drive properties ISOHybrid image detected
question and ‘Yes'
to checking For Fo rm at O p tio n s ----------------------------------
The image you have selected is an 'ISOHybrid1image. This means it can be
Volume label
updates. With RuFus written either in ISO Image (file copy) mode or DD Image (disk image) mode.
Linux Mint 19.1 Cinnamon 64-bit
Rufus recommends using ISO Image mode, so that you always have full
launched, it should Filesystem Cluster size access to the drive after writing it.
have already identiFied FAT32 4095 bytes (Default) However, if you encounter issues during boot, you can try writing this image
again in DD Image mode.
your inserted USB v Show advanced format options

Flash drive (iF not, just Statu s Please select the mode that you w ant to use to write this image:
remove and reinsert). READY (•) Write in ISO Image mode (Recommended)
Q W rite in DD Image mode
© 0 5 ® CLOSE

OK Cancel
1 devicefound

0 Rufus 3.4.1430 X
B JS H S g : At First glance the RuFus interface can look a little
confusing, don’t worry though, it's really quite D rive P ro p erties --------------------------------
Device
simple. To begin with, click on the SELECT button next to the ’Disk The Linux ISO is now
Linux Mint 19.1 Cinnamon 64-bit (F:) [4.1GB]
or ISO Image (Please select)' pull-down menu. This will launch a being transferred to Boot selection
Windows Explorer window From where you can locate and select the USB Flash drive. The linuxmint-19.1-cinnamon-64bit.i50 v- @ SELECT

the Linux ISO. process shouldn't take Partition scheme Target system
MBR v j BIOS or UEFI
too long, depending on
J v Show advanced drive properties
SOpn,
the speed oFthe USB
Form at O ption s ------------------------
device and the PC. During
Volume label
fume OatmoMml Type Sut
the process, you may Find | Linux Mint 19,1 Cinnamon 64-bit
PrLiUvn.theme r.r, „ ^ Vo,
4 .0 . Rufus will auto-open the File system Cluster size
v Showedvtnteddintptopartin FAT32 ~j 4096 bytes (Default)
USB drive in Windows
<*ci v Show advanced format options
Explorer, don't worry you
F«!«iyttem CHmwi sin Status
ta n . . . . «*j rn tru o ix u n ■ » ! can minimise or close it
READY
Status -------------------------------------------- if you want. Click on the
Close button once the © (D 2 US | START ] CLOSE
® 0 = lia CLOSE Flitmane ISOIn.nn
process is complete.
---- '
' Using image: linuxmint-19.1-cinnamon-64bit.iso

Coding & Programming 9


Coding on Linux

Installing Linux on a PC
M o st Linux distros come as a Live Environment. This m eans you can boot into an actual,
fully working distro straight from the D V D or USB you’ve just created. Let's see how
that w orks and how you go about installing Linux from there.

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

Insert your DVD or USB Flash drive into your PC and, 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 First is via the BIOS you're already in. Locate the Boot Sequence and
identical. Start the PC and when prompted press the appropriate change the First boot device From its original setting, usually Internal
keys to enter the BIOS or SETUP; these could be, For example, F2, PIDD or similar, to: USB Storage Device For the USB media option; or
Del or even F12. DVD Drive, For the DVD media option.

Phoenix - AuardBIOS CMOS Setup Utility


Award Modular BIOS m 6.00PG, An Energy Star Ally Advanced BIOS Features
Copyright (C) 1984-99, Award Software, Inc.

BIU1M/BIW2M BIOS U1.3 Hyper-Threading Technology[Enabled! Itea Help


Quick Power On Self Test [Enabled!
ERA POLLUTION PREVENTEP|
Hain Processor PENTIUM II 910MHz First Boot Device [USB-HDD1 Menu Level
ory Testing 13107ZK OK * 1024K Shared Menory Second Boot Device [HDD-0!
Third Boot Device |ect Your Boot
ft Plug and Play BIOS Extension ul.0A
right (C) 1999, Award Software, Inc.
Boot Other Device First Boot Device ice Priority
Boot Up Floppy Se
IITrend ChipAuayUirus(R) On Guard Uer 1.64 Security Option HDD-3 ...... M i
OS Select For DBA ZIP100 ...... 1 !
USB-FDD ...... [ 1
Curd Header .... 1 1 1
USB-CDHON .... 1 !
USB-HDD ...... til
LAN .... t1
Disabled ...... r ) »
ti:Move ENTER:Accept ESC:Abort

A There are diFFerent versions oFa UEFI BIOS, so Alternatively use the Boot Option Menu. With this
■ ■ ■ ■ V covering them all would be impossible. Whatyou're option, you can press F12 (or something similar)
looking For is a section that details the Boot Sequence or Boot to display a list oF boot media options; From there, you can choose
Mode. Flere you’ll have the option to turn oFF UEFI and choose 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. Changes and Exit.

Coding & Programming


Installing Linux on a PC

INSTALLING LINUX
Once the Live Environment has booted, you will see the option to install the distro to your computer. Have a look around and
when you're ready, look For the Install option on the desktop.

Providing you're connected to the Internet (if not, 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 Continue when you're ready. Linux Mint, click Continue. iFyou need to back up your Files remove
the Linux disc/USB, reboot, back up and start again.

While the installation process is very similaracross Eventually you will be asked to set up your Linux
most Linux distros, some oFFer diFFerent questions username and password. Enteryour Name to begin
during the installation. Generally, the questions aren’t too diFFicult, or with, then Computer Name - which is the name used to identify
technical, butsomesuch 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 Continue, 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.

When installing a new operating system it's 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 diskand install Linux...' option isselected. NOTE: end up being asked to Continue Testing the Live Environment, or
This will completely wipe Windows 10 from your computer; make Restarting to use the newly installed OS. IF you're ready to use Linux,
sure you have backups of all your personal files and data. then click Restart Now.

Coding & Programming


Coding on Linux

Installing a Virtual
Environm ent
A Virtual Environment is a simulated com puter system. Using a Virtual Machine, you
can mimic a standard PC and install an entire operating system on it w ithout affecting
the one installed on your computer. It’s a great way to test and use Linux, while still
having W indow s 10 as your main OS.

GOING VIRTUAL
Using a Virtual Machine (VM) will take resources From your computer: memory, hard drive space, processor usage and so on.
So make sure you've got enough of each before commencing.

We're using VirtualBox in this instance, as it's one of 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
Enterwww.virtualbox.org and dick 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.
Award Modular BIOS vB.OOPG, An Energy Star Ally
Copyright CC) 1984-99, Award Software, Inc.

IIH1M/BIM2M BIOS VI. 3


EPA POLLUTION PREVENTER
lain Processor : PENTIUM II 910MHz
lemory Testing : 13107ZK OK + 10Z4K Shared Memory

luard Plug and Play BIOS Extension ol.BA


Copyright (C) 1999, Award Software. Inc.

Trend ChipAuayUirus(R) On Guard Uer 1.64

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

VirtualBox /iS U S -FI B IO S U tility - AcJva 9

D o w n lo a d V irtu a lB o x
Hire you *w find linkstovirtuelBox tWnnesera Ire source co
:= « . E i Cl d) a
Advanced Monitor
VirtualBox binaries
ftaek •ifv.ancedx CPU Confljurat
If you're lookingfor thel«e« VMwWwi6,0 packages,si
II you're lookingtor thelatest VirtualBox 5.2 packages,si
VirtualBox 6.1.16 platform packages

ed undermetermsofmeGPLversion 2 CPU Ratio

Intel Adaptive ihermai Moulton | E n a b le d |


Irtte! virtualization Technologij
• SHA2S6checksums, M05checksums lFiber-thread lnx

VirtualBox 6.1.16 Oracle VM VirtualBox Extension Pack Active Processor cores Disabled
Enabled
■ 'All supported platforms Limit CPUID Maximum
Supportfor USB2.0 endUSB3.0 devices. VirluolBc
(PutL). Measetnitall tile SemeVWSKKIActoAWMp,
FXiBraiie Dlsutiie Rli
VirtualBox 6.1.16 Software Developer Kit (SDK)

Coding & Programming


Installing a Virtual Environment

With the computer back up and running, locate 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 thatany VM installed will beable to access the
Internetand your home network resources, via the computer's,
already established, network connection. Click Yes, then, Install to
begin the installation.

$$Oracle VM VirtualBox 6.1.16

W a rn in g :
N e tw o rk In te rfa ce s

Installing the Orade VM VirtualBox 6.1.16 Networking


feature will reset your network connection and temporarily
disconnect you from the network.

Proceed with installation now?

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

Click on the Icons in the tree below to change the way features will be installed.

j- l a - I VirtualBox Application Orade VM VirtualBox 6.1.16


VirtualBox USB Support application.
0 i ^i ^ | VirtualBox Networking
_ j l - | VirtualBox Bridget
This feature requires 740KB on your
VirtualBox Host-C hard drive. It has 3 of 3
| VirtualBox Python 2.x Sl subfeatures selected. The
subfeatures require 0KB on your ...

Location: C : program Files\Orade\VirtualBox\

Version 6.1.16 Disk Usage < Back | Next > | Cancel

This section can be left to the defaults, should you With VirtualBox up and running, you can now
■ ■ ■ H ^ F 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'.
Oracle VM VirtualBox 6.1.16 Setup X

C usto m Se tu p

Select the way you want features to be installed.


^ VirtualBox - Information

Please choose from the options below: The extension pack


0 Create start menu entries
o Oracle VM VirtualBox Extension Pc
0 Create a shortcut on the desktop
was installed successfully.
0 Create a shortcut in the Quick Launch Bar

0 Register file assodations


OK

Coding & Programming 23


Coding on Linux

Installing Linux in a
Virtual Environm ent
With Oracle's VirtualBox now up and running, the next task is to create the Virtual
Machine (VM) environment into which you will install Linux. This process w on't affect
your currently installed operating system, which is w hy a V M is a great choice.

CREATING THE VM
There are plenty oF options to choose From when creating a VM. For now though, we'll setup a VM adequate to run the
excellent Linux Mint, and perForm well.

K E H S B ’: With VirtualBox open, click on the New icon in the The next section will deFine the amount oF system
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
yourcomputer, 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.

In the box next to Name type Linux Mint, and This section is where you'll start to create the virtual
VirtualBox should autom atically 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 (remem ber Mint using. Click Create to move on.
mainstream is based on Ubuntu). Click Next when you're ready
to proceed.

Coding & Programming


Installing Linux in a Virtual Environment

The pop-up window that appears after clicking 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 theSettings 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.

The question of whether to optfor Dynamically or 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
virtual hard disk is a more flexible storage management option. It won't 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.

The virtual hard disk will be a single folder, up to the B S H jr M 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.S0CB 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.

Coding & Programming 25


Coding on Linux

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

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

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

The Terminal will give you access to the Linux The flashing cursorat the very end of the line is
Mint Shell, called BASH; this gives you access to where your text-based commands will be entered.
the underlying operating system, which is why scripting is such a You can begin to experiment with a simple command, Print Working
powerful language to learn and use. Everything in Mint, and Linux Directory (pwd), which will output to the screen the current folder
as a whole, including the desktop and GUI, is a module running from you're in. Type: pwd and press Enter.
the command line.
david@davii
File Edit View Search Terminal Help
david@dav±d-mint - t pwd
/home/david
da vid(ada v i d - m i n t - $

Coding & Programming


Getting Ready to Code in Linux

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

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

Having access to the Terminal means you're 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 quickand handy backup waiting foryou.
deleted files.

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

Google dd if-/dev/random of=/dev/sda Q,

All Videos News Maps Images More Settings Tools

About 305.000 results (0 98 seconds)

udev - What does dd if=/dev/zero of=/dev/sda' do - Unix & Linux Stack ...
https //unix slackexchange convquestions/ /what-does-dd-rf-dev-zero-of-dev-sda-do »
8 Apr 2016 - dd if=/dev/zero ol=/deWsda bs=4096 count=4096 Q why 4096 is particularly used for
counter? This will zero out the first 16 MiB of the drive

Dd - Destroyer of Disks - Noah.org


www.noafi.org/wihi/Dd_-_Deslroyer_of_Disks *
10 Aug 2015 - sudo dd if=ubuntu-1d 04-desktop-amd64.dmg of=fdev/sda1 sudo cp II takes 30
seconds to destroy the file using 'dd if=/dev/zero of=somefile
Securely erase a drive Erase MBR Erase GPT (GUID Fill a file with bytes

Can "dd if=/dev/zero of=/dev/sda" physically damage your hard disk ...
https://wwwcenlos.org > Board index > C en tos General Purpose > C en tos Social *

Coding & Programming


Coding on Linux

Creating Bash Scripts


-P a rt 1
Eventually, as you advance with Linux Mint, you'll w ant to start creating your own
autom ated tasks and programs. These are essentially scripts, Bash Shell scripts
to be exact, and they w ork in the sam e way as a D O S Batch file does, or any other
program m ing language.

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

You'll be working within the Terminal and with a 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.
davii:
davii File Edit View Search Terminal Help
File Edit View Search Term inal Help david@david-mint — $ mkdir scripts
d a v i d @ d a v i d - m i n t - $ cd s c r i p t s /
david<adavid-mint ~ $ s u d o a p t - g e t u p d a t e & & s u d o a p t - g e t up g r
david@david-mint -/scripts S |
[sudo] p a s s w o r d for david:
H i t :1 h t t p : / / p p a . l a u n c h p a d .n e t / o p e n s h o t . d e v e l o p e r s / p p a / u b u n t u
H i t : 2 h t t p : / / p p a . l a u n c h p a d . n e t / p e t e r l e v i / p p a / u b u n t u x e n i a l In
Hit:3 http://archive.canonical.com/ubuntu xenial InRelease
Hit:4 http://ppa.launchpad.net/thomas-schiex/blender/ ubuntu x
Hit:5 http://archive.ubuntu.com/ubuntu xenial InRelease
I g n :6 h t t p : / / v / w w . m i r r o r s e r v i c e .o r g / s i t e s / p a c k a g e s . l i n u x m i n t .c
Get:7 http://archive.ubuntu.com/ubuntu xenial-updates InRelea
H i t : 8 http:// p p a . l a u n c h p a d . n e t / w i n e / w i n e - b u i l d s / u b u n t u xenial
H i t :9 h t t p : / / w w w . m i r r o r s e r v i c e .o r g / s i t e s / p a c k a g e s .l i n u x m i n t .c
H i t : 10 h t t p : / / r e p o s i t o r y . s p o t i f y . c o m s t a b l e I n R e l e a s e
.Get:11 h t t p ; / / a r c h i v e.ub.unlu , c o m / u b u n t u x e n i a l - b a c k p o r t s I n R e

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

d avi
File Edit View Search Terminal Help
|david@da v i d - m i n t - / s c r i p t s $ Is
scriptl.sh script2.sh scrlpt3.sh script4.sh
david@david-mint -/scripts S |

Coding & Programming


Creating Bash Scripts - Part 1

Let's start with a sim ple script to output som ething W hen you enter is again, you can see that the
to the Terminal. Enter xed helloworld.sh. helloworld.sh script has now turned from being
This w ill launch Xed and create a file called helloworld.sh. In Xed, white to green, meaning that it's now an executable file. To run
enter the Following: # ! /bin/bash, then on a new line: echo the script, in other w ords make it do the things you've typed into it,
Hello World!. enter: . /helioworld, sh.

davi
File Edit View Search Terminal Help

d a v i d @ d a v i d - m i n t - / s c r i p t s s xe d h e l l o w o r l d . s h david@david-mint -/scripts s xedhelloworld.sh


d a v i d @ d a v i d - m i n t - / s c r i p t s $ [] david@david-mint -/scripts $ Is
h e l l o w o r i d .sh
david@david-mint -/scripts $ ch m o d +x h e l l o w o r l d . s h
david(adavid-mint -/scripts S Is
File Edit View Search Tools Documents Help h e l l o w o r i d .sh
david@david-mint -/scripts s ./helloworld.sh
H e l l o World!
H e Di I" « ID 6 9. 9.
david@david-mint -/scripts S |
[ |*helloworld.sh X

# ! /bin/bash

echo H e l l o World!

The # ! /bin/bash line tells the system w hat Shell Although it’s not terribly exciting, the w ords 'Hello
you're going to be using, in this case Bash. The hash World!' should now be displayed in the Terminal.
(#) denotes a com m ent line, one that is ignored by the system, the The echo command is responsible for outputting the w ords after
exclamation mark (!) means that the com m ent 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.

*hi;
*helloworld.s File Edit
File Edit View Search Tools Documents Help
File Edit View Search Tools Documents Help david@da
david@d;
C IO Di **** X i D B Q, 9. hellowo
david@da
£> 6 Di ^ (□ 6 9, 9,

david<ada a ^helloworld.sh x
*helloworld.5h X hellowor
# ■ /bin/bash
david@da
# ! /b i n / b a s h
Hello W
e c h o H e l l o World! This is my fi r s t s c r i p t in Li n u x Mil
david@da
e c h o He l l o World!

You can save this file, clicking File > Save, and exit Think o f echo as the old BASIC Print command. It
back to the Terminal. Entering is, w ill 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
o f the week.
davi
File Edit View Search Terminal Help
david@david-mint -/scripts £ xe d h e l l o w o r l d . s h
david@david-mint -/scripts s Is
h e l l o w o r l d .sh
david@david-mint -/scripts S c h m o d +x h e l l o w o r l d . s h
david@david-mint -/scripts % |

Coding & Programming .9


Coding on Linux

Creating Bash Scripts


-P a rt 2
Previously w e looked at creating your first Bash script, H ello W orld, and adding a
system variable. Now you can expand these and see w hat you can d o w hen you start
to play around w ith creating your own unique variables.

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

Let's start by creating a new script called hello.sh; The output now w ill be Hello David. This is because
xed hello .sh. In it enter: # ! /bin/bash, then, Bash autom atically assigns variables For the user,
echo Hello $1. Save the File and exit Xed. Back in the Terminal which are then held and passed to the script. So the variable
make the script executable with: chmod +x hello.sh. '$1' now holds ’David'. You can change the variable by entering
som ething diFFerent: ./hello.sh Mint.

File Edit View Search Term inal Help


david<adavid-m int - / s c r i p t s $ . / h e llo . s h
H e llo
david@ david-m i.nt - / s c r i p t s S . / h e llo . s h David
H e llo David
d a v id @ d a vid -m in t - / s c r ip t s i . / h e llo . s h M in t
H e llo M in t
d a v id @ d a vid -m in t -/ s c rip t s $

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

david@davi< File Edit View Search Tools Documents Help

File Edit View Search Terminal Help


n © ^ vc x e c Q. 9.
d a v i d @ d a v i d - m i n t - / s c r i p t s s ./h e l l o . s h
He l l o
H*hello.sh x
d a v i d @ d a v i d ~ m i n t - / s c r i p t s % . / h e l l o . s h Da v i d
Hel l o David #!/bin/bash
davidjBdavid-mint - / s c r i p t s S | firstname=$l
surname=$2
echo H e l l o $ f i r s t n a m e $surname|

Coding & Programming


C reatin g B ash Scrip ts - P art 2

W hen you run the script now you can use two 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. A t the m om ent 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.

d greetings, sh

File Edit View Search Tools Documents Help


File Edit View Search Term inal H elp
d a v id @ d a v id -m in t - / s c r i p t s & ./ h e l l o . s h D a v id Haywan O Di
H e llo D a v id Hayward
d a v id @ d a v id -m in t - / s c r i p t s S ./ h e l l o . s h L in u x M in t B greetings.sh x
H e llo L in u x M in t
# !/b in /b ash
d a v id @ d a v id -m in t - / s c r i p t s s
echo -n Hello, w h a t is y o u r name? "
read firs tn a m e
echo -n "T h a n k you, a n d w h a t is y o u r s u r n a m e 7 "
read surname
c le a r
echo H e llo $ firstn a m e ^surname, how a re you today?

Create a new script called addition, sh, using We've added a -n to the echo command here
the same Format as the hello.sh script, but which w ill leave the cursor on the same line as the
changing the variable names. Here we've added firstnumber and question, instead oF a new line. The read command stores the
secondmumber, and used the echo command to ou tpu t some users’ input as the variables Firstname and surname, to then read
simple arithm etic by placing an integer expression, echo The sum back later in the last echo line. And the clear command clears
is $ (($firstnumber+$secondnumber) ). Save the script, and the screen.
m aKe ic ex ecu ca D ie tcnmoa +x aaaition.sn).
dav
addition.sh File Edit View Search Terminal Help
File Edit View Search Tools Documents Help H e l l o D a v id H a y w a rd , how a r e you to d a y ?
d a v id t a d a v id - m in t - / s c r i p t s S
^ « y. id g Q . &

B addition.sh x
# !/b in /b ash
firstnumber=$l
secondnumber=$2
echo The sum i s $ ( ($f irstn um b er+ isecon dn u m b er))

W hen you now run the addition.sh script we can As a Final addition, let's include the date variable
enter two numbers: . /addition, sh 1 2.The we used in the last section. Am end the last line
result w ill hopeFuily be 3, w ith the Terminal displaying 'The sum oF the script to read: echo Hello $firstname $surname, how
is 3'. Try it with a Few diFFerent numbers and see what happens. are you on this fine $ (date +%A) ?. The ou tpu t should
See also iFyou can alter the script and rename it do m ultiplication, display the current day oF the week, calling it from a system variable.
and subtraction.
greetings, sh

davic File Edit View Search Tools Documents Help

File Edit View Search Terminal Help P 6 °i ^ “■ Xi£>G Q. 9,


d a v id @ d a v ± d -m in t - / s c r ip t s $ ./ a d d it io n .s h 1 2
The sum i s 3 B greetings.sh x
■ d a v id fB d a v id -m in t - / s c r ip t s $ ./ a d d it io n .s h 34 45
# !/bin/bash
|The sum i s 79
d a v id e d a v id - m i n t - / s c r ip t s $ ./ a d d it io n .s h 65756 1456
echo -n "Hello, w h a t is y o u r n a m e ? "
IThe sum i s 67212 read firs tn a m e
d a v id e d a v id - m i n t - / s c r ip t s S . / m u l t i p l i c a t i o n . sh 2 8 echo -n "T h a n k you, an d w h a t is y o u r s u r n a m e ? "
The sum i s 16 read surname
d a v id @ d a v id - m in t - / s c r ip t s $ c le a r
echo H e llo $ firstn a m e $surnamer how a re you on t h i s f i n e $ (d a t

Coding & Programming


Coding on Linux

Creating Bash Scripts


- Part 3
In the previous pages w e looked at som e very basic Bash scripting, which involved
outputting text to the screen, getting a user's input, storing it and outputting that to
the screen; as w ell as including a system variable using the Date command. Now let's
com bine w hat you've achieved so Par and introduce Loops.

IF, THEN, ELSE


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

Let's look at the If, Then and Else statem ents now, The next line, ELSE, is what happens if the variable
which when executed correctly, com pare a set of doesn’ t equal 'David'. In this case it sim ply outputs
instructions and simply w ork out that IF som ething is present, TFIEN to the screen the now familiar 'Hello...'. The last line, the FI
do something, ELSE do som ething different. Create a new script statem ent, 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 w ithout a Fi command, then you get an error.
into it.
david@david
*greetings.sl File Edit View Search Terminal Help
File Edit View Search Tools Documents Help H e l l o P i n k Floyd, h o w are you on t h i s fine W e d n e s d a y ?
dauidQdavid-mint -/scripts £
p 5 Qi l i i s e

S *greetings.sh X

#! / b i n / b a s h

e c h o -n Hello, w h a t is y o u r name?
read firs tn a m e
e c h o -n "Thank you, and w h a t is y o u r s u r n a m e ?
read surname
clear
if [ $ firs tn a m e == David' ]

Creeting2.sh is a copy o f greeting.sh but with a You can obviously play around w ith the script a
slight difference. Here we've added a loop starting little, changing the name variable that triggers a
at the if statem ent. This means, IF the variable entered is equal to response; or maybe even issuing a response w here the first name
David the next line, THEN, is the reaction to w hat happens, in this and surname variables match a specific variable.
case it w ill output to the screen 'Awesome name,' follow ed by the
variable (which is David).

david@davi
File Edit View Search Terminal Help
A w e s o m e name, Da v i d
david@david-mint -/scripts S

Coding & Programming


C reatin g B ash Scrip ts - P art 3

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

Create a new script called count, sh, Enter the The UNTIL loop works much the same way as the
text in the screenshot below, save it and make it WHILE loop only, more oFten than not, in reverse.
executable. This creates the variable 'count' which at the beginning So our counting to a hundred, using UNTIL, would be: until
oF the script equals zero. Then start the WHILE loop, which WHILE [ $count -gt 100 ] ; do. The diFFerence being, UNTIL count is
count is less than (the LT part) 100 w ill print the current value o f greater than (the gt part) one hundred, keep on looping.
count in the echo command.
*count.sh (
count.sh (■ File Edit View Search Tools Documents Help
File Edit View Search Tools Documents Help
n e °r ^ y. ip e a
O O Di ir» y. ip e Q. &
B *count.sh x
B countsh X
#!/bin/bash
# ! /b i n / b a s h
until [
$ c o u n t -gt
ec h o $count
100 ]; do
count=0
let count=count+l
done
w h i l e [ $co u n t -It
echo $co u n t
let c o u n t = c o u n t + l
100 ;do
i
done]

Executing the count.sh script will result in the You're not limited to numbers zero to one hundred.
num bers 0 to 99 listing down the Term inal screen; You can, within the loop, have w hatever set oF
when it reaches 100 the script w ill end. M odifying the script with the commands you like and execute them as many times as you w ant
FOR statem ent, makes it w ork in much the same way. To use it in our the loop to run For. Renaming a million Files, creating Fifty Folders
script, en ter the text From the screenshot into the count.sh script. etc. For example, this script w ill create ten Folders named Folderl
through to fo ld e rl 0 using the FOR loop.
*count.sh (

File Edit View Search Tools Documents Help *count.sh (

File Edit View Search Tools Documents Help


U 6 ** «•
(P B Q .9 .
S *countsh x
# ! / b i n/bash B * count.sh x

#!/bin/bash
for count in {0..10© }; do
echo $count
for co u n t in {6|. .16};do
let c o u n t = c o u n t + l
mkdir Folder$count
done
let count=count+l
done

The addition we have here is: for count in Using the FOR statem ent once more, w e can
(0 . . 1 0 0 } ; do. W hich means: FOR the variable execute the counting sequence by manipulating the
’count’ IN the num bers From zero to one hundred, then start the {0..100} part. This section oF the code actually means {START..END..
oop. The rest o f the script is the same. Run this script, and the same NCREMENT}, if there's no increm ent then it's just a single digit up to
o u tpu tsh ou ld a ppe arin the Terminal. the END. For example, w e could get the loops to count up to 1000 in
W O ’ S With: lo t: c o u n t I n { 0 . . 1000 . . 2 }; do.

9 *count.sh x
*count.sh (

# ! / b in / b a s h File Edit View Search Tools Documents Help

£> C Di «■' ^ i P G CL &


f o r c o u n t in { 0 .. 1 0 0 } ; do
echo $ c o u n t a *count.sh x
L e t c o u n t= c o u n t+ l
# ! /bin/bash
done
| fo r co u n t in { 0 . . 1 0 0 0 . .2};do
ec h o $count
le t c o u n t = c o u n t + l
done

Coding & Programming 33


Coding on Linux

Creating Bash Scripts


-P a rt 4
You've encountered user interaction w ith your scripts, asking w hat the user's name
is and so on. You've also looked at creating loops w ithin the script to either count or
sim ply do som ething several times. Let's com bine and expand som e more.

CHOICES AND LOOPS


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

You can, o f course, increase the num ber of choices


File Edit View Search Tools Documents Help
bu tyo u need to make sure th atyo u match the
tl 6 i£lP6 9. &
The mychoice.sh script num ber o f choices to the num ber o f IF statem ents. The script can
ES mychoice.sh X
is beginning to look a # !/bin/bash quickly become a very busy screen to look a t This lengthy script
lot m ore complex. W hat choice=4 is another way o f displaying a menu, this time w ith a fancy colour
we have here is a list echo 1. Mint" scheme too.
echo '2. I s
of four choices, with echo "3. Awesome"
If/bin/bash
echo -n "Please choose an option (1, 2 or
three possible options. while [ Schoice -eq 4 ]; do
£='eeho -e ':e= 'ech o -en’ ;tr a p " R ;e x it " 2
e s c -S ( Se
The options: M int, Is, read choice
T P U T (){ $e ' \ e [ S { l ) :S { 2 } H - ;}
CLEARQl Se
C IV IS O t Se ’ le O E S ! ' ;}
and Aw esom e w ill be i f [ schoice -eq 1 ] ; then OftAW<){ 5® -^*^<><0' ; }
WRITEOC Se
echo 'You have chosen: Mint MARKOt Se ’ \e [7 n "; }
displayed if the user else UNMAftXOt i s -\«;[2Tn-j>
if [ Schoice -eq 2 ] ; then R< )t CLEAR ;s t t y sanc;$e -\e c \e [3 7 ;4 4 m \e (J"; ) ;
presses the correct echo You have chosen: Is" HEADO f DRAW
f o r each in Stseq 1 1 3 );do
else SE • x *"
option key. If not, then if [ $choice -eq 3 ] ; then done
echo "You have chosen; Awesome" WRITE[MARK;TPUT 1 S
else SE ’ BASH SELECTION NENU " ; UNMARK;)
the menu w ill reappear, echo ‘Please make a choice between 1 to 3" 1=8} CLEAR; cm s;N U LL= /de v/nuU
F00T O { MARK; TPUT 13 s
echo I Mint"
the fourth choice. echo "2. Is
printf "FNTFR
ARROWQt read -s -n3 key 2> /dev/null >12
SFI FCT.NFXT ";UNHARK;}

echo 3. Awesome I f ( [ Skey = $ESC[A ] ];th e n echo u p jf i


echo -n 'Please choose an option (1. 2 or 3) i f [ [ Skey = SE5C[8 ] ] ;t h e n echo d n ; f i ; )
TPUT a 20} s= Login In fo -’; )
choice=4
R l ( ) t TPUT 5 20; Se "N e tw o rk';}
fi R 2 ()t TPUT 6 20; Se " D is k * ;}
fi R 3 0 1 TPUT J 20; Se "R o u tin g ";}
R 4 (){ TPUT 8 26; Se " U M e ':}
R S Q t TPUT 9 20; Se "ABOUT " ; }
H6( ) { TPUT 18 20; Se "EXIT " ;}
IM=6
HENUOt f o r each in S(seq 0 SLM);do H ${each};do n e;}
P 0 S (){ i f [ [ Scur == up ]];th e n { ( i - ) ) ; f i
i f [ [ Scur == dr J ] : then < ( l * + ) ) ;f i
i f [ [ S i - it 0 JJjth e n l= $ L R jfl
i f ( [ S i -gt SLR ) ] ;then l=8 ; f i ; }
If you follow the script through you soon get the REFRESHOf a f t e r = S C ( U l) ) ; b e fo r e = $ (( l- l))
t r t [ Sberore -T t o ] ] ;t h e n Derore=5c";TL
i f [ [ S a fte r -gt SLR ]];t h e n a ftc r = e ;ft
hang o f what's going on, based on what we've i f [[ SI - It Si ] ] ; then UNMARK;HSbefore;«lse UNHARK;HSafter; f i
If [[ Safrer -pq * ]] || [ Shpfnrp -pq SIM ];thpn
UNMARK: RSheforc; R S a f t c r j f i ;J-Si;UNM ARK;M Sbefore;HSafter;}
already covered. WHILE, IF, and ELSE, w ith the FI closing loop IM IT () { R;HEAO;FOOT;MENU;}
S C ()t REFRESH;HARK;SS;Sb;cur= ARROW ; }
ES(){ m ark ; Se enter = natn menu ; S b ;re a d ;lN lT ;} ;INIT
statem ent w ill run through the options and bring you back to the w h ile [ [ '$ 0' != " " ] ] ; do case 51 in
8) S*MB SC i f [ scur . . "• ];th e n ;5e \nSCw ) \ " _ ;E S f t : ;
start if you pick the wrong option. 1 ) S=M1 sc i f f Scur = •- ] ; then ;S r \n $(tfco n Ig )\n * ;FS f i : ;
2) 5=M2 sc i f [ Scur == “ * ];th e n ;Se \n S(d f -h )\ n ' ; es f i : :
3) S-HJ sc i f [ $cur - - ] ; then ;Se \n$(route -n )\ n ' ;E S f i ; |
4) S=R4 sc i f [ Scur == - ];th e n ;Se \n$(date )\ n ' JES f t ; :
d a v id s jd avid -m in t -/sc rip ts SiMS bt [ scur == - ;s e \nsC5« by o io )\n - ;fcb f t ; ;
S) S=M6 sc i f [ Scur . . '■ ];th e n ;e x it e ; f i ; j
File Edit View Search Terminal Help esac;ROS;done
|david@david-mir»t - / s c r i p t s £ ./m ychoice.sh
1. M int
2. IS
3. Awesome
P le a se choose an o p tio n (1, 2 o r 3) 1 You can use the
You have chosen: M int
d av id gd av id -m in t - / s c r i p t s S ./m ychoice.sh arrow keys and Enter
1. M int
2. I s in the menu setup in the script. Each
3. Awesome
P le a se choose an o p tio n (1, 2 o r 3) 2 choice is an external com m and that
You have chosen: Is
david@ david-m int - / s c r i p t s S ./m ychoice.sh feeds back various inform ation. Play
1. M int
2. I s around with the com m andsand
|3. Awesome
[Please choose an o p tio n (1, 2 o r 3) 3 choices, and see w h atyou can come
You have chosen: Awesome
davidQ david-m int - / s c r i p t s S ./m ychoice.sh up with. It's a bit beyond w hat we've
1. M int
2. I s looked at but it givesa good idea of
3. Awesome
w hat can be achieved.

Coding & Programming


C reatin g B ash Scrip ts - P art 4

CREATING A BACKUP TASK SCRIPT


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

A very basic backup script would look som ething Once the -/backups Folder is created, we can now
along the lines oF: # ! /bin/bash, then, create a new subFolder within it based on the
tar cvrfz ~/backups/my-backup. tgz - “/Documents/, This Time Stamp variables you set up at the beginning. Add mkdir -p
will create a compressed File backup oF the -/D ocum ents Folder, $dest/"$day $month $year". It's in here that you put the
with everything in it, and put it in a Folder called /backups with the backup File relevant to that day/month/year.
name my-backup.tgz.
E9 backup 1,sh x

# ! /b in /b a s h
backupl.sh ('/scripts)
File Edit View Search Tools Documents Help c le a r
# Time stamp
d a y = s(d ate +%A)
^ x t D B m onth=$(date +%B)
ye a r= $ (date +%Y)
9 backupl .sh X
# F o ld e rs
# ! / b in /b a s h dest= ~/b ackups
sauce=~/Documents
t a r c v f z ~ /b a c k u p s/m y -b a c k u p .tg z -/Docum ents/I
i f [ -d S d e st ]; then
echo "Backup fo ld e r e x i s t s "
e ls e
echo Backup fo ld e r does not e x i s t ! I'm now c r e a tin g i t . . . " ; (m kdir -p Sd e st)
echo
fi
read -p " P r e ss any key to co ntinue . -n l -s
m kdir -p $ d e st/ $day Smonth $year

W hile perfectly Fine, we can make the sim ple script W ith everything in place, you can now enter the
a lot more interactive. Let's begin with deFining actual backup routine, based on the Tar command
some variables. Enter the text in the screenshot into a new backup, From Step 5. Com bined with the variables, you have: tar cvf z
sh script. Notice that we've m isspelt 'source' as ’sauce', this is $dest/"$day $month Syear"/DocmentsBackup.tgz
because there's already a built-in command called 'source' hence the Ssance. In the screenshot, w e added a handy "Now backing up..."
diFFerent spelling on our part. echo command.

£9 backupl .sh X

# ! / b in / b a s h

c le a r
# T im e stam p
d a y -S (d a t e
m o n th -$ (d a ta +%B)
y e a r= S (d a t e +%Y)

# Folders
d e st= ~ /b ac k u p s
s a u c e=~/Document s

i f [ -d S d e s t ] ; the n
e cho "B a ck u p f o ld e r e x i s t s "
e ls e
• c h o "B a ck u p f o ld e r d o e s n o t e x i s t ! I ‘ m now c r e a t i n g it ; (m k d ir -p s d e s t )
echo
fi
re ad -p " P r e s s a n y key to c o n t in u e . - n l -s
m k d ir -p S d e s t / Sday Smonth S y e a r

c le a r
• c h o "Now b a c k in g u p . P le a s e w a i t . . . "
t a r c v f z S d e s t / Sday Smonth S y e a r /D o c u m e n ts B a c k u p .tg z S sa u c e

The previous script entries allowed you to create Finally, you can add a Friendly message: echo
a Time Stamp, so you know when the backup was "Backup complete. All done...".T h e
taken. You also created a 'd e s f variable, which is the Folder where com pleted script isn't too over-complex and it can be easily
the backup File w ill be created (-/backups). You can now add a customised to include any Folder within your Home area, as w ell as
section oF code to First check iF the -/backups Folder exits, iF not, the entire Home area its e lf
then it creates one.
B backupl .sh X
# ! /b in /b a s h
B backupl .sh x
c le a r
# ! /b in /b a s h # Tim e stamp
d a y = S (d a te +%A)
m onth=S(date +%B)
c le a r y e a r= $(d a te +VO
# Time stamp
day = $ (d ate +%A) # F o ld e r s
m onth=$(date +%B) d e s t— /backups
sauce=~/Documents
y e a r=$ (d a te +%Y)
i f [ -d S d e s t ] ; then
# F o ld e r s echo Backup f o ld e r e x is t s "
d e st= "-/back ups echo kup f o ld e r does not e x i s t ! I ‘ n now c r e a t in g i t j (m k d ir -p s d e s t)
sa u c e=~/Docum ents echo
fi
read -p P r e s s any key to c o n tin u e . - n l -s
i f [ -d $ d e st 3; then m kd ir -p s d e s t/ sday smonth S y e a r
ache "Backup f o ld e r e x i s t s "
e ls e c le a r
■cho "Now b a c kin g up. P le a s e w a i t . .
echo Backup f o ld e r does not e x i s t ! I ’ m now c r e a t in g i t . . . " ; (m k d ir -p S d e st) t a r c v f z $ d e s t / ’Sday $month S y e a r /D o cum entsB ackup.tg z Ssauce
echo
fi

Coding & Programming 35


Coding on Linux

Creating Bash Scripts


- Part 5
The backup script w e looked at previously can be further am ended to incorporate
choices; or in other words, user-interaction w ith regards to w here the backup file w ill
be copied to and so on. Autom ating tasks is one o f the main benefits o f Bash scripting,
a sim ple script can help you out in many ways.

EASY AUTOMATION AND HANDY SCRIPTS


Are you entering line aFter line oF commands to retrieve system inFormation, Find a File or rename a batch oF Files? A script is a
better answer.

Let's start by creating a script to help display the Each oF the sections runs a diFFerent Terminal
M in t 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 lo t more, such as the current
Following into Xed, or the text editor oF your choice. aliases being used in the system, the current tim e and date and so
on. Plus, you could also pipe all that inFormation into a handy HTML
File, ready to be viewed in a browser.
■-----------------------------------------------------------------------------
david@david-mint -/scripts
File Edit View 5earch Terminal Help
Idav i d @ d a v i d - m i n t - / s c r i p t s 5 ./ s y s i n f o . s h > s y s i n f o . h t m l
david@david-mint -/scripts $

Although there are simple Terminal com m ands to


help you look For a particular File or Folder, it's oFten
more Fun to create a script to help you. Plus, you can use that script
For oth e r non-technical users. Create a new script called look4 .sh,
entering the content From the screenshot below.

look4.sh (-j1
We've included a couple oF extra commands in File Edit View Search Tools Documents Help
this script. The First is the -e extension For echo,
£ )© 0| X E> 6 Q.9.
this means it’ll enable echo interpretation oF additional instances
oFa new line, as w ell as other special characters. The proceeding Ej§ look4.sh X
'31;43m' elem ent enables colour For Foreground and background. #! /bin/bash

target*-/

read name

output=$( find $target -iname Sname 2> /d ev/ n u ll )

if [[ -n $output" ]]; then


echo $output"
else
echo ‘No match found"
f^

Coding & Programming


C reatin g B ash Scrip ts - P art 5

W hen executed the script waits for input from the The output from colours.sh can, o f course, be
user, in this case the file extension, such asjpg, mixed together, bringing different effects
mp4 and so on. It's not very friendly though. Let's make it a little depending on w h atyou w ant to the output to say. For example,
friendlier. Add an echo, with: echo -n "Please enter the white text in a red background flashing (or blinking). Sadly the
extension of the file you're looking' tor: " J u s t blinking effe ct doesn't work on all Terminals, so you may need to
before the read command. change to a d iffe re nt Terminal.

a *look4.sh x
Normal Text
#!/bin/bash
Default Default
target=~/ Default

read name
Yellow
output=$< find Starget -iname Sname 2> /dev/null ) Default

if [[ -n "$output" ]]; then


echo "$output ' Default Light gray
else
echo No match found Default
fi reu
Light green
Default Light yellow
Default Light blue
Default Light magenta
Default Light cyan
Here's an interesting, fun kind of script using the Default White
app espeak. Install espeak w ith sudo apt-get
Default Default
install espeak, then enter the text below into a new script called Default Black
Default Red
speak, sh. A s you can see it's a rehash o f the first greeting script Default Green
we ran. Only this time, it uses the variables in the espeak output. Default Yellow
Default |Blue
Default Magenta
a speak.sh x Default Cyan______
#! /bin/bash Defau^:
^HDarkgray
echo -n Hello, what is your first name? " Default Light red
read firstname Default Light green
echo -n “Thank you, and what is your surname? "
read surname
clear ■ ■ ■ L i g h t blue
espeak Hello $ firs t n a m e Ssurname. how are you on this fine S(date Default Light magenta
Default Light cyan
Default ■ ■
david@david-mint •/scripts

We briefly looked a t putting som e colours in the


output for our scripts. W hilst it’s too long to dig a W hilst w e'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 w h a tyo u 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 o f dialogue
boxes appear, follow ed by a final message.
E9|colours.sh x
#!/bin/bash E9 mmenush X

c le a r # ! /b in /b a s h
echo e "N o rm a l \ e [lm B o ld "
echo e “ N o rm a l \ e [ 2mDim" firs tn a m e = $ < z e n ity - - e n t r y - - t i t l e = ' Your Name - te x t= W h a t i s yo ur f i r s t nam e?’ )
echo e 'N o rm a l \ e [4 m U n d e r lin e d "
s u rn a m e = $ (ze n ity - - e n t r y - - t it le ® "You: Name - -text=~W hat i s yo ur f i r s t surnam e?' )
echo e 'N o rm a l \ e [ 5 m B l in k "
echo e 'N o rm a l \e [7 m in v e rte d "
z e n i t y - - in f o - - t i t l e = “ H ell< --te x t= 'W e lc o m e to L in u x M in i;. s n \n Have fu> , S fir s tn a m e Ssurname-
echo e 'N o rm a l \ e [8 m H id d e n "
echo
echo e ' \ e [ 0mNo r m a l T e x t "
echo

echo e “ D e fa u lt \e [3 9 m D e fa u lt"
echo e ' D e f a u l t \ e [ 3 0 m B la c k " W hile gaming in a Bash script isn't som ething
echo e “ D e f a u l t \ e [31mRed"
echo
echo
e 'D e f a u l t \ e [3 2 m fir e e n " that’s often touched upon, it is entirely possible,
e ‘ D e f a u l t \ e [ 3 3 m Y e llo w "
echo
echo
e 'D e f a u l t \ e [3 4 m B lu e "
e 'D e f a u l t \ e [35m M agenta“
albeit, a little basic. Movement-based games are diffiuclt, and
echo e “ D e f a u l t \ e [3 6 m C y a n "
echo e • D e f a u lt \ e [ 3 7 m L ig h t g r a y "
som etim es buggy, however a good text adventure, or Fighting
echo e “ D e f a u l t \e [9 0 m D a r k g r a y "
echo e 'D e f a u l t \ e [ 9 1 m l ig h t r e d " Fantasy type game is a perfect choice for gaming in the Terminal,
echo e 'D e f a u l t \ e [ 9 2 m L ig h t g r e e n ”
echo e " D e f a u l t \ e [ 9 3 m L ig h t y e llo w " give ita go, and let us know how you get on.
echo e 'D e f a u l t \ e [ 9 4 m L ig h t b lu e "
echo e 'D e f a u l t \ e [ 9 5 m L ig h t m a g e n ta "
echo e • D e f a u l t \ e [ 9 6 m L ig h t c y a n "
©

echo e " D e f a u l t \ e [9 7 m W h ite " -0 -0 -0 -0 -0


0
0
a

1
1

echo
echo e 'D e f a u l t \ e [ 4 9 m D e f a u lt '' -0 -0 -0 -0 -0 -0 -0 -0 -0 -0
echo e 'D e f a u l t \ e [4 0 m B la c k ''
echo e " D e f a u l t \ e [4 1 m R e d " /o\/o\/o\/o\/o\/o\/o\/o\/o\/o\
echo e ' D e f a u l t \ e [4 2 m G r e e n "
echo e “ D e f a u l t \ e [ 4 3 m Y e llo w "
echo e " D e f a u l t \ e [4 4 m B lu e "
/o\/o\/o\/o\/o\/o\/o\/o\/o\/o\
echo e 'D e f a u l t \e [4 5 m M a g e n ta ”
echo e " D e f a u l t \ e [4 6 m C y a n ”
echo e “ D e fa u lt
echo e 'D e f a u l t \e [1 0 O m D a rk g r a y "
echo e " D e fa u lt \ e [ 1 0 lm lig h t re d "
echo e " D e f a u l t \ e [ 1 0 2 m L ig h t g r e e n "
echo e 'D e f a u l t \ e [ 1 0 3 m L i g h t y e llo w " mu uuu mu ###
echo e 'D e f a u l t \ e [ 1 0 4 m L i g h t b lu e " it ttftU K »#### uuuuu
echo e " D e f a u l t \ e [ 1 0 5 m L i g h t m a g e n ta " U ttU U U U U ####### ####### #######
echo e 'D e f a u l t \ e [ 1 0 6 m L i g h t c y a n " ## ## u# ## ## uu
echo e " D e f a u l t \ e t l0 7 m W h it e " ** **

Coding & Programming


< /> Coding on Linux

C om m and Line
Quick Reference
W hen you start using Linux full time, you w ill quickly realise that the graphical
interfaces o f 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 o f
Linux but also improves your know ledge o f coding and program m ing in general. O ur
com mand line quick reference guide is designed to help you m aster Linux quicker.

TOP 10 CO M M A N D S
These may not be the most common commands used by everyone but they will certainly Feature Frequently For many users oF
Linux and the command line.

The c d com m and is one oF the com m andsyou The m? com m and moves a File to a diFFerent
w ill use the m ost at the com m and line in Linux. It location or renames a File. For example mv file
allow s you to change your working directory. You sub renames the original File to sub. mv sub
use it to move around w ithin the hierarchy oFyour -/Desktop moves the File 'sub' to your desktop
File system. You can also use chdir. directory but does not rename it. You must speciFy
a new Filename to rename a File.

The is com m and shows you the Files in your The chown command changes the user and/
current directory. Used with certain options, it lets or group ow nership oF each given File. IF only an
you see File sizes, when Files w here created and File ow ner (a user name or numeric user ID) is given,
permissions. For example, is - shows you the Files that user is made the ow ner oFeach given file, and
that are in your home directory. the Files' group is not changed.

The cp command is used to make copies oF Files The chmod com m and changes the permissions on
and directories. For example, cp file sub makes the Files listed. Permissions are based on a Fairly
an exact copy oF the File whose name you entered sim ple model. You can set permissions For user,
and names the copy sub but the First File will still group and world and you can set w hether each can
exist with its original name. read, w rite and or execute the File.

The pwd command prints the Full pathname of The m c o m m a n d removes (deletes) Files or
the current working directory (pwd stands For directories. The removal process unlinks a Filename
"print working directory"). Note that the G N O M E in a Filesystem From data on the storage device
terminal also displays this inFormation in the title and marks that space as usable by Future writes. In
bar o f its window. other words, removing Files increases the am ount
o f available space on your disk.

The clear com m and clearsyou rscreen if this Short For "make directory", mkdir is used to
is possible. It looks in the environm ent fo r the create directories on a file system, if the speciFied
terminal type and then in the terminFo database directory does not already exist. For example,
to Figure out how to clear the screen. This is mkdir w ork creates a w ork directory. M ore than
equivalent to typing Control-L when using the one directory may be speciFied when calling mkdir.
bash shell.

Coding & Programming


(r

C :\Commonly_Used_Commands

USEFUL HELP/INFO C O M M A N D S
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 iw aiis com m and displays the to ta l am ount The H iS l com m and opens a stream editor.
o f free and used physical and swap m em ory in A stream e dito r is used to perform text
the system. For example, gives the transform ations on an input stream: a file or input
inform ation using megabytes. from a pipeline.

The EH com m and displays filesystem disk space


The gg£jggnng command adds a new user to the
usage fo r all partitions. The com m and m a i l
df adduser system. Similarly, the BEBBBBBBI com m and adds a
is probably the m ost u seful (the -h means
new group to the system.
human-readable).
Y//A

The BUM program provides a dynamic real-time


view o f a running system. It can display
system summary inform ation, as welt as a list
o f processes.

The BffBWHB com m and w ith the B § option prints


all system inform ation, including machine name,
kernel name, version and a few o th e r details.

The [|§ com m and allow s you to view all the


The command brings up the manual
processes running on the machine. Every
man man en try for the man command, which is a great place
operating system's version of ps is slightly
to start when using it.
d iffe re n t but all do the same thing.

W//////7A '////A
The ffH Sffi com m and allow s you to search inside a The B B lW iB H B com m and is especially useful.
num ber o f files for a particular search pattern and It displays the Introduction to User Commands,
then prin t m atching lines. An exam ple w ould be: man intro which is a welt w ritten, fairly b rief introduction to
|grep blah file| the Linux com m and line.

Coding & Programming 39


C o d e P ro jects and Ideas

To help you on your way to becoming


a better coder, we've included some
great coding projects and ideas that
you can apply to your own code, use
as a demo For those who are starting
to code, or improve and send out into
the coding community. Want to learn
how to era Ft some retro code? How
about learning how to code a text
L-J
adventure? These and more are all ii! u
2
Found in this Final section. S ill
n
M
>■
UJ
No matter where you go next in J 1
coding, whether it's on to learning
more languages, creating amazing
apps and games, or helping out and
teaching new coders to avoid the
pitFalls you made, remember the
basics, and have Fun!

From here, it's down to you and your f lir t


[rytrjfpf 11 i p 7[T|7j
imagination. So dream it, and code it. m l l l i r ' fTflj
llfrl«17||
11'1iJH
142 P la n n in g y o u r C o d e 11ni[ [«1iW
144 F in d in g R e s o u rc e s
iiin m
146 C re a tin g a L o a d in g S c re e n iTFW fM ~ "| J j 1llli^ I ' l ' i ' M 'I f 11 ■ I.
148 P la n n in g a T e x t A d v e n t u r e h v w is m t * ■ ‘j *w n 1Wij' n n a r r
150 T e x t A d v e n t u r e S c r ip t t iB M l i ' m t m 'J 'I i H i j n i
F u B 111 51B P r i r i
152 R e t ro C o d in g

156 C o m m o n C o d in g M is ta k e s jJTTM T
158 P y th o n B e g in n e r 's M is ta k e s

160 C++ B e g in n e r 's M is ta k e s

Coding & Programming


Index

Coding & Programming


C o d e P ro jects and Ideas

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

You w ill find that nearly all the professional developers out there w ill
set aside some time to plan out how their code is going to fit into the
wider project on which they're working. Regardless o f w hether they're
working as part of a team on the latest game, developing a w orkflow
user interface for the company, or creating a set o f automated
tasks that can be used across a num ber o f different platforms, each
developer will set out their code in a plan.

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


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

PSEUD O CO DE
Code Example
Line 1 RECEIVE userName FROM (STRING) KEYBOARD
Line 2 RECEIVE pmNmnber FROM (STRING) KEYBOARD
Line 3 IF userName VALID OR pinNumber VALID THEN
Line 4 Allow access to network
Line 5 ELSE
Line 6 SEND “Access Denied” TO SCREEN
Line 7 END IF

N = input
One o f the more popular m ethods 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 im plem entation of code, the sequence continue to plan the remainder
of the actions, using plain English and a mixture o f code examples o f the code needed w ithout
together with a flowchart or two to help 'picture' loops within the taking up too much valuable
coding project. t im e - b u t while also having a
readable plan o f action for how
For example, a developer who is planning to write a program that w ill the code is going to be formed.
check user input for odd or even numbers w ill probably begin with a
basic statem ent o f pseudocode: The actual writing o f 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 statem ent can be expanded: a plan o f action in place, the

Coding & Programming


Planning Your Code

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

This process w ill not only trim the Fat o ff the code before it's even
written but w ill 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 you r 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 o f coding games - is
graph paper.

Super M ario Bros., launched for the Nintendo Entertainm ent


System in 1985, was nearly exclusively drawn o u t - b o t h characters
and levels - on graph paper b efore being applied to code. Entire Once the graphical planning stage is com plete, it's then down to
game maps w ere often created this way, especially on the you as the developer to fill in the blanks, as it were. This means
old e r 8-bit machines such as the Com m odore 64 and Sinclair ZX creating the code that w ill place and anim ate you r characters
Spectrum home com puters. 8-Bit graphics w ere ideal fo r graph w ithin the game, as w e ll as developing interactions, collision
paper since the sprites used then w ere m ade up o f eight or sixteen detection, num ber o f lives, and so on. W ith the help o f some
blocks; the developer could then visualise the layout o f the sprite pseudocode, you could easily plan ou t w hat m odules you'd use or
using the drawing on the graph paper and apply that to the code. create, the num ber o f variables needed, and the various endgam e
The end result, o f course, is the character appearing on the screen. states that w ill arise when som eone plays you r game.

G ET PLANNING
The w hole poin t o f planning is to create som ething easy to fo llo w that
w ill help you w rite the code fo r your project. Planning isn't supposed
to be a chore; it's there to aid you when you get stuck trying to w ork
ou t which variables you've used, w here you are in the game, with w hat
you're le ft and how the game w ill eventually pan ou t and end.

W hen planning, begin with sm all steps. Coding a Hangman game, for
example, begins w ith the plan to get the player's name, then includes
the w ord bank, drawing ou t the stages o f the Hangman, asking the
righ t questions, and finishing the game in one of two s ta te s - a win or
a lose - then asking if the player w ants another go.

Once you're used to planning it'll come naturally, and y o u 'll find
you rse lf thankful fo r all those post-it notes stuck to a sheet o f A3
paper, as w e ll as the ream s o f graph paper that d e ta il your characters
and level designs.

Pseudocode Actual Python code

if the score is 90 or above if score >= 90;


grade is an "A " grade = "A"
else else:
if the score is 80 or above if score >= 80: Pseudocode flowcharts can be simple, or as complex
grade is a "B " grade = "B" as necessary
else else:
if the score is 70 or above if score >= 70:
grade is a f>C “ grade = "C”
else else: Writing pseudocode will help
grade is an “F ” grade = "F"
you visualise the actual code

Coding & Programming !3


«
C o d e P ro jects and Ideas

Finding
Resources
The Python com m unity is huge and spans countless websites and forum s on the
Internet, so finding extra help here and there isn't too much o f a problem. However,
finding good Python resources can be, so here are som e ideas for you to try.

You w ill reach a point in your Python coding experience when you need to rely f reeCodeCamp(A)

on some external resources to help you through a sticky patch in your project
Welcome t o free Code Cam p .o rg
or give you a bit of inspiration. Python resources are available throughout
Learn to code.
the Internet, but not all o f them are any good. If you spend any time looking
up code fo ra particular project, then you're likely to come across copious B uild p rojects.

examples, yet not all o f them seem to work.


Earn c e r t if ic a t io n s .

That's one o f the main issues with resources for Python. W ith the language Since 2814, more than 40,080 freeCodeCainp.org graduates have gotten
Jobs at tech companies including:
being twenty-nine years old, and many different versions under the bridge,
there's a significant am ount o f content out there that's simply out of date - or Apple Google Amazon M icrosoft S p otify

just wrong for the version you're using. Newer versions, even by one number Sign in and get s ta rte d ( I t ' s fre e )
out, can have d ifferent outputs for your code from a previous version - it's
C e rtification s:
not always that case, but it can happen. Therefore, you need to find yourself Responsive Web Design
some trusted Python resources that work, or at least 90% would work, with the
version you're using and the code within.

THE HITCHHIKER'S GUIDE TO PYTHON T™ “

One o f the first places that's worth turning to is: freeCodeCamp.org. This website P ytho n Exa m p le s

features a wealth o f code that covers most aspects o f the learning experience, □ TUTORIALS S EXAMPLES 0 REFERENCES © ONUNE COMPILER

even for those who are experts at Python. You'll find content that w ill take your Popular Examples

Python journey to new heights; with code snippets to help you access networking
elements, military-style encryption and more, and you can even gain certification
through the site.

Programiz is another useful resource that features Python code examples


covering a wide range o f concepts. There’s everything in here from the original
"Hello, world!" code, through to code that will transpose a matrix or find the hash
of a file. There’s also an online compiler and in-depth looks into further reading Python program to interchange first and last elements in a list
for aspiring data scientists. Given a Hat, write a Python program to swap first and last element of the Use.

If you're looking for resources about using graphics in Python, then Input ! [12, 35, 9, 55, 24)
Output 3 [74, 15, 9, 56, 17J
ProgramArcadeCames.com is a good place to start. This site has plenty of code for Input ! f l , 2, 31
the Pygame module, including moving an object around the screen using a mouse Output s [3, 2, 1)

or game controller, creating fractals, moving sprites, and an example o f a classic Approach #1 r I ind the length of the list and simply swap the first element with {n-1 )th element

Pong game for you to try out.

GitHub is always worth a look. However, the code featured here isn't always up
to date, and you may find yourself having to convert Python 2 code into Python
iv Swopping
U-p « n«wLl»L[0)
3. Nevertheless, you do come across some gems from time to time, especially if
21
newlist[W] ■ newList[si£« - l]
newList[sl e - ] = temp
you look up the Pygame examples that users have uploaded. We recommend the
excellent Solarwolf, by Pete Shinners.

Coding & Programming


Finding Resources

m p o r t pygsme

£ Define some colons


buvck = (0. 0, 0)
IJ-HTE = (255, 255, 255)
G’EE'J = (8, 255, 8)
kED = (255, e. e)
SLUE = (5*. 50. 255|
D-OE’EE'I = (0, 1», 0)

£ T h is c l a s s re p re se n ts t h e p la y e r
£ I t d r i v e s ” ron tn e ’ S p r it e ' c la s s in Fygame
c la s s Pla> e"(pygflrte.sp,,it e . :5 p r i t e ) :
£ C o n s t r u c t o r . P a ss in t r e co lo n o f t h e b lo c k , and i t s x and y p o s itio n
def in i t ( s e lf ) :
£ C a l l t h e p a re n t c la s s ( S p r it e ) c o n s t ru c t o r

£ V a r ia b le s t o h o ld t h e h e i y r t and w idth o f t h e olocfc


w id th = 20

STRONG GOOGLE-FU h e ig h t = 15

£ C re a te an image o f tn e p la y e r , and f i l l i t w ith a c o lo r .


There's no trick to Finding good Python resources online; m ost £ T h is co u ld a ls o y t am image lo aded *ro n trie d is k ,
s e l f , image = pygame. S u r f a ce ( [ w id t h , h e ig h t ] )
o f the time, it’s a case o f trial and error. You’ll need to make sure s e l f . image . f i l l (B U C K )
you're searching fo r the right content, though, ju st to save you
£ Fetch t h e r e c t a n g le o b je c t t h a t h a s th e dim ensions o f th e image
some time. If it's a Pygam e specific set o f resources you 're looking s e i f . r e c t = s e l f . image .g e t jn e c t ( )

For then y o u 'll need to specify the Python version you're using; £ Uodate th e p o s it io n o f th e p la y e r
include Pygame, and include w hat it is you're looking for - it may •def update ( s e l f ) :
£ Get t h e c u r r e n t mouse p o s it io n . T h is r e t j m s t h e o o s it io n
sound like w e’ re teaching you to suck eggs, but effective searching £ as a l i s t o f two numbers,
pos = p y g am e.n ouse.g et_pos()
is often overlooked.
£ Fetch t i e x and y ou t o f th e l i s t , j u s t l i c e w e'd f e t c h l e t t e r s o j t
£ o f a s t r in g .
£ fJOTE: I f you want t o ceeo th e mouse a t t h e r o t t e n th e s c r e e n , j u s t
Again, it’s also w orth looking up w orking exam ples o f a type o f £ s e t y s 5S0, and no t update i t w ith t h e mouse p o s it io n sto red in
f p o s [ l]
game if you're looking for Pygame content. If you w an t to learn X = oos[0]
how to engineer sprites moving from one side o f the screen
to the other, then look up some exam ples o f Space Invaders, £ S e t t h e a t t r ib u t e f o r t h e too l e f t co rn e r where t h i s o b je c t i s
£ lo cated
which feature such m ovem ents. The same goes if you're making s e lf .r e c t .x = x
s e if .r e c t .y = y
a platform game, exam ine som e classic games that involved
platform ing, like M ario and so on. pygame. i n i t ( )

£ S e t t i e " e ig n t and width o f th e screen


s i r e = [7&S, =00]
screen = pygame. d is p l a y . set_mode( s i r e )
One last resource is our very own code portal. Log in to
£ D o n 't d is p la y t h e mouse a o in te r
https://pclpublications.com/exdusives , and y o u 'll find a LO/gsme.mouse. s e t _ v i s ib l e ( F a ls e )
continually grow ing list o f Python code and resources that you can
£ Loop >until t r e u se r d i c e s th e c lo s e b u tto n ,
freely add to you r own code, then chop, change, and use for done = - a ls e
w hatever projects you have in mind.
£ Used t o manage how ~ sst th e scre e n up dates
c lo c k = pygame". t im e .C lo c k ( )

£ T h is i s a l i s t o f ' s o r i t e s . ' Each s p r it e in th e program ( t h e r e i s o n ly 1) i s


£ aided t o t h i s l i s t . The l i s t i s managed by a c l a s s c a ll e d 'G ro u p .'
a l l _ s p r i t e s _ l i s t = pygame. s p r i t e . Group ()

£ T h is re p r e s e n ts th e b a l l c o n t r o lle d by t h e p la y e r
p la y e r = P la y e r Q

£ -dd tn e o a l l t o th e l i s t o f p la y e r - c o n t r o lle d o b je c t s
a l l _ s p r i t e s _ l i s t . add (p la y e r )

£ ------------- H a m P ro g ra m L w p --------------------
w h ile not done:
f o r e ven t in pygame. e v e n t , g e t ( ) :
i f e v e n t .ty p e = pygame.QUIT:
done = True

£ — Game lo g i c
a ll_ s |id t e s _ lis t .u p d a t e ( )

£ — D is p la y f Drawing coda

£ C le a r tn e screen
s c r e e n , f i l l (U tTTE)

£ Update t h e p o s it io n o f th e o a l l (u s in g t h e mouse) and draw t h e o a l l


a ll _ s p r it e s _ li s t _ d P B w ( scre e n ]

£ L in i t _t o £0 fram es p e r second
c lo c k .t ic k ( = 0 )

£ Go ahead and update t h e scre e n w ith wnat w e've drawn.


pygame. d is p l a y . f l i p ( )

j/ js iis .q jit Q

Coding & Programming 15


«
Code Projects and Ideas

Creating a Loading Screen


IF you're looking to add a little som ething extra to your Python code, then consider
including a loading screen. The loading screen is a short introduction, or piece oF art,
that appears beFore the main part oF your code.

LOAD"" THE CODE


Back in the 80s, in the 8-bit Launch Python and e nter the follow ing code to a New Fii
hom e com puting era, loading
import os
screens w ere often used to
import time
display the cover o f a game
as it loaded from tape. The def loading s c r e e n (s e c o n d s ) :
J I k . im age w ould load itse lf in,
usually one-line-at-a-time, for lines in s c r e e n s :

© RERLTIME Q
-
SOFTURRE 54
m lA 1

t
then proceed to colour
its e lf in w hile the loading t i m e .s l e e p (seconds)
raster bars danced s c r e e n s .c l o s e ()
around in the borders of
#Main Cod e Start
the screen.
o s .s y s t e m ( 'els' if os.name == 'nt' else
Loading screens w ere a part o f the 'clear')
package and often the buy-in for loading screen (.5)
the w hole game as an experience. Some
rint ("\nYour code begi n s here...")
loading screens featured anim ations, or a countdow n fo r tim e
rem aining as the game loads, w hile others even w ent so far as to
File Edit Form at Run Options W indow Help
include some kind o f playable game. The poin t being: a loading
|import os
screen is n ot ju st an a rtistic part o f com puting history, b u t an lnport time
introduction to the program that's about to be run.
def loading_screen(seconds):
screens=open(“screens.txt“, *r *)
W hile these days loading screens may no longer be w ith us, in for lines in screens:
term s o f m odern gaming w e can still include them in ou r own print(lines, end='')
time.sleep(seconds)
Python content. Either ju st fo r fun, or to add a little retro-them ed screens.close()
spice to the mix.

SCREENS #Main Code Start


os.system('els' if os.name == 'nt' else 'clear')
loading_screen(.5)
Creating a loading screen in Python is rem arkably easy. You have
several options to hand: you can create a tkin te r w indow and print ("NnYour code begins here...")

display an image, follo w ed by a brief pause, before starting your


main code, or you could opt fo r a console-based ASCI^ art version
that loads one-line-at-a-time. Let's lo ok at the la tte r and see how
it works.
The code is quite simple: im port the OS and Time m odules and
First you'll need some ASCII art, you can look up plenty o f examples
then create a Python Function called loading_screen w ith a
online, or use an image to ASCII A rt converter to transform any
(seconds) option. W ithin the fu n ction, o pen the te xt file with the
images you have to ASCII. When you have your ASCII art, drop it into
ASCII art as read-only and create a S B loop th a t'll read the te xt
a newly created folder inside a normal text file.
file one-line-at-a-time. Next, print the lines - incidentally, the
S E L E S E S elem ent w ill strip the new line From th e te xt
L
File Edit Search Options Help docum ent, w ith o u t it y o u 'll end up with a double-line spaced
_(!)_ wWWWw display. Include the tim ing in seconds and close the te xt file buffer.
(_)@(_) vVWv (__ ) The final part o f the code, is w here you'll
@@066 wwwww ( _ ) \ (___ ) @ 6066 Y (_)©{_)
@@@@ (__ ) '\ f y (_)©(_.) @@@@ M/ C_)\ clear the screen (CLS For W indows, Clear for Linux (Raspberry
/ Y \| \|/ /(_) \| |/ 1
\ 1 \ 1/ l /\ l / \|/ 1/ M \|/ Pi) and macOS) and call the Function, together w ith the output
|// \\|/// \\\|//\\\|/// \|/// \\\|// \ \ | / / \\\|//
num ber o f seconds to w ait for each line to be w ritten to the screen
- in this case, .5 of a second.

Coding & Programming


Creating a Loading Screen

(_)_ wWWWw
>rint ("\nYour code begins h e r e . ..
@
@@@ (.)0( ) vVWV ( ) ()
m m wwwww ( )\ ( ) () m m v (: )@( )
( ) •|/ V <m ) \ i1 ( )\ The code works in much the same way as the previous, except,
/ Y VI VI/ a ) M / l
\ 1 \ 1/ 1/ \ 1/ M/ 1/ \| \|/ instead o f reading from a te xt file, it's running through a For loop
1// \\|/// \\\|//\u|//y \|/// \\\|// \\|// Y\\|//
that prints Loading... follow ed by an animation of sorts, along w ith a
yo ur code b e g in s h e r e . . . percentage counter; clearing the screen every second and displaying
C;\Users\david\Docui!ients\Python\SplashScr> the new results. It's simple, yes, but quite effective in its design.

Save the code as screens.py, drop into a Command P rom pt or COMBINING TH E TWO
Term inal and execute it. The screen w ill clear and you r ASCII art
Flow about com bining the two elem ents we've looked at? Let's
inside the text file w ill load in line-by-line, creating a loading
begin w ith a Loading... progress bar, follo w ed by the loading
screen effect.
screen. A fte r that, you can include your own code and continue
you r program. Flere's the code:
LOADING...
timel
inpniNr
Luriuii iu loading bar(seconds):|
for loading in r a n g e (0,seconds+1) :|
percent = (loading * 100) // seconds!
pr int("\n") |
print("Loading..
p r i n t ("<" + ("-" * loading) + (' * (seconds-!
A n oth e r favourite introduction screen is th a t o f a sim ple loading
loading ) ) + "> " + str(percent) +
anim ation, w here the w ord loading is displayed, follow ed by
print("\n")|
some characters, and a percentage o f the program loaded. W hile
t i m e .s l e e p (
it may not take long for your Python code to load, the e ffe c t can
o s .system('els' if os.name == 'nt' els
be interesting.
'clear'
Create a New File in Python and enter the follow ing code:
def 1oa ding screen(seconds) :|
screens=open("screens.txt"
import time for lines in screens:|
print(lines, end='')|
def loading bar(seconds):
ti m e .sleep(seconds) |
for loading in ran g e (0,seconds+1):
screens.clo s e (
percent = (loading * 100) // seconds
print("\n") #Main
p r i n t ("Loading.. 1 loading_bar(10) |
p r i n t ("<" + C * loading) +
loading)) + "> " + str(percent) + "%") |
(seconds- V o s .s y s t e m ('els' if o s .name ==
loading screen(.5)1
'nt' else Aclear'

print("\n")
print ("\nYour code begins here.
t i m e .s l e e p (1)
os.system!'els' if os.name == 'nt' els You can, o f cours^, pull those functions up w herever and w henever
'clear') you w ant in you r cade and th e y'll display, as they should, at the
beginning. Rem em ber to have the ASCII text file in the same folder
#Main Code Start
as the Python code; or, at the screens=open("screens.txt”, 'r') part
loading b a r (10)
o f the code, point to w here the te xt file is located.

AD VEN TURE TIME


A good example o f 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
having a play around with and it’ll definitely add a little
som ething else extra.

Coding & Programming


Code Projects and Ideas

Planning a Text Adventure


Planning a text adventure is one o f the best ways oF teaching yourselF som e new
Python tricks and essential code. A good text adventure contains many aspects, all oF
which w ill need to be careFully planned and structured, to get the best From the code.

If you can think back to some o f the classic text adventures you
may have played in the past, consider the am ount o f 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.
co.uk/gam es/play/5zyoqrsugeopel3ffhz_vq. This is an online version
of the classic text adventure Zork.Zork was created for the DEC PDP
10 workstations, using the M D L programming language back in the
late seventies. Despite its age, it's still considered one o f the best text
adventures to play. The second crucial elem ent is choice. W ithout that, the player may as
w ell 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
Welcome to ZORK.
wrong, they could be punished, whereas a correct choice could gain
Release 13 / Serial number 040826 / Inform V6.14 Library 6/7
W e s t o f H o u se
them gold or some other form o f reward. However, it doesn't always
This is an open field west o f a white house, with a boarded front door. need to be a positive or negative choice; after all, m ost common real-
There is a small mailbox here.
A rubber mat saying ’Welcome to Zork!' lies by the door. life decisions we make aren't life or death, they merely result in one
>open mailbox thing happening or another.
You open the mailbox, revealing a small leaflet

>read leaflet
(first taking the small leaflet) Locations are similarly important. Text Adventures rely on good the
WELCOME TO ZORK
locations featured in the game can draw a picture in the mind o f the
ZORK is a game o f adventure, danger, and low cunning. In it you will explore some o f the most amazing
territory ever seen by mortal man. Hardened adventurers have run screaming from the terrors contained player. W hether they're on a wooden ship in the middle of the sea or
within!
trying to escape a haunted mansion, each location has to stand out.
In ZORK the intrepid explorer delves into the forgotten secrets o f a lost labyrinth deep in the bowels of the
earth, searching for vast treasures long hidden from prying eyes, treasures guarded by fearsome monsters
and diabolical traps!
Items are also a vital requirement for a good adventure game. A
Zork, o r any o th e r te xt adventure game, features several elem ents player w ill need to be able to pick up, examine, take, and use, an item
necessary to m ake the game both interestin g and playable. from its location in the game. For example, your character could find a
key in the first location, pocket it, and then use it later on in the game
to unlock a door. You'll need to factor in the list o f possible items, and ■
INGREDIENTS F O R A you'll also need to factor in the real-world physics o f each item too. If
COM PELLING ADVEN TURE you have your adventurer enter a room with an anvil, then allowing
The first ingredient is a story, a plot that w ill take the player on a ride them to pick up the anvil and put it in their pocket isn’t particularly
through their own imagination. It doesn't necessarily have to include realistic. One o f the major drawbacks o f some text adventures, and
dragons, barbarians, spaceships, or other such things, but it needs to even modern graphical games, is the unrealistic carrying capability of
be engaging. Perhaps it could follow the theme of a m urder mystery, the player.
much in the same vein as an Agatha Christie novel, or it could be
something that explores the base fears o f people.

Coding & Programming


Planning a Text Adventure

Although not always necessary, puzzles do Form an interesting aspect Lists, tu ples and dictionaries w ill be needed to store the
o f a text adventure. These puzzles can test the player's abilities various elem ents o f the game. These can be descriptions o f
and expand the game beyond simply finding an object and using characters w hom you’ ll meet, e ith e r friend or foe. Locations, with
it. Puzzles can range from using these objects correctly to achieve descriptions, th rou gh ou t the game; item s you 'll come across that
something to finding the correct route through a maze, with some can be used, along w ith a player inventory, which w ill grow or
being vital to the plot while others are simply there to give the player lessen depending on w hat the player has used/dropped/picked up.
something interesting to do. Ideally, puzzles should be easy near the
beginning o f the game and get progressively harder as your character Variables w ill be needed to hold v ita l statistics during gameplay,
advances through the game. the player's name, am ount o f strength, endurance, skill and health,
for example. You'll also need variables to hold the current score
or num ber o f moves used so far, plus any statistics regarding the
S m a 11 building other characters you 'll m eet.

Vou are inside the small building. You discover


that this is a one room house. There are broken Random ly generated num bers are v ital for those w ho w ant to
windows in all four walls. There is debris spread include an elem en t o f com bat. W ithin such examples, a virtual dice
over the entire floor and it is obvious that there roll w ill determ ine the w inner or loser, eith er in a fig h t or when
h a s n ’t been anyone here for a Iona time. Over in
using luck to win through som ething.
the corner there is a large open trophy case.
There is a large rug covering most of the floor.
There is a large gas lamp. Strings can be used to keep non-moving elem ents o f the game,
in other words the names of the room s you may enter. These
What would you like t o do?
components are static throughout the game, each and every time you
» GET LAMP play, so they can be called upon when the player interacts with them.

i Functions are the life b lo o d o f a te xt adventure, as they w ill form


Hints and help along the way can make the adventure seem less the backbone o f the locations, interactions, events and anything
daunting. O f course, if you're particularly mean-spirited, then you can else th a t happens w ithin the game.
opt to exclude any form o f help along the way altogether. However,
most text adventures do include some Form o f a hint. If you’ve Loops w ill keep a process going, such as a fight with an ore, until an
created a great set of puzzles for the player to beat, and they're stuck event o c c u rs -e ith e r the death o f the ore o ry o u r player. In addition,
in their progression o f the game, then allowing them to enter the you’ ll need to include a loop, if and else com ponents to help out
word: help, or hint, into the system, w ill reveal a small clue as to what with choices made: do you take the green door or the red door?
to do next. It's not cheating, just keeping the story moving along.

Pacing is the final aspect of the adventure game that needs to be


planned correctly. Good pacing within the story is vital to keeping
your player's attention, as w ell as keeping them entertained and
engaged with what's going on. It's n otan 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 CO D E * ----
It's im possible to list the code you 'll need fo ry o u r adventure
game since it'll be d iffe re n t from each reader to the next, but here
are som e pointers to help you out.

I C o lo ssal Cave Adventure ► Score: 36 ► Turns 4

Somewhere nearby i s C o lo ssal Cave, where others have


found fortunes in treasure and gold, though i t i s rumored
that some who enter are never seen again. Magic is said
to work in the cave. I w ill be your eyes and hands. D irect
me with commands o f 1 or 2 words. I should warn you that I
look at only the f i r s t fiv e le tte rs o f each word, so y o u 'll
have to enter "Northeast" as "ne" to d istin g u ish i t from GOOD LUCK, A D VEN TU RER
"N orth .” (Should you get stuck, type "help" or "in fo " for
some general h in ts).
There's a lo t to take in and plan, so our advice is to start sm all and
You are standing at the end o f a road before a sm all brick
b u ildin g. Around you i s a fore st. A small stream flows out plan ou t you r story first. Once you've go t the basic story, build on
o f the b u ild in g and down a g u lly .
the settings and locations, then puzzles and oth e r elem ents. From
You are in a v a lle y in the forest beside a stream tumbling
there, you can begin to expand the game w orld and add things like
along a rocky bed.
combat.

in open fore st, with a deep v a lle y to one side


It w o n't be easy, but it’ ll be great fun and w ill help you becom e a
b e tte r Python coder.

Coding & Programming


Code Projects and Ideas

Text Adventure Script —


Text adventures are an excellent way to build your Python coding skills and have
som e Pun at the same time. This exam ple that w e created w ill start you on the path to
making a classic text adventure; w here it w ill end is up to you.

A D VEN TU RE.PY i m p o r t t ime


The Adventure game uses just the Time module to begin
Iprint("\n" * 200)
with, creating pauses between print Functions. There's a help
|p r i n t ( " » » » » » A w e s o m e Adventure<<<<<<<<<<\n")
system in place to expand upon, as well as the story itselF.
|p r i n t ("\n" * 3)
time, sleep (3)
1 *?:. ~.. 1 Ip r i n t ("\nA l ong t i m e ago, a w a r r i o r strode f o r t h from
t he frozen north.")
j .. . |t i m e . s l e e p (1)
"E S F j k a . .— | print("Does t his wa r r i o r h a v e a name?")
n a me=input("> ")
jp r i n t (name, "the barbarian, s w o r d in h a n d a n d lo o k i n g
...-“* w"- " a --- for adventure!")
time, sleep (1)
i s ..:...— -..... p r i n t ("However, evil is l u r k i n g n e a r b y __ ")
time, sleep (1)
print("A p a i r of b u l b o u s e yes r e gards t he hero...")
It i m e . s l e e p (1)

pi(S>raspberrypi ~7Documents/Python Code


I p r i n t ("Will", name, "prevail, a n d w i n g r e a t fortune...")
File Edit Tabs Help I t i m e . s l e e p (1)
p r i n t ("Or die b y the h a n d s of g r e a t evil...?")
|t i m e . s l e e p (1)
You find yourself at a small inn. There's l i t t l e gold in your purse Ip r i n t ("\n" *3)
but your sword is sharp, and you're ready for adventure.
With you are three other customers. print("Only t i m e will tell...")
A ragged looking man. and a p air o f dangerous looking guards.
time, sleep (1)
i you approach the... p r i n t ('../)
time, sleep (1)
1. Ragged looking man
2. Dangerous looking guards p r i n t ('../)
David>help
|t i m e . s l e e p (1)
Enter your choices as detailed in the game,
or enter 'q u it' to leave the game p r i n t ('../)
David>quit
time, sleep (1)
idly you return to your homeland without fame or fortune.. print('../)
time, sleep (5)
*Advemure.py-/home/pi/Documen ./Python Code/Adventure.py (3 4.2)* - □
Iprint("\n" *200)
File gdit Format Sun fiptlom Windows Help

p r i n t ('" Y ou find y o u r s e l f at a s mall inn. There's


i fin d y o u r s e lf a t £
but your little g o l d in y o u r p u r s e b u t y o u r s word is sharp,
W ith you
A raggec > lo o kin g g u a rd s.' a n d you're r e a d y for adventure.
: sta rt(): With y o u a re t h r e e o ther customers.
p r i n t ( " \ n ........................." )
print("0o you approach th e ..." )
p r i n t ( ” \n ” ) A r a g g e d l o o k i n g man, a n d a p a i r of d a n g e r o u s
p rin tC 'i. Raj
looking guards/")
c m d lis t- [ " 1 " . ''2'']
cmd=get cm d(cm dlist)

and == " i " :


d e f start():
raggedC)
e l i t cmd == "2 “ : p r i n t ("\n ")
gu a rd sf)
p r i n t ("Do y o u a p p r o a c h the...")
p r i n t ("\n")
I lo oking man and g re e t him.
ind. w ith a s tra n g e a c c e n t, s a y s . p r i n t ("1. R a g g e d l o oking man")
I ' l l t e l l you o f g re a t t r e a s u r e . . . ' ” )
p r i n t ("2. D a n g e r o u s lo o k i n g guards")
p r in t ( " \ n " * 200)
p r in t (' ' ' You w alk up to the dangerous lo oking guards and g re e t them
The guards lo o k up from t h e i r d rin k s and s n a r l a t you. cmdlist=["l", "2"]
"What do you w ant, b a rb a ria n ? " One guard reaches fo r the h i l t o f h is s
tim e .s le e p (2 ) c m d = g e t c m d (cmdlist)
II def getond(cmdlist):
cmd = input(name*">
. and -i c m d lis t:

j l. J Coding & Programming


Text Adventure Script

if c m d = = "1": d e f getcmd(c m d l i s t ) :
r a g g e d () c m d = input(name+">")
elif c m d = = "2": if c m d in cmdlist:
g u a r d s () return cmd
elif c m d = = "help":
d e f ragged(): p r i n t ("\nEnter y o u r choices as d e t a i l e d in
print("\n" * 200) t he game.")
pri n t ( ' " Y o u w a l k u p to t h e r a g g e d l o o k i n g m a n a n d p r i n t ("or e nter 'quit' to leave t he game")
g r e e t him. r e t u r n getcmd(cmdlist)
H e s m i l e s a t o o t h l e s s g r i n and,, w i t h a strange elif c m d = = "quit":
accent, says. p r i n t ("\n ")
"Buy m e a c u p of wine, a n d I'll tell y o u of time, s leep (1)
g r e a t treasure...'") p r i n t ("Sadly y o u r e t u r n to y our h o m e l a n d w ithout
time, s l e e p (2) f a m e or fortune...")
time, s leep (5)
d e f g u a r d s (): exit()
print("\n" *200)
pri n t ( ' " Y o u w a l k u p to the d a n g e r o u s l o o k i n g g u a r d s
a n d g r e e t them. if name = =" main ":
T h e g u a r d s look u p f r o m t h e i r d r i n k s a n d startO
snarl at you.
" W h a t d o y o u want, b a r b a r i a n ? " O n e g u a r d r e aches
for t h e h i l t of h i s sword../")
time, s l e e p (2)

Adventure Time
This, asyou can see, is just the beginning oF the adventure and •Adventure py - /home/pi/Documents/Python Code/Adventure py (3.4.2)*
takes up a Fair Few Lines oFcode. When you expand it, and weave file §dit Format Bun Qptions Windows Help
the story along, you'll find thatyou can repeat certain instances print<“W * 200)
such as a chance meeting with an enemy or the like. CR=0
S tre n g th s
Health=0
Luck=0
We've created each oFthe two encounters as a deFined set
p rin t("T h e mountains o f the north make fo r a hard l i f e . " )
of Functions, along with a list oF possible choices under the p r in t ( "Press Enter to r o l l the d ic e and see how stro n g ", name, “is : " )
in p u t()
cmdlist list, and cmd variable, o f which is also a deFined Function. Strength= randam .randint(1,20)
print(nam e, "has a Strength value o f : " . Strength)
Expanding on this is quite easy, just map out each encounter and p r in t ( " \ n lt ‘ s a hard l i f e indeed, and a l l northeners are born w a rrio rs ." )
p r in t ( “Press Enter to r o l l the d ic e and see the Combat R a ting f o r " , name+
choice and create a deFined Function around it. Providing the user in p u t( )
CR=random.randint(1, 30)
doesn't enter quit into the adventure, they can keep playing. print(nam e, "has a Combat R ating o f : - , CR)
p r in t ( "XnYoUr H ealth i s the t o t a l o f your Strength and Combat R a tin g .")
p n n t ( “Press Enter to se e", name+’" s " , "Health v a lu e .")
in p u t()
There's also room in the adventure Fora set oF variables designed Health=Strength+CR
print(nam e, “has a Health value o f : " . H ealth)
p r in t ( "\nEveryone needs a c e rta in amount o f lu ck to s u r v iv e ." )
For combat, luck, health, endurance and even an inventory or p r in t ( "Press Enter to r o l l the d ic e and see how lu ck y ", name, " i s . " )
in p u t( )
am ount of gold earned. Each successFul com bat situation can Luck=random .randintf1. 15)
i f Luck > 13:
reduce the main character's health but increase their com bat skills print(nam e, " i s lu ck indeed, and has a Luck value o f : " . Luck)
e ls e :
or endurance. Plus, they could loot the body and gain gold, or earn pnnt(nam e, “has a Luck value o f : " . Luck)
tim e .sle ep (5)
gold through quests. p rin t ( " \ n " *200)
p r in t ( "H ere 's your ch a ra cter s t a ts :\ n " )
print(nam e)
p r in t ( "\nCombat R ating CR)
Finally, how about introducing the Random module. This will p n n t ( "Strength =” . Strength)
p r in t ( "Health =", H ealth)
enable you to include an elem ent oFchance in the game. For p rin t( " L u c k =“ , Luck)
p r in t ( “\n" *5)
example, in combat, when you strike an enemy you will do a p r in t ( “Press En te r to s t a r t your adventure.
in p u t( )
random am ount o f damage as will they. You could even work out p n n tC 'M i" *200)

the maths behind improving the chance oFa better hit based on
p r in t ( ‘ ' You fin d y o u rs e lf at a sm a ll in n . T h e re 's l i t t l e g old in your purse
your oryo ur opponent's com bat skills, current health, strength and but your sword i s sharp, and y o u 're ready f o r adventure.
With you are three other custom ers.
endurance. You could create a game oFdice in the inn, to see if you A ragged lo oking man. and a p a ir o f dangerous lo oking g u a rd s .1•')

win or lose gold (again, improve the chances of winning by working def s t a r t ( ) :
p r i n t ( " \ n --------------” )
p rin t( " 0 o you approach t h e . . . " )
ou ty o u r luck Factor into the equation). p rin t ( " \ n " )
p r i n t ( “ l . Ragged looking man")
p r in t ( " 2 . Dangerous lo o k in g guards")
Needless to say, your text adventure can grow exponentially
and prove to be a w ork oF wonder. Good luck, and have Fun with
your adventure.

Coding & Programming


Code Projects and Ideas

Retro Coding
There's a school o f thought, that to m aster the Foundations oF good coding skills you
need to have som e experience oF how code was w ritten in the past. In the past is a bit
oFa loose term, but mostly, it means coding From the 80s.

5 HOME recognised that one o f the 'best', and possibly m ost utilised, form of
18 PRINT "--- U N I T C O N V E R T E R --- “ BASIC from the 80s was that of BBC BASIC.
28 I N P U T " C F 3 A H - C E L O R CC3EL-Fft
H ; II •QJ
BBC BASIC was used on the Acorn BBC M icro range o f computers,
30 INPUT "ENTER UNIT “ ;U N
48 X = C U N I T - 3 2 ) *. 5
_ ✓ 9 utilising the M OS 6502-based processor technologies. It was one of

50 .............
Y = <UNI 41T * >• 5> + 32
IF C * = I p II
60
?a
S I US;
IF CS
“}
= ‘C
THEN PRINT
T H E N __ P R I N T
“C E L
1F f lH
the quickest examples of BASIC and, thanks to an inline assembler, it
was also capable o f allowing the developers o f the time to write code
for different processor types, such as the Zilog Z 8 0 - a CPU present in
THE GOLDEN ERA O F CODE the ZX Spectrum, as w ell 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 C o m pu te rs-a
language that's virtually obsolete, there are some surprising benefits company that is historically responsible for the creation o f the ARM
to getting your hands dirty with a bit o f retro coding. Firstly, learning CPU - the processor that's used in virtually every Android phone and
old code w ill help you build the structure of code as, regardless of tablet, smart TV, set top box and so on, as w ell as the Raspberry P i-
whether it is a language that was developed yesterday, or forty years so essentially, the BBC Micro is the grandfather o f the Raspberry Pi.
ago, code still demands strict discipline to work correctly. Secondly,
The BBC Micro was born in a time when the UK government was
everyday coding elements, such as loops, sub routines and so on, are
looking for a countrywide com puter platform to be used throughout
a great visual aid to learn in older code, especially BASIC. Lastly, it's
education. D ifferent companies bid, but it was the BBC’s Computer
simply good fun.
Literacy Project (the BBC Micro) that was chosen, due to its
±050 REM F O R I- ruggedness, upgradability, and potential for education. A s a result,
1060 REM PRINT
1070 REM NEXT I the BBC Micro, or the Beeb as it’s affectionately known, became the
1080 REM dominant educational com puter throughout the 80s.
1080 POKE 512, O
1100 POKE 513,6
111© REM
iiZG
1130
FOR
READ
1=1536
A BEEBEM
Naturally, you could scour eBay and look fo ra working BBC Micro to
GOING BASIC play around on, and it'll be a lot o f fun. However, for the sake o f just
getting hands-on with some retro code, we'll use one o f the best BBC
The easiest retro language to play around with is, wfthout 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 BeebEm was originally developed for UNIX in 1994 by Dave Gilbert and
language whose design was geared toward ease o f 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 W indows 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.
TH EBEEB
The problem with BASIC is that there were so many different versions
available, across m ultiple 8-bit platforms, with
each having its own unique elem ents
on top of the core BASIC
functions. The BASIC that
was packaged with the
Com modore 64 was different
to that on the ZX Spectrum,
or the Atari home computers, Once downloaded, launch the executable and follow the on-screen
due to the differing hardware of 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

Coding & Programming


Retro Coding

will have to do a little nifty keyboard work before they can enjoy the clears the screen; although the Pi uses Clear instead o f CLS. W e’re also
benefits o f the Beeb on their screens. Here's how to get it working able to do some maths work, and play around with variables too:
under Linux:

First, drop to a Terminal and enter:

sudo ap t - g e t u p d a t e && u p g r a d e |
|30 i f a > 40 p r i n t " Y o u ' r e o v e r 40 y e a r s o l d
[wget h t t p :/ / b e e b e m - u n i x .b b c m i c r o .c o m / d o w n l o a d / !
|40 i f a < 40 p r i n t " Y o u ' r e u n d e r 40 y e a r s old.
b e e b e m - 0 . 0 . 1 3 . t a r .gzl

Then, extract the compressed files with:


BBC BASIC also has some interesting built-in features, such as the
value o f PI:

R E M A r e a of c i rcle

Now enter the following lines, hitting Enter and answering Y to accept
20 I n p u t " E n t e r t he r a dius:
any changes:
30 l e t a r e a = PI*r*r|
40 p r i n t " The a r e a o f y o u r c i r c l e is:
sudo apt- g e t install l i b g t k 2 . - d e v l i b s d l l .2-devi
./ configure
ke >LIST
1 REM AREA OF A CIRCLE
2 CLS
20 INPUT "ENTER THE RADIUS: “ R
This may take some time, but when it's all done, simply enter: 30 LET AREA = PI*R*R
40 PRINT "THE AREA OF YOUR CIRCLE IS:
to start the BBC M icro emulator. ";AREA
50 PRINT ‘11
>
BBC BASIC
Once installed and pow ered up, BeebEm w ill display the defau lt As you'll notice, variables with a dollar ($) represent strings, nothing
BBC system start-up, along w ith a couple o f beeps. Those o f you after the variable, or a hash (#) represent floating point decimals; a
old enough to have been in a UK school in the 80s w ill certainly w hole integer has a % character, and a byte has an am persand (&).
recall this setup. The single quotes a fte r 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 lo t you can learn, as w ell as having fun, with
BBC Computer 32K BBC BASIC. It's a rainy day project and something that's interesting to
Acorn DFS show the kids - this is how we rolled back in the 80s, kids!
Once you've typed the above in, press
There are a num ber o f sites you can visit to learn BBC BASIC, such
Enter and then type:
>10 PRINT "HELLO" as http://archive.retro-kit.co.uk/bbc.nvg.org/docs.php3.html.
>RUN See w hat you can come up with using BBC BASIC, or o th e r BASIC
HELLO
> types fo r d iffe re n t systems, and le t us know what you've created.

We can o f course expand the code to


include variables, multi-line print statements, and so on:
OTHER SYSTEM S
Naturally, you don’t have
to look to the BBC M icro
to play around w ith some l i * —
20 p r i n t retro code. If you grew up I
30 p r i n t h o p e y o u ' r e w e l l today.' with a C om m odore 64, then i .T .
you can always try VICE, the I.' “ J,
HI, DAVID I HOPE YOU'RE UELL TODAY. C64 em ulator. Likewise, the _________ H
>LIST ZX Spectrum has a slew o f _________ .... • '
1 CLS
10 INPUT "HELLO, UHAT'S YOUR NAME? " qreat em ulators available fo r J L '
every m odern system to play ■?-.»,
“ 20 PRINT
30 PRINT "HI, " NS " I HOPE YOU'RE UE around on. In fact, you can
LL TODAY."
> probably find an em ulator for ____________
virtually every 8-bit or 16-bit _ __|
machine that was produced 4“
Type RUN to execute the code, you can also type LIST to view the
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 coding nuances, so find a few
Python, a print statem ent on its own displays a blank line, and CLS and see w h at you can create. U L ______________________

Coding & Programming 53


Code Projects and Ideas

Text Anim ations


There's a rem arkable am ount you can do w ith som e sim ple text and a little Python
know-how. Com bining w hat you've already learned, w e can create som e interesting
anim ation e ffects from the com mand line.

print(message) |
THE FINAL COUNTDOWN p r i n t ("<
Let's begin with some example code that w ill display a large
countdown from ten, then clear the screen and display a message. Iprint ("\n\n\n") I

The code itself is quite simple, but lengthy. You w ill 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:
some time, but it’s worth it in the end. O f course, you can always take https://pclpublications.com/exdusives, where
a different approach and design the numbers yourself. you're free to copy it to your own Python IDLE
and use it as you see fit. The end effect is quite
The next step o f the process is to initialise the code settings and start
good and it'll be worth adding to your own games,
the countdown:
o r presentations, in Python.

To extend the code, 6r make it easier to use, J


you can always create the number functions
in their own Python code, ca llitC ou n t.py f o r _______________
example, then im port C o u n ta t the beginning of
a new Python file called Countdown.py, along with the OS and Time
#Start the countdowng
modules:
fo r c o u n t e r in r a n g e (start, 0,
if c o u n t e r = = 10:

From there, you w ill need to specify the im ported code in the
Countdown section:

Coding & Programming


Text Animations

RO CKET LAUNCH
Building on the previous
countdown example, we can
create an animated rocket that'll
launch after the Blast OFF!!
message has been printed. The
code would look something like:

d e f R o c k e t () :
highest roller wins the round and the losers' health drops as a result.
distanceFromTop = 2 0
It's an age-old combat sequence, used mainly in the Dungeon and
while T r u e :
Dragons board games and Fighting Fantasy novels, but it works well.
o s .s y s t e m ( 'els' =
if os.name = 'nt' else 'clear')
print("\n" * distanceFromTop) | The code you'll need to animate a dice roll is:
p r i n t (" A ")
p r i n t (" 11 ") i m p o r t os[
p r i n t (" 11 ") i m p o r t time|
p r i n t (" / 11 \ ")l from random import randint|
t i m e .s l e e p (0.2)
die [' \n O \n ']
o s .s y s t e m f 'els'
d i e . a p p e n d (" 0\n \nO ") #2
distanceFromTop -
|die.append ("0 \n 0 \n O") #3
if d i s t a n c e F r o m T o p <0:
d i e .a p p e n d ("0 0\n \nO O") #4[
d i s t a n c e F r o m T o p = 20
d i e .a p p e n d ("0 0\n 0 \nO O") #5|

I# L a u n c h Rocket!) d i e .a p p e n d ("0 0\n0 0\n0 0") #6


R o c k e t ()
gdef dice () :|
for roll in r a n g e (0,15) :|
Here, we've created a new Function called Rocket, which produces
o s .s y s t e m ('els ' if os.name = = 'nt' else 'clear'
the eFFect oFan ASCII-like rocket taking oFFand scrolling upwards;
print("\n")
using the distanceFrom Top variable.
__n u m b e r — randi n t ( Q ,
To use this, add it to the end oF the previous countdow n code and, p r i n t ( d i e [ n u m b e r ] )|
at the end of the Blast Off!! message, add the Following lines: t i m e .s l e e p (0.2)

JttMain C o d e B e g i n s |
p r i n t ( " \ n \ n\n\n")
i n p u t ( " P r e s s E n t e r to l a u n c h r o c k e t ..."|

You may need to tweak the 0 entries, to line up the dots on the
This w ill allow your m essage 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 w ill launch.
Function to your adventure game code and call it up w henever your
Again, the code in its e ntirety can be Found in the Code Repository character, or the situation, requires some elem ent o f luck, combat,
at: https://bdmpublications.com/ code-portal. or chance roll o f the dice.

D ISCO VER ANIMATIONS


The great thing about Python code is that it’s so accessible. These You’ll find that many professionals w ill often take to the Internet
Few examples w ill help you add some fun, or somethi ng different, to find content they're after. True, they're able to code it
to your programs, but they’re just the tip o f 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.
at a sticking point, then consider heading over to Stack Overflow
Q How io create A S C II animation In a console application using Python 3 x ?
and search for Python 3 content. + Mac Oo) Howto crootc ASCII animation ir|

asked Apr 28 TU by Hamishi |


Stack O verflow is a great online help and resource portal, where Grubijan

you can ask questions and experts w ill try and help you. It doesn't Q Simple rectangle terminal animation in Python 3.x
always work out, but m ost of the time, you’ll find what you're change its lie

looking for within this great resource. Teams


asked Oct 28 '17 by Banosz i |

Q&A torwork 1

Also, if you're after a simple animation then take to Google and Q: Carriage return escape character behaves like a newline in Python 3 and O S X
J trom "Learn Python the Hard Way" while Irue lor i in | T "--.T/tt'.TJ pnnt("%s\r % i, end=") It's suppo|
spend some time searching for it. While you may not Find exactly lo look like a little rotating bar like a busy animation or I searched and couidnt find an answer to this r
trying to use V as a carnage return in a program but it behaves like a newline instead. Here's the code I'm t
w hat it is you're aFter, you're bound to come across something to use. adapted tor Python
p>0ion mecos asked Jan 15 '14 by nonet
very like the desired eFFect; all you need to do is m odify it slightly
to accomplish your own goals. Q Belousov-Zhabotinsky (BZ) reaction animation code in python

Coding & Programming 55


Code Projects and Ideas

Com m on Coding Mistakes


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

X=M ISTAKE, PRINT Y


There are many pitfalls For the programmer to be aware of, Far too many to be listed here. Being able
to recognise a mistake and Fix it is when you start to move into more advanced territory.

SMALL CHUNKS
It would be w onderful to be able to M ean in gfu l naming for variables is a m ust to elim inate
work like Neo from The M atrix movies. com m on coding mistakes. Having le tte rs o f the alphabet
Simply ask, your operator loads it into is fine but w hat happens when the code states there's
your m em ory and you instantly know a problem with x variable. It's not too d ifficu lt to name
everything about the subject. Sadly variables lives, money, p la y e rl and so on.
though, we can't do that. The first
major pitfall is som eone trying to learn 1 var points = 1023;
2 var lives = 3 ;
too much, too quickly. So take coding in
3 var totalTime - 45;
small pieces and take your time. 4 write("Points: "tpoints);
5 write("Lives: "+lives);
6 write("Total Time: "+totalTime+" secs");
7 write ("-------------------------- ") ;
8 var totalScore = 0;
9 write("Your total Score is: "+totalScore);
//COMMENTS
Use com m ents. It’s a simple concept b ut com m enting on
you r code saves so many problem s when you next come to
lo ok over it. Inserting com m ent lines helps you quickly sift
through the sections o f code that are causing problems;
PLAN AHEAD
also useful if you need to review an old e r piece o f code.
W hile it's great to wake up one m orning and decide to code
orig += 2 ? a classic te xt adventure, it’s n ot always practical w ith o u t a
target +■ 2;
good plan. Sm all snippets o f code can be w ritten w itho u t
— n;
too much thou ght and planning bu t longer and m ore in-
55 >
5c #endxf depth code requires a good w orking plan to stick to and
if (n == 0) help iron out the bugs.
return?

6° //
// Loop unrolling. Bare be dragonj.
62 //
c J
// (n & (-3)) la the greateat multiple of 4 r
// In the while loop ahead, orig will move ov
^ MamMenu
==D
// increments (4 elements of 2 bytes).
// end rcarJcs our barrier for not falling outa
char const * const end = orig + 2 * (n & (~3)
c J

// See if we*re aligned for writting in 64 oi


c >
- #if ACE_SIZEOF_LONG = 8 45 \
_____!_((defined ( and64 > 11 defined < x86 64
< ;

Coding SProgramming
Common Coding Mistakes
USER ERROR
User input is often a paralysing mistake in code. For
example, when the user is supposed to enter a num ber for
their age and instead they enter it in letters. O ften a user
can enter so much into an input that it overflow s some
internal buffer, thus sending the code crashing. Watch those
BACKUPS
user inputs and clearly state what's needed from them.
Alw ays make a backup o f you r work, w ith a secondary
Enter an integer number
backup for any changes you've made. M istakes can be
aswdfdsf rectified if there's a good backup in place to revert to for
You haue entered wrong input
s
those tim es when som ething goes wrong. It's much easier
You haue entered wrong input to start w here you le ft off, rather than starting from the
!"£"!£!”
beginning again.
You haue entered wrong input
sdfsdf213213123
You haue entered wrong input
123234234234234234
You haue entered wrong input
12
the number i$: 12

Process returned 0 (0x0) execution time : 21.495 s


Press any key to continue.

RE-INVENTING WHEELS r
You can easily spend days trying to fathom ou t a section SECURE DATA
o f code to achieve a given resu lt and it's frustrating and
often tim e-wasting. W hile it's equally rewarding to solve If you’re w riting code
the problem yourself, often the same code is out there on to deal w ith usernames
the Internet som ew here. D on't try and re-invent the wheel, and passwords, or
lo ok to see if some else has done it first. other such sensitive
data, then ensure
that the data isn't in
cleartext. Learn how
to create a function
to encrypt sensitive
data, p rior to feeding
into a routine that can
transm it or store it
w here som eone may be
able to get to view it.

V_____________________________ / V

Coding & Programming


C o d e P ro jects and Ideas

Python Beginner's Mistakes


Python is a relatively easy language to get started in where there's plenty of room for
the beginner to find their programming feet. However, as with any other programming
language, it can be easy to make common mistakes that'll stop your code from running.

D EF B EG IN N ER(MISTAKES= 10)
Here are ten common Python programming mistakes most beginners Find themselves making. Being able to identiFy these
mistakes will save you headaches in the Future.

V ER SIO N S INDENTS, T AB S A N D S PACES


To add to the contusion that m ost beginners already Face when Python uses precise indentations when displaying its code. The
coming into programming, Python has two live versions oF its indents mean that the code in that section is a part oF the previous
language available to dow nload and use. There is Python version statem ent, and not som ething linked w ith another part oF the code.
2.7.x and Python 3.6.x. The 3.6.x version is the m ost recent, and Use Four spaces to create an indent, not the Tab key.
the one we'd recom m end starting. But, version 2.7.x code doesn't
MOVESPEED « 11
always w ork with 3.6.x code and vice versa. MOVE « 1
SHOOT = 15

* sec up counting
score = 0

p y th o n t sec up font
fone = pygame.fone.Sysfonc(1califcxa', 50)

def makeplayerO :
A bout D o w n lo a d s D o c u m e n ta tio n C o m m u n ity S u c c e ss S to rie s New player = pygame.Rect(370, 635, 60, 25)

/C\TT
def makeinvaders(invaders):
Download the latest version for Windows y = 0
for i ir. invaders:
x = 0
for 3 in range(1 1 ):
invader = pygame.Rect(75+x, 75+y, 50, 20)
Wondering which version to use? Here's more about the difference i .append(invader)
x += 60
between Python 2 and 3.

Looking for Python with a different OS? Python for Windows,


Linux/UNIX, Mac OS X, Other
j \
y += 45

ief make walls (walls) ;


wall! - pygame,Rest(60, 520, 120, 30)
Want to help test development versions of Python? Pre-releases
wall2 - pygame.Rece(246, 520, 120, 30)
wall3 = pygame.Rect(432, 520, 120, 30)
wall4 = pygame.Rece(618, 520, 120, 30)

TH E IN TERN ET C O M M E N T IN G
Every programmer has and does at some point go on the Internet Again w e m ention com m enting. It's a hugely im portant Factor in
and copy som e code to insert into their own routines. There's programming, even iFyou're the only one who is ever going to view
nothing wrong with using others' code, but you need to know how the code, you need to add com m ents as to what's going on. Is this
the code works and w hat it does beForeyou go blindly running it on Function w here you lose a life? W rite a com m ent and help you, or
your own computer. anyone else, see what's going on.

# set up pygame
Create/delete a ,txt file in a python program
pygame.init()
mainClock = pygame.time.Clock ()
I have created a program to grab values from a text file. A s you can see, depending on the value of the
results, I have an if/else statement printing out the results of the scenario.
# set up the window
M y problem is I want to set the code up s o that the i
fstatement creates a simple .txt file called data.txt
to the C:\Python\Scripts directory.
width = 800
height = 700
In the event the opposite is . I would like tire else statement to delete this .txt file if it exists.
0 screen = pygame.display.set_mode((width, height), 0, 32) 0 0 1
I’m a novice programmer and anything I've looked up or tried hasn't worked for me, s o any help or pygame.display.set_caption('caption')
assistance would be hugely appreciated.

# set up movement variables


1 0 0
moveLeft = False
x = o p e n {" te s t .tx t" ,”p")
California = x . readlines(11) moveRight = False

0 1 1
dublin = X .readlines(125) moveUp = False 11 1
percentaBe_velue = [flo a t( re .f in d a ll( 1kd+\. \d+(?=\X)|\d+\.\d+<: i[- l] )[6 ] ) foi• i in [Ci moveDown = False
1 o 1 print(percentage_value)
)u
1 0
i t set up direction variables n
u n
u
111 i f percentage_value[0] <= percentage_value[l]; i DO W NLEFT = 1

0 1 else:
print('W ebsite i s hosted in D u blin')
0 D O W N R IG H T = 3 0 10
;

10 10 1 10 0 0 0 0 1 10 1 1
o

0 0i n 0
°

0 i

1 0 0 ) 1 1 1 1 10 o 10 1 o 1 10 1 0
goding & Programming
0 0 1 11 10 0 0 10 1 0 o0 1 0
o

0
o

0 1 1 1 0 o 00o 1 i 00 0 0 1 00 1 1 1 1 1 1 0 0 0 11 10 10 0 1
Python Beginner's Mistakes

COUNTING LOOPS COLONS


Rem em ber that in Python a loop doesn't count the last num beryou It's com m on for beginners to fo rg e t to add a colon to the end of a
specify in a range. So iFyou w anted the loop to count from 1 to 10, structural statement, such as:
then you w ill need to use:
class Hangman:
n = l i s t ( r a n g e (1, 11)) def guess(self, letter):

Which w ill return 1 to 10. And so on. The colon is w hat separates the code, and creates the
indents to which the follow ing code belongs to.
L* Python 3.6.2 Shell - □ X

File Edit Shell Debug Options Window Help class Hangman:


Python 3.€.2 (v 3 .6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] def __init__ (self,word) :
on Win32 self.word = word
Type "copyright", "credits" or "license!)" for more information. self.missed_letters = []
»> self.guessed_letters = []
= = = = = = = = RESTART: C :\Users\david\.Documents\Python\Space Invaders.py ===== = =
> » n = list (range (1, 11)) def guess(self,letter):
> » print (n) if letter in self, word and letter not ir. self.guess ed_letters:
[1, 2, 3, 4, 5, 6, 7, S, 9, 10] self.guessed letters.append(letter)
>»l elif letter not in self.word and letter not ir. self .missed_letters:
self.missed letters.append(letter)
else :
return False
return True

def hangman_over(self):
recurr se l f .hangman_won() or (len(self.missed_letters) — 6)

def hangxnan_won (self) :


if ' 125 not in self.hide word():
4
3
return True

CA SE SENSITIVE return False

clef hide word (self) :


rtn = '1
Python is a case sensitive program m ing language, so you w ill need for letter in self.word:
if letter not ir. self .guessed_letters:
to check any variables you assign. For example, L i v e s = 1 0 is a rtn +=
different variable to lives=10, calling the w rong variable in your code els e :
rtn += letter
can have unexpected results. rtn

L* Python 3.6,2 Shell


File Edit Shell Debug O ptions W indow Help
python 3.6.2 (V3.6.2:5fd33b5, Jul 8 2017, 04:14:3 OPERATORS
on Win32
Using the w rong operator is also a com m on mistake to make. When
Type "copyright", "credits" or "licensed" for nsor
you’ re perform ing a comparison between two values, for example,
> » Lives=10
» > live5=9 you need to use the equality operator (a double equals, ==). Using
>>> print(Lives, lives) a single equal (=) is an assignm ent operator that places a value to a
10 9 variable (such as, lives=10).
»>
1 b = 5
2 c = 10
3 d = 10
4 b = = c #falsebecause 5 is not.equal to 10
5 c = d #truebecause 10 is equal to 10
BRACKETS
Everyone forgets to include that extra bracket they should have
added to the end of the statem ent. Python relies on the routine OPERATING SYSTEM S
having an equal am ount of closed brackets to open brackets, so any
W riting code for m ultiple platform s is difficult, especially when you
errors in y o u rc o d e c o u ld be due to you forgetting to c o u n ty o u r
start to utilise the external com m ands o f the operating system. For
brackets; including square brackets.
example, if your code calls for the screen to be cleared, then for
W indow s you w ould use els. Whereas, for Linux you need to use
def print game status(self): clear. You need to solve this by capturing the error and issuing it
print (board[len(self.missed letters)])
with an alternative command.
print ( " W o r d : ' + self.hide woxd()J
0 print ( " L e t t e r s M i s s e d : ',) P— ’ 1 1 " " n
# Code to detect error
I 1 for letter ir. self .missed letters:
run=l
1 print (letter,)
print 0
print ( " L e t t e r s G u e s s e d : ",)
1 1
f o r letter in self.guessed letters:
0 1 print (letter,)
1 1 print !)
0 1
0 0 0 1 o 1 o .
0 0 0 1 0 110 1 o i i
0 o o io i i
0 l 1 1 o o 0 00
Code Projects and Ideas

C++ Beginner's Mistakes


There are many pitfalls the C++ developer can encounter, especially as this is a m ore
com plex and often unforgiving language to master. Beginners need to take C++ a step
at a tim e and digest w hat they've learned before moving on.

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

U N D E C L A R E D IDENTIFIERS STD N A M E S P A C E
A com m on C++ mistake, and to be honest a common mistake with Referencing the Standard Library is com m on for beginners
most programming languages, is when you try and output a variable throughout their code, but if you miss the std:: elem ent o f a
that doesn't exist. Displaying the value o f x on-screen is fine but not statem ent, your code errors out when compiling. You can com bat
if you haven't told the com piler w hat the value o f x is to begin with. this by adding:

using namespace std;


File Edit View Search Tools Documents Help
Under the #include part and simply using cout, cin and so on from

P <D □j ^ ^ then on.


a i° e Qs 9 #include <io stre am >
u s in g namespace std ;
jc j test! .cpp x i n t m ain!)

#include <iostream> i n t a, b, c, d;
a=10;
b=20;
int maint) c=30;
{ d =40;
std::cout « x; cout « a, b, c, d;

} }

S E M IC O LO N S GCCORG++
Rem em ber that each line o f a C++ program m ust end with a If you're com piling in Linux then you w ill no doubt come across
semicolon. If it doesn't then the com piler treats the line with the gcc and g++. In short, gcc is the Gnu Com piler Collection (or Gnu
missing sem icolon as the same line with the next semicolon on. This C Com piler as it used to be called) and g++ is the Gnu ++ (the C++
creates all m ann erof problem s when trying to compile, so don't version) o f the compiler. If you're compiling C++ then you need to
forget those semicolons. use g++, as the incorrect com piler drivers w ill be used.

#inelude <iostream> david@mint-mate '-/Documents

File Edit View Search Terminal Help


david@mint-roate -/Documents s gcc t e s t l . c p p -o t e s t
int mainO /tm p/ccA 5 zh tg .o : In f u n c t io n ‘ m a in 1:
{ t e s t l . c p p : ( .te x t+ 0 x 2 a ): u n d efin e d re fe re n c e to s td ::c o u t'
int a, b, c, d; t e s t l . c p p ; [ ,t e x t + 0 x 2 f) : u n d efin e d re fe re n c e to s t d ;;o s t r e a m : :
a=10; /tm p /ccA S zh tg .o ; In f u n c t io n ‘ __s t a t i c _ in it i a l iz a t io n _ a n d _ d e s t
)' :
b=20; t e s t l . c p p t e x t + D x S d ) : u n d efin e d re fe re n c e to ' s t d : : io s _ b a s e :
C=30 t e s t l . c p p : [ . te x t+ 0 x 6 c ): u n d efin e d re fe re n c e to 1s t d : : io s _ b a s e :
d=40; c o l l e c t 2 : e r r o r : Id re tu rn e d 1 e x it s t a t u s
david@fflint-mate -/Documents S g++ t e s t l . c p p -o t e s t
david<§mint-inate -/Documents $
std::cout « a, b, c, d;

JMI Coding & Programming


C++ Beginner's Mistakes

COMMENTS (AGAIN) TOO MANY BRACES


Indeed the mistake of never making any commentson code is back The braces, or curly brackets, are beginning and ending markers
once more. As we've previously bemoaned, the lack of readable around blocks of code. So for every {you must have a }. Often it's
identifiers throughout the code makes it very difficult to look back at easy to include or miss out one or the other facing brace when
how it worked, for both you and someone else. Use more comments. writing code; usually when writing in a text editor, as an IDE adds
them foryou.
ftincLude <iostream>
^include <vector>
#inelude ^algorithms
using namespace s td ; #include <iostream>
in t m ain() using namespace std;
vector<double> v ;

double d;
w h ile (c in » d ) v.push_back(d).j / / read elements in t mainU
i f ( Ic i n .e o f O ) { (/ cfiecft- i f in pu t f a ile d
c e r r << "format e r r o r W . {
/ / e r r o r return
i in t x;
cout << "read ” << v .s iz e Q •« " elementstn” ; strin g mystring = This is a string \n ;
re v e rs e (v.b e g in C ),v.e n d ()> ;
cout << "elements in reverse o rd e r;\n ” ;
cout « ‘Wh a t ’s the value of x? ;
f o r ( i n t i » 0; i c v .s i z e f ) ; -n -i) cout « v £ i] « A n ';
cin » x;
return 0 ; / / success return
} cout « x;
{
cout « \n\n ;
cout « mystring;
QUOTES
Missing quotes is a common mistake to make, for every level of user. >
Remember that quotes need to encase strings and anything that's
going to be outputted to the screen or into a file, for example. Most
compilers errors are due to missing quotes in the code.
INITIALISE VARIABLES
In C++ variables aren’t initialised to zero by default. This means if
you create a variable called x then, potentially, it is given a random
number from 0 to 18,446,744,073,709,551,616, which can be
difficult to include in an equation. When creating a variable, give it
the value of zero to begin with: x = 0 .

# in c tu d e < io strea m >


using namespace s t d ;

in t m a in O
t
i n t x;
x=0;

cou t « x;
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++ c o d e .cpp
you went wrong.
This compiles the code in the file code.cpp and create an a.out file
// Program to print positive number entered by the user
// If user enters negative number, it is skipped that can be executed with ./a.out. However, if you already have code
#include <iostream> in a.out then it's overwritten. Use:
using namespace std;

int main() g++ c o d e .cpp -o nameofprogram


{
int number;
cout « "Enter an integer:
cin » number; d a vid @ m in t-m a te -/ D o c u m e n ts

// checks if the number is positive


File Edit View Search Terminal Help
if ( number > 0) david@mint-mate -/Documents S g++ test1.cpp
{ david@mint-mate -/Documents s ./a.out
cout « "You entered a positive integer: “ « number « endl;
} 0
david@mint-mate -/Documents s g++ testl.cpp -o printzero
cout << "This statement is always executed."; david(amint-mate -/Documents S ./printzero
return 0;
0
} david@mint-mate -/Documents $

Coding & Programming


ALL Teen M a n u a ls
with S j P a p e r c u t
,0817 TOP TIPS fOKTMt IBBT-i.lUHIli-j|.|Jl.|j|,mIjij.
THE »j 2.
T - io s s a thesam sung
W in d o w s ll
iPhone manual Galaxy
Guidebook n K»17wpKHrooin pain EnQlish manual7
Cv.vth.na yo. t0 got more (fom you[ ^

™ pt MAC & MOBILE DFVICES_ GUIDES&HAQcT IEARNPYTHONRC++CODING


THE APPLE The Com plete

S watch
M ANUAL
C++
vm.r ultlmaie 'o™«eHng V~rom«W, < < « & P y th o n
§5 Manual >«ev
•uictv Thooasential codjna I L ' J *I
progtammng

,C “ e *

Not only can you learn new skills and master your
tech, but you can now SAVE 25% off all of our coding
and consumer tech digital and print guidebooks!

Simply use the following exclusive code at checkout

NYHF23CN

www.pclpublications.com
Get Your Exclusive
FREE Gift Worth
£9.99 Here!
Download FREE Software! Great G am ^ i Essential
Hardware!

Your FREE
Copy of 1

Q 9 £ mazing
GADGETS
Tech Shopper A P P S & G A M ES IN SID E'

Magazine a
Head over to your web Do you need a
Home Security
browser and follow these Chromebook?
Rflad our expert guide
to Google’s notebook!
Inside & Out!
Discover how to keep your
home safe and secure!

simple instructions...

I/ Enter the following URL: www.pclpublications.com/exclusives


2/ Sign up/in and from the listings of our exclusive customer
downloads, highlight the Tech Shopper Magazine option.
3/ Enter your unique download code (Listed below) in the "Enter
download code" bar.
4/ Click the Download Now! Button and your file will automatically
download.
5/ Your file is a high resolution PDF file, which is compatible with
the majority of customer devices/platforms.

Exclusive Download Code: P C L 3 7 8 6 2 R E


NOTE: This is a limited reader offer running from 1st March 2024 to 1st July 2024.
Term s and conditions app ly and can be found at w ww .pclpublications.com
Want to master your Code?
Then don t miss our Programming
magazine on ■r Readly now!

Bumper Holiday Special! BONUS DOUBU tomON!

issue Eight | December 202B 1100% I INDEPENDENT ^

The Essent
Guide for tl ^ F irsr
Time Progt mmer

IciRLBONVJS

, a 170 page
Nlagaz'ne

Discover Mew Skills to Se^ m ghtS.


Improve Your Work Life

Click our handy link to read now: https://bit.ly/30cL1 zx

The Complete Manual Series: device. It remains the purchaser’s sole responsibility to determine acknowledged. Relevant graphic imagery reproduced with
the suitability of this book and its content for whatever purpose. courtesy of Lenovo, Hewlett- Packard, Dell, Microsoft, Samsung,
Coding & Programming
Any app images reproduced on the front and back cover are Linux Mint, NASA, and Apple. Additional images contained within
21 | ISBN: 978-1-914404-36-8 solely for design purposes and are not representative of content. this publication are reproduced under licence from Shutterstock.
Published by: Papercut Limited We advise all potential buyers to check listing prior to purchase Prices, international availability, ratings, titles and content are
Digital distribution by: Readly, Zinio & Pocketmags for confirmation of actual content. All editorial opinion herein is subject to change.
© 2024 Papercut Limited All rights reserved. No part of this that of the reviewer - as an individual - and is not representative of All information was correct at time of publication. Some content
publication may be reproduced in any form, stored in a retrieval the publisher or any of its affiliates. Therefore the publisher holds may have been previously published in other volumes or titles.
system or integrated into any other publication, database or no responsibility in regard to editorial opinion and content.
commercial programs without the express written permission of This is an independent publication and as such does not Papercut Limited
the publisher. Under no circumstances should this publication and
its contents be resold, loaned out or used in any form by way of
trade without the publisher’s written permission. While we pride
necessarily reflect the views or opinions of the manufacturers or
hardware and software, applications or products contained within.
This publication is not endorsed or associated in any way with
3 Registered in England & Wales No: 04308513

ADVERTISING - For our latest media packs please contact:


ourselves on the quality of the information we provide, Papercut The Linux Foundation, The Raspberry Pi Foundation, ARM Holding, Brad Francis - brad@papercutltd.co.uk
Limited reserves the right not to be held responsible for any Canonical Ltd, Python, Debian Project, Linux Mint, Microsoft, Web - www.pclpublications.com
mistakes or inaccuracies found within the text of this publication. Lenovo, Dell, Hewlett-Packard, Apple and Samsung or any INTERNATIONAL LICENSING - Papercut Limited has many great
Due to the nature of the tech industry, the publisher cannot associate or affiliate company. All copyrights, trademarks and publications and all are available for licensing worldwide.
guarantee that all apps and software will work on every version of registered trademarks for the respective companies are For more information email: jgale@pclpublications.com

You might also like