Professional Documents
Culture Documents
BDM s
PAGES ¦ Python 3 ¦ C++ ¦
Batch
Files ¦ Linux
Scripting
Manual Series
THE COMPLETE
BDM s Manual Series The Complete Coding Manual Volume 21
MANUAL
Learn to Code Projects & Ideas Develop Your Skills
NEW
for
2020
US$24.99
Can$25.99
Volume 21
(Spring 2020)
Aus$25.25
NZ$29.99
UK£12.99
Printed in the UK.
100% INDEPENDENT
THE COMPLETE
MANUAL
Engineer your future; learn to code!
Code is everywhere. Turn on your TV, start your
car, power up the washing machine, whatever 60 Python
programs
process enables you to interact with a device 21,500+ lines of code
or object contains some form of code. From Master Python
with the help of our fantastic
simply displaying an icon on your iPad, through Code Portal, featuring code for
to the latest graphically immersive game, there games, tools and more.
Visit: https://bdmpublications.com/
are layers of code that define everything that code-portal, and log in
to get access!
happens. And you can learn how it all works.
Coding requires patience, imagination and great
tutorials to help you understand what to enter, and what exactly is
happening when you enter the code. The Complete Coding Manual
provides you with a solid foundation, on which to begin learning how
to code, before moving on to introduce more complex techniques and
advanced concepts that enable you to create your own unique code.
This manual is your guide to discovering the boundless world of code
and programming. So let’s get started and learn how to code.
Contents
Compl
The
ete
l
Co
ua
di
n g M an
16 Introducing Python
58 Manipulating Data
18 Python in Numbers
20 Why Python? 60 Lists
22 Equipment You Will Need 62 Tuples
24 Getting to Know Python 64 Dictionaries
26 How to Set Up Python in Windows 66 Splitting and
Joining Strings
28 How to Set Up Python in Linux
68 Formatting Strings
70 Date and Time
72 Opening Files
74 Writing to Files
76 Exceptions
78 Python Graphics
80 Combining What
You Know So Far
Your Unique Download ID Code:
0000 0919 MS26 BMD
4 www.bdmpublications.com
Index
82 Using Modules
84 Calendar Module
142 Loops and Decision Making
86 OS Module
88 Random Module 144 While Loop
90 Tkinter Module 146 For Loop
92 Pygame Module 148 Do… While Loop
96 Create Your Own Modules 150 If Statement
152 If… Else Statement
98 Introducing C++
Coding
Foundations
Your Unique Download ID Code:
0000 0919 MS26 BMD
6 www.bdmpublications.com
Coding Foundations
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 Arthur Scherbius
but was made famous by Alan
Turing at Bletchley Park’s
codebreaking centre.
Computer programming
was mainly utilised by
universities, the military and
big corporations during the ‘60s
and the ‘70s. A notable step
toward a more user-friendly,
or home user language, was
the development of BASIC
(Beginners All-purpose
Symbolic Instruction Code) in
the mid-sixties.
Being a Programmer
Programmer, developer, coder, they’re all titles for the same occupation, someone who
creates code. What they’re creating the code for can be anything from a video game
to a critical element on-board the International Space Station. How do you become a
programmer though?
“It’s up to you
creating something from a few lines of BASIC code was achievable and so
the first generation of home-bred programmer was born.
your coding
game. This of course led to the programmer becoming more than simply
someone who could fashion a sprite on the screen and make it move at the
press of a key.
adventure!” Naturally, time has moved on and with it the technology that we use.
However, the fundamentals of programming remain the same; but what
exactly does it take to be a programmer?
Being able to see the big picture is certainly beneficial for the modern
programmer. Undoubtedly, as a programmer, you will be part of a team
of other programmers, and more than likely part of an even bigger team
of designers, all of whom are creating a final product. While you may only
be expected to create a small element of that final product, being able to
understand what everyone else is doing will help you create something
that’s ultimately better than simply being locked in your own coding cubicle.
Choosing a
Programming
Language
It would be impossible to properly
explain every programming language in
a single book of this size. New languages
and ways in which to ‘talk’ to a computer
or device and set it instructions are being
invented almost daily; and with the
onset of quantum computing, even more
complex methods are being born. Here
is a list of the more common languages
along with their key features.
Creating a
Coding Platform
The term ‘Coding Platform’ can denote a type of hardware, on which you can code,
or a particular operating system, or even a custom environment that’s pre-built and
designed to allow the easy creation of games. In truth it’s quite a loose term, as a
Coding Platform can be a mixture of all these ingredients, it’s simply down to what
programming language you intend to code in and what your end goals are.
The trick is to slow down and, to begin with, not look too deeply
into coding. Like all good projects, you need a solid foundation
on which to build your skill and to have all the necessary tools
available to hand to enable you to complete the basic steps. This
is where 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.
HARDWARE SOFTWARE
Thankfully, coding at the In terms of
foundation level doesn’t software, most of
require specialist equipment, the development
or a top of the range, liquid environments - the
hydrogen-cooled PC. If you tools that allow you
own a computer, no matter to code, compile the
how basic, you can begin to learn how to code. Naturally, if code and execute it - are freely available to download and
your computer in question is a Commodore 64 then you may install. There are some specialist tools available that will cost,
have some difficulty following a modern language tutorial, but but at this level they’re not necessary; so don’t be fooled into
some of the best programmers around today started on an thinking you need to purchase any extra software in order to
8-bit machine, so there’s hope yet. start learning how to code
Access to the Internet is necessary to download, install and Over time, you may find yourself changing from the
update the coding development environment, alongside a mainstream development environment and using a collection
computer with either: Windows 10, macOS, or Linux installed. of your own, discovered, tools to write your code in. It’s all
You can use other operating systems, but these are the ‘big personal preference in the end and as you become more
three’ and you will find that most code resources are written experienced, you will start to use different tools to get the
with one, or all of these, in mind. job done.
Your Unique Download ID Code:
0000 0919 MS26 BMD
14 www.bdmpublications.com
Creating a Coding Platform
Linux, however, is by far one of the most popular and This, of course, makes it a fantastic coding platform, as you can
important, coding operating systems available. Not only have different installations of operating systems running from
does it have a Unix-like backbone, but also it’s also free to the host computer while using different coding languages.
download, install and use and comes with most of the tools You can test your code without fear of breaking your host OS
necessary to start learning how to code. Linux powers most of and it’s easy to return to a previous configuration without the
the servers that make up the Internet. It’s used on nearly all of need to reinstall everything again.
the top supercomputers, as well as specifically in organisations
such as NASA, CERN and the military and it forms the base of Virtualisation is the key to most big companies now. You will
Android-powered devices, smart TVs and in-car systems. Linux, probably find, for example, rather than having a single server
as a coding platform, is an excellent idea and it can be installed with an installation of Windows Server, the IT team have
inside a virtual machine without ever affecting the installation instead opted for a virtualised environment whereby each
of Windows or macOS. Windows Server instance is a virtual machine running from
several powerful machines. This cuts down on the number
of physical machines, allows the team to better manage
resources and enables them to deploy an entire server
dedicated to a particular task in a fraction of the time.
THE RASPBERRY PI
If you haven’t already heard
of the Raspberry Pi, then
we suggest you head over MINIX NEO N42C-4
to www.raspberrypi.org, and
check it out. In short, the Raspberry The NEO N42C-4 is an extraordinarily
Pi is a small, fully functional computer that comes with its own small computer from mini-PC developer,
customised Linux-based operating system, pre-installed with MINIX. Measuring just 139 x 139 x 30mm, this Intel N4200 CPU
everything you need to start learning how to code in Python, powered, Windows 10 Pro pre-installed computer is one of the
C++, Scratch and more. best coding platforms we’ve come across.
It’s incredibly cheap, costing around £35 and allows you to utilise The beauty, of course, lies in the fact that with increased storage
different hardware, in the form of robotics and electronics and memory available, you’re able to create a computer that can
projects, as well as offering a complete desktop experience. easily host multiple virtual machines. The virtual machines can
Although not the most powerful computing device in the world, cover Linux, Android and other operating systems, allowing you
the Raspberry Pi has a lot going for it, especially in terms of being to write and test cross-platform code without fear of damaging,
one of the best coding platforms available. or causing problems, with other production or home computers.
The MINIX NEO N42C-4 starts at around £250, with the base
32GB eMMC and 4GB of memory. You’ll need to add another
YOUR OWN CODING PLATFORM hundred and fifty, or so, to increase the specifications, but
consider that a license for Windows 10 Pro alone costs £219
Whichever method you choose, remember that your coding
from the Microsoft Store and you can begin to see the benefits
platform will probably change, as you gain experience and favour
of opting for a more impressive hardware foundation over the
one language over another. Don’t be afraid to experiment along
likes of the Raspberry Pi.
the way, as you will eventually create your own unique platform
that can handle all the code you enter into it. Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 15
Index
Introducing
Python
18 Python in Numbers
20 Why Python?
22 Equipment You Will Need
24 Getting to Know Python
26 How to Set Up Python in Windows
28 How to Set Up Python in Linux
in PYTHON AND
LINUX SKILLS
N umbers
Python Data Science is Google is the top Data Science, Blockchain New York and San
thought to become the company for hiring Python and Machine Learning Francisco are the top
most sought-after job in developers, closely are the fastest growing Python developer cities
the coming years. followed by Microsoft. Python coding skills. in the world.
£60,000
Compiled from various sources.
95% OF ALL BEGINNER 75% OF ALL PYTHON 79% OF ALL 49% OF WINDOWS
CODERS START WITH DEVELOPERS USE PROGRAMMERS 10 DEVELOPERS
AND STILL USE, PYTHON 3, WHEREAS USE PYTHON USE PYTHON 3
PYTHON AS THEIR 25% STILL USE THE REGULARLY, 21% USE AS THEIR MAIN
PRIMARY OR OUTDATED PYTHON 2 IT AS A SECONDARY PROGRAMMING
SECONDARY LANGUAGE. VERSION. LANGUAGE. LANGUAGE.
Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 19
Introducing Python
Why Python?
There are many different programming languages available for the modern computer,
and some still available for older 8 and 16-bit computers too. Some of these languages
are designed for scientific work, others for mobile platforms and such. So why choose
Python out of all the rest?
PYTHON POWER
Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee
hours, slaving over an overheating heap of circuitry to create something akin to magic.
These pioneers of programming carved their way into a new Regardless of whether you use an Android device, iOS device, PC,
frontier, forging small routines that enabled the letter ‘A’ to scroll Mac, Linux, Smart TV, games console, MP3 player, GPS device built-in
across the screen. It may not sound terribly exciting to a generation to a car, set-top box or a thousand other connected and ‘smart’
that’s used to ultra high-definition graphics and open world, multi- appliances, behind them all is programming.
player online gaming. However, forty-something years ago it was
blindingly brilliant. All those aforementioned digital devices need instructions to tell
them what to do, and allow them to be interacted with. These
Naturally these bedroom coders helped form the foundations for instructions form the programming core of the device and that core
every piece of digital technology we use today. Some went on to can be built using a variety of programming languages.
become chief developers for top software companies, whereas
others pushed the available hardware to its limits and founded the The languages in use today differ depending on the situation, the
billion pound gaming empire that continually amazes us. platform, the device’s use and how the device will interact with its
environment or users. Operating systems, such as Windows, macOS Python was created over twenty six years ago and has evolved to
and such are usually a combination of C++, C#, assembly and some become an ideal beginner’s language for learning how to program a
form of visual-based language. Games generally use C++ whilst web computer. It’s perfect for the hobbyist, enthusiast, student, teacher
pages can use a plethora of available languages such as HTML, Java, and those who simply need to create their own unique interaction
Python and so on. between either themselves or a piece of external hardware and the
computer itself.
More general-purpose programming is used to create programs,
apps, software or whatever else you want to call them. They’re Python is free to download, install and use and is available for Linux,
widely used across all hardware platforms and suit virtually every Windows, macOS, MS-DOS, OS/2, BeOS, IBM i-series machines, and
conceivable application. Some operate faster than others and some even RISC OS. It has been voted one of the top five programming
are easier to learn and use than others. Python is one such general- languages in the world and is continually evolving ahead of the
purpose language. hardware and Internet development curve.
Python is what’s known as a High-Level Language, in that it ‘talks’ So to answer the question: why Python? Simply put, it’s free, easy to
to the hardware and operating system using a variety of arrays, learn, exceptionally powerful, universally accepted, effective and a
variables, objects, arithmetic, subroutines, loops and countless 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
and easy to learn.
Java is a powerful
language that’s used in
web pages, set-top boxes,
TVs and even cars.
Equipment You
Will Need
You can learn Python with very little hardware or initial financial investment. You
don’t need an incredibly powerful computer and any software that’s required is
freely available.
COMPUTER
Obviously you’re going to need a computer in order to learn how to program in
Python and to test your code. You can use Windows (from XP onward) on either a 32
or 64-bit processor, an Apple Mac or Linux installed PC.
AN IDE
An IDE (Integrated Developer Environment) is used to enter and execute Python
code. It enables you to inspect your program code and the values within the code, as
well as offering advanced features. There are many different IDEs available, so find
the one that works for you and gives the best results.
PYTHON SOFTWARE
macOS and Linux already come with Python preinstalled as part of the operating
system, as does the Raspberry Pi. However, you need to ensure that you’re running
the latest version of Python. Windows users need to download and install Python,
which we’ll cover shortly.
TEXT EDITOR
Whilst a text editor is an ideal environment to enter code into, it’s not an absolute
necessity. You can enter and execute code directly from the IDLE but a text editor,
such as Sublime Text or Notepad++, offers more advanced features and colour coding
when entering code.
INTERNET ACCESS
Python is an ever evolving environment and as such new versions often introduce
new concepts or change existing commands and code structure to make it a more
efficient language. Having access to the Internet will keep you up-to-date, help you
out when you get stuck and give access to Python’s immense number of modules.
THE RASPBERRY PI
Why use a Raspberry Pi? The Raspberry Pi is a tiny computer that’s very cheap to purchase, but offers the user a fantastic learning
platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many modules and extras.
RASPBERRY PI
The Raspberry Pi 4 Model B is the latest version,
incorporating a more powerful CPU, a choice of 1GB,
2GB or 4GB memory versions and Wi-Fi and Bluetooth
support. You can pick up a Pi from around £33, increasing
up to £54 for the 4GB memory version, or as a part of kit
for £50+, depending on the kit you’re interested in.
FUZE PROJECT
The FUZE is a learning environment built on the latest model
of the Raspberry Pi. You can purchase the workstations that
come with an electronics kit and even a robot arm for you
to build and program. You can find more information on the
FUZE at www.fuze.co.uk.
BOOKS
We have several great Raspberry Pi titles available via www.
bdmpublications.com. Our Pi books cover how to buy your
RASPBIAN first Raspberry Pi,
set it up and use NEW ¦ Py
thon 3 ¦ C+
Raspber
+ ¦ Raspbe
it; there are some great step- rry Pi 4 ¦
Projects
The Raspberry Pi’s main operating system is a Debian-based BD
Ultimate M s
ry Pi
Series
by-step project examples
Linux distribution that comes with everything you need in
and guides to get the most
a simple to use package. It’s streamlined for the Pi and is an
ideal platform for hardware and software projects, Python
from the Tips, Tricks & F
BDM s Ult
on ¦ Code
¦ Projects you to un
Pi too. BD
Ultimate M s
lock the
power of
the Rasp
ies
ry Pi
Series be rry Pi
Raspberr
Raspb
y Pi - Tip
THE COM
erry
Pi 4
BDM s Ult
P LETE GU
s, Tricks
Upda
IDE Editio te
imate Ser
Unlock an n
& Fixes
d master
the powe
r of the Ra
spberry Pi
ies
Volume
Over
814
Raspberr
Over
814
35
inside fo
tips & tricks 202r0
e Complet
inside
£9.99
Volume
35
US$19.99
Can$25.50
e Guide
Aus$21.25
Learn Lin
ux, NZ$20.99
Ultimate
m
hardware the
Series -
Raspberr
Raspberry
Pi - Tips
y Pi
Tricks &
Fixes - Vol
35.indd
1-2
Pi4
Unlock the
power of £9.99
the Volume
05/08/2019
16:45:03
Raspberr 36
y Pi US$19.99
Can$25.50
Aus$21.25
tips ild
& help advanced Learn ho
Pi w to
projects create am Boost yo
azing ur
Pi projec knowled
Ultimate
Series - ts ge
Raspberry
Pi - The
Complete
Guide Vol
of coding
36.indd
1-2
PYTHON POWER
Python is a high-level, general-purpose programming language that was designed by Guido van Rossum in the late ‘80s, as a
successor to the ABC Programming Language, and became available to use in 1990.
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 AI 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 AI, 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, AI 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 AI 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. Your Unique
that similar products start to appear, whether Download
within Amazon ID Code:
itself,
0000 0919 MS26 BMD
24 www.bdmpublications.com
Getting
GettingtotoKnow
KnowPython
Python
PYTHON
PYTHON33VS
VSPYTHON
PYTHON22
InIn
a typical
a typical
computing
computingscenario,
scenario,
Python
Python
is is
complicated
complicated
somewhat
somewhat
byby
the
the
existence
existence
ofof
two
two
active
active
versions
versions
ofof
the
the
language:
language:
Python
Python 22and
andPython
Python3.3.
You
Youneed
need totobebecareful
careful when
when youyou look
lookupup Python
Python codecode online,
online,although
although
there
thereareare
countless
countless websites
websites that
that offer
offer quick
quicktutorials,
tutorials, code
codesnippets
snippets
and
and
support
support – and
– and 99%99% ofof
these
these site
siteareare
a great
a greathelphelp totothose
those starting
starting
out
out
with
withPython
Python – a– lot
a lot
ofof
the
thesites
siteshaven’t
haven’t been
been updated
updated forfor
some
some
time,
time,
andandasas
such
such useuse Python
Python 2. 2.
If you
If you enter
enterPython
Python 2 code
2 code into
intothethe
Python
Python 3 IDLE,
3 IDLE,thethechances
chances are
areit won’t
it won’t work
workduedue toto incompatibilities
incompatibilities
between
between the
theolder
older version
versionand
and thethenewer.
newer. Python
Python 2 is
2 is
good,
good,butbut
Python
Python 3 is
3 is
better.
better. YouYou can
can
obviously
obviously spend
spend time
time converting
converting thethe
Python
Python 2 code
2 code into
intoversion
version3, 3,
but,
but, totobegin
begin with,
with,it’sit’s
best
besttotomake
make sure
sure
that
that
thethecode
codeyou’re
you’re looking
lookingatatis is
forforthethePython
Python 3 libraries.
3 libraries. Don’t
Don’t
Python
Python3 is
3 is
the
the
best
best
option
optiontoto
worry,
worry,though,
though, allall
thethecode
code
in in
this
thisbook
book is is
designed
designed forfor
Python
Python 3, 3,
andand
download,
download, oror
update
updateto.to.
that
that
includes
includes allall
thethesubsubversions
versions from
from Python
Python 3.13.1toto thethe
latest
latest3.x.
3.x.
Python
Python 3 is
3 is
the the newest
newest release
release ofofthetheprogramming
programming language.
language.
However,
However, if you
if you digdiga little
a little
deeper
deeper intointo
the
thePython
Python site
site
andandinvestigate
investigate Python
Python3’s3’s
growing
growing
popularity
popularityhas
has
meant
meantthat
that
it’sit’s
nownowprudent
prudent
toto
start
start
Python
Python code
code online,
online, youyouwill
will
undoubtedly
undoubtedly come
come across
across Python
Python 2. 2. learning
learning
totodevelop
develop
with
with
the
the
new
newfeatures
features
and
andbegin
begin toto
phase
phase
out
out
the
the
Crucially,
Crucially,
although
although youyoucancan run
runPython
Python 3 and
3 and Python
Python 2 alongside
2 alongside previous
previousversion.
version.
Many
Manydevelopment
development companies,
companies, such
such
asas
SpaceX
SpaceXand
and
each
each
other,
other, it’sit’s
notnotrecommended.
recommended. Always
Alwaysoptoptforfor thethelatest
lateststable
stable NASA,
NASA,use
usePython
Python
3 for
3 for
snippets
snippets
ofof
important
importantcode.
code.
release,
release,asasposted
posted byby the
the Python
Python website.
website. YouYouwill will
find,
find,
when
when using
using
macOS
macOS ororLinux,
Linux, that
thatPython
Python 2 is
2 is
already
alreadyinstalled.
installed. This
This
is is
because
because However,
However, support
support forfor Python
Python2 is
2 issetset
toto
endend ononJanuary
January 1st
1st2020,
2020, butbut
both
boththese
these operating
operating systems
systems utilise
utiliseelements
elements ofof codecode necessary
necessary toto this
this
doesn’t
doesn’tmean
mean it’llit’ll
bebe the
the
last
lastyouyousee
seeofofit.it.
Many
Many Linux
Linuxdistros
distros useuse
the
the
core
core
functionality
functionality ofof
thetheOS.OS.Linux
Linux users
userstend
tend toto bebebetter
better off,
off, Python
Python 2 libraries,
2 libraries, asas doesdoesmacOS,
macOS, andandtotobebefair,
fair,
forfor
thethedevelopers
developers
asas
most
most distributions
distributions package
package the
the latest
latest
version
version ofofPython
Python 3 out-of-
3 out-of- toto
transfer
transferthe
theexisting
existing Python
Python 2 content
2 content totoPython
Python 3 may
3 may take
take more
more
the-box,
the-box,whereas
whereas macOS
macOS often
oftenhashas Python
Python 3, 3,
it’sit’s
usually
usually ananolder
older time
timethan
thanthey
theyhave
have available,
available,i.e.i.e.
before
before thethestart
start
ofof 2020.
2020.It’sIt’s
likely
likely
version.
version.Microsoft
Microsoft doesn’t
doesn’t useuseanyanyPython
Pythoncode
code forfor
itsits
core
coreWindows
Windows then,
then,that
thatwewe
willwill
still
stillbebe seeing
seeing Python
Python 2 long
2 long after
afterit has
it has
hadhad thethefinal
final
systems,
systems, which
which is is
whywhy you
you won’t
won’t find
findPython
Python inherent
inherent totoWindows
Windows and
and nail
nail
hammered
hammered into
intoitsitscoffin
coffin
– in
– infact,
fact,
expect
expect totosee
see that
that
cut-off
cut-off date
date
therefore
therefore needneed toto
install
installit from
it fromscratch.
scratch. extend
extend further
furtherinto
intothe the future.
future.
oror
from
from
a search
a search
engine,
engine,oror
even
evenFacebook.
Facebook. The
The code
codebehind
behind
these
these
targeted
targeted
snippets
snippets is is
Python,
Python,
and
andit’sit’s
using
using
a form
a form ofof
AIAI
toto
help
help
determine
determinewhat
whatit it
is is
youyou
would
wouldlikely
likelysearch
search
for.
for. ZEN OF PYTHON
Despite
Despite thethefact
fact that
thatmany
many people
people find
findthethetargeting
targeting ofofadvertising
advertising Python lets you access
intrusive,
intrusive, ororeven
even anan invasion
invasion ofofprivacy,
privacy, youyou have
havetoto admit
admit that
that the
the all the power of a
code
code technology
technology behind
behindit it
allall
is is
rather
rather impressive.
impressive. With
With some
some very
very computer in a language
clever
clever techniques,
techniques, a Python
a Python developer
developer is is
able
abletotocreate
create a machine
a machine that humans can
thinking
thinking script
scriptthat
thatnotnot
only
onlydisplays
displays items,
items, news
news stories,
stories,books,
books, understand. Behind all
other
other websites
websites andand ideas
ideasrelating
relating totowhat
what you’ve
you’ve searched
searched for,
for, this is an ethos called
butbutit it
cancanalso
alsopredict
predict what
what you
you may
may bebeinterested
interested inin
looking
looking for for “The Zen of Python”.
ininthe
the future.
future. Another
Another element
element totoconsider,
consider, with
withregards
regards totoAI,AI,
is is This is a collection of 20
that
thatPython
Python code
code cancan
bebeused
used totohelp
help a computer
a computer learn
learnhowhow toto dodo software principles that
something
something more
more efficiently.
efficiently.InIn
thethecase
caseofof neural
neural networks
networks inin
AI,AI,
thethe influences the design of
Python
Python code
code is is
designed
designed toto
return
return a result,
a result, then,
then,asasthethecode
code is is
runrun the language. Principles The
TheZen
Zenofof
Python,
Python, asas
over
overand andover
overagain,
again, the
the
AIAIportion
portion will
willbegin
begin toto
learn
learnhowhow totoobtain
obtain include “Beautiful is seen
seenwhen
when entering:
entering:
a more
a more accurate
accurate result,
result,
orordodothethemaths
maths behind
behind thethecode
code quicker.
quicker. It It better than ugly” and import
importthis,
this,
into
into
the
the
allall
depends
depends onon what
what the
the
developer
developer wants
wants from
fromtheir
theirAIAIPython
Python code.
code. “Simple is better than Python
Python IDLE.
IDLE.
complex.” Type import
this into Python and it will display all the principles.
AnAn
example
example
ofof
Python
PythonAIAI
code,
code,
using
using
aa
feedforward
feedforward
neural
neural
network.
network.
As you will discover over the coming pages, Python is a
fantastic language to learn. Get to grips with the basics, and
before long, you’ll be creating your own Python code for
games, tools, and maybe even something in AI. The only limit
with Python is your own imagination.
Manual Series - The Complete Coding Manual - Vol 21.indd 23 03/01/2020 12:55:22
Introducing Python
How to Set Up
Python in Windows
Windows users can easily install the latest version of Python via the main Python
Downloads page. Whilst most seasoned Python developers may shun Windows as the
platform of choice for building their code, it’s still an ideal starting point for beginners.
STEP 1 Start by opening your web browser to www.python. STEP 3 Choosing the Customise option allows you to
org/downloads/. Look for the button detailing the specify certain parameters, and whilst you may
Download link for Python 3.x. Python is regularly updated, changing stay with the defaults, it’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.8, or more, as long as it’s Python 3, the code in this features. On the first screen available, ensure all boxes are ticked
book will work fine. and click the Next button.
STEP 2 Click the Download button for version 3.x and STEP 4 The next page of options include some interesting
save the file to your Downloads folder. When the additions to Python. Ensure the Associate file with
file is downloaded, double-click the executable and the Python Python, Create Shortcuts, Add Python to Environment Variables,
installation wizard will launch. From here, you have two choices: Precompile Standard Library and Install for All Users options are
Install Now and Customise Installation. We recommend opting for ticked. These make using Python later much easier. Click Install when
the Customise Installation link. you’re ready to continue.
STEP 5 You may need to confirm the installation with STEP 8 Clicking on the IDLE (Python 3.x 32-bit) link will launch
the Windows authentication notification. Simply the Python Shell, where you can begin your Python
click Yes and Python will begin to install. Once the installation is programming journey. Don’t worry if your version is newer, as long
complete, the final Python wizard page will allow you to view the as it’s Python 3.x our code works inside your Python 3 interface.
latest release notes and follow some online tutorials.
STEP 6 Before you close the install wizard window STEP 9 If you now click on the Windows Start button again,
however, it’s best to click on the link next to the and this time type: CMD, you’ll be presented with
shield detailed Disable Path Length Limit. This will allow Python the Command Prompt link. Click it to get to the Windows command
to bypass the Windows 260 character limitation, enabling you to line environment. To enter Python within the command line, you
execute Python programs stored in deep folders arrangements. need to type: python and press Enter.
Click Yes again, to authenticate the process, then you can Close the
installation window.
STEP 7 Windows 10 users can now find the installed Python STEP 10 The command line version of Python works in
3.x within the Start button Recently Added section. much the same way as the Shell you opened in
The first link, Python 3.x (32-bit) will launch the command line Step 8; note the three left-facing arrows (>>>). Whilst it’s a perfectly
version of Python when clicked (more on that in a moment). To open fine environment, it’s not too user-friendly, so leave the command
the IDLE, type IDLE into Windows start. line for now. Enter: exit() to leave and close the Command
Prompt window.
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. If you’re not going down
the Pi route, then here’s how to check and install Python for Linux.
PYTHON PENGUIN
Linux is such a versatile operating system that it’s often difficult to nail down just one-way of doing something. Different
distributions go about installing software in different ways, so 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:
STEP 1 STEP 4
is currently installed in your Linux system. To begin python3 --version again to see if Python 3.x is
with, drop into a Terminal session from your distro’s menu, or hit the updated, or even installed. As long as you have Python 3.x, you’re
Ctrl+Alt+T keys. running the most recent major version, the numbers after the 3.
indicate patches plus further updates. Often they’re unnecessary,
but they can contain vital new elements.
Open up your Linux web browser and go to the For the GUI IDLE, you’ll need to enter the following
STEP 6 STEP 9
Python download page: https://www.python.org/ command into the Terminal:
downloads. Click on the Downloads, followed by the button under
sudo apt-get install idle3
the Python Source window. This opens a download dialogue box,
choose a location, then start the download process. The IDLE can then be started with the command: idle3. Note, that
IDLE runs a different version to the one you installed from source.
PYTHON ON macOS
Installation of Python on macOS can be done in much the
same way as the Windows installation. Simply go to the Python
webpage, hover your mouse pointer over the Downloads
link and select Mac OS X from the options. You will then be
guided to the Python releases for Mac versions, along with the
necessary installers for macOS 64-bit for OS X 10.9 and later.
Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 29
Index
Python
Foundations
STARTING PYTHON
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!
STEP 1 Click on the Windows Start button, and start typing STEP 3 For example, in the Shell enter: 2+2
‘idle’. The result will be the currently installed After pressing Enter, the next line will display the
version of Python, IDLE (Python 3.7 32-bit), for example. You can answer: 4. Basically, Python has taken the ‘code’ and produced the
Pin it to the Start for convenience, otherwise simply click the icon to relevant output.
launch the Python Shell.
STEP 2 The Shell is where you can enter code and see the STEP 4 The Python Shell acts very much like a calculator,
responses and output of code you’ve programmed since code is basically a series of mathematical
into Python. This is a kind of sandbox, if you will, where you’re able 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.
STEP 5 While that’s very interesting, it’s not particularly STEP 8 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.
STEP 6 This is a little more like it, since you’ve just produced STEP 9 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.
STEP 7 You’ll have noticed the colour coding within the STEP 10 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 Blue – User Functions
https://docs.python.org/3/library/idle.html, which details many of
Green – Strings Dark Red – Comments
the IDLE’s features.
Purple – Functions Light Red – Error Messages
Orange – Commands
STEP 1 If you’ve closed Python 3 IDLE, re-open it as you STEP 3 You’ll notice that instead of the number 4, the
did in the previous page. In the Shell, enter the output is the 2+2 you asked to be printed to the
familiar following: 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:
print(2+2)
STEP 2 As predicted, the word Hello appears in the Shell STEP 4 You can continue as such, printing 2+2, 464+2343
as blue text indicating output from a string. It’s and so on to the Shell. An easier way is to use a
fairly straightforward, and doesn’t require too much explanation. variable, which is something we will cover in more depth later. For
Now try: now, enter:
print(“2+2”) a=2
b=2
STEP 5 What you have done here is assign the letters a STEP 8 Now let’s add a surname:
and b two values: 2 and 2. These are now variables,
surname=”Hayward”
which can be called upon by Python to output, add, subtract, divide
print(surname)
and so on, for as long as their numbers stay the same. Try this:
We now have two variables containing both a first name and a
print(a)
surname, and we can print them independently.
print(b)
STEP 6 The output of the last step displays the current STEP 9 If we were to apply the same routine as before,
values of a and b individually, as essentially you’ve using the + symbol, the name wouldn’t appear
asked them to be printed separately. If you want to add them up, correctly in the output in the Shell. Try it:
you can use the following:
print(name+surname)
print(a+b)
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.
STEP 7 You can play around with different kinds of variables STEP 10 In Python 3 we can separate the two variables
together with the Print function. For example, we with a space by using a comma:
could assign variables for someone’s name:
print(name, surname)
name=”David”
Alternatively, you can add the space yourself:
print(name)
print(name+” “+surname)
As you can see, the use of the comma is much neater.
Congratulations, you’ve just taken your first steps into the wide
world of Python.
EDITING CODE
You will eventually reach a point where you have to move on from inputting single lines of code into the Shell. Instead, the
IDLE Editor will allow you to save and execute your Python code.
STEP 1 First, open the Python IDLE Shell. When it’s up, click STEP 3 As you can see the same colour coding is in place in
on File > New File, this will open a new window with the IDLE Editor as it is in the Shell, enabling you to
Untitled as its name. This is the Python IDLE Editor, and within it, you better understand what’s going on with your code. To execute the
can enter the code you need to create your future programs. code, however, you need to first save it. Press F5 and you’ll have a
Save…Check box open.
STEP 2 The IDLE Editor is, for all intents and purposes, a STEP 4 Click on the OK button in the Save box, and select a
simple text editor with Python features, colour destination where you’ll save all your Python code.
coding and so on. You enter code as you would within the Shell, so The destination can be a dedicated folder called Python, or you can
taking an example from the previous tutorial, enter: 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!”)
STEP 5 Enter a name for your code, ‘print hello’ for STEP 8 Let’s extend the code and enter a few examples
example, and click on the Save button. As soon from the previous tutorial:
as the Python code is saved, it’s executed and the output will be
a=2
detailed in the IDLE Shell; In this case, the words ‘Hello everyone!’.
b=2
name=”David”
surname=”Hayward”
print(name, surname)
print (a+b)
If you press F5 now, you’ll be asked to save the file again, as it’s been
modified from before.
STEP 6 This is how the vast majority of your Python code STEP 9 If you click the OK button the file will be overwritten
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 edit a 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.
STEP 7 If you open the file location of the saved Python STEP 10 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.
STEP 1 When you first installed Python, the installation STEP 3 Now you’re at the command line, we can start
routine automatically included all the necessary Python using the command python and pressing
components to allow the execution of code outside of the GUI the Enter key. This will put you into the command line version of the
IDLE; in other words, the command line. To begin with, click on the Shell, with the familiar, three right-facing arrows as the cursor (>>>).
Windows Start Button, and type: cmd.
STEP 2 As you did when launching the Python IDLE, STEP 4 From here you’re able to enter the code you’ve
click on the returned result from the search, the looked at previously, such as:
Command Prompt App. This will launch a new window, with a black
a=2
background and white text. This is the command line, also called a
print(a)
Terminal in macOS, Linux, and Raspberry Pi operating systems.
As you can see, it works exactly the same.
STEP 5 Now enter exit() to leave the command line STEP 6 From within the same folder as the code you’re going
Python session, and return back to the command to run, enter the following into the command line:
prompt. Enter the folder where you saved the code from the
python hello.py
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:
a=”Python”
b=”is”
c=”cool!”
print(a, b, c)
STEP 1 Open up the GUI version of Python 3, as mentioned STEP 3 You can use all
you can use either the Shell or the Editor. For the the customary
time being, we’re going to use the Shell. If you’ve opted to use a Mathematical operations: divide,
third-party text editor, note that you need to get to the IDLE Shell multiply, brackets and so on.
for this part of the tutorial. Practise with a few, for example:
1/2
6/2
2+2*3
(1+2)+(3*4)
STEP 7 Numbers and STEP 10 Execute the code from Step 9, and you’ll see a
expressions don’t series of True or False statements depending on
stop there. Python has numerous the result of the two defining values: 6 and 7. It’s an extension of
built-in functions to work out what we’ve looked at, and an important part of programming.
sets of numbers, absolute values,
complex numbers, and a host of
Mathematical expressions and
Pythogarian tongue-twisters. For
example, to convert a number to
binary, use:
bin(3)
Using Comments
When writing your code, the flow, what each variable does, how the overall program
will operate and so on, is all inside your head. Another programmer could follow the
code line by line, but when the code starts to hit thousands of lines, things get a little
difficult to read.
#COMMENTS!
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.
STEP 1 We’ll start by creating a new instance of the IDLE STEP 3 Re-save the code and execute it. You’ll see that the
Editor (File > New File), and then create a simple output in the IDLE Shell is still the same as before,
variable and print command: despite the extra lines being added. Simply put, the hash symbol (#)
denotes a line of text the programmer can insert, to inform them
a=10
and others of what’s going on, without the user being aware.
print(“The value of A is,”, a)
Save the file, and execute the code.
STEP 2 Running the code will return the line: The value of STEP 4 Let’s assume that the variable A we’ve created is
A is, 10 into the IDLE Shell window – which is what the number of lives in a game. Every time the player
we expected. Now let’s add some of the types of comments you’d dies, the value decreases by 1. The programmer could insert a
normally see within code: routine along the lines of:
# Set the start value of A to 10 a=a-1
a=10 print(“You’ve just lost a life!”)
# Print the current value of A print(“You now have”, a, “lives left!”)
print(“The value of A is,”, a)
STEP 5 While we know that the variable A denotes number STEP 8 Inline Comments are comments that follow a
of lives and the player has just lost one, a casual section of code. Take our examples from above,
viewer, or someone checking the code, may not know. Imagine for a instead of inserting the code on a separate line, we could use:
moment that the code is twenty thousand lines long, instead of just
a=10 # Set the start value of A to 10
our seven. You can see how handy comments are.
print(“The value of A is,”, a) # Print the current
value of A
a=a-1 # Player lost a life!
print(“You’ve just lost a life!”)
print(“You now have”, a, “lives left!”) # Inform
player, and display current value of A (lives)
STEP 6 Essentially, the new code together with comments STEP 9 The comment, the hash symbol, can also be used to
could look like: comment out sections of code you don’t want to be
executed in your program. For instance, if you wanted to remove
# Set the start value of A to 10
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!
a=a-1
# Inform player, and display current value of A
(lives)
print(“You’ve just lost a life!”)
print(“You now have”, a, “lives left!”)
STEP 7 You can use comments in different ways. For STEP 10 You also use three single quotes to comment
example, Block Comments are a large section of out a Block Comment, or multi-line section of
text that details what’s going on in the code, such as telling the code comments. For them to work, place them before and after the areas
reader which variables you’re planning on using: you want to comment:
# This is the best game ever, and has been ‘’’
developed by a crack squad of Python experts This is the best game ever, and has been developed
# who haven’t slept or washed in weeks. Despite by a crack squad of Python experts
being very smelly, the code at least who haven’t slept or washed in weeks. Despite
# works really well. being very smelly, the code at least
works really well. ’’’
VARIOUS VARIABLES
We’ll be working with the Python 3 IDLE Shell in this tutorial. If you haven’t already, open Python 3 or close down the previous
IDLE Shell to clear up any old code.
STEP 1 In some programming languages, you’re required STEP 3 As we’ve seen previously, variables can be
to use a dollar sign to denote a string, which is a concatenated using the plus symbol between the
variable made up of multiple characters, such as a name of a person. variable names. In our example, we can use: print (name + “:
In Python this isn’t necessary, so, for example, in the Shell enter: “ + title). The middle part, between the quotations, allows
name=”David Hayward” (use your own name, unless you’re also us to add a colon and a space. As variables are connected without
called David Hayward). spaces, we need to add them manually.
STEP 2 You can check the type of variable in use by issuing STEP 4 We can also
the type () command, placing the name of the combine variables
variable inside the brackets. In our example, this would be: within another variable. For
type (name). Add a new string variable: title=”Descended example, to combine both name
from Celts”. and title variables into a new
variable, we use:
character=name + “: “ +
title
Then output the content of the
new variable as:
print (character)
Numbers are stored as different
variables:
age=44
Type (age)
Which, as we know, are integers.
STEP 5 However, you can’t combine both strings and STEP 8 This presents a bit of a problem when you want
integer type variables in the same command as you to work with a number that’s been inputted by
would a set of similar variables. You’ll need to turn one into the the user, for example, as age + 10 is both a string variable and an
other, or vice versa. When you do try to combine both, you’ll get an integer, it won’t work. Instead, you need to enter:
error message:
int(age) + 10
print (name + age)
This will TypeCast the age string into an integer that can be
worked with.
STEP 6 This is a process known as TypeCasting. The Python STEP 9 The use of TypeCasting is also important when
code is: dealing with floating point arithmetic; remember:
numbers that have a decimal point in them. For example, enter:
print (character + “ is “ + str(age) + “ years
old.”) shirt=19.99
Alternatively, you can use: Now enter type(shirt) and you’ll see that Python has allocated
the number as a ‘float’, because the value contains a decimal point.
print (character, “is“, age, “years old.”)
Notice again that in the last example, you don’t need the spaces
between the words in quotes, as the commas treat each argument
to print separately.
STEP 7 Another example of TypeCasting is when you ask STEP 10 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 our case instead of 19.99, it becomes 19.
User Input
We’ve seen some basic user interaction with the code from a few of the examples
earlier, so now would be a good time to focus solely on how you get information from
the user, then store and present it.
USER FRIENDLY
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.
STEP 1 If it’s not already, open the Python 3 IDLE Shell, STEP 3 Now that we have the user’s name stored in a
and start a New File in the Editor. Let’s begin with couple of variables, we can call them up whenever
something really simple, enter: we want:
print(“Hello”) print(“Welcome”, firstname, surname, “. I hope
firstname=input(“What is your first name? “) you’re well today.”)
print(“Thanks.”)
surname=input(“And what is your surname? “)
STEP 2 Save and execute the code, and, as you no doubt STEP 4 Run the code and you’ll notice a slight issue, the
suspected, in the IDLE Shell the program will ask full stop after the surname follows a blank space.
for your 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:
print(“Welcome”, firstname, surname+“. I hope
you’re well today.”)
STEP 5 You don’t always have to include quoted text within STEP 8 What you’ve created here is a condition, based on
the input command. For example, you can ask the the user’s input. In short, we’re using the input
user their name, and have the input in the line below: from the user and measuring it against a condition. Therefore, if the
user enters David as their name, the guard will allow them to pass
print(“Hello. What’s your name?”)
unhindered. If, however, they enter a name other than David, the
name=input()
guard challenges them to a fight.
STEP 6 The code from the previous step is often regarded STEP 9 As you learned previously, any input from a user
as being a little neater than having a lengthy is automatically a string, so you’ll need to apply a
amount of text in the input command, but it’s not a rule that’s set in TypeCast in order to turn it into something else. This creates some
stone, so do as you like in these situations. Expanding on the code, interesting additions to the input command. For example:
try this:
# Code to calculate rate and distance
print(“Halt! Who goes there?”) print(“Input a rate and a distance”)
name=input() rate = float(input(“Rate: “))
STEP 7 It’s a good start to a text adventure game, perhaps? STEP 10 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:
print(“Time:”, (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:
floating point number rather than a string.
print(“I know you not. Prepare for battle!”)
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.
FUNKY FUNCTIONS
A function is a command that you enter into Python in order to do something. It’s a little piece of self-contained code that
takes data, works on it, and then returns the result.
STEP 1 It’s not only data that a function works on. Functions STEP 3 You can pass variables through functions in much
can do all manner of useful things in Python, such as the same manner. Let’s assume you want the
sort data, change items from one format to another, and check the number of letters in a person’s surname, you could use the following
length or type of items. Basically, a function is a short word followed code (enter the text editor for this example):
by brackets. For example, len(), list(), or type().
name=input (“Enter your surname: “)
count=len(name)
print (“Your surname has“, count, “letters in
it.”)
Press F5 and save the code to execute it.
STEP 2 A function takes data, usually a variable, works on STEP 4 Python has tens of functions built into it, far too
it depending on what the function is programmed many to get into in the limited space available here.
to do, and returns the end value. The data being worked on goes However, to view the list of built-in functions available to Python
inside the brackets, so if you wanted to know how many letters 3, navigate to https://docs.python.org/3/library/functions.html.
are in the word antidisestablishmentarianism, then you’d enter: These are the pre-defined functions, but since users have created
len(“antidisestablishmentarianism”), and the number 28 many more, they’re not the only ones available.
would return.
STEP 5 Additional functions can be added to Python STEP 6 To use a function from a module, enter the name of
through modules. Python has a vast range of the module, followed by a full stop, then the name
modules available that can cover numerous programming duties. of the function. For instance, using the math module, since we’ve
They add functions and can be imported as and when required. For just imported it into Python, we can utilise the square root function.
example, to use advanced Mathematics functions enter: To do so, enter:
import math math.sqrt(16)
Once entered, you’ll have access to all the Math module functions. As you can see, the code is presented as module.function(data).
FORGING FUNCTIONS
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.
STEP 1 Choose File > New File to enter the editor, let’s STEP 3 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:
def Hello():
print (“Hello”) from Hello import Hello
Hello() Hello(“David”)
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.
STEP 2 Let’s now expand the function to accept a variable, STEP 4 What you’ve just done is import the Hello function
the user’s name for example. Edit your script to read: from the saved Hello.py program, and then used it
to say hello to David. This is how modules and functions work, you
def Hello(name):
import the module then use the function. Try this one, and modify
print (“Hello”, name)
it for extra credit:
Hello(“David”)
def add(a, b):
This will now accept the variable name, otherwise it will print Hello
result = a + b
David. In the Shell, enter: name=(“Bob”), then, Hello(name). Your
return result
function can now pass variables through it.
TRUE CONDITIONS
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.
STEP 1 Let’s create a new Python program that will ask the STEP 3 Now we’ll use an if statement to check if the word_
user to input a word, then check it to see if it’s a length variable is equal to four, and print a friendly
four-letter word or not. Start with File > New File, and begin with conformation if it applies to the rule:
the input variable:
word=input(“Please enter a four-letter word: “)
word=input(“Please enter a four-letter word: “) word_length=len(word)
if word_length == 4:
print (word, “is a four-letter word. Well done.”)
The double equal sign (==) check if something is equal to
something else.
STEP 2 Now we can create a new variable, then use the len STEP 4 The colon at the end of if tells Python that if this
function and pass the word variable through it to statement is true, do everything after the colon
get the total number of letters the user has just entered: that’s indented. Next, move the cursor back to the beginning of
the Editor:
word=input(“Please enter a four-letter word: “)
word_length=len(word) word=input(“Please enter a four-letter word: “)
word_length=len(word)
if word_length == 4:
print (word, “is a four-letter word. Well
done.”)
else:
print (word, “is not a four-letter word.”)
STEP 5 Press F5 and save the code to execute it. Enter STEP 6 Now expand the code to include other conditions.
a four-letter word in the Shell to begin with, you Eventually, it could become quite complex. We’ve
should have the returned message that the word is four letters. added a condition for three-letter words:
Now press F5 again, and re-run the program, but this time, enter a
word=input(“Please enter a four-letter word: “)
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.”)
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.
STEP 1 Let’s start with a simple while statement. Like if, STEP 3 The for loop, is another example. For is used to
this will check to see if something is TRUE, then run loop over a range of data, usually a list stored as
the indented code: variables inside square brackets. For example:
x = 1 words=[“Cat”, “Dog”, “Unicorn”]
while x < 10:
for word in words:
print (x)
print (word)
x = x + 1
STEP 2 The difference between if and while is that when STEP 4 The for loop can also be used in the countdown
while gets to the end of the indented code, it goes example by using the range function:
back and checks the statement is still true. In our example x is less
for x in range (1, 10):
than 10. With each loop, it prints the current value of x, then adds
print (x)
one to that value. When x does eventually equal 10 it’ll stop.
The x=x+1 part isn’t needed here, because the range function
creates a list between the first and last numbers used.
Python Modules
We’ve mentioned modules previously, using the Math module as an example, but since
using modules is such a large part of getting the most from Python it’s worth dedicating
a little more time to them.
MASTERING MODULES
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.
STEP 1 Although good, the built-in functions within Python STEP 3 The result is an error in the IDLE Shell, as the
are limited. The use of modules, however, allows us Pygame module isn’t recognised or installed in
to make more sophisticated programs. As you are aware, modules Python. To install a module we can use PIP (Pip Installs Packages).
are Python scripts that are imported, such as import math. Close down the IDLE Shell and drop into a command prompt or
Terminal session. At an elevated admin command prompt, enter:
pip install pygame
STEP 2 Some modules, especially on the Raspberry Pi, are STEP 4 The PIP installation requires an elevated status due
included by default; the Math module is a prime 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.
STEP 5 Close the command prompt or Terminal, and re- STEP 8 Multiple modules can be imported within your code.
launch the IDLE Shell. When you now enter import To extend our example, use:
pygame, the module will be imported into the code without any
import random
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 of errors in execution. for I in range(5):
print(random.randint(1, 25))
print(math.pi)
STEP 6 The modules contain the extra code needed to STEP 9 The result is a string of random numbers followed
achieve a certain result within your own code, with by the value of Pi, as pulled from the math
which we’ve previously experimented. For example: module using the print(math.pi) function. You can also pull in
certain functions from a module by using the from and import
import random
commands, such as:
Brings in the code from the Random number generator module. We
from random import randint
can then use this module to create something like:
for i in range(5):
for i in range(10):
print(randint(1, 25))
print(random.randint(1, 25))
STEP 7 This code, when saved and executed, will display ten STEP 10 This helps create a more streamlined approach to
random numbers from 1 to 25. You can play around programming. You can also use: import module*,
with the code to display more or less, and from a greater or lesser which will import everything defined within the named module.
range. For example: However, it’s often regarded as a waste of resources, but it works
nonetheless. Finally, modules can be imported as aliases:
import random
import math as m
for i in range(25):
print(random.randint(1, 100)) print(m.pi)
Of course, adding comments helps to tell others what’s going on.
Python Errors
It goes without saying that you’ll eventually come across an error in your code, where
Python will declare it’s not able to continue due to something being missed out, wrong,
or simply unknown. Being able to identify these errors makes for a good programmer.
DEBUGGING
Errors in code are called bugs, they’re perfectly normal and can often be easily rectified with a little patience. The important
thing is to keep looking, experimenting, and testing. Eventually your code will be bug free.
STEP 1 Code isn’t as fluid as the written word, no matter STEP 3 Thankfully Python is helpful when it comes to
how good the programming language is. Python is displaying error messages. When you receive an
certainly easier than most languages, but even it is prone to some error in red ink from the IDLE Shell, it will define the error itself,
annoying bugs. The most common are typos by the user, and while along with the line number where the error has occurred. While in
easy to find in simple dozen-line code, imagine having to debug the IDLE Editor this is a little daunting for lots of code, text editors
multi-thousand line code. help by including line numbering.
STEP 2 As we’ve mentioned, the most common of errors is STEP 4 Syntax errors are probably the second most
the typo, often at the command level, mistyping the common errors you’ll come across as a programmer.
print command for example. However, they also occur when you’ve Even if the spelling is correct, the actual command itself is wrong. In
got numerous variables, all of which have lengthy names. The best Python 3 this often occurs when Python 2 syntaxes are applied. The
advice is to simply go through the code and check your spelling. most annoying of these is the print function. In Python 3, we use
print(“words”), whereas Python2 uses print “words”.
STEP 5 Pesky brackets are also a culprit of programming STEP 8 An excellent way to check your code step-by-step is
errors, especially when you have something like: to use Python Tutor’s Visualise web page, found at
www.pythontutor.com/visualize.html#mode=edit. Simply paste
print(balanced_check(input()))
your code into the editor and click the Visualise Execution button to
Remember that for every ‘(‘ there must be an equal number of ‘)’. run the code line-by-line. This help to clear bugs, and any
misunderstandings.
STEP 6 There are thousands of online Python resources, STEP 9 Planning makes for good code. While a little old
code snippets, and lengthy discussions across school, it’s a good habit to plan what your code will
forums on how best to achieve something. While 99% of it is good do before sitting down to type it out. List the variables that will be
code, don’t always be lured into copying and pasting random used, along with the modules, and write out a script for any user
code into your editor. More often than not, it won’t work and interaction or outputs.
frustratingly, you won’t have learned anything.
STEP 7 Indents are a tricky part of Python programming STEP 10 Purely out of interest, the word debugging in
that a lot of beginners fall foul of. Recall the If loop computing terms comes from Admiral Grace
from the Conditions and Loops section, where the colon means Hopper, who, back in the ‘40s, was working on a monolithic Harvard
everything indented following the statement is to be executed Mark II electromechanical computer. According to legend, Hopper
as long as it’s true? Missing the indent, or having too much of an found a moth stuck in a relay, thus preventing the system from
indent, will come back with an error. working. Removal of the moth was hence called: debugging.
Combining What
You Know So Far
As we’ve reached the end of this section, let’s take a moment to combine all we’ve
looked at so far and apply it to writing a piece of code. This code can then be used to
insert in your own programs in future; either in part or or as a whole.
PLAYING WITH PI
For this example, we’re going to create a program that will calculate the value of Pi to a set number of decimal places; as
described by the user. It combines much of what we’ve learned, and a little more.
STEP 1 Start by opening Python and creating a New File in STEP 4 The previous step defines the rules that make up
the Editor. First, we need to get hold of an equation both the algorithm and creating the string that
that can accurately calculate Pi without rendering the computer’s will eventually display the value of Pi according to the Chudnovsky
CPU useless for several minutes. The recommended calculation brother’s algorithm. As you have no doubt already surmised, it
used in such circumstances is the Chudnovsky Algorithm, you would be handy to actually output the value of Pi to the screen. To
can find more information about it at en.wikipedia.org/wiki/ rectify that we can add:
Chudnovsky_algorithm.
print(calc(1))
STEP 3 Now we can insert the Pi calculation algorithm numberofdigits = int(input(“please enter the
part of the code. This is a version of the number of decimal place to calculate Pi to: “))
Chudnovsky Algorithm: getcontext().prec = numberofdigits
def calc(n):
t = Decimal(0)
pi = Decimal(0)
deno = Decimal(0)
k = 0
for k in range(n):
t = (Decimal(-1)**k)*(math.
factorial(Decimal(6)*k))*(13591409+545140134*k)
deno = math.factorial(3*k)*(math.
factorial(k)**Decimal(3))*(640320**(3*k))
pi += Decimal(t)/Decimal(deno)
pi = pi * Decimal(12)/
Decimal(640320**Decimal(1.5))
pi = 1/pi
return str(pi)
Your Unique Download ID Code:
0000 0919 MS26 BMD
56 www.bdmpublications.com
Combining What You Know So Far
STEP 7 We can execute the code now, and it’ll ask the user STEP 9 Now we need to import the colorama module
to how many decimal places they want to calculate (which will output text in different colours), along
Pi, and then output the result in the IDLE Shell. Try it with 1000 with the Fore function (which dictates the foreground, ink, colour),
places, but don’t go too high or else your computer will be locked up and the time module to start a virtual stopwatch to see how long
in calculating Pi. our calculations take:
import time
STEP 8 Part of programming is import colorama
being able to modify code, from colorama import Fore
making it more presentable. Let’s include
an element that times how long it takes our
computer to calculate the Pi decimal places,
and present the information in a different
colour. For this, drop into the command line
and import the colorama module (RPi users
already have it installed):
pip install colorama
Manipulating
Data
Your Unique Download ID Code:
0000 0919 MS26 BMD
58 www.bdmpublications.com
Manipulating Data
60 Lists
62 Tuples
64 Dictionaries
66 Splitting and Joining Strings
68 Formatting Strings
70 Date and Time
72 Opening Files
74 Writing to Files
76 Exceptions
78 Python Graphics
80 Combining What You Know So Far
Lists
Lists are one of the most common types of data structures you will come across in
Python. A list is simply a collection of items, or data if you prefer, which can be accessed
as a whole, or individually if wanted.
STEP 1 A list is a sequence of data values called items. You STEP 3 You can also access, or index, the last item in a list by
create the name of your list followed by an equal using the minus sign before the item number [-1], or
sign, then square brackets and the items separated by commas; the second to last item with [-2], and so on. Trying to reference an
note that strings use quotes: item that isn’t in the list, such as [10] will return an error:
numbers = [1, 4, 7, 21, 98, 156] numbers[-1]
mythical_creatures – [“Unicorn”, “Balrog”, mythical_creatures[-4]
“Vampire”, “Dragon”, “Minotaur”]
STEP 2 Once you’ve defined your list, you can call each by STEP 4 Slicing is similar to indexing, but you can retrieve
referencing its name followed by a number. Lists multiple items in a list by separating item numbers
start the first item entry as 0, followed by 1, 2, 3, and so on. with a colon. For example:
For example:
numbers[1:3]
numbers
Will output 4 and 7, those being item numbers 1 and 2. Note that
To call up the entire contents of the list. the returned values don’t include the second index position (as you
would numbers[1:3] to return 4, 7 and 21).
numbers[3]
To call the item third from zero in the list (21 in this case).
STEP 5 You can update items within an existing list, remove STEP 8 You can view what can be done with lists by entering
items, and even join lists together. For example, to dir(list) into the Shell. The output is the available
join two lists we can use: functions, for example, insert and pop are used to add, and remove,
items at certain positions:
everything = numbers + mythical_creatures
numbers.insert(4, 62)
Then view the combined list with:
Inserts the number 62 at item index 4. And:
everything
numbers.pop(4)
Will remove it.
STEP 6 Items can be added to a list by entering: STEP 9 You also use the list function to break a string down
into its components. For example:
numbers=numbers+[201]
list(“David”)
Or for strings:
Breaks the name David into ‘D’, ‘a’, ‘v’, ‘i’, ‘d’. This can then be passed
mythical_creatres=mythical_creatures+[“Griffin”]
to a new list:
Or by using the append function:
name=list(“David Hayward”)
mythical_creatures.append(“Nessie”) name
numbers.append(278) age=[44]
user = name + age
user
STEP 7 Removal of items can be done in two ways. The first STEP 10 Based on that, we can create a program to store
is by the item number: someone’s name and age as a list:
del numbers[7] name=input(“What’s your name? “)
lname=list(name)
The second, by item name:
age=int(input(“How old are you: “))
mythical_creatures.remove(“Nessie”) lage=[age]
user = lname + lage
The combined name and age list is called user, which can be called
by entering user into the Shell. Experiment and see what you can do.
Tuples
Tuples are virtually identical to lists, however, where lists can be updated, deleted,
or changed in some way, a tuple remains a constant. This is called immutable, and it’s
perfect for storing fixed data items.
STEP 1 A tuple is created the same way as a list, but in this STEP 3 You can create grouped tuples into lists that contain
instance you use curved brackets instead of square multiple sets of data. For instance, here we have a
brackets. For example: tuple called NPC (Non-Playable Characters) containing the character
name, and their combat rating, for an adventure game:
months=(“January”, “February”, “March”, “April”,
“May”, “June”) NPC=[(“Conan”, 100), (“Belit”, 80), (“Valeria”,
months 95)]
STEP 2 As with lists, the items within a named tuple can be STEP 4 Each of these data items can be accessed as a whole
indexed according to their position in the data range: by entering NPC into the Shell, or they can be
indexed according to their position NPC[0]. You can also index the
months[0]
individual tuples within the NPC list:
months[5]
NPC[0][1]
And so on. However, any attempt at deleting, or adding, to the tuple
will result in an error in the Shell. Will display 100.
STEP 5 It’s worth noting that when referencing multiple STEP 8 Now unpack the tuple into two c
tuples within a list, the indexing is slightly different orresponding variables:
from the norm. You would expect the 95 combat rating of the
(name, combat_rating)=NPC
character Valeria to be NPC[4][5], however it’s not, it’s actually:
You can now check the values by entering name and combat_rating.
NPC[2][1]
STEP 6 This means, of course, that the indexing follows thus: STEP 9 Remember, as with lists, you can also index tuples
using negative numbers, which count backwards
0 1, 1
from the end of the data list. So, for our example, using the tuple with
0, 0 2
multiple data items, we would reference the Valeria character with:
0, 1 2, 0
1 2,1 NPC[2][-0]
1, 0
This, as you can imagine, gets a little confusing when you have a lot
of tuple data to deal with.
STEP 7 Tuples though, utilise a feature called unpacking, STEP 10 We can use the max and min functions to find the
where the data items stored within a tuple are highest and lowest values of a tuple composed of
assigned variables. First, create the tuple with two items (name and numbers. For example:
combat rating):
numbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99)
NPC=(“Conan”, 100)
The numbers can be integers and floats. To output the highest and
lowest, use:
print(max(numbers))
print(min(numbers))
Dictionaries
Lists are extremely useful, but dictionaries in Python are by far the more technical way
of dealing with data items. Although they can be tricky to get to grips with at first,
you’ll soon be able to apply them to your own code.
KEY PAIRS
A dictionary is like a list, but instead each data item comes as a pair, these are known as Key and Value. The Key part must be
unique and can either be a number or string, but the Value can be any data item you like.
STEP 1 Let’s say you want to create a phonebook in Python. STEP 3 As with lists and tuples, you can check the contents
You would create the dictionary name, and contain of a dictionary by calling the dictionary name;
the data in curly brackets, separating the key and value by a colon phonebook, in this example. This will display the data items you’ve
Key:Value. For example: entered in a similar fashion to a list, which you’re no doubt familiar
with by now.
phonebook={“Emma”: 1234, “Daniel”: 3456, “Hannah”:
6789}
STEP 2 As with most lists, tuples, and so on, strings need STEP 4 The benefit of using a dictionary is that you
to be enclosed in quotes (single or double), while can enter the key to index the value. Using the
integers can be left open. Remember that the value can be either a phonebook example from the previous steps, we can enter:
string, or an integer, you just need to enclose the relevant one
phonebook[“Emma”]
in quotes:
phonebook[“Hannah”]
phonebook2={“David”: “0987 654 321”}
STEP 5 Adding to a dictionary is easy too. You can include STEP 8 Next, we need to define the user inputs and
a new data item entry by adding the new key and variables, one for the person’s name, the other
value items as such: for their phone number (we will keep it simple to avoid lengthy
Python code):
phonebook[“David”] = “0987 654 321”
phonebook name=input(“Enter name: “)
number=int(input(“Enter phone number: “))
STEP 6 And you can also remove items from a dictionary STEP 9 Note we’ve kept the number as an integer instead
by issuing the del command followed by the of a string, even though the value can be both
item’s key – the value will also be removed as well, since both an integer and a string. Now we need to add the user’s inputted
work as a pair of data items: variables to the newly created blank dictionary. Using the same
process as in Step 5, we can enter:
del phonebook[“David”]
phonebook[name] = number
STEP 7 Taking this a step further, how about creating a STEP 10 Now when we save and execute the code, Python
piece of code that will ask the user for the dictionary will ask for a name and a number. It will then insert
key and value items? Create a new Editor instance, and start by those entries into the phonebook dictionary, which we can test by
coding in a new, blank dictionary: entering into the Shell:
phonebook={} phonebook
phonebook[“David”]
If the number needs to contain spaces you’ll need to make it a
string, so remove the int part of the input.
Splitting and
Joining Strings
When dealing with data in Python, especially from a user’s input, you will undoubtedly
come across long sets of strings. A useful skill to learn, in Python programming, is being
able to split those long strings for better readability.
STRING THEORIES
We’ve already looked at some list functions, using .insert, .remove, and .pop, but there are also functions that can be applied
to strings.
STEP 1 The main tool in the string function arsenal is .split(). STEP 3 Note that the text.split part contains the brackets,
With it, you’re able to split apart a string of data, quotes, then a space followed by closing quotes
based on the argument within the brackets. For example, here’s a and brackets. The space is the separator, indicating that each list
string with three items, each separated by a space: item entry is separated by a space. Likewise, CSV (Comma Separated
Value) content has a comma, so we would use:
text=”Daniel Hannah Emma”
text=”January,February,March,April,May,June”
months=text.split(“,”)
months
STEP 2 Now let’s turn the string into a list, and split the STEP 4 We’ve previously seen how, using a name, we can
content accordingly: split a string into individual letters as a list:
names=text.split(“ “) name=list(“David”)
name
And enter the name of the new list, names, to see the three items.
The returned value is ‘D’, ‘a’, ‘v’, ‘i’, ‘d’. While it may seem a little
useless under ordinary circumstances, it could be handy for creating
a spelling game, for example.
STEP 5 The converse of the .split function is .join, where STEP 8 As with the .split function, the separator doesn’t
separate items in a string, can join together to form have to be a space, it can also be a comma, or a full
a word, or just a combination of items; depending on the program stop, or a hyphen, or whatever you like:
you’re writing. For instance:
colours=[“Red”, “Green”, “Blue”]
alphabet=””.join([“a”,”b”,”c”,”d”,”e”]) col=”,”.join(colours)
alphabet col
This will display ‘abcde’ in the Shell.
STEP 6 We can therefore apply .join to the separated name STEP 9 There’s some interesting functions you can apply to
we made in Step 4, combining the letters again to a string, such as .capitalize and .title. For example:
form the name:
title=”conan the cimmerian”
name=””.join(name) title.capitalize()
name title.title()
We’ve joined the string back together, and retained the list called
name, passing it through the .join function.
STEP 7 A good example of using the .join function is when STEP 10 You can also use logic operators on strings,
you have a list of words you want to combine into with the in and not in functions. These enable you
a sentence: to check if a string contains (or does not contain) a sequence
of characters:
list=[“Conan”, “raised”, “his”, “mighty”, “sword”,
“and”, “struck”, “the”, “demon”] message=”Have a nice day”
text=” “.join(list) “nice” in message
text
”bad” not in message
Note the space between the quotes before the .join function (where “day” not in message
there were no quotes in Step 6’s .join). “night” in message
Formatting Strings
As you work with data, creating lists, dictionaries, and objects you’ll often want to print
out the results. Merging strings with data is easy, especially with Python 3, as earlier
versions of Pythons tended to complicate matters
STRING FORMATTING
Since Python 3, string formatting has become a much neater process, using the .format function combined with curly brackets.
This makes things easier to follow and, as with most coding, there are other ways to do things but this way is recommended.
STEP 1 The basic formatting in Python is to call each STEP 3 We can, of course, also include integers into the mix:
variable into the string using the curly brackets:
number=10000
name=”Conan” print(“{} of {} was a skilled mercenary,
print(“The barbarian hero of the Hyborian Age is: and thief too. He once stole {} gold from a
{}”.format(name)) merchant.”.format(name, place, number))
STEP 2 Remember to close the print function with two sets STEP 4 There are many different ways to apply string
of brackets, as you’ve encased the variable in one, formatting, some are quite simple, as we’ve shown
and the print function in another. You can include multiple cases of you here, and others can be significantly more complex. It all
string formatting in a single print function: depends on what you want from your program. A good place to
reference frequently, regarding string formatting, is the Python
name=”Conan”
Docs webpage, found at https://docs.python.org/3.1/library/
place=”Cimmeria”
string.html. Here, you will find tons of help.
print(“{} hailed from the North, in a cold land
known as {}”.format(name, place))
STEP 5 Interestingly, you can reference a list using the STEP 8 You can print out the content of a user’s input in the
string formatting function. You need to place an same fashion:
asterisk in front of the list name:
name=input(“What’s your name? “)
numbers=1, 3, 45, 567546, 3425346345 print(“Hello {}.”.format(name)
print(“Some numbers: {}, {}, {}, {}, {}”.
format(*numbers))
STEP 6 As with indexing in lists, the same applies to calling a STEP 9 And you can extend this simple code example to
list using string formatting. We can index each item display the first letter in a person’s entered name:
according to its position (from 0 to however many are present):
name=input(“What’s your name? “)
numbers=1, 4, 7, 9 print(“Hello {}.”.format(name))
print(“More numbers: {3}, {0}, {2}, lname=list(name)
{1}.”.format(*numbers)) print(“The first letter of your name is a {0}”.
format(*lname))
STEP 7 And as you probably suspect, you can mix strings STEP 10 You can also call upon a pair of lists, and reference
and integers in a single list to be called in the them individually within the same print function.
.format function: Looking back at the code from Step 7, we can alter it with:
characters=[“Conan”, “Belit”, “Valeria”, 19, 27, names=[“Conan”, “Belit”, “Valeria”]
20] ages=[25, 21, 22]
print (“{0} is {3} years old. Whereas {1} is {4}
Creating two lists. Now we can call each list, and individual items:
years old.”.format(*characters))
print(“{0[0]} is {1[0]} years old. Whereas {0[1]}
is {1[1]} years old.”.format(names, ages))
TIME LORDS
The Time module contains functions that help you retrieve the current system time, read the date from strings, format the
time and date, and much more.
STEP 1 First you need to import the Time module. It’s one STEP 3 You can see the structure of how time is presented
that’s built-in to Python 3, so you shouldn’t need to by entering:
drop into a command prompt and pip install it. Once it’s imported,
time.local.time()
we can call the current time and date with a simple command:
The output is displayed as such: ‘time.struct_time(tm_
import time
year=2019, tm_mon=9, tm_mday=7, tm_hour=9,
time.asctime()
tm_min=6, tm_sec=13, tm_wday=3, tm_yday=250, tm_
isdst=0)’; obviously dependent on your current time, as opposed
to the time this book was written.
STEP 2 The time function is split into nine tuples, these are STEP 4 There are numerous functions built into the
divided up into indexed items, as with any other Time module. One of the most common of these
tuple, and shown in the screen shot below. is .strftime(). With it, you’re able to present a wide range of
arguments as it converts the time tuple into a string. For example,
to display the current day of the week we can use:
time.strftime(‘%A’)
STEP 5 Naturally, this means you can incorporate various STEP 8 We can also use the Time module to display the
functions into your own code, such as: amount of time taken for an event to happen. For
example, taking the above code, we can alter it slightly by including:
time.strftime(“%a”)
time.strftime(“%B”) start_time=time.time()
time.strftime(“%b”)
And.
time.strftime(“%H”)
time.strftime(“%H%M”) endtime=time.time()-start_time
STEP 6 Note the last two entries, with %H and %H%M, as STEP 9 The output will look similar to the screenshot below.
you can see, these are the hours and minutes and as The timer function needs to be either side of the
the last entry indicates, entering them as %H%M doesn’t display the input statement, as that’s when the variable name is being created –
time correctly in the Shell. We can easily rectify this with: depending on how long the user took to log in. The length of time is
then displayed on the last line of the code, as the endtime variable.
time.strftime(“%H:%M”)
STEP 7 This means you’re going to be able to display either STEP 10 There’s a lot that can be done with the Time
the current time, or the time when something module, some of it is quite complex too – such
occurred, such as a user entering their name. Try this code in the Editor: as displaying the number of seconds since January 1st 1970. If you
want to drill down further into the Time module, then in the Shell
import time
enter: help(time) to display the current Python version help file
name=input(“Enter login name: “)
for the Time module.
print(“Welcome”, name, “\d”)
print(“User:”, name, “logged in at”, time.
strftime(“%H:%M”))
Try to extend it further to include day, month, year, and so on.
Opening Files
In Python, you can read text and binary files in your programs. This enables you to
import data from one source to Python; handy if you have another program language
running, that’s creating an output, and you want to analyse the results in Python.
STEP 1 Start by entering some text into your system’s STEP 3 If you now enter poem into the Shell, you will get
text editor. The text editor is preferable to a word some information regarding the text file you’ve just
processor, as word processors include background formatting and asked to be opened. We can now use the poem variable to read the
other elements. In our example, we have the poem The Cimmerian, contents of the file:
by Robert E Howard, and we’ve saved the file as poem.txt.
poem.read()
Note than a /n entry in the text represents a new line, as we have
used previously.
STEP 2 You use the open() function to pass the file into a STEP 4 If you enter poem.read() a second time, you will
variable as an object. You can name the file object notice that the text has been removed from the
anything you like, but you will need to tell Python the name and file. You will need to enter poem=open(“C:\\Users\\david\\
location of the text file you’re opening: Documents\\poem.txt”) again to recreate the file. This time,
however, enter:
poem=open(“C:\\Users\\david\\Documents\\poem.txt”)
print(poem.read())
The reason for the double slash (\\) is because Python will read this
as a Unicode Error, thinking you’ve entered: \U. This is Windows-only, Now, the /n entries are removed in favour of new lines and
Linux and Mac won’t have this issue. readable text.
STEP 5 As with lists, tuples, dictionaries and so on, you’re STEP 8 Extending this further, you can use readlines() to
able to index individual characters of the text. grab all the lines of the text and store them as
For example: multiple lists. These can then be stored as a variable:
poem.read(5) poem=open(“C:\\Users\\david\\Documents\\poem.txt”)
lines=poem.readlines()
Displays the first five characters, while entering:
lines[0]
poem.read(5) lines[1]
lines[2]
Will display the next five. Entering (1) will display one character at
a time.
STEP 6 Similarly, you can display one line of text at a time by STEP 9 We can also use the for statement to read the lines
using the readline() function. For example: of text back to us:
poem=open(“C:\\Users\\david\\Documents\\poem.txt”) for lines in lines:
poem.readline() print(lines)
Will display the first line of the text. And: And, since this is Python, there are other ways to produce the
same output:
poem.readline()
poem=open(“C:\\Users\\david\\Documents\\poem.txt”)
Will display the next line of text.
for lines in poem:
print(lines)
STEP 7 As you may suspect, you can pass the readline() STEP 10 Let’s imagine that you wanted to print the text
function into a variable, allowing you to call it again, a character at a time, as would an old dot matrix
when needed: printer. We can use the Time module mixed with what we’ve looked
at here. Try this:
poem=open(“C:\\Users\\david\\Documents\\poem.txt”)
line=poem.readline() import time
line poem=open(“C:\\Users\\david\\Documents\\poem.txt”)
lines=poem.read()
for lines in lines:
print(lines, end=””)
time.sleep(.15)
The output is fun to view, and easily incorporated into your own code.
Writing to Files
Being able to read external files within Python is certainly handy, but writing to a file
can be even more useful. Using the write() function, you’re able to output the results
of a program to a file, which you can then use to read() back into Python, or as a text
file for perusal later.
STEP 1 Start by opening IDLE and enter the following STEP 3 However, the actual text file is still blank (you can
(obviously entering your own username location): check by opening it up). This is because you’ve
written the line of text to the file object, but not committed it to the
t=open(“C:\\Users\\david\\Documents\\text.txt”, “w”)
file itself. Part of the write() function is that we need to commit the
This code will create a text file, called text.txt in write mode, using changes to the file, we can do this by entering:
the variable ‘t’. If there’s no file of that name in the location, it will
t.close()
create one. If one already exits, it will overwrite it – so be careful.
STEP 2 We can now write to the text file using the write() STEP 4 If you now open the text file with a text editor, you’ll
function. This works opposite to read(), writing lines see that the line you created has been written to the
instead of reading them. Try this: file. This gives us the foundation for some interesting possibilities,
perhaps the creation of your own log file, or even the beginning of
t.write(“You awake in a small, square room. A
an adventure game.
single table stands to one side, there is a locked
door in front of you.”)
Note, the 109, it’s the number of characters you’ve entered.
STEP 5 To expand this code, we can re-open the file using STEP 8 We can pass variables to a file that we’ve created
‘a’, for access or append mode. This will add any text in Python. Perhaps we want the value of Pi to be
at the end of the original line, instead of wiping the file and creating written to a file. We can call Pi from the Math module, create a new
a new one. For example: file, and pass the output of Pi into the new file:
t=open(“/home/pi/Documents/text.txt”,”a”) import math
t.write(“\n”) print(“Value of Pi is: “,math.pi)
t.write(“ You stand and survey your surroundings. print(“\nWriting to a file now…”)
On top of the table is some meat, and a cup of
water.\n”)
STEP 6 We can keep extending the text line by line, STEP 9 Now let’s create a variable called pi, and assign it the
ending each with a new line (\n). When you’re value of Pi:
done, finish the code with t.close(), and open the file in a text
pi=math.pi
editor to see the results:
We also need to create a new file to write Pi to:
t.write(“The door is made of solid oak with iron
strips. It’s bolted from the outside, locking you t=open(“C:\\Users\\david\\Documents\\pi.txt”, “w”)
in. You are a prisoner!.\n”)
Remember to change your file location to your own particular
t.close()
system setup.
STEP 7 There are various types of file access to consider STEP 10 To finish, we can use string formatting to call the
using the open() function. Each depends on how the variable and write it to the file, then commit the
file is accessed, and even the position of the cursor. For example, r+ changes and close the file:
opens a file in read and write, and places the cursor at the start of
t.write(“Value of Pi is: {}”.format(pi))
the file.
t.close()
As you can see from the results, you’re able to pass any variable to
a file.
Exceptions
As your code begins to form and lengthen, you’ll naturally come across some exceptional
circumstances that are mostly out of your control. Let’s assume you ask a user to divide
two numbers, and they try to divide by zero. This will create an error, and break your code.
EXCEPTIONAL OBJECTS
Rather than stop the flow of your code, Python includes exception objects, which handle unexpected errors in the code. We
can combat errors by creating conditions where exceptions may occur.
STEP 1 You can create an exception error by simply trying STEP 3 We can use the functions raise exception to create
to divide a number by zero. This will report back our own error handling code within Python. Let’s
with the ZeroDivisionError: Division by zero message, as seen in assume your code has you warping around the cosmos, too much,
the screenshot. The ZeroDivisionError part is the exception class, of however, results in a warp core breach. To stop the game from
which there are many. exiting due to the warp core going supernova, we can create a
custom exception:
raise Exception(“warp core breach”)
STEP 2 Most exceptions STEP 4 To trap any errors in the code we can encase the
are raised potential error within a try: block. This block consists
automatically when Python of: try, except, else, where the code is held within try, then if there’s
comes across something that’s an exception do something, or do something else.
inherently wrong with the code.
However, we can create our own
exceptions that are designed to
contain the potential error and
react to it, as opposed to letting
the code fail.
STEP 5 For example, using the divide by zero error, we can STEP 8 Naturally, we can quickly fix the issue by changing
create an exception where the code can handle the the “r” read only instance with a “w” for write. This,
error without Python quitting due to the problem: as you already know, will create the file and write the content then
commit the changes to the file. The end result will report a different
try:
set of circumstances, in this case, a successful execution of the code.
a=int(input(“Enter the first number: “))
b=int(input(“Enter the second number: “))
print(a/b)
except ZeroDivisionError:
print(“You have tried to divide by zero!”)
else:
print(“You didn’t divide by zero. Well done!”)
Python Graphics
While dealing with text on the screen, either as a game or in a program, is perfectly fine,
there comes a time when a bit of graphical representation wouldn’t go amiss. Python 3
has numerous ways in which to include graphics, and they’re surprisingly powerful too.
GOING GRAPHICAL
You can draw simple graphics, lines, squares and so on, or you can use one of the many Python modules available to bring out
some spectacular effects.
STEP 1 One of the best graphical modules to begin learning STEP 3 The command turtle.circle(50) is what draws the
Python graphics is Turtle. The Turtle module is, as circle on the screen, with 50 being the size. You
the name suggests, based on the turtle robots used in many schools can play around with the sizes if you like, going up to 100, 150, and
that can be programmed to draw something on a large piece of beyond; you can draw an arc by entering turtle.circle(50,
paper on the floor. The Turtle module can be imported with: 180), where the size is 50, but you’re telling Python to only draw
import turtle. 180º of the circle.
STEP 2 Let’s begin by drawing a simple circle. Start a New STEP 4 The last part of the circle code tells Python to keep
File, then enter the following code: the window where the drawing is taking place to
remain open, so the user can click to close it. Now let’s make a square:
import turtle
import turtle
turtle.circle(50)
turtle.getscreen()._root.mainloop() print(“Drawing a square…”)
As usual press F5 to save the code and execute it. This will open up a for t in range(4):
new window and the ‘Turtle’ will draw a circle. turtle.forward(100)
turtle.left(90)
turtle.getscreen()._root.mainloop()
You’ll notice we’ve inserted a loop to draw the sides of the square.
STEP 5 To add some colour, we can add a new line to the STEP 8 Now let’s get the code by importing the pygame module:
square code:
import pygame
turtle.color(“Red”) pygame.init()
And we can even change the character to an actual turtle by entering: img = pygame.image.load(“RPi.png”)
turtle.shape(“turtle”) white = (255, 255, 255)
w = 900
We can also use the command turtle.begin_fill(), and turtle.end_
h = 450
fill() to fill in the square with the chosen colours; in this case, red
screen = pygame.display.
outline, and yellow fill.
set_mode((w, h))
screen.fill((white))
screen.fill((white))
screen.blit(img,(0,0))
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
STEP 6 As you can see, the Turtle module can draw out STEP 9 In the previous step we’ve imported pygame,
some pretty good shapes, and become a little more initiated the pygame engine, and asked it to import
complex, as you begin to master the way it works. Enter this example: our saved Raspberry Pi logo image, saved as RPi.png. Next, we
defined the background colour of the window to display the image,
from turtle import *
and the window size as per the actual image dimensions. Finally, we
color(‘red’, ‘yellow’)
have a loop to close the window.
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()
It’s a different method,
but very effective.
STEP 7 Another way you can display graphics is by using STEP 10 Press F5 to save and execute the code, and your
the Pygame module. There are numerous ways in image will be displayed in a new window. Have a
which pygame can help you output graphics to the screen, but for play around with the colours, sizes and so on, and take time to look
now let’s look at displaying a pre-defined image. Start by opening a up the many functions within the Pygame module too.
browser and finding an image, then save it to the folder where you
save your Python code.
Combining What
You Know So Far
Based on what we’ve looked at over this section, let’s combine it all and come up with a
piece of code that can easily be applied into a real-world situation; or at the very least,
something which you can incorporate into your programs.
LOGGING IN
For this example, let’s look to a piece of code that will create user logins then allow them to log into the system, and write the
time at which they logged in. We can even include an option to quit the program by pressing ‘q’.
STEP 1 Let’s begin by importing the Time module, creating STEP 3 The global status statement separates a local
a new dictionary to handle the usernames and variable from one that can be called throughout
passwords, and creating a variable to evaluate the current status of the code, this way we can use the q=quit element without it being
the program: changed inside the function. We’ve also referenced some newly
defined functions: oldUser and newUser which we’ll get to next.
import time
users = {}
status = “”
STEP 5 Since we’re using a Raspberry Pi, you will need to STEP 8 Finally, we need to continually check that the ‘q’ key
specify your own location for the logins.txt file. hasn’t been pressed to exit the program. We can do
Essentially, this adds the username and password inputs, from the this with:
user, to the existing users{} dictionary. Therefore, the key and value
while status != “q”:
structure remains; each user is the key, the password is the value.
status = displayMenu()
def oldUser():
login = input(“Enter login name: “)
passw = input(“Enter password: “)
# check if user exists and login matches
password
if login in users and users[login] == passw:
print (“\nLogin successful!\n”)
print (“User:”, login, “accessed the system
on:”, time.asctime())
else:
print (“\nUser doesn’t exist or wrong
password!\n”)
STEP 9 Although a seemingly minor two lines, the while
loop is what keeps the program running. At the end
of every function, it’s checked against the current value of status. If
that global value isn’t ‘q’ then the program continues. If it’s equal to
‘q’ then the program can quit.
STEP 10 You can now create users, and then login with
their names and passwords, with the logins.txt
file being created to store the login data and successful logins being
time-stamped. Now it’s up to you to further improve the code.
Perhaps you can import the list of created users from a previous
session and, upon a successful login, display a graphic?
Using
Modules
84 Calendar Module
86 OS Module
88 Random Module
90 Tkinter Module
92 Pygame Module
96 Create Your Own Modules
Calendar Module
Beyond the Time module, the Calendar module can produce some interesting results
when executed within your code. It does far more than simply display the date in the
time module-like format, you can actually call up a wall-calendar type display.
STEP 1 Launch Python 3 and enter: import calendar to STEP 3 There are numerous functions, within the Calendar
call up the module and its inherent functions. Once module, that may be of interest to you when
it’s loaded into memory, start by entering: forming your own code. For example, you can display the number of
leap years between two specific years:
sep=calendar.TextCalendar(calendar.SUNDAY)
sep.prmonth(2019, 9) leaps=calendar.leapdays(1900, 2019)
print(leaps)
The result is 29, starting from 1904 onward.
STEP 2 You can see that the days of September 2019 are STEP 4 You could even fashion that particular example into
displayed in a wall calendar fashion. Naturally you a piece of working, user interactive Python code:
can change the 2019, 9 part of the second line, to any year and
import calendar
month you want, a birthday for example (1973, 6). The first line
print(“>>>>>>>>>>Leap Year Calculator<<<<<<<<<<\n”)
configures TextCalendar to start its weeks on a Sunday; you can opt
y1=int(input(“Enter the first year: “))
for Monday if you prefer.
y2=int(input(“Enter the second year: “))
leaps=calendar.leapdays(y1, y2)
print(“Number of leap years between”, y1, “and”,
y2, “is:”, leaps)
STEP 5 You can also create a program that will display all STEP 8 You’re also able to print the individual months or
the days, weeks, and months within a given year: days of the week:
import calendar import calendar
year=int(input(“Enter the year to display: “) for name in calendar.month_name:
print(calendar.prcal(year)) print(name)
We’re sure you’ll agree that’s quite a handy bit of code to have import calendar
to hand. for name in calendar.day_name:
print(name)
STEP 6 Interestingly we can also list the number of days in a STEP 9 The Calendar module also allows us to write the
month by using a simple for loop: functions in HTML, so that you can display it on a
website. Let’s start by creating a new file:
import calendar
cal=calendar.TextCalendar(calendar.SUNDAY) import calendar
for i in cal.itermonthdays(2019, 6): cal=open(“C:\\Users\\david\\Documents\\cal.html”, “w”)
print(i) c=calendar.HTMLCalendar(calendar.SUNDAY)
cal.write(c.formatmonth(2019, 1))
cal.close()
This code will create an HTML file called cal, open it with a browser
and it displays the calendar for January 2019.
STEP 7 You can see that code produced some zeros at the STEP 10 Of course, you can modify that to display a given
beginning, this is due to the starting day of the year as a web page calendar:
week, Sunday in this case, and overlapping days from the previous
import calendar
month. So, the counting of the days will start on Saturday 1st June
2019 and will total 30 as the output correctly displays. year=int(input(“Enter the year to display as a
webpage: “))
cal=open(“C:\\Users\\david\\Documents\\cal.html”, “w”)
cal.write(calendar.HTMLCalendar(calendar.MONDAY).
formatyear(year))
cal.close()
This code asks the user for a year, then creates the necessary
webpage. Remember to change your file destination.
OS Module
The OS module allows you to interact directly with the built-in commands found in
your operating system. The commands can vary, depending on the OS on which you’re
running the module, as some will work with Windows whereas others will work with
Linux and macOS.
STEP 1 We can start the OS module with some simple STEP 3 The Windows output is different as that’s the
functions to see how it interacts with the operating current working directory of Python, as determined
system environment that Python is running on. If you’re using Linux, by the system. As you suspect, the os.getcwd() function is asking
or the Raspberry Pi, try this: Python to retrieve the Current Working Directory. Linux users will
see something along the same lines as the Raspberry Pi, as will
import os
macOS users.
home=os.getcwd()
print(home)
STEP 2 The returned result, from printing the variable STEP 4 Another interesting element to the OS module is its
home, is the current user’s home folder on the ability to launch programs that are installed in the
system. In Step 1 that’s /home/pi, it will be different depending on host system. For instance, if we wanted to launch the Chromium Web
the user name you login as, and the operating system you use. For Browser from within a Python program we can use the command:
example, Windows 10 would output: C:\Users\david\AppData\
import os
Local\Programs\Python\Python37-32.
browser=os.system(‘start chrome’)
STEP 5 The os.system() function is what allows interaction STEP 8 Being able to manipulate directories, or folders if
with external programs – you can even call up you prefer, is one of the OS module’s best features.
previous Python programs using this method. You will obviously For example, to create a new directory you can use:
need to know the full path and program file name for it to work
import os
successfully. However, you can also use the following:
os.mkdir(“C:\\BDM\\NEW”)
import os
This creates a new directory within the specified Directory (C:\BDM\),
os.system(‘‘start chrome “https://www.youtube.com/
named according to the object in the mkdir function (C:\BDM\NEW).
feed/music”’)
Random Module
The Random module is one you will likely come across many times in your Python
programming lifetime. As the name suggests, it’s designed to create a random set of
numbers from a given set. Although it’s not exactly random, there is a pattern behind
it, it will suffice for most needs.
RANDOM NUMBERS
There are numerous functions within the Random module, which, when applied, can create some interesting and very useful
Python programs.
STEP 1 As with other modules, you’ll need to import STEP 4 However, the Random module isn’t used exclusively
random before you can use any of the functions for numbers. We can use it to select a list entry from
we’re going to look at in this tutorial. Let’s begin by simply printing a random; and the list can contain anything:
random number from 1 to 5:
import random
import random random.choice([“Conan”, “Valeria”, “Belit”])
print(randomint(0,5))
This will display one of the names of our adventurers at random,
which is a great addition to a text adventure game.
STEP 6 Interestingly, we can also use a function within the STEP 9 Let’s use an example piece of code, which flips a
Random module to shuffle the items in the list, thus virtual coin ten thousand times and counts how
adding a little more randomness into the equation: many times it’ll land on Heads or Tails:
random.shuffle(lst) import random
print(lst) output={“Heads”:0, “Tails”:0}
coin=list(output.keys())
This way, you can keep shuffling the list before displaying a random
item from it. for i in range(10000):
output[random.choice(coin)]+=1
print(“Heads:”, output[“Heads”])
print(“Tails:”, output[“Tails”])
Tkinter Module
While running your code from the command line, or even in the Shell, is perfectly fine,
Python is capable of so much more. The Tkinter module enables the programmer to set
up a Graphical User Interface to interact with the user, and it’s surprisingly powerful too.
GETTING GUI
Tkinter is easy to use, but there’s a lot more you can do with it. Let’s start by seeing how it works, and then getting some code
into it.
STEP 1 Tkinter is usually built into Python 3, however if STEP 3 The ideal approach is to add mainloop() into the
it’s available when you enter: import tkinter, code to control the Tkinter event loop, but we’ll
then you’ll need to pip install tkinter from the command prompt. get to that soon. You’ve just created a Tkinter widget, and there are
We can start to import modules differently than before, to save on several more we can play around with:
typing, by importing all their contents:
btn=Button()
import tkinter as tk btn.pack()
from tkinter import * btn[“text”]=”Hello everyone!”
The first line focuses on the newly created window. Click back into
the Shell and continue the other lines.
STEP 2 Although it’s not recommended to import everything STEP 4 We can combine the above into a New File:
from a module using the asterisk, normally it won’t
import tkinter as tk
do any harm. Let’s begin by creating a basic GUI window, enter:
from tkinter import *
wind=Tk() btn=Button()
btn.pack()
This creates a small, basic window. At this point, there’s not much
btn[“text”]=”Hello everyone!”
else to do but click the X in the corner to close the window.
Then add some button interactions:
def click():
print(“You just clicked me!”)
btn[“command”]=click
STEP 5 Save and execute the code from Step 5, and a STEP 8 We can create radio buttons too. Try:
window will appear with ‘Hello everyone!’ inside.
from tkinter import *
If you click the Hello everyone! button, the Shell will output the
text ‘You just clicked me!’. It’s simple, but shows you what can be root = Tk()
achieved with a few lines of code.
v = IntVar()
Label(root, root.title(“Options”), text=”””Choose
a preferred language:”””,
justify = LEFT, padx = 20).pack()
Radiobutton(root,
text=”Python”,
padx = 20,
variable=v,
value=1).pack(anchor=W)
Radiobutton(root,
text=”C++”,
padx = 20,
variable=v,
STEP 6 We can also display both text and images within a value=2).pack(anchor=W)
Tkinter window. However, only GIF, PGM, or PPM
mainloop()
formats are supported. So find an image, and convert it before using
the code. Here’s an example using the Raspberry Pi logo:
STEP 9 And we can create check boxes, with buttons, and
from tkinter import *
output to the Shell:
root = Tk()
from tkinter import *
logo = PhotoImage(file=”C:\\Users\\david\\Downloads\\
root = Tk()
PiLogo.gif”)
w1 = Label(root, root.title(“Raspberry Pi”), def var_states():
image=logo).pack(side=”right”) print(“Warrior: %d,\nMage: %d” % (var1.get(),
content = “”” The Raspberry Pi Foundation is a var2.get()))
UK-based charity that works to put the power of
Label(root, root.title(“Adventure Game”),
computing and digital making into the hands of
text=”>>>>>>>>>>Your adventure role<<<<<<<<<<”).
people all over the world. We do this so that more
grid(row=0, sticky=N)
people are able to harness the power of computing
var1 = IntVar()
and digital technologies for work, to solve
Checkbutton(root, text=”Warrior”, variable=var1).
problems that matter to them, and to express
grid(row=1, sticky=W)
themselves creatively. “””
var2 = IntVar()
w2 = Label(root,
Checkbutton(root, text=”Mage”, variable=var2).
justify=LEFT,
grid(row=2, sticky=W)
padx = 10,
Button(root, text=’Quit’, command=root.destroy).
text=content).pack(side=”left”)
grid(row=3, sticky=W, pady=4)
root.mainloop()
Button(root, text=’Show’, command=var_states).
grid(row=3, sticky=E, pady=4)
STEP 7 The previous code is quite weighty, mostly due to
mainloop()
the content variable holding a part of Raspberry Pi’s
About page, from the company website. You can obviously change
the content, the root.title, and the image to suit your needs. STEP 10 The code from Step 9 introduced some new
geometry elements into Tkinter. Note the
sticky=N, E and W arguments? These describe the locations of the
check boxes and buttons (North, East, South and West). The row
argument places them on separate rows. Have a play around and
see what you get.
Pygame Module
We’ve had a brief look at the Pygame module already, but there’s a lot more to it that
needs to be explored. Pygame was developed to help Python programmers create
games, whether they’re graphical or not. You will, however, need to install Pygame
before you can use it.
PYGAMING
As stated, Pygame isn’t an inherent module to Python. Those using the Raspberry Pi will already have it installed. Everyone
else will need to use pip install pygame from the command prompt.
STEP 1 Naturally, we need to load up the Pygame modules STEP 3 Sadly, you can’t close the newly created Pygame
into memory before we’re able to utilise them. window without closing the Python IDLE Shell;
Once that’s done, Pygame requires the user to initialise it prior to which isn’t very practical. For this reason, we need to work in the
any of the functions being used: editor (New > File) and create a True/False while loop:
import pygame import pygame
pygame.init() from pygame.locals import *
pygame.init()
gamewindow=pygame.display.set_mode((800,600))
pygame.display.set_caption(“Adventure Game”)
running=True
while running:
for event in pygame.event.get():
if event.type==QUIT:
running=False
pygame.quit()
STEP 5 We’re going to shift the code around a bit now, img=pygame.image.load(“C:\\Users\david\\
running the main Pygame code within a while loop Downloads\\sprite.png”)
– it makes it neater and easier to follow. Also, we’ve downloaded a
def sprite(x,y):
graphic to use and we need to set some parameters for pygame:
gamewindow.blit(img, (x,y))
import pygame
x=(800*0.45)
pygame.init()
y=(600*0.8)
running=True
gamewindow.fill(white)
while running: sprite(x,y)
pygame.display.update()
gamewindow=pygame.display.set_mode((800,600))
pygame.display.set_caption(“Adventure Game”) for event in pygame.event.get():
black=(0,0,0) if event.type==pygame.QUIT:
white=(255,255,255) running=False
STEP 6 Let’s quickly go through the code changes. We’ve downloaded image called sprite.png, and allocated it to the variable
defined two colours, black and white, together img. We’ve also defined a sprite function, and the Blit function,
with their respective RGB colour values. Next, we’ve loaded the which will allow us to eventually move the image.
STEP 7 Now we can change the code around again, this imgspeed=0
time containing a movement option within the
while running:
while loop, and adding the variables needed to move the sprite
for event in pygame.event.get():
around the screen:
if event.type==QUIT:
import pygame running=False
from pygame.locals import *
if event.type == pygame.KEYDOWN:
pygame.init()
if event.key==pygame.K_LEFT:
running=True xchange=-5
elif event.key==pygame.K_RIGHT:
gamewindow=pygame.display.set_mode((800,600))
xchange=5
pygame.display.set_caption(“Adventure Game”)
if event.type==pygame.KEYUP:
black=(0,0,0)
if event.key==pygame.K_LEFT or event
white=(255,255,255)
key==pygame.K_RIGHT:
img=pygame.image.load(“C:\\Users\\david\\
xchange=0
Downloads\\sprite.png”)
x += xchange
def sprite(x,y):
gamewindow.blit(img, (x,y)) gamewindow.fill(white)
sprite(x,y)
x=(800*0.45)
pygame.display.update()
y=(600*0.8)
pygame.quit()
xchange=0
STEP 8 Copy the code down and, using the left and right arrow keys on the keyboard, you will be able to move your sprite across
the bottom of the screen. It looks like we have the makings of a classic arcade 2D scroller in the works.
BUILDING MODULES
Modules are Python files, containing code, that you save using a .py extension. These are then imported into Python using the
now familiar import command.
STEP 1 Let’s start by creating a set of basic Mathematics STEP 3 Now we’re going to take the function definitions
functions. Multiply a number by two or three, and out of the program and into a separate file.
square or raise a number to an exponent (power). Create a New File Highlight the function definitions and choose Edit > Cut. Choose
in the IDLE and enter: File > New File and use Edit > Paste in the new window. We now
have two separate files, one with the function definitions, and the
def timestwo(x):
other with the function calls.
return x * 2
def timesthree(x):
return x * 3
def square(x):
return x * x
def power(x,y):
return x ** y
STEP 2 Under the above code, enter functions to call STEP 4 If you now try and execute the basic_math.py code
the code: again, the error ‘NameError: name ‘timestwo’ is
not defined’ will be displayed. This is due to the code no longer
print (timestwo(2))
having access to the function definitions.
print (timesthree(3))
print (square(4))
print (power(5,3))
Save the program as basic_math.py and execute it to get the results.
STEP 5 Return to
the newly
created window containing
the function definitions, and
click File > Save As. Name this
minimath.py and save it in the
same location as the original
basic_math.py program. Now
close the minimath.py window,
so the basic_math.py window is
left open.
Your Unique Download ID Code:
0000 0919 MS26 BMD
96 www.bdmpublications.com
Create Your Own Modules
STEP 6 Back to the basic_math.py window, at the top of the STEP 9 Finally, we can now create a range of if statements
code enter: to determine what to do with the number, and
utilise the newly created function definitions:
from minimath import *
if choice == ‘1’:
This will import the function definitions as a module. Press F5 to
print(timestwo(num1))
save and execute the program, and see it in action.
elif choice == ‘2’:
print(timesthree(num1))
elif choice == ‘3’:
print(square(num1))
elif choice == ‘4’:
num2 = int(input(“Enter second number: “))
print(power(num1, num2))
else:
print(“Invalid input”)
STEP 8 Now we can add the user input to get the number
the code will work on:
num1 = int(input(“\nEnter number: “))
This will save the user-entered number as the variable num1.
STEP 10 Note that for the last available options, the Power
of choice, we’ve added a second variable: num2.
This passes a second number through the function definition called
power. Save and execute the program to see it in action.
Introducing
C++
Why C++?
C++ is one of the most popular programming languages available today. Originally
called C with Classes, the language was renamed to C++ in 1983. It’s an extension of
the original C language, and is a general purpose object-oriented (OOP) environment.
C EVERYTHING
Due to both the complexity of the language and its power and performance, C++ is often used to develop games, programs,
device drivers, and even entire operating systems.
Dating back to 1979, the start of the golden era of home using C++. For example, all of Adobe’s major applications, such as
computing, C++, or rather C with Classes, was the brainchild of Photoshop, InDesign and so on, are developed in C++. You will find
Danish computer scientist Bjarne Stroustrup, while working on his that the browser you use to surf the Internet is written in C++, as
Ph.D thesis. Stroustrup’s plan was to further the original C language, well as Windows 10, Microsoft Office, and the backbone to Google’s
which had been widely used since the early seventies. search engine. Apple’s macOS is written largely in C++ (with some
other languages mixed in depending on the function), and the likes
C++ proved to be popular among the developers of the 80s, since of NASA, SpaceX, and even CERN use C++ for various applications,
it was a much easier environment with which to get to grips, programs, controls, and umpteen other computing tasks.
and, more importantly, it was 99% compatible with the original C
language. This meant that, beyond the mainstream computing labs, As well as being an easier addition to the core C language, C++ is
regular people who didn’t have access to the mainframes and large also extremely efficient and performs well across the board. This
computing data centres could use it. higher level of performance over other languages, such as Python,
BASIC and such, makes it an ideal development environment for
C++’s impact in the digital world is immense. Many of the programs, modern computing; hence the aforementioned companies using it
applications, games, and even operating systems are coded so widely.
C++ 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, and just about 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 most of 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.
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++.
90
THE
C++ is
used in computer
networking as the
main code behind the
th
Programmable Logic Most of Adobe’s
PERCENTILE SALARY stable of products
Controller, connecting FOR A UK-BASED C++ are developed
servers, processors, other DEVELOPER IS using C++.
£120,000
hardware, and
even robotics.
MRI scanning
machines and
Windows 95, 89, 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.
RADAR
PROCESSING
TECHNOLOGIES
USE C++, AS
WELL AS
ADVANCED
MISSILE
DETECTION
SYSTEMS.
FLIGHT CONTROL SYSTEMS IN
MODERN AIRCRAFT, INCLUDING
MILITARY AIRCRAFT, USE C++.
Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 103
Introducing C++
Equipment You
Will Need
You don’t need to invest a huge amount of money in order to learn C++, and you
don’t need an entire computing lab at your disposal either. Providing you have a fairly
modern computer, everything else is freely available.
C++ SETUPS
As most, if not all, operating systems have C++ at their core, it stands to reason that you can learn to program in C++ no matter
what OS you’re currently using.
COMPUTER
Unless you fancy writing out your C++ code by hand on a sheet of paper (which is
something many older coders used to do), then a computer is an absolute must have
component. PC users can have any recent Linux distro or Windows OS, Mac users the
latest macOS.
AN IDE
As with Python, an IDE is used to enter and execute your C++ code. Many IDEs come
with extensions and plugins that help make it work better, or add an extra level of
functionality. Often, an IDE will provide enhancements depending on the core OS
being used, such as being enhanced for Windows 10.
COMPILER
A compiler is a program that will convert the C++ language into binary that the
computer can understand. While some IDEs come with a compiler built in, others
don’t. Code::Blocks is our favourite IDE that comes with a C++ compiler as part of the
package. More on this later.
TEXT EDITOR
Some programmers much prefer to use a text editor to assemble their C++ code
before running it through a compiler. Essentially you can any text editor to write
code, just save it with a .cpp extension. However, Notepad++ is one of the best code
text editors available.
INTERNET ACCESS
While it’s entirely possible to learn how to code on a computer that’s not attached
to the Internet, it’s extraordinarily difficult. You will need to install the relevant
software, keep it up to date, install any extras or extensions, and look for help when
coding. All of which require access to the Internet.
OS SPECIFIC NEEDS
C++ will work in any operating system, however, getting all the necessary pieces together can be confusing to a newcomer. Here’s
some OS specifics for C++.
LINUX WINDOWS
Linux users are lucky in that they already have a compiler and As we’ve mentioned previously, a good IDE is Microsoft’s
text editor built into their operating system. Any text editor Visual Studio. However, a better IDE and compiler is
will allow you type out your C++ code, when it’s saved with a Code::Blocks, which is regularly kept up to date with a new
.cpp extension, use g++ to compile it. release twice a year, or so. Otherwise Windows users can
enter their code in Notepad++ then compile it with MinGW –
which Code::Blocks uses.
RASPBERRY PI MAC
The Raspberry Pi’s operating Mac owners will need to
system is Raspbian, which download and install Xcode
is Linux based. Therefore, to be able to compile their
you’re able to write your code C++ code natively. Other
out using a text editor, then options for the macOS
compile it with g++ as you include Netbeans, Eclipse or
would in any other Linux distro. Code::Blocks. Note: the latest
Code::Blocks isn’t available for
Mac due to a lack of
Mac developers.
How to Set Up
C++ in Windows
Windows users have a wealth of choice when it comes to programming in C++. There
are loads of IDEs and compilers available, including Visual Studio from Microsoft.
However, in our opinion, the best C++ IDE to begin with is Code::Blocks.
CODE::BLOCKS
Code::Blocks is a free C++, C and Fortran IDE that is feature rich and easily extendible with plugins. It’s easy to use, comes with
a compiler and has a vibrant community behind it too.
STEP 1 Start by visiting the Code::Blocks download site, at STEP 3 When you’ve located the file, click on the
www.codeblocks.org/downloads. From there, click Sourceforge.net link at the end of the line and a
on the ‘Download the binary releases’ link to be taken to the latest download notification window appears; click on Save File to start
downloadable version for Windows. the download and save the executable to your PC. Locate the
downloaded Code::Blocks installer and double-click to start. Follow
the on-screen instructions to begin the installation.
STEP 2 There you can see, there are several Windows STEP 4 Once you agree to the licencing terms, a choice of
versions available. The one you want to download installation options becomes available. You can opt
has mingw-setup.exe at the end of the current version number. At for a smaller install, missing out on some of the components but we
the time of writing this is: codeblocks-17.12mingw-setup.exe. The recommend that you opt for the Full option, as default.
difference is that the mingw-setup version includes a C++ compiler
and debugger from TDM-GCC (a compiler suite).
STEP 5 Next choose an install location for the Code::Blocks STEP 8 There’s a lot you can do in Code::Blocks, so you need
files. It’s your choice but the default is generally to dig in and find a good C++ tutorial to help you
sufficient (unless you have any special requirements of course). get the most from it. However, to begin with, click on File > New >
When you click Next, the install begins; when it’s finished a Empty File. This creates a new, blank window for you to type in.
notification pops up asking you if you want start Code::Blocks now,
so click Yes.
STEP 6 The first time Code::Blocks loads it runs an STEP 9 In the new window, enter the following:
autodetect for any C++ compilers you may already
have installed on your system. If you don’t have any, click on the #include <iostream>
first detected option: GNU GCC Compiler and click the Default
Int main()
button to set it as the system’s C++ compiler. Click OK when you’re
{
ready to continue.
//My first C++ program
Std::cout << “Hello World!\n”;
}
Notice how Code::Blocks auto-inserts the braces and speech quotes.
STEP 7 The program starts and another message appears STEP 10 Click File > Save as and save the code with a
informing you that Code::Blocks is currently not .cpp extension (helloworld.cpp, for example).
the default application for C++ files. You have two options, to leave Code::Blocks changes the view to colour code according to C++
everything as it is or allow Code::Blocks to associate all C++ file standards. To execute the code, click on the Build and Run icon
types. Again, we would recommend you opt for the last choice, to along the top of the screen. It’s a green play icon together with a
associate Code::Blocks with every supported file type. yellow cog.
XCODE
Apple’s Xcode is primarily designed for users to develop apps for macOS, iOS, iPadOS, tvOS and watchOS applications in Swift
or Objective-C, but you can use it for C++ too.
STEP 1 Start by opening the App Store on your Mac, Apple STEP 3 When you’re ready, click on the Get button which
Menu > App Store. In the Search box enter Xcode and then turns into ‘Install App’. Enter your Apple ID
press Return. There will be many suggestions filling the App Store and Xcode begins to download and install. It may take some time
window but it’s the first option, Xcode, that you need to click on. depending on the speed of your Internet connection.
STEP 2 Take a moment to browse through the app’s STEP 4 When the installation is complete, click on the Open
information, including the compatibility to ensure button to launch Xcode. Click Agree to the licence
you have the correct version of macOS. Xcode requires macOS terms and enter your password to allow Xcode to make changes
10.12.6 or later to install and work. to the system. When you’ve done that, Xcode begins to install
additional components.
STEP 5 With everything now installed, including the STEP 8 The next step asks where to create a Git Repository
additional components, Xcode launches, displaying for all your future code. Choose a location on your
the version number along with three choices and any recent projects Mac, or a network location, and click the Create button. When
that you’ve worked on; although for a fresh install, this shows blank. you’ve done all that, you can start to code. The left-hand pane
details the files used in the C++ program you’re coding. Click on the
main.cpp file in the list.
STEP 6 Start by clicking on Create New Xcode Project; this STEP 9 You can see that Xcode has automatically
opens a template window from which to choose the completed a basic Hello World program for you.
platform you’re developing code for. Click the macOS tab, then the The differences here are that the int main () function now contains
Command Line Tool option and finally, Next to continue. multiple functions and the layout is slightly different. This is just
Xcode utilising the content that’s available to your Mac.
STEP 7 Fill in the various fields but ensure that the STEP 10 When you want to run the code, click on Product >
Language option at the bottom is set to C++. Simply Run. You may be asked to enable Developer Mode
choose it from the drop-down list. When you’ve filled in the fields, on the Mac; this is to authorise Xcode to perform functions without
and made sure that C++ is the chosen language, click on the Next needing your password every session. When the program executes,
button to continue. the output is displayed at the bottom of the Xcode window.
LINUX++
For this example, we’re using a fresh installation of Linux Mint. However, these also work if you’re using Ubuntu or any other
Debian-based Linux OS.
STEP 1 The first step with ensuring Linux is ready for your STEP 3 Amazingly, that’s it. Everything is all ready for you
C++ code is check the system and software are to start coding. Here’s how to get your first C++
up to date. Open a Terminal and enter: sudo apt-get update program up and running. In Linux Mint the main text editor is Xed
&& sudo apt-get upgrade. Press Return and enter your can be launched by clicking on the Menu and typing Xed into the
password. These commands updates the entire system and any search bar. Click on the Text Editor button in the right-hand pane to
installed software. open Xed.
STEP 2 Most Linux distros come preinstalled with all the STEP 4 In Xed, or any other text editor you may be using,
necessary components to start coding in C++. enter the lines of code that make up your C++ Hello
However, it’s always worth checking to see if everything is present, World program. To remind you, its:
so still within the Terminal, enter: sudo apt-get install
#include <iostream>
build-essential and press Return. If you have the right
components, nothing is installed but if you’re missing some then int main()
they are installed by the command.
{
//My first C++ program
std::cout << “Hello World!\n”;
STEP 5 When you’ve entered your code, click File > Save As STEP 8 Before you can execute the C++ file you need to
and choose a folder where you want to save your compile it. In Linux it’s common to use g++, an open
program. Name the file as helloworld.cpp, or any other name just as source C++ compiler and as you’re now in the same folder as the
long as it has .cpp as the extension. Click Save to continue. C++ file, go to the Terminal, enter: g++ helloworld.cpp and
press return.
STEP 6 The first thing you can see is that Xed has STEP 9 There will be a brief pause as the code is compiled
automatically recognised this as a C++ file, since the by g++ and providing there are no mistakes or
file extension is now set to .cpp. The colour coding is present in the errors in the code you are returned to the command prompt. The
code and if you open up the file manager you can also see that the compiling of the code has created a new file. If you enter ls into the
file’s icon has C++ stamped on it. Terminal you can see that alongside your C++ file is a.out.
STEP 7 With your code now saved, drop into the Terminal STEP 10 The a.out file is the compiled C++ code. To run the
again. You need to navigate to the location of code enter: ./a.out and press Return. The words
the C++ file you’ve just saved. Our example is in the Documents ‘Hello World!’ appears on the screen. However, a.out isn’t very friendly.
folder, so we can navigate to it by entering: cd Documents. To name it something else post-compiling, you can recompile with:
Remember, the Linux Terminal is case sensitive, so any capitals must g++ helloworld.cpp -o helloworld. This creates an output
be entered correctly. file called helloworld which can be run with: ./helloworld.
DEVELOPING C++
Here are ten great C++ IDEs that are worth looking into. You can install one or all of them if you like, but find the one that
works best for you.
ECLIPSE Eclipse is a hugely popular C++ IDE that offers CODELITE CodeLite is a free and open source IDE that’s
the programmer a wealth of features. It has a regularly updated and available for Windows,
great, clean interface, is easy to use and available for Windows, Linux and macOS. It’s lightweight, uncomplicated and extremely
Linux and Mac. Head over to www.eclipse.org/downloads/ to powerful. You can find out more information as well as how to
download the latest version. If you’re stuck, click the Need Help link download and install it at www.codelite.org/.
for more information.
GNAT The GNAT Programming Studio (GPS) is a powerful NETBEANS Another popular choice is NetBeans. This
and intuitive IDE that supports testing, debugging is another excellent IDE that’s packed with
and code analysis. The Community Edition is free, whereas the features and a pleasure to use. NetBeans IDE includes project based
Pro version costs; however, the Community Edition is available for templates for C++ that give you the ability to build applications with
Windows, Mac, Linux and even the Raspberry Pi. You can find it at dynamic and static libraries. Find out more at www.netbeans.org/
www.adacore.com/download. features/cpp/index.html.
VISUAL STUDIO Microsoft’s Visual Studio is a ANJUTA The Anjuta DevStudio is a Linux-only IDE that
mammoth C++ IDE that allows you features some of the more advanced features you
to create applications for Windows, Android, iOS and the web. The would normally find in a paid software development studio. There’s
Community version is free to download and install but the other a GUI designer, source editor, app wizard, interactive debugger and
versions allow a free trial period. Go to www.visualstudio.com/ to much more. Go to www.anjuta.org/ for more information.
see what it can do for you.
QT CREATOR This cross-platform IDE is designed to MONODEVELOP This excellent IDE allows developers
create C++ applications for desktop and to write C++ code for desktop and
mobile environments. It comes with a code editor and integrated web applications across all the major platforms. There’s an advanced
tools for testing and debugging, as well as deploying to your chosen text editor, integrated debugger and a configurable workbench to
platform. It’s not free but there is a trial period on offer before help you create your code. It’s available for Windows, Mac and Linux
requiring purchasing: www.qt.io/qt-features-libraries-apis-tools- and is free to download and use: www.monodevelop.com/.
and-ide/.
DEV C++ Bloodshed Dev C++, despite its colourful name, U++ Ultimate++ is a cross-platform C++ IDE that boasts a
is an older IDE that is for Windows systems only. rapid development of code through the smart and
However, many users praise its clean interface and uncomplicated aggressive use of C++. For the novice, it’s a beast of an IDE but behind
way of coding and compiling. Although there’s not been much its complexity is a beauty that would make a developer’s knees go
updating for some time, it’s certainly one to consider if you want wobbly. Find out more at www.ultimatepp.org/index.html.
something different: www.bloodshed.net/devcpp.html.
C++
Foundations
HELLO, WORLD!
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.
STEP 1 As mentioned, we’re using Windows 10 and the STEP 3 At the moment it doesn’t look like much, and
latest version of Code::Blocks for the rest of the C++ it makes even less sense, but we’ll get to that
code in this book. Begin by launching Code::Blocks. When open, click in due course. Now click on File > Save File As. Create or find a
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.
STEP 2 Now you can see a blank screen, with the tab STEP 4 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.
#include <iostream>
STEP 5 Auto-selection of commands is extremely handy and STEP 8 Note again the colour coding change. Press Return at
cuts out potential mistyping. Press Return to get to the end of the previous step’s line, and then enter:
line 3, then enter:
std::cout << “Hello, world!\n”;
int main()
Note: there’s no space between the brackets.
STEP 6 On the next line below int main(), enter a curly bracket: STEP 9 Just as before, Code::Blocks auto-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.
STEP 7 Notice that Code::Blocks has automatically created STEP 10 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
Structure of a
C++ Program
C++ has a very defined structure and way of doing things. Miss something out, even
as small as a semicolon, and your entire program will fail to be compiled and executed.
Many a professional programmer has fallen foul of sloppy structure.
C++ #INCLUDE
The structure of a C++ program
C++ was invented by Danish is quite precise. Every C++ code
student Bjarne Stroustrup in begins with a directive: #include
1979, as a part of his Ph.D. <>. The directive instructs the
thesis. Initially C++ was called C pre-processor to include a
with Classes, which added section of the standard C++
features to the already popular code. For example: #include
C programming language, <iostream> includes the
while making it a more iostream header to support
user-friendly environment input/output operations.
through a new structure.
BRACES
The open brace (curly brackets) is something
that you may not have come across before,
especially if you’re used to Python. The
open brace indicates the beginning of the
main function and contains all the code that
belongs to that function. Your Unique Download ID Code:
0000 0919 MS26 BMD
118 www.bdmpublications.com
Structure of a C++ Program
COMMENTS <<
Lines that begin with a double slash are comments. This means they The two chevrons used here are insertion operators. This means
won’t be executed in the code and are ignored by the compiler. that whatever follows the chevrons is to be inserted into the
Comments are designed to help you, or another programmer std::cout statement. In this case they’re the words ‘Hello, world’,
looking at your code, explain what’s going on. There are two types which are to be displayed on the screen when you compile and
of comment: /* covers multiple line comments, // a single line. Lines execute the code.
that begin with a double slash are comments. This means they won’t
be executed in the code and
are ignored by the compiler.
Comments are designed
to help you, or another
programmer looking at
your code, explain what’s
going on. There are two
types of comment: /* covers
multiple line comments, // a
single line.
STD OUTPUTS
While std stands for something quite different, in C++ it means Leading on, the “Hello, world!” part is what we want to appear on
Standard. It’s part of the Standard Namespace in C++, which covers the screen when the code is executed. You can enter whatever you
a number of different statements and commands. You can leave the like, as long as it’s inside the quotation marks. The brackets aren’t
std:: part out of the code but it must be declared at the start with: needed but some compilers insist on them. The \n part indicates a
using namespace std; not both. For example: new line is to be inserted.
#include <iostream>
using namespace std;
COUT ; AND }
In this example we’re using cout, which is a part of the Standard Finally you can see that lines within a function code block (except
Namespace, hence why it’s there, as you’re asking C++ to use it from comments) end with a semicolon. This marks the end of the
that particular namespace. Cout means Character OUTput, which statement and all statements in C++ must have one at the end or
displays, or prints, something to the screen. If we leave std:: out we the compiler fails to build the code. The very last line has the closing
have to declare it at the start of the code, as mentioned previously. brace to indicate the end of the main function.
STEP 1 Open Code::Blocks, if you haven’t already, and STEP 3 Start by clicking on the Build icon, the yellow cog.
load up the previously saved Hello World code you At this point, your code has now been run through
created. Ensure that there are no visible errors, such as missing the Code::Blocks compiler and checked for any errors. You can see
semicolons at the end of the std::cout line. the results of the Build by looking to the bottom window pane. Any
messages regarding the quality of the code are displayed here.
STEP 2 If your code is looking similar to the one in our STEP 4 Now click on the Run icon, the green play button.
screenshot, then look to the menu bar along the top A command line box appears on your screen
of the screen. Under the Fortran entry in the topmost menu you can displaying the words: Hello, world!, followed by the time it’s taken
see a group of icons: a yellow cog, green play button and a cog/play to execute the code, and asking you press a key to continue. Well
button together. These are Build, Run, Build and Run functions. done, you just compiled and executed your first C++ program.
STEP 5 Pressing any key in the command line box closes it, STEP 8 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;
Then, delete the std:: part of the Cout line; like so:
cout << “Hello, world\n”;
STEP 6 In order to apply the new changes to the code, you STEP 9 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.
STEP 7 Just as we mentioned in the previous pages, you STEP 10 Replace the semicolon and under the cout line,
don’t need to have std::cout if you already declare enter a new line to your code:
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.
Using Comments
While comments may seem like a minor element to the many lines of code that
combine to make a game, application or even an entire operating system, in actual fact
they’re probably one of the most important factors.
C++ COMMENTS
Commenting in C++ involves using a double forward slash ‘/’, or a forward slash and an asterisk, ‘/*’. You’ve already seen some
brief examples but this is how they work.
STEP 1 Using the Hello World code as an example, you can STEP 4 Be careful when commenting, especially with block
easily comment on different sections of the code comments. It’s very easy to forget to add the closing
using the double forward slash: asterisk and forward slash and thus negate any code that falls inside
the comment block.
//My first C++ program
cout << “Hello, world!\n”;
STEP 2 However, you can also add comments to the end STEP 5 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.
STEP 3 You can comment out several lines by using the STEP 6 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
Just remember to finish the block comment with the opposite
* without the need to add more slashes */
asterisk and forward slash.
Variables
Variables differ slightly when 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.
STEP 1 Open up a new, blank C++ file and enter the usual STEP 3 You can build and run the code but it won’t do
code headers: much, other than store the values 10 and 5 to the
integers a and b. To output the contents of the variables, add:
#include <iostream>
using namespace std; cout << a;
cout << ”\n”;
int main()
cout << b;
{
The cout << “\n”; part
}
simply places a new line
between the output of
10 and 5.
STEP 2 Start simple by creating two variables, a and b, with STEP 4 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;
cout << result;
int b;
Insert the above into the code as per the screenshot.
a = 10;
b = 5;
STEP 5 You can assign a value to a variable as soon as you STEP 8 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;
STEP 6 Specific to C++, you can also use the following int main()
to assign values to a variable as soon as you
{
declare them:
double area, radius = 1.5;
int a (10);
area = pi * radius * radius;
int b (5);
cout << area;
Then, from the C++ 2011 standard, using curly brackets:
}
int result {a+b};
Data Types
Variables, as we’ve seen, store information that the programmer can then later call up,
and manipulate if required. Variables are simply reserved memory locations that store
the values the programmer assigns, depending on the data type used.
Boolean bool
No Value void
These basic types can also be extended using the following modifiers:
Long, Short, Signed and Unsigned. Basically this means the modifiers
can expand the minimum and maximum range values for each data
type. For example, the int data type has a default value range of
-2147483648 to 2147483647, a fair value, you would agree.
Now, if you were to use one of the modifiers, the range alters:
Unsigned int = 0 to 4294967295
Signed int = -2147483648 to 2147483647
Short int = -32768 to 32767
Unsigned Short int = 0 to 65,535 Build and run the code and as you can see the output is only
Signed Short int = -32768 to 32767 3.14159, representing cout’s limitations in this example.
Long int = -2147483647 to 2147483647
You can alter the code including the aforementioned cout.precision
Signed Long int = -2147483647 to 2147483647
function, for greater accuracy. Take precision all the way up to 22
Unsigned Long int = 0 to 4294967295
decimal places, with the following code:
Naturally you can get away with using the basic type without the
#include <iostream>
modifier, as there’s plenty of range provided with each data type.
using namespace std;
However, it’s considered good C++ programming practise to use the
double PI = 3.141592653589793238463;
modifiers when possible.
int main()
There are issues when using the modifiers though. Double
{
represents a double-floating point value, which you can use for Your Unique Download ID Code:
0000 0919 MS26 BMD
126 www.bdmpublications.com
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
of data, of which 52-bits are 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. If you divide 53 by 3.5, then you
arrive at 15.142857 recurring, which is 15-digits of precision.
To be honest, if you’re creating code that needs to be accurate to
more than fifteen decimal places, then you wouldn’t be using C++,
you would use some scientific specific language with C++ as the
connective tissue between the two languages.
You can create your own data types, using an alias-like system called
typedef. For example:
Again, build and run the code; as you can see from the command
line window, the number represented by the variable PI is different
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.
#include <iostream>
using namespace std;
typedef int metres;
int main()
{
metres distance;
distance = 15;
cout << “distance in metres is: “ << distance;
}
This code when executed creates a new int data type called metres.
Then, in the main code block, there’s a new variable called distance,
which is an integer; so you’re basically telling the compiler that
there’s another name for int. We assigned the value 15 to distance
and displayed the output: distance in metres is 15.
It might sound a little confusing to begin with but the more you use
C++ and create your own code, the easier it becomes.
Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 127
C++ Foundations
Strings
Strings are objects that represent and hold sequences of characters. For example, you
could have a universal greeting in your code ‘Welcome’ and assign that as a string to be
called up wherever you like in the program.
STRING THEORY
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++.
STEP 1 To create a string you use the char function. Open a STEP 3 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”;
}
STEP 2 It’s easy to confuse a string with an array. Here’s an STEP 4 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’, ‘l’, ‘c’, ‘o’, ‘m’, {
‘e’, ‘\0’}; string greet = “Welcome”;
cout << greet << “\n”; cout << greet << “\n”;
} }
STEP 5 There are also many different operations that you STEP 8 Just as you might expect, you can mix in an integer
can apply with the string function. For instance, to and store something to do with the string. In this
get the length of a string you can use: example, we created int length, which stores the result of string.
size() and outputs it to the user:
#include <iostream>
using namespace std; #include <iostream>
using namespace std;
int main ()
int main ()
{
string greet = “Welcome”; {
cout << “The length of the string is: “; int length;
cout << greet.size() << “\n”; string greet1 = “Hello”;
string greet2 = “, world!”;
}
string greet3 = greet1 + greet2;
length = greet3.size();
cout << “The length of the combined strings
is: “ << length << “\n”;
}
C++ Maths
Programming is mathematical in nature and as you might expect, there’s plenty of
built-in scope for some quite intense maths. C++ has a lot to offer someone who’s
implementing mathematical models 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.
STEP 1 C++’s mathematical operations follow the STEP 3 Multiplication and division can be applied as such:
same patterns as those taught in school, in that
#include <iostream>
multiplication and division take precedence over addition and
using namespace std;
subtraction. You can alter that though. For now, create a new file
and enter: int main ()
{
#include <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”;
}
STEP 5 The interesting maths content comes when you call STEP 8 Calculating powers of numbers can be done with:
upon the C++ Math Library. Within this header are
dozens of mathematical functions along with further operations. #include <iostream>
Everything from computing cosine to arc tangent with two #include <cmath>
parameters, to the value of PI. You can call the header with: 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 << “ to the power of 3 is “ <<
}
pow(number, 3) << “\n”;
cout << number << “ to the power of .08 is “
<< pow(number, 0.8) << “\n”;
}
STEP 6 Start by getting the square root of a number: STEP 9 Here we created a float called number with the
value of 12, and the pow(variable, power) is where
the calculation happens. Of course, you can calculate powers and
#include <iostream>
square roots without using variables. For example, pow (12, 2)
#include <cmath>
outputs the same value as the first cout line in the code.
using namespace std;
int main ()
{
float number = 134;
cout << “The square root of “ << number << “
is: “ << sqrt(number) << “\n”;
}
C++ Input/
Output
User Interaction
There’s nothing quite as satisfying as creating a program that responds to you. This
basic user interaction is one of the most taught aspects of any language and with it
you’re able to do much more than simply greet the user by name.
HELLO, DAVE
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.
STEP 1 Anything that you want the user to input into the STEP 3 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.
STEP 5 The principal works the same as the previous code. STEP 8 While cin works well for most input tasks, it does
The user’s input, their name, is stored in a string, have a limitation. Cin always considers spaces as a
because it contains multiple characters, and retrieved in the second terminator, so it’s designed for just single words not multiple words.
cout line. As long as the variable ‘name’ doesn’t change, then you However, getline takes cin as the first argument and the variable as
can recall it wherever you like in your code. the second:
#include <iostream>
using namespace std;
int main ()
{
string mystr;
cout << “Enter a sentence: \n”;
STEP 6 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> }
using namespace std;
int main ()
{
int num1, num2;
cout << “Enter two whole numbers: “;
cin >> num1 >> num2;
cout << “you entered “ << num1 << “ and “ <<
num2 << “\n”; STEP 9 Build and execute the code, then enter a sentence
with spaces. When you’re done the code reads the
}
number of characters. If you remove the getline line and replace it
with cin >> mystr and try again, the result displays the number of
characters up to the first space.
Character Literals
In C++ a literal is an object or variable that once defined remains the same throughout
the code. However, a character literal is defined by a backslash, such as the \n you’ve
been using at the end of a cout statement to signify a new line.
ESCAPE SEQUENCE
When used in something like a cout statement, character literals are also called escape sequence codes. They allow you to
insert a quote, an alert, new line and much more.
STEP 1 Create a new C++ file and enter the relevant headers: STEP 3 If you wanted to insert speech quotes inside a cout
statement, you would have to use a backslash as it
#include <iostream> already uses quotes:
using namespace std;
#include <iostream>
int main () using namespace std;
{
int main ()
{
} cout << “Hello, user. This is how to use
\”quotes\”.”;
}
STEP 2 You’ve already experienced the \n character literal STEP 4 There’s even a character literal that can trigger an
placing a new line wherever it’s called. The line: cout alarm. In Windows 10, it’s the notification sound
<< “Hello\n” << “I’m a C++\n” << “Program\n”; outputs three lines that chimes when you use \a. Try this code, and turn up your sound.
of text, each starting after the last \n.
#include <iostream>
using namespace std;
int main ()
{
cout << “ALARM! \a”;
}
A HANDY CHART
There are numerous character literals, or escape sequence codes, to choose from. We therefore thought it would be good for
you to have a handy chart available, for those times when you need to insert a code.
\’ Single Quote
\? Question Mark
\a Alert/Alarm
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab
\0 Null Character
UNICODE
CHARACTER TABLE
A complete list of the available Unicode
characters can be found at www.unicode-
table.com/en/. Hover your mouse over the
character to see the unique code to enter in
C++. While it may be a little overwhelming
to look at to begin with, bookmark the page
as you will probably need to come back to
it for reference as you dig deeper into C++,
and indeed character literals. One more
thing, the table will also display characters
from different languages, such as Tibetan
or Sudanese. This means your code can be
truly universal. Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 137
C++ Input/Output
Defining Constants
Constants are fixed values in your code. They can be any basic data type but as the
name suggests their value remains constant throughout the entire code. There are two
separate ways to define a constant in C++, the #define pre-processor and const.
#DEFINE
The pre-processors are instructions to the compiler to pre-process the information before it goes ahead and compiles the
code. #include is a pre-processor as is #define.
STEP 1 You can use the #define pre-processor to define any STEP 3 Note the capitals for defined constants, it’s
constants you want in our code. Start by creating a considered good programming practise to define all
new C++ file complete with the usual headers: constants in capitals. Here, the assigned values are 50, 40 and 60, so
let’s call them up:
#include <iostream>
using namespace std; #include <iostream>
using namespace std;
int main ()
#define LENGTH 50
{
#define WIDTH 40
} #define HEIGHT 60
int main ()
{
cout << “Length is: “ << LENGTH << “\n”;
cout << “Width is: “ << WIDTH << “\n”;
cout << “Height is: “ << HEIGHT << “\n”;
}
STEP 5 You can also define other elements as a constant. STEP 8 Another method of defining a constant is with the
For example, instead of using \n for a newline in the const keyword. Use const together with a data type,
cout statement, you can define it at the start of the code: variable and value: const type variable = value. Using Pi as an example:
#include <iostream> #include <iostream>
using namespace std; using namespace std;
#define LENGTH 50 int main ()
#define WIDTH 40
{
#define HEIGHT 60
const double PI = 3.14159;
#define NEWLINE ‘\n’
cout << “The value of Pi is: “ << PI << endl;
int main () }
{
cout << “Length is: “ << LENGTH << NEWLINE;
cout << “Width is: “ << WIDTH << NEWLINE;
cout << “Height is: “ << HEIGHT << NEWLINE;
}
File Input/Output
The standard iostream library provides C++ coders with the cin and cout input and
output functionality. However, to be able to read and write from a file you need to
utilise another C++ library, called fstream.
FSTREAMS
There are two main data types within the fstream library that are used to open a file, read from it and write to it; these are
ofstream and ifstream. Here’s how they work.
STEP 1 The first task is to create a new C++ file and along STEP 3 We’ve included comments in the screenshot of step
with the usual headers you need to include the new 2 to help you understand the process. You created
fstream header: a string called name, to store the user’s inputted name. You also
created a text file called name.txt (with the ofstream newfile and
#include <iostream>
newfile.open lines), asked the user for their name and stored it and
#include <fstream>
then written the data to the file.
Using namespace std;
int main ()
{
STEP 2 Begin by asking a user for their name and writing string line;
that information to a file. You need the usual string ifstream newfile (“name.txt”);
to store the name, and getline to accept the input from the user.
cout << “Contents of the file: “ << endl;
#include <iostream>
getline(newfile, line);
#include <fstream>
cout << line << endl;
using namespace std;
newfile.close();
int main ()
{
string name;
ofstream newfile;
newfile.open(“name.txt”);
cout << “Enter your name: “ << endl;
getline(cin, name);
newfile << name << endl;
newfile.close();
} Your Unique Download ID Code:
0000 0919 MS26 BMD
140 www.bdmpublications.com
File Input/Output
STEP 5 The code above is great for opening a file with one STEP 8 Just as you might expect, you can write almost
or two lines but what if there are multiple lines? Here anything you like to a file, for reading either in
we opened a text file of the poem Cimmeria, by Robert E Howard: Notepad or via the console through the C++ code:
string line; string name;
ifstream newfile (“c:\\users\\david\\ int age;
Documents\\Cimmeria.txt”);
ofstream newfile;
cout << “Cimmeria, by Robert E Howard: \n” << newfile.open(“name.txt”);
endl;
cout << “Enter your name: “ << endl;
while (getline(newfile, line)) getline(cin, name);
cout << line << endl;
newfile << name << endl;
newfile.close();
cout << “\nHow old are you: “ << endl;
cin >> age;
newfile << age << endl;
newfile.close();
STEP 7 You can also see that the location of the text file STEP 10 Here’s an exercise: see if you can create code to
Cimmeria.txt isn’t in the same folder as the C++ write several different elements to a text file. You
program. When we created the first name.txt file, it was written to can have a user’s name, age, phone number etc. Maybe even the
the same folder where the code was located; this is done by default. value of Pi and various mathematical elements. It’s all good practice.
To specify another folder, you need to use double-back slashes, as
per the character literals/escape sequence code.
Loops and
Decision Making
Your Unique Download ID Code:
0000 0919 MS26 BMD
142 www.bdmpublications.com
Loops and Decision Making
While Loop
A while loop’s function is to repeat a statement, or a group of statements, while a certain
condition remains true. When the while loop starts, it initialises itself by testing the
condition of the loop and the statements within, before executing the rest of the loop.
TRUE OR FALSE?
While loops are one of the most popular form of C++ code looping. They repeatedly run the code contained within the loop
while the condition is true. Once it proves false, the code continues as normal.
STEP 1 Clear what you’ve done so far and create a new C++ STEP 3 First you
file. There’s no need for any extra headers at the need to
moment, so add the standard headers as per usual: create a condition, so use a
variable called num and give
#include <iostream>
it the value 1. Now create
using namespace std;
the while loop, stating that
int main () as long as num is less than
30, the loop is true. Within
{
the loop the value of num
} is displayed and adds 1 until
it’s more than 30.
STEP 6 It’s important to remember not to add a semicolon STEP 9 You can further expand the code to enable each
at the end of a while statement. Why? Well, as you word of the poem to appear every second. To do
know, the semicolon represents the end of a C++ line of code. If so, you need to pull in a new library, <windows.h>. This is a Windows
you place one at the end of a while statement, your loop will be only library and within it you can use the Sleep() function:
permanently stuck until you close the program.
#include <iostream>
#include <fstream>
#include <windows.h>
using namespace std;
int main ()
{
string word;
ifstream newfile (“C:\\users\\david\\
Documents\\Cimmeria.txt”);
cout << “Cimmeria, by Robert E Howard: \n” <<
endl;
while (newfile >> word)
STEP 7 In our example, if we were to execute the code {
the value of num would be 1, as set by the int cout << word << endl;
statement. When the code hits the while statement it reads Sleep(1000);
that while the condition of 1 being less than 30 is true, loop. The }
semicolon closes the line, so the loop repeats; but it never adds 1 to
return 0;
num, as it won’t continue through the compound statement.
}
STEP 8 You can manipulate the while statement to display STEP 10 Sleep() works in milliseconds, so Sleep(1000) is
different results depending on what code lies within one second, Sleep(10000) is ten seconds and so
the loop. For example, to read the poem, Cimmeria, word by word, on. Combining the sleep function (along with the header it needs)
you would enter: and a while loop enables you to come up with some interesting
countdown code.
#include <iostream>
#include <fstream> #include <iostream>
using namespace std; #include <windows.h>
using namespace std;
int main ()
int main ()
{
string word; {
ifstream newfile (“C:\\users\\david\\ int a = 10;
Documents\\Cimmeria.txt”);
while (a != 0)
cout << “Cimmeria, by Robert E Howard: \n” << {
endl; cout << a << endl;
a = a - 1;
while (newfile >> word)
Sleep(1000);
{
}
cout << word << endl;
} cout << “\nBlast Off!” << endl;
return 0; return 0;
} } Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 145
Loops and Decision Making
For Loop
In some respects, a for loop works in a very similar way to that of a while loop, although it’s
structure is different. A for loop is split into three stages: an initialiser, a condition and an
incremental step. Once set up, the loop repeats itself until the condition becomes false.
LOOPY LOOPS
The initialise stage of a for loop is executed only once and this sets the point reference for the loop. The condition is evaluated
by the loop to see if it’s true or false and then the increment is executed. The loop then repeats the second and third stage.
STEP 1 Create a new C++ file, with the standard headers: STEP 4 After the loop, you created a compound statement
in braces (curly brackets), that displays the current
#include <iostream> value of the integer num. Every time the for loop repeats itself, the
using namespace std; second and third stages of the loop, it adds 1 until the condition <30
is false. The loop then ends and the code continues, ending neatly
int main ()
with return 0.
{
STEP 2 Start simple and create a for loop that counts from
1 to 30, displaying the value to the screen with
each increment:
STEP 5 A for loop is quite a neat package in C++, all
{ contained within its own brackets, while the other
//For Loop Begins elements outside of the loop are displayed below. If you want to
for( int num = 1; num < 30; num = num +1 ) create a 10-second countdown, you could use:
{
#include <iostream>
cout << “Number: “ << num << endl;
#include <windows.h>
}
using namespace std;
return 0;
int main ()
}
{
//For Loop Begins
STEP 3 Working through the process of the for loop, begin for( int a = 10; a != 0; a = a -1 )
by creating an integer called num and assigning it a {
value of 1. Next, set the condition, in this case num being less than cout << a << endl;
30. The last stage is where you create the increments; here it’s the Sleep(1000);
value of num being added by 1. }
cout << “\nBlast Off!” << endl;
return 0;
} Your Unique Download ID Code:
0000 0919 MS26 BMD
146 www.bdmpublications.com
For Loop
STEP 6 With the countdown code, don’t forget to include STEP 9 Here’s an example of a for loop displaying the
the windows.h library, so you can use the Sleep multiplication tables of a user inputted number.
command. Build and run the code; in the command console you can Handy for students:
see the numbers 10 to 1 countdown in one second increments, until
{
it reaches zero and Blast Off! appears.
int n;
cout << “Enter a number to view its times
table: “;
cin >> n;
for (int i = 1; i <= 12; ++i) {
cout << n << “ x “ << i << “ = “ << n * i
<< endl;
}
return 0;
}
STEP 8 The code from step 7, when built and run, asks for a
number, then displays the factorial of that number
through the for loop. The user’s number is stored in the integer
n, followed by the integer I which is used to check if the condition
is true or false, adding 1 each time and comparing it to the user’s
number, n.
DO LOOPS
The good thing about a do… while loop is that it’s guaranteed to run through at least once. It’s structure is: do, followed by
statements, while condition is true. This is how it works.
STEP 1 Begin with a new, blank C++ file and enter the STEP 3 Now, here’s a look at the structure of a do… while
standard headers: loop. First you create an integer called num, with
the value of 1. Now the do… while loops begins. The code inside
#include <iostream>
the body of the loop is executed at least once, then the condition is
using namespace std;
checked for either true or false.
int main ()
{
{
STEP 4 If the condition is true, the loop is executed. This
int num = 1;
continues until the condition is false. When the
do condition has been expressed as false, the loop terminates and the
{ code continues. This means you can create a loop where the code
cout << “Number: “ << num << endl; continues until the user enters a certain character.
num = num + 1;
}
while (num < 30 );
return 0;
}
STEP 5 If you want code to add up user inputted numbers STEP 8 Finally, the while statement checks the condition
until the user enters zero: of the variable number. If the user has entered
zero, then the loop is terminated, if not then it continues
{
indefinitely. When the user finally enters zero, the value of sum,
float number, sum = 0.0;
the total value of all the user’s input, is displayed. The loop, and
cout << “**** Program to execute a Do...
the program, then ends.
While loop continuously ****” << endl;
cout << “\nEnter 0 to stop and display the
sum of all the numbers entered\n” << endl;
cout << “\n---------------------------------
---\n” << endl;
do {
cout<<”\nPlease enter a number: “;
cin>>number;
sum += number;
}
while(number != 0.0);
STEP 9 Using the countdown and Blast Off! code used
cout<<”Total sum of all numbers: “<<sum; previously, a do… while loop would look like:
return 0; {
int a = 10;
}
do
{
cout << a << endl;
a = a - 1;
}
while ( a != 0);
If Statement
The decision making statement ‘if’ is probably one of the most used statements in any
programming language, regardless of whether it’s C++, Python, BASIC or anything
else. It represents a junction in the code, where IF one condition is true, do this; or IF it’s
false, do that.
IF ONLY
If uses a Boolean expression within its statement. If the Boolean expression is true, the code within the statement is executed.
If not, then the code after the statement is executed instead.
STEP 1 First, create a new C++ file and enter the relevant
standard headers, as usual:
#include <iostream>
using namespace std;
int main ()
{
STEP 2 If is best explained when you use a number- STEP 3 What’s going on here? To begin, an integer called
based condition: num was created and assigned with the value of 1.
The if statement comes next, and in this case we’ve instructed the
{
code that if the condition, the value, of num is less than 1, then the
int num = 1;
code within the braces should be executed.
if ( num < 30 )
{
cout << “The number is less than 30.” <<
endl;
}
cout << “Value of number is: “ << num << endl;
STEP 4 The second cout statement displays the current
return 0; value of num and the program terminates safely. It’s
easy to see how the if statement works if you were to change the
}
initial value of num from 1 to 31.
STEP 5 When you change the value to anything above STEP 7 The code in Step 6 is simplistic but effective. First we
30, then build and run the code, you can see that created a floating point integer called temp, then a
the only line to be outputted to the screen is the second cout do… while loop that asks the user to enter the current temperature.
statement, displaying the current value of num. This is because the
initial if statement is false, so it ignores the code within the braces.
IF YES, ELSE NO
There are two sections of code that can be executed depending on the outcome in an if… else statement. It’s quite easy to
visualise once you get used to its structure.
STEP 1 Begin with a new C++ file and the standard headers: STEP 3 The first line in the code creates the integer called
num and gives it a value of 1. The if statement
checks to see if the value of num is less than thirty and if it is it
#include <iostream>
outputs “The number is less than 30!” to the console.
using namespace std;
int main ()
{
}
STEP 6 The code works the same way, as you would expect, STEP 8 You can take this up a notch and create a two-player
but what if you wanted to display something if the number guessing game. Begin by creating the variables:
user entered the number 30? Try this:
int num, guess, tries = 0;
{
int num; cout << “***** Two-player number guessing game
****” << endl;
cout << “Enter a number: “;
cout << “\nPlayer One, enter a number for
cin >> num;
Player Two to guess: “ << endl;
if ( num < 30 ) cin >> num;
{ cout << string(50, ‘\n’);
cout << “The number is less than 30!” <<
endl;
STEP 9 The cout << string(50, ‘\n’) line clears the screen so
}
Player Two doesn’t see the entered number. Now
else if ( num > 30 )
you can create a do… while loop, together with if… else:
{
cout << “The number is greater than 30!” do
<< endl; {
} cout << “\nPlayer Two, enter your guess: “;
else if ( num == 30 ) cin >> guess;
{ tries++;
cout << “The number is exactly 30!” << if (guess > num)
endl; {
} cout << “\nToo High!\n” << endl;
}
return 0;
else if (guess < num)
} {
cout << “\nToo Low!\n” << endl;
}
else if (guess == num)
{
cout << “Well done! You got it in “ <<
tries << “ guesses!” << endl;
}
} while (guess != num);
return 0;
Introducing
Windows 10
Batch Files
Your Unique Download ID Code:
0000 0919 MS26 BMD
154 www.bdmpublications.com
Introducing Windows 10 Batch Files
.BAT MAN
A Windows batch file is simply a script file that runs a series of commands, one line at a time, much in the same fashion as a
Linux script. The series of commands are executed by the command line interpreter and stored in a plain text file with the .BAT
extension; this signifies to Windows that it’s an executable file, in this case, a script.
Batch files have been around since the earliest versions of Microsoft 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, an Autoexec.bat file could be created to
Batch files are plain text and often created using Notepad. However, if you’re working in the command prompt with
elevated privileges to begin with, as the Administrator, then
the UAC won’t question the batch file and continue regardless
of what files are being deleted.
The Autoexec.bat was the first such file many users came across in
their PC-based computing lives; since many had come from a 16-bit
or even 8-bit background; remember, this was the late eighties
and early nineties. The batch file was the user’s primary tool for
automating tasks, creating shortcuts and adventure games and
translating complex processes into something far simpler.
Nowadays however, a batch file isn’t just for loading in drivers and
such when the PC boots. You can use a batch file in the same way
as any other scripting language file, in that you can program it to
ask for user input and display the results on the screen; or save to
a file and even send it to a locally or network attached printer. You
can create scripts to back up your files to various locations, compare
date stamps and only back up the most recently changed content as
well as program the script to do all this automatically. Batch files are
remarkably powerful and despite them not being as commonly used
as they were during the older days of DOS, they are still there and
can be utilised even in the latest version of Windows 10; and can be
as complex or simple as you want them to be.
A NEW BATCH
Throughout this section on batch files we’re going to be working with Notepad, the command prompt and within a folder
called ‘Batch Files’. To begin with, let’s see how you get to the Windows command prompt.
STEP 1 The Windows STEP 3 While at the command prompt window, enter:
command dir/w. This lists all the files and directories from
prompt may look a little where you are at the moment in the system. In this case, that’s your
daunting to the newcomer Home directory that Windows assigns every user that logs in. You
but it’s simply another can navigate by using the CD command (Change Directory). Try:
interface (or Shell) used to
cd Documents
access the filesystem. You
can go anywhere you like in Then press Return.
the command prompt, as
you would with the graphical
interface. To begin, click on
the Windows Start button and
enter CMD into the search box.
STEP 2 Click on the search result labelled Command Prompt STEP 4 The prompt should change and display \
(Desktop App) and a new window pops up. The Documents>; this means you’re in the Documents
Command Prompt window isn’t much to look at to begin with but directory. Now, create a new directory call Batch Files. Enter:
you can see the Microsoft Windows version number and copyright
md “Batch Files”
information followed by the prompt itself. The prompt details the
current directory or folder you’re in, together with your username. You need the quotations because without them, Windows creates
two directories: Batch and Files. Now change directory into the
newly created Batch Files.
cd Batch Files
You won’t need the quotes to change directories.
STEP 5 Now that you have the directory set up, where you STEP 8 Back at the command prompt window, enter:
store your batch files, here is how you can create dir/w again to list the newly created Test.bat file.
one. Leave the command prompt window open and click on the By the way, the /w part of dir/w means the files are listed across
Windows Start button again. This time enter Notepad and click on the screen as opposed to straight down. Enter dir if you want
the search result to open the Notepad program. Notepad is a simple (although you need more files to view) but it’s considered easier to
text editor but ideal for creating batch scripts with. read with the /w flag.
STEP 6 To create your first batch file, enter the following STEP 9 To execute the batch file you’ve just created, simply
into Notepad: enter its name, Test, in the command prompt
window. You don’t need to add the .bat part, as Windows recognises
@echo off
it as an executable file, and the only one with that particular name in
echo Hello World!
the current directory. Press return and see how you’re greeted with
By default, a batch file displays all the commands that it runs Hello World! in the command prompt.
through, line by line. What the @echo off command does is turn
that feature off for the whole script; with the ‘@’ (at) sign to apply
that command to itself.
Getting an Output
While it’s great having the command prompt window display what you’re putting after
the echo command in the batch file, it’s not very useful at the moment, or interactive
for that matter. Let’s change up a gear and get some output.
INPUT, OUTPUT
Batch files are capable of taking a normal Windows command and executing it, while also adding extra options and flags in to
the equation.
STEP 1 Let’s keep things simple to begin with. Create a new STEP 3 You have no doubt noticed that there is no
batch file called ‘dirview.bat’, short for Directory indication that the batch file worked as there’s
View. Start with the @echo off command and under that add: no meaningful output on the screen. However, if you now open
Explorer and browse to c:\Users\YOURNAME, remembering to
dir “c:\users\YOURNAME\Documents\Batch Files” >
substitute YOURNAME with your Windows username, and double-
c:\users\YOURNAME\dirview.txt
click the dirview.txt file, you can see the batch file’s output.
Substitute YOURNAME with your Windows username.
STEP 2 The new line uses the dir command to list the STEP 4 If you want to automate the task of opening the
contents of the directory Batch Files, in your Home text file that contains the output, add the following
directory, dumping the output to a text file called dirview.txt in line to the batch file:
the root of your Home directory. This is done, so that the Windows
notepad.exe c:\users\YOURNAME\dirview.txt
UAC doesn’t require elevated permissions, as everything is in your
own Home area. Save and run the batch file. Save the file and once again run from the command prompt. This
time, it creates the output and automatically opens Notepad with
the output contents.
STEP 1 Create a new batch file and call it name.bat. Start STEP 4 This is extremely useful if you want to create a
with the @echo off command, then add the unique, personal batch file that automatically runs
following lines: when a user logs into Windows. Using the default systems variables
that Windows itself creates, you can make a batch file that greets
set /p name= What is your name?
each user:
echo Hello, %name%
@echo off
Note: there’s a space after the question mark. This is to make it look
neater on the screen. Save it and run the batch file. echo Hello, %USERNAME%.
echo.
echo Thanks for logging in. Currently the network
is operating at 100%% efficiency.
echo.
echo Your Home directory is located at: %HOMEPATH%
echo The computer name you’re logged in to is:
%COMPUTERNAME%
echo.
STEP 6 Alternatively, you can run the batch file and display
it on the user’s desktop as a text file:
@echo off
echo Hello, %USERNAME%. > c:%HOMEPATH%\user.txt
STEP 3 Variables stored with Set can be called with the
echo. >> c:%HOMEPATH%\user.txt
%VARIABLENAME% syntax. In the batch file, we
echo Thanks for logging in. Currently the network
used the newly created %name% syntax to call upon the contents of
is operating at 100%% efficiency. >> c:%HOMEPATH%\
the variable called name. Your username, for example, is stored as a
user.txt
variable. Try this in a batch file:
echo. >> c:%HOMEPATH%\user.txt
echo Hello, %USERNAME%. What are you doing? echo Your Home directory is located at: %HOMEPATH%
>> c:%HOMEPATH%\user.txt
echo The computer name you’re logged in to is:
%COMPUTERNAME% >> c:%HOMEPATH%\user.txt
echo. >> c:%HOMEPATH%\user.txt
notepad c:%HOMEPATH%\user.txt
The > outputs to a new file called user.txt, while the >> adds the
lines within the file. Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 161
Introducing Windows 10 Batch Files
STEP 1 Create a new batch file called list.bat and start it off STEP 3 Now, create a batch file that displays the contents
with the @echo off command. Begin by clearing of any directory and post it as a text file to the user’s
the command prompt screen and displaying a list of the current screen. Add the following to the list.bat batch file:
directories on the computer:
echo Hello, %USERNAME%.
cls echo From the list, which folder would you like to
dir “c:\” > list.txt view?
type list.txt set /p view= (enter as c:\folder)
echo. dir “%view%” > view.txt
notepad.exe view.txt
STEP 2 Save and execute the batch file. Within the STEP 4 What’s happening here is the batch file asks the user
command prompt you can see the contents of all to enter any of the directories displayed in the list it
the files and directories from the root of the C:\ drive; and as any generated, in the form of ‘c:\directory’. Providing the user enters a
user under Windows has permission to see this, there’s no UAC valid directory, its contents are displayed as a text file. We created
elevated privileges required. the view variable here along with %HOMEPATH%, to store the input
and the text file.
STEP 5 It’s always a good idea, when creating text files STEP 8 Instead of left clicking on the Command Prompt
for the user to temporarily view, to clean up after result, as you did the first time you opened it,
yourself. There’s nothing worse than having countless, random right-click it and from the menu choose Run as Administrator. There
text files cluttering up the file system. That being the case, let’s is a risk that you could damage system files as the Administrator
clear up with: but as long as you’re careful and don’t do anything beyond viewing
directories, you will be okay.
cls
del /Q view.txt
del /Q list.txt
echo All files deleted. System clean.
STEP 7 Depending
on how
your system is configured,
you may not get any
directory information
at all or a message
stating Access Denied.
This is because the UAC STEP 10 With the UAC active, the command prompt looks
is blocking access to a little different. For starters, it’s now defaulting
protected areas of the to the C:\WINDOWS\system32 folder and the top of the windows is
system, like c:\Windows labelled Administrator. To run the batch file, you need to navigate to
or C:\Program Files. the Batch Files directory with: cd \Users\USERNAME\Documents\
Therefore, you need to Batch Files. To help, press the Tab key to auto-complete the
run the batch file as an directory names.
Administrator. Click the
Windows Start button and
enter CMD again.
STEP 1 We are introducing a couple of new commands STEP 3 Now let’s extend the seek.bat batch file:
into the mix here but we think they’re really useful.
Create a new batch file called seek.bat and in it put: @echo off
cls
@echo off
color 2
cls
echo Please enter the type of file you want to
color 2
search for (MP3, DOC, JPG for example)
echo Please enter the type of file you want to
echo.
search for (MP3, DOC, JPG for example)
set /p ext=
echo.
where /R c:\ *.%ext% > found.txt
notepad.exe found.txt
cls
color
del /Q found.txt
STEP 2 The new command in this instance is color STEP 4 Another new command, Where, looks for a specific
(Americanised spelling). Color, as you already file or directory based on the user’s requirements.
assume, changes the colour of the command prompt display. The In this case, we have created a blank variable called ext that the user
color attributes are specified by two hex digits, the first corresponds can enter the file type in, which then searches using Where and
to the background colour of the Command console and the second dumps the results in a text file called found.txt. Save and run the
to the foreground, and can be any of the following values: batch file.
CHOICE MENUS
Creating a menu of choices is a classic batch file use and a good example to help expand your batch file programming skills.
Here’s some code to help you understand how it all works.
STEP 1 Rather than using a variable to process a user’s STEP 4 ErrorLevels are essentially variables and the /M
response, batch files can instead use the Choice switch of Choice allows a descriptive message string
command in conjunction with an ErrorLevel parameter to make a to be displayed. Extend this menu with something new:
menu. Create a new file called menu.bat and enter the following:
@echo off
@echo off cls
cls echo.
choice /M “Do you want to continue? Y/N” echo ---------------------------------------------
if errorlevel 2 goto N echo.
if errorlevel 1 goto Y echo Please choose a directory.
goto End: echo.
echo Press 1 for c:\Music
echo.
echo Press 2 for c:\Documents
echo.
echo Press 3 for c:\Pictures
echo.
echo Press 4 for c:\Videos
echo.
echo ---------------------------------------------
STEP 2 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 No. Goodbye. STEP 5 Now add the Goto sections:
goto End
:Y :Videos
echo. cls
echo You chose Yes. Hello CD %HOMEPATH%\Videos
echo You are now in the Videos directory.
:End
goto End
:Pictures
cls
CD %HOMEPATH%\Pictures
echo You are now in the Pictures directory.
goto End
:Documents
cls
CD %HOMEPATH%\Documents
echo You are now in the Documents directory.
STEP 3 The output from your choice is different depending on
goto End
whether you pick Y or N. The :End part simply signifies
the end of the file (also known as EOF). Without it the batch file runs :Music
through each line and display the Y response even if you enter N; so it’s cls
important to remember to follow your Goto commands. CD %HOMEPATH%\Music
echo you are now in the Music directory.
goto End
:End
STEP 6 When executed, the batch file displays a menu and with
each choice the code changes directory to the one the
user entered. The %HOMEPATH% system variable will enter the currently
logged in user’s Music, Pictures and so directories, and notDownload
Your Unique anyone else’s.
ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 165
Introducing Windows 10 Batch Files
COUNTERS
Creating code that counts in increasing or decreasing number sets is great for demonstrating loops. With that in mind, let’s look
at the If statement a little more, alongside more variables, and introduce the Else, Timeout and eof (End of File) commands.
STEP 1 Start by creating a new batch file called count.bat. STEP 3 The count.bat is a rough way of demonstrating a
Enter the following, save it and run: loop; a better approach would be to use a for loop.
Try this example instead:
@echo off
cls @echo off
set /a counter=0 for /L %%n in (1,1,99) do echo %%n
:numbers
set /a counter=%counter%+1
if %counter% ==100 (goto :eof) else (echo
%counter%)
timeout /T 1 /nobreak > nul
goto :numbers
STEP 4 Breaking it
down, there’s
For, then the /L switch, which
handles a range of numbers.
Then the parameter labelled as
STEP 2 The count.
%%n to denote a number. Then
bat code
the in (1,1,99) part, which tells
starts at number one and
the statement how to count,
counts, scrolling down the
as in 1 (start number), 1 (steps
screen, until it reaches 100.
to take), 99 (the end number).
The Timeout command
The next part is do, meaning DO
leaves a one second gap
whatever command is after.
between numbers and the
Else statement continues
until the counter variable
equals 100 before going to
the eof (End Of File), thus
closing the loop.
STEP 5 You can include the pause between the numbers STEP 8 There are different ways of using the For loop. In
easily enough within the far simpler For loop by this example, the code creates 26 directories, one
adding multiple commands after the Do For loop. The brackets and for each letter of the alphabet, within the directory c:\test which the
ampersand (&) separate the different commands. Try this: batch file makes using the MD command:
@echo off @echo off
for /L %%n in (1,1,99) do (echo %%n & timeout /T 1 FOR %%F IN (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,
/nobreak > nul) s,t,u,v,w,x,y,z) DO (md C:\test\%%F)
STEP 6 One of the great time saving uses of batch files is to STEP 9 Loops can be powerful and extremely useful
create multiple, numbered files. Assume that you elements in a batch file. While creating 26
want twenty five text files within a directory, all numbered from 1 to directories may not sound too helpful, imagine having to create
25. A For loop much like the previous example does the trick: 1,000 users on a network and assign each one their own set of
unique directories. This is where a batch file saves an immense
@echo off
amount of time.
for /L %%n in (1,1,25) do copy nul %%n.txt
STEP 7 If you open Windows Explorer, and navigate to the STEP 10 Should you ever get stuck when using the various
Batch Files directory where you’re working from, commands within a batch file, drop into the
you can now see 25 text files all neatly numbered. Of course, you command prompt and enter the command followed by a question
can append the file name with something like user1.txt and so on by switch. For example, for /? or if /?. You get an on-screen help file
altering the code to read: detailing the commands’ use. For easier reading, pipe it to a text file:
@echo off For /? > forhelp.txt
for /L %%n in (1,1,25) do copy nul User%%n.txt
:Game
set /a question=%question%+1
cls
if %question% ==5 (goto end) else (echo you are on
question %question%)
echo.
echo get ready for the question...
echo.
timeout /T 5 /nobreak > nul
if %question% ==5 (goto end) else (goto %question%)
:1
cls
echo.
echo ******************************
echo. Your Unique Download ID Code:
0000 0919 MS26 BMD
168 www.bdmpublications.com
Creating a Batch File Game
Coding Projects
& Ideas
Your Unique Download ID Code:
0000 0919 MS26 BMD
170 www.bdmpublications.com
Coding Projects & Ideas
STEP 1 Let’s begin by creating a sample folder within your STEP 3 Now open Python and create a New File. Enter the
Python directory; call it batpy, for example. Within following code:
the batpy folder, create a new text file and enter the following:
import os
@echo off
n = os.environ[‘name’]
set /p name=What is your name?
print(“Your name is... “, n)
echo Let’s try and pass this to a Python script...
python batpy1.py
echo It worked!!
STEP 2 We won’t go into the intricacies of Windows batch STEP 4 Here we’re using the OS module that will utilise the
files here. Suffice to say this code will ask for a user’s system variables. When we create a variable in a
name, store the name as a variable called name, display a message, batch file, (or Bash script) we’re storing the contents of the variable
then open the Python code we’re about to create. We need to save as a system variable. In Python, we’re passing n as the variable
the file as a batch file, click File > Save As, call it batpy1.bat and set content of the command os.environ. Os.environ is calling the
Save As Type as All Files. system variable ‘name’, which we created in the batch file. Save the
code as batpy1.py.
STEP 5 To recap: we have a batch file called batpy1.bat, STEP 6 Drop into a Windows command prompt and
which asks the user their name and stores the info navigate to the folder Batpy. To run a Windows
as a system variable called name. It’ll then print to the screen a batch file, simply enter the command:
message, then run the Python code, and finally print “It worked!!”.
batpy1.bat
The Python code, called batpy1.py, uses the OS module to call
os.environ[‘name’], stored as n. It’ll then print the value of n after Enter your name as instructed and the reply will be passed to
a message. Python, then back to the batch file to end.
STEP 1 Start by opening your favourite Linux text editor, STEP 3 Now create a new Python file, and enter the following:
and entering the following:
import os
#!/bin/bash
n = os.environ[‘firstname’]
echo -n “Hello, what is your name? “
read firstname print(“Your name is... “, n)
export firstname Save the Python code as batpy1.py.
python3 ./batpy1.py
echo
echo
echo -n “It worked!!!”
echo
STEP 2 Drop into a Terminal session and make a new STEP 4 Back in the Terminal, enter: ./batpy.sh to run the
directory called batpy (mkdir batpy). Save the Bash script. As you can see, the results are the same
Bash script as batpy.sh, and from the Terminal enable the script as as in Windows. The major differences are making the Bash script
executable with: chmod +x batpy.sh. executable, and adding the export firstname command to the Bash
file. In Linux, you need to export system variables before they can be
accessed by the subsystem, in this case the Python code.
Retro Coding
There’s a school of thought on the Internet, that to master the foundations of good coding
skills you need to have some experience of how code was written in the past. In the past is a
bit of a loose term, but mostly, it means coding from the 80s.
BBC BASIC also has some interesting built-in features, such as the value
of PI:
1 REM Area of a circle
2 CLS
20 Input “Enter the radius: “ r
30 let area = PI*r*r
40 print “The area of your circle is: “; area
50 print ‘’’
As you’ll notice, variables with a dollar ($) represent strings, nothing after
the variable, or a hash
Once downloaded, launch the executable and follow the on-screens
(#) represent floating
instructions to install it. Linux users can find the installation files, as well
point decimals; a
as full instructions, at: http://beebem-unix.bbcmicro.com/download.
whole integer has a %
html. MacOS users can get everything they need from: http://www.
character, and a byte
g7jjf.com/.
has an ampersand (&).
The single quotes after
BBC BASIC the Print on line 50
indicate a blank line, one
Once installed and powered up, for each tick, while REM
BeebEm will display the default BBC on line 1 is a comment,
system start-up, along with a couple and thus ignored by the
of beeps. Those of you old enough to BASIC compiler.
have been in a UK school in the 80s
Needless to say, there’s a lot you can learn, as well as having fun, with
will certainly recall this setup.
BBC BASIC. It’s a rainy day project and something that’s interesting to
In BASIC, we use line numbers to determine which lines of code run in show the kids – this is how we rolled back in the 80s, kids!
sequence. For example, to print something to screen we’d enter:
There are a number of sites you can visit to learn BBC BASIC, such
10 print “hello” as http://archive.retro-kit.co.uk/bbc.nvg.org/docs.php3.html. See
what you can come up with using BBC BASIC, or other BASIC types for
Once you’ve typed the above in, press
different systems, and let us know what you’ve created.
Enter and then type:
run
We can of course expand the code to OTHER SYSTEMS
include variables, multi-line print statements and so on:
1 CLS Naturally, you don’t have
10 Input “Hello, what’s your name? “ n$ to look to the BBC Micro to
20 print play around with some retro
30 print “Hi, “ n$ “ I hope you’re well today.” code. If you grew up with a
Commodore 64, then you
Type RUN to execute the code, you can also type LIST to view the code
can always try VICE, the C64
you’ve entered.
emulator. Likewise, the ZX
Spectrum has a slew of great
emulators available for every
modern system to play around
on. In fact, you can probably
find an emulator for virtually
every 8-bit or 16-bit machine
that was produced over the
As you can see, variables are handled in much the same way as Python, a
years. Each has their own
print statement on its own displays a blank line, and CLS clears the screen
unique perspective and coding
– as used in conjunction with the OS module in Python and when running
nuances, so find a few and see
Windows. We’re also able to do some maths work, and play around with
what you can create.
variables too:
1 CLS
10 input “how old are you? “ a
20 print
30 if a > 40 print “You’re over 40 years old.”
40 if a < 40 print “You’re under 40 years old.”
50 print
Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 175
Coding Projects & Ideas
Text Animations
There’s a remarkable amount you can do with some simple text and a little Python know-how.
Combining what you’ve already learned, we can create some interesting animation effects
from the command line.
THE FINAL COUNTDOWN and so on to 10. It’ll take some time, but it’s worth it in the end. Of course,
you can always take a different approach and design the numbers yourself.
The next step of the process is to initialise the code settings and start
the countdown:
#Initialise settings
start = 10
message = “> BLAST OFF!! <”
To extend the code, or make it easier to use, you can always Here we’ve created a new function called Rocket, which
create the number functions in their own Python code, call it produces the effect of an ASCII-like rocket taking off and
Count.py for example, then import Count at the beginning of scrolling upwards; using the distanceFromTop variable.
a new Python file called Countdown.py, along with the OS and
To use this, add it to the end of the previous countdown code and
Time modules:
at the end of the Blast Off!! message, add the following lines:
import os
print(“\n\n\n\n”)
import time
input(“Press Enter to launch rocket...”
import count
This will allow your message to be displayed and then, when the
From there, you will need to specify the imported code in the
user has hit the Enter button, the rocket will launch.
Countdown section:
Again, the code in its entirety can be found in the Code
#Start the countdown Repository at: https://bdmpublications.com/ code-portal.
for counter in range(start, 0, -1):
if counter == 10:
count.ten()
elif counter == 9:
ROLLING DIE
count.nine()
elif counter == 8: Aside from the rocket animation, together with its countdown,
count.eight() another fun bit of text-based animation is that of a rolling dice.
elif counter == 7: A rolling dice can be a great animation to include in an adventure
count.seven()
game, where the player rolls to see what their score is compared
elif counter == 6:
to that of an enemy. The highest roller wins the round and the
count.six()
elif counter == 5: losers’ health drops as a result. It’s an age-old combat sequence,
count.five() used mainly in the Dungeon and Dragons board games and
elif counter == 4: Fighting Fantasy novels, but it works well.
count.four()
The code you’ll need to animate a dice roll is:
elif counter == 3:
count.three()
import os
elif counter == 2:
import time
count.two()
from random import randint
elif counter == 1:
count.one()
die = [“ \n O \n “] #1
die.append(“ O\n \nO “) #2
This will pull the functions from the imported Count.py and print die.append(“O \n O \n O”) #3
them to the screen. die.append(“O O\n \nO O”) #4
die.append(“O O\n O \nO O”) #5
die.append(“O O\nO O\nO O”) #6
ROCKET LAUNCH
def dice():
Building on the previous countdown example, we can create an for roll in range(0,15):
animated rocket that’ll launch after the Blast Off!! message has os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
been printed. The code for this would look something like this: print(“\n”)
number = randint(0,5)
def Rocket(): print(die[number])
distanceFromTop = 20 time.sleep(0.2)
while True:
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’) #Main Code Begins
print(“\n” * distanceFromTop) dice()
print(“ /\ “)
print(“ || “) You may need to
print(“ || “) tweak the O entries,
print(“ /||\ “) to line up the dots on
time.sleep(0.2)
the virtual dice. Once
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
it’s done, though,
distanceFromTop -= 1
if distanceFromTop <0: you’ll be able to add
distanceFromTop = 20 this function to your
adventure game code
and call it up whenever
#Launch Rocket your character, or the situation, requires some element of luck,
Rocket() combat or chance roll of the dice.
Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 177
Coding Projects & Ideas
LOAD”” a countdown for time remaining as the game loads, while others even
went so far as to include some kind of playable game. The point being:
a loading screen is not just an artistic part of computing history, but an
introduction to the program that’s about to be run.
While these days loading screens may no longer be with us, in terms of
modern gaming we can still include them in our own Python content.
Either just for fun, or to add a little retro-themed spice to the mix.
SCREEN$
Creating a loading screen in Python is remarkably easy. You have several
options to hand: you can create a tkinter window and display an image,
followed by a brief pause, before starting your main code, or you could
opt for a console-based ASCII art version, that loads one-line-at-a-time.
Let’s look at the latter and see how it works.
First you’ll need
some ASCII art, you
can look up plenty
of examples online,
Back in the 80s, in the 8-bit home computing era, loading screens were or use an image to
often used to display the cover of a game as it loaded from tape. The ASCII Art converter
image would load itself in, usually one-line-at-a-time, then proceed to to convert any
colour itself in while the loading raster bars danced around in the borders images you have to
of the screen. ASCII. When you have your ASCII art, drop it into a newly created folder
inside a normal text file.
Loading screens were a part of the package, and the buy-in for the whole
game as an experience. Some loading screens featured animations, or Save the file, call it screens.txt for now.
ADVENTURE TIME
A good example of using loading screen
ASCII art, text images, is when coding a text
adventure. Once you’ve established your story,
created the characters, events and so on, you
could easily incorporate some excellently
designed ASCII art to your game.
Imagine coming across a dragon, in game, and
displaying its representation as ASCII. You can
then load up the image lines one-by-one, and
continue with the rest of the adventure code. It’s
certainly worth having a play around with and
it’ll definitely add a little something else extra.
#Main Code Start The code works in much the same way as the previous except, instead
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’) of reading from a text file, it’s running through a for loop that prints
loading _ screen(.5) Loading… followed by an animation of sorts, along with a percentage
counter; clearing the screen every second and displaying the new results.
print (“\nYour code begins here...”) It’s simple, yes, but quite effective in its design.
The code is quite simple: import the OS and Time modules and then create
a Python function called loading_screen with a (seconds) option. Within COMBINING THE TWO
the function, open the text file with the ASCII art as read-only and create
a For loop that’ll read the text file one-line-at-a-time. Next, print the lines How about combining the two elements we’ve looked at? Let’s begin with
– incidentally, the lines, end=’’ element will strip the newline from the a Loading… progress bar, followed by the loading screen. After that, you
text document, without it you’ll end up with a double-line spaced display. can include your own code and continue your program. Here’s the code:
Include the timing in seconds and close the text file buffer.
import os
The final part of the code, #Main Code Start, is where you’ll clear the import time
screen (CLS for Windows, Clear for Linux and macOS) and call the
function, together with the output number of seconds to wait for each def loading _ bar(seconds):
line to be written to the screen – in this case, .5 of a second. for loading in range(0,seconds+1):
percent = (loading * 100) // seconds
Save the code as screens.
print(“\n”)
py, drop into a Command print(“Loading...”)
Prompt or Terminal and print(“<” + (“-” * loading) + (“ “ * (seconds-
execute it. The screen loading)) + “> “ + str(percent) + “%”)
will clear and your ASCII print(“\n”)
art inside the text file time.sleep(1)
will load in line-by-line, os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
creating a loading
screen effect.
def loading _ screen(seconds):
Loading… screens=open(“screens.txt”, ‘r’)
for lines in screens:
print(lines, end=’’)
time.sleep(seconds)
screens.close()
TO BOLDLY GO…
Indeed, the ISS is something most of us consider as a worthy example of
what can happen when we work together. NASA, among other agencies,
uses a wealth of Python code on-board the ISS to help automate
routines, as well as act as an in-between link to translate code from one
language to another, and then into a human-readable format. If you’re
considering a career in space, then learning Python is a must-have skill.
While we’re not able to fill you in on all the details, regarding the code
the ISS utilises, we can look at a fun Python script that will track the ISS,
details over three screens: a text document window -displaying the
display the number of astronauts on board, update the station’s current
astronauts and your current latitude and longitude, a command line
latitude and longitude every five seconds, while also displaying your
(or Terminal window) - displaying the continually updating latitude and
current latitude and longitude.
longitude of the ISS as it orbits Earth, and a final, large window displaying
Displaying all that information in a single screen can become a little a map of the world, together with an icon representing the ISS, that’s
cluttered, so in this instance we’re going to look at spreading all those updated as it orbits. Interested? Read on.
THE GRAPHICS
Firstly, we need to get hold of a map of the world, and an image of the
ISS to use as an icon, that will be updated according to the position of the
space station as it travels over the surface. A quick Google of World Map
will help you out here. Look for one that’s reasonably large, the one we
used for this example was 1280 x 700, and one that has the names of the
countries – if you’re using this with young people, to help with putting
shapes of countries to names.
First, we need to import the modules used in the code: json, turtle, urlib.
request, time and webbrowser. The json and urlib.request modules deal
with the data being pulled from the APIs, turtle will display the graphics,
and time you already know. The Webbrowser module will open text files
in the default text file application – despite what its name may suggest.
Simply load the image up in your image editor app and choose Save As,
The Geocoder module is a new element, and you will need to install it
call them map and iss respectively, and click GIF as the image format.
with: pip install geocoder. Geocoder can retrieve a users’ location based
Remember to also resize the ISS image before saving it as a GIF.
on their IP address, as each ISP will have a geo-specific IP.
This section will use the json and urllib.request modules to pull the data
from the API that contains the names of the astronauts on board the ISS.
It then creates a new text file called iss.txt, where it’ll write ‘There are
currently X astronauts on the ISS…’ and list them by name. The second
part of this section will then use the Geocoder module to retrieve your
current latitude and longitude, based on your IP address, and also write
that information to the end of the text file that contains the names of
the astronauts. The last line, webbrowser.open(“iss.txt”) will use the
Webbrowser module to open and display the newly written text file in
the system’s default text file reading app.
screen.register _ shape(“iss.gif”)
iss = turtle.Turtle()
iss.shape(“iss.gif”)
iss.setheading(45)
iss.penup()
This section of the code sets up the graphical window containing the
world map and the ISS icon. To begin we set up the turtle screen, using
the resolution of the world map image we downloaded at the start of
this tutorial (1280 x 720). The screen.setworldcoordinates syntax will ID Code:
Your Unique Download
0000 0919 MS26 BMD
www.bdmpublications.com 181
Coding Projects & Ideas
mark the boundaries of the screen, creating the x and y coordinates of Here’s the code in its entirety:
the four corners of the canvas, so that the ISS icon can freely travel across
the map of the world and wrap itself back to the opposite side when it import json, turtle, urllib.request, time, webbrowser
reaches an edge. The ISS icon is set as the turtle pen shape, giving it an import geocoder # need to pip install geocoder for your
angle of 45 degrees when moving. lat/long to work.
for p in people:
#Output Latitude and Longitude to the console
a.write(p[“name”] + “ - on board” + “\n”)
lat = float(lat)
lon = float(lon)
g=geocoder.ip(‘me’) # need to pip install geocoder, and
print(“\nLatitude: “ + str(lat))
import
print(“Longitude: “ + str(lon))
as in the headers above
a.write(“\nYour current Lat/Long is: “ + str(g.latlng)) #
#Update the ISS location on the map
prints
iss.goto(lon, lat)
your current lat/long in the text file.
#refresh every 5 seconds
a.close()
time.sleep(5)
webbrowser.open(“iss.txt”)
Now for the final part of the code: Here we collect the location data from #Setup world map in Turtle
the ISS status API, pulling out the latitude and longitude elements of the screen = turtle.Screen()
JSON file. The code then prints the latitude and longitude data to the screen.setup(1280, 720)
console/Terminal, transferring the data from a float to a string in order screen.setworldcoordinates(-180, -90, 180, 90)
#Load the world map image
to print it correctly. The last section will use the latitude and longitude as
screen.bgpic(“map.gif”)
variables lat and lon, to update the ISS icon on the map every five seconds.
ASCII ANIMATION
Let’s assume you wanted to create an animated ASCII Happy Birthday Python script, with the words Happy and Birthday
alternating in appearance. Here’s how it’s done.
STEP 1 First we need to create some ASCII-like text, head STEP 3 Save the text file as 1.txt (you can call it what you
over to http://patorjk.com/software/taag. This is like, but now for ease of use 1.txt will suffice). Save
an online Text to ASCII generator, created by Patrick Gillespie. Start the file in the newly created Test folder. When it’s saved, do exactly
by entering Happy into the text box, the result will be displayed the same for the word Birthday. You can select a new font from the
in the main window. You can change the font with the drop-down ASCII Generator, or add extra characters and when you’re ready,
menu, to the side of the text box; we’ve opted for Big. save the file as 2.txt.
STEP 2 Now create a folder in your Python code directory STEP 4 Open up Python and create a New File. We’re going
on your computer (call it Test, for now), and open to need to import the OS and Time modules for this
either Notepad for a Windows 10 computer, or, if you’re using Linux, example, followed by a line to clear the screen of any content. If
then the currently installed text editor. Click on the Select & Copy you’re using Windows, then you’ll use the CLS command, whereas
button at the bottom of the ASCII Generator webpage, and paste it’s Clear for Linux. We can create a simple if/else statement to
the contents into the text editor. handle the command.
STEP 5 Next we need to create a list of the names of the STEP 8 Here’s the code in full:
text files we want to open, and then we need to
import os, time
open them for display in the Terminal.
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
filenames = [“1.txt”, “2.txt”]
frames = [] filenames = [“1.txt”, “2.txt”]
frames = []
for name in filenames:
with open(name, “r”, encoding=”utf8”) as f: for name in filenames:
frames.append(f.readlines()) with open(name, “r”, encoding=”utf8”) as f:
frames.append(f.readlines())
for i in range(10):
for frame in frames:
print(“”.join(frame))
time.sleep(1)
os.system(‘cls’ if os.name == ‘nt’ else
‘clear’)
STEP 9 Note from the loop within the code, we’ve used
the same CLS and Clear if/else statement as before.
Again, if you’re running on Windows then the OS module will use
STEP 6 We’ve used the UTF8 standard when opening the the CLS command, ‘ELSE’ if you’re using Linux or a Mac, the Clear
text files, as ASCII art as text, within a text file, command will work correctly. If you want, you could use a Try/
often requires you to save the file as UTF compliant – due to the Except statement instead.
characters used. Now we can add a loop to display the files as 1.txt,
then 2.txt, creating the illusion of animation while clearing the
screen after each file is displayed.
STEP 7 Save the Python code in the same folder as the text STEP 10 You can spice things up a little by adding system/
files and drop into a Terminal or Command Prompt. Terminal colours. You’ll need to Google the system
Navigate to the folder in question, and enter the command: codes for the colours you want. The code in our example turns the
Windows Command Line to green text on a black background, then
python NAME.py
changes it back to white on black at the end of the code. Either way,
Where NAME is whatever you called your saved Python code. it’s a fun addition to your Python code.
X=MISTAKE, PRINT Y
There are many pitfalls for the programmer to be aware of, far too many to be listed here. Being
able to recognise a mistake and fix it is when you start to move into more advanced territory, and
become a better coder. Everyone makes mistakes, even coders with over thirty years’ experience.
Learning from these basic, common mistakes help build a better coding foundation.
//COMMENTS
Use comments. It’s a simple concept but commenting on
your code saves so many problems when you next come to
look over it. Inserting comment lines helps you quickly sift PLAN AHEAD
through the sections of code that are causing problems;
also useful if you need to review an older piece of code.
While it’s great to wake up one morning and decide to code
a classic text adventure, it’s not always practical without a
good plan. Small snippets of code can be written without
too much thought and planning but longer and more in-
depth code requires a good working plan to stick to and
help iron out the bugs.
RE-INVENTING WHEELS
You can easily spend days trying to fathom out a section
SECURE DATA
of code to achieve a given result and it’s frustrating and
often time-wasting. While it’s equally rewarding to solve If you’re writing code
the problem yourself, often the same code is out there on to deal with usernames
the Internet somewhere. Don’t try and re-invent the wheel, and passwords, or
look 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, prior to feeding
into a routine that can
transmit or store it
where someone may be
able to get to view it.
HELP! MATHS
Asking for help is something most of us has struggled If your code makes multiple calculations then you need
with in the past. Will the people we’re asking laugh at us? to ensure that the maths behind it is sound. There are
Am I wasting everyone’s time? It’s a common mistake for thousands of instances where programs have offered
someone to suffer in silence. However, as long as you ask incorrect data based on poor mathematical coding, which
the query in the correct manner, obey any forum rules and can have disastrous effects depending on what the code is
be polite, then your question isn’t silly. set to do. In short, double check your code equations.
DEF BEGINNER(MISTAKES=10)
Here are ten common Python programming mistakes most beginners find themselves making. Being able to identify these
mistakes will save you headaches in the future.
CASE SENSITIVE
Python is a case sensitive programming language, so you will need
to check any variables you assign. For example, Lives=10 is a
different variable to lives=10, calling the wrong variable in your code
can have unexpected results.
OPERATORS
Using the wrong operator is also a common mistake to make. When
you’re performing a comparison between two values, for example,
you need to use the equality operator (a double equals, ==). Using
a single equal (=) is an assignment operator that places a value to a
variable (such as, lives=10).
BRACKETS
Everyone forgets to include that extra bracket they should have
added to the end of the statement. Python relies on the routine OPERATING SYSTEMS
having an equal amount of closed brackets to open brackets, so any
Writing code for multiple platforms is difficult, especially when you
errors in your code could be due to you forgetting to count your
start to utilise the external commands of the operating system. For
brackets; including square brackets.
example, if your code calls for the screen to be cleared, then for
Windows you would use cls. Whereas, for Linux you need to use
clear. You need to solve this by capturing the error and issuing it
with an alternative command.
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.
QUOTES
Missing quotes is a common mistake to make, for every level of user.
Remember that quotes need to encase strings and anything that’s
going to be outputted to the screen or into a file, for example. Most
compilers errors are due to missing quotes in the code.
INITIALISE VARIABLES
In C++ variables aren’t initialised to zero by default. This means if
you create a variable called x then, potentially, it is given a random
number from 0 to 18,446,744,073,709,551,616, which can be
difficult to include in an equation. When creating a variable, give it
the value of zero to begin with: x=0.
EXTRA SEMICOLONS
While it’s necessary to have a semicolon at the end of every C++ line,
there are some exceptions to the rule. Semicolons need to be at
the end of every complete statement but some lines of code aren’t
complete statements. Such as:
A.OUT
#include
A common mistake when compiling in Linux is forgetting to name
if lines
your C++ code post compiling. When you compile from the Terminal,
switch lines
you enter:
If it sounds confusing don’t worry, the compiler lets you know where
g++ code.cpp
you went wrong.
This compiles the code in the file code.cpp and create an a.out file
that can be executed with ./a.out. However, if you already have code
in a.out then it’s overwritten. Use:
g++ code.cpp -o nameofprogram
Where Next?
Coding, like most subjects, is a continual learning experience. You may not class yourself
as a beginner any more but you still need to test your code, learn new tricks and hacks to
make it more efficient and even branch out and learn another programming language.
#INCLUDE<KEEP ON LEARNING>
What can you do to further your skills, learn new coding practises, experiment and present your code and even begin to help
others using what you’ve experienced so far?
EXCLUSIVE
Offers on our Tech
Guidebooks
bdmpublications.com/ultimate-photoshop
Buy our Photoshop guides and download
tutorial images for free!
Simply sign-up and get creative.
BDM’s Manual Series - The Complete Coding Manual Editorial and design are the copyright © Papercut Limited and BDM’s Manual Series – The Complete Coding Manual vol.21 is
Volume 21 - ISSN 2056-6662 are reproduced under licence to Black Dog Media . No part of this an independent publication and as such does not necessarily
Published by: . . . . . . . . . . . . . . . . .Black Dog Media Limited (BDM) publication may be reproduced in any form, stored in a retrieval reflect the views or opinions of the producers contained
Editor: . . . . . . . . . . . . . . . . . . . . . . . . .James Gale system, or integrated into any other publication, database, or within . This publication is not endorsed or associated in any
Art Director & Production: . .Mark Ayshford commercial programs, without the express written permission of
Production Manager: . . . . . . . .Karl Linstead way with The Linux Foundation, The Raspberry Pi Foundation,
Design: . . . . . . . . . . . . . . . . . . . . . . . .Robin Drew, Martin Smith, Lena Whitaker the publisher . Under no circumstances should this publication and ARM Holding, Canonical Ltd, Python, Debian Project, Lenovo,
Editorial: . . . . . . . . . . . . . . . . . . . . . .Russ Ware, David Hayward its contents be resold, loaned out, or used in any form by way of Dell, Hewlett-Packard, Apple, Microsoft and Samsung or any
Sub Editor: . . . . . . . . . . . . . . . . . . . .Alison Drew trade without the publisher’s written permission . While we pride associate or affiliate
Black Dog i-Tech Series – Coding for Python Copyright © 2019 Black Dog Media . All rights reserved . responsibility incompany.
regard to All copyrights,
editorial opiniontrademarks
and content .
ourselves on the quality of the information we provide, Black Dog and registered trademarks for the respective companies are
Volume 41 Printed
– ISSNand 2044-4060 bound in Great Britain by: Acorn Web Offset Ltd
Editorial
Media and design
Limited are the
reserves copyright
the right not ©toPapercut
be held Limited andfor
responsible areany Black DogRelevant
acknowledged . i-Tech Series
graphic– Coding
imagery for Python vol.with
reproduced 41 is an independent
PublishedNewsstand
by: . . . . . . . . distribution
. . . . . . . .Black by: DogSeymourMedia Limited (BDM) Limited
Distribution
Editor: . . .2, . .East
. . . . .Poultry
. . . . . . . .Avenue
. . . . .James Gale EC1A 9PT reproduced
mistakes, under licence tofound
or inaccuracies, Black within
Dog Media . Noof
the text part
thisofpublication .
this publication courtesypublication
of Lenovo,andHewlett-
as such does not necessarily
Packard, Dell, Samsung, reflect the views or opinions
FUZE
London
Art Director & Production: . . .Mark Ayshford mayDuebe reproduced
to the nature in
of any
the form, stored
software in
industry,a retrieval
the system,
publisher or integrated
cannot of the producers
Technologies Ltd, and contained
Apple . within . This publication is not endorsed
International distribution by: guarantee
into any otherthat all tutorials
publication, will work
database, oron every version
commercial of Raspbian
programs without
Production Manager: . . . . . . . .Karl Linstead
Pineapple Media Limited www .pineapple-media .com Additional images contained within this publication are The Raspberry Pi
or associated in any way with The Linux Foundation,
Design: . . . . . . . . . . . . . . . . . . . . . .Robin Drew, Lena Whitaker theOS . It remains
express writtenthepermission
purchaser’sofsole theresponsibility
publisher . Under to determine
no circumstances reproduced Foundation,
underARM Holding,
licence Canonical Ltd, Python, Debian Project, Lenovo,
from Shutterstock .com .
Digital distribution: www .pocketmags .com,
Editorial: . . . . . . . . . . . . . . . . . . . . .David Hayward www .zinio .com the suitability
should of this and
this publication bookitsand its content
contents for whatever
be resold, loaned purpose .
out, or used Dell,
Prices, Hewlett-Packard,
international Apple
availability, or anytitles
ratings, associate or affiliate
and content are company. All
For all advertising and
Sub Editor: . . . . . . . . . . . . . . . . . . .Alison Drew promotional opportunities contact: in Images
any form reproduced
by way of on the
trade front
without and
the back covers
publisher’s are solely
written for
permission . copyrights,
subject to change .trademarks and registered
All information was correct trademarks
at time offor the respective
print .
enquiries@bdmpublications .com design
While purposes
we pride and are
ourselves onnottherepresentative
quality of the of content . We
information we provide,
Printed and bound in Great Britain by: Acorn Web Offset Ltd Somecompanies
content may arehave
acknowledged . Relevant
been previously graphic
published inimagery
other reproduced
INTERNATIONAL LICENSING advise
Black Dog all potential
Media Limited buyers to
reserves check
the listing
right prior
not totobepurchase
held for
responsible
Newsstand distribution by: Seymour Distribution Limited volumes or BDM titles . We advise potential buyers to check theDell, Python,
with courtesy of Lenovo, Raspberry Pi, Hewlett- Packard,
Black Dog
2, East Poultry Avenue, MediaLondon has many EC1A great 9PT publications and all are available for licensingforconfirmation
any mistakesof oractual content.
inaccuracies All editorial
found opinion
within the text herein
of thisispublication .
that Samsung,
suitability Canonical
of contents and
prior toApple . Additional images contained within this
purchase .
worldwide . For
International distribution by: Pineapple Media Limited more information go to: www .brucesawfordlicensing .com; of the reviewer as an individual and is not representative
Due to the nature of the software industry, the publisher cannot of the
publication are reproduced under licence from Shutterstock .com . Back
email: bruce@brucesawfordlicensing .com telephone: 0044 7831 567372
www .pineapple-media .com publisherthat
guarantee or any of its affiliates.
all tutorials will work Therefore,
on everythe publisher
version holds noOS . It
of Raspbian Black Dog Media Limited (BDM)
cover image courtesy of Borderlands 3 by Gearbox Software and 2K Games .
Digital distribution:
Copyright ©www .pocketmags .com, 2020 Black Dog Media . All www .zinio .com
rights reserved . responsibility
remains in regardsole
the purchaser’s to editorial opinion
responsibility toand content .the suitability
determine Your Unique Download ID Code:
Registered in England & Wales No: 5311511
Prices, international availability, ratings, titles and content are subject to
For all advertising and promotional opportunities contact: of this book and its content for whatever purpose . Images reproduced
enquiries@bdmpublications .com on the front and back cover are solely for design purposes and are not 0000 0919 MS26 BMD
change . All information was correct at time of print . Some content may
have been previously published in other volumes or BDM titles . We advise
INTERNATIONAL LICENSING – Black Dog Media has many great publications representative of content . We advise all potential buyers to check listing
potential buyers to check the suitability of contents prior to purchase .
and all are available for licensing worldwide . For more information go to: prior to purchase for confirmation of actual content. All editorial opinion
www .brucesawfordlicensing .com; email: bruce@brucesawfordlicensing .com; herein is that of the reviewer as an individual and is not representative Black Dog Media Limited (BDM)
telephone: 0044 7831 567372 of the publisher or any of its affiliates. Therefore, the publisher holds no Registered in England & Wales No: 5311511
Manual Series - The Complete Coding Manual - Vol 21.indd 22 02/01/2020 13:45:30
Your Unique Download ID Code:
0000 0919 MS26 BMD
BDM s Manual Series Python 3
Python is, without a doubt, the most popular
THE COMPLETE programming language with which to begin
learning to code. Not only is it easy to understand
and follow, but it s also quick to achieve great
results, and it s astonishingly powerful too.
We re using Python 3, the latest version of the
MANUAL
language. With it, you re able to create everyday
useful software, graphical games, text adventures
and interactive programs for use at home or work.
C++
C++ is one of the most powerful, high-performing
and efficient programming languages you can
learn. It s used to code and create web browsers,
games, applications, and even entire operating
systems; which makes understanding it a highly
sought after skill to have.
Where do you begin, though? We look at how
It s time to engineer your future! Learn
to get started with C++ on Windows, macOS and
to code, and you will not only discover Linux; from entering a few lines of code to produce
an incredible world of innovation, something on your screen, through to data types
but you will also master your digital and user interaction.
environment. Coding is one of the Batch Files
most sought-after skills of the modern Windows 10 s command line programming comes
workplace and with a little knowledge in the form of batch files. These easy to learn
you can improve your current scripts can be powerful enough to help automate
prospects, or secure your dream job. tasks, back up your important files and even
create games.
Batch files are used by Microsoft system
administrators the world over, as a stepping stone
on to more powerful scripting languages such as
PowerShell, or even into Python and C++. Learning
how to create a batch file will help you get more
from your Windows PC.
Manual Series - The Complete Coding Manual - Vol 21.indd 3 03/01/2020 11:13:47