You are on page 1of 196

190

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

FREE Packed with Learn the Learn C++ Windows 10


Your Unique Download ID Code:
DOWNLOAD top tips and latest version for better
0000 0919 MS26 BMD
batch files
60 PROGRAMS tutorials of Python coding and projects
Manual Series - The Complete Coding Manual - Vol 21.indd 2 02/01/2020 14:53:09
Your Unique Download ID Code:
0000 0919 MS26 BMD
BDM’s Manual Series

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.

@bdmpubs BDM Publications www.bdmpublications.com

Your Unique Download ID Code:


0000 0919 MS26 BMD
Index

Contents
Compl

The

ete
l
Co

ua
di
n g M an

6 Coding Foundations 30 Python Foundations

8 A Brief History of Coding 32 Starting Python for the First Time


10 Being a Programmer 34 Your First Code
12 Choosing a Programming Language 36 Saving and Executing Your Code
14 Creating a Coding Platform 38 Executing Code from the
Command Line
40 Numbers and Expressions
42 Using Comments
44 Working with Variables
46 User Input
48 Creating Functions
50 Conditions and Loops
52 Python Modules
54 Python Errors
56 Combining What You
Know So Far

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

100 Why C++?


102 C++ Facts & Figures
104 Equipment You Will Need
106 How to Set Up C++ in Windows 154 Introducing Windows 10 Batch Files
108 How to Set Up C++ on a Mac
156 What is a Batch File?
110 How to Set Up C++ in Linux
158 Getting Started with
112 Other C++ IDEs to Install
Batch Files
160 Getting an Output
162 Playing with Variables
164 Batch File Programming
166 Loops and Repetition
168 Creating a Batch
File Game

114 C++ Foundations


116 Your First C++ Program
118 Structure of a C++ Program
170 Coding Projects and Ideas
120 Compile and Execute
172 Passing Variables to Python
122 Using Comments
174 Retro Coding
124 Variables
176 Text Animations
126 Data Types
178 Creating a Loading Screen
128 Strings
180 Tracking the ISS with Python
130 C++ Maths
184 Using Text Files for Animation
186 Common Coding Mistakes
188 Python Beginner’s Mistakes

132 C++ Input/Output 190 C++ Beginner’s Mistakes


192 Where Next?
134 User Interaction
136 Character Literals
138 Defining Constants
140 File Input/Output
Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 5
Index

Coding
Foundations
Your Unique Download ID Code:
0000 0919 MS26 BMD
6 www.bdmpublications.com
Coding Foundations

Where to start learning how to code?


Remarkably, this is the most difficult
step. There are plenty of programming
languages out there, and a seemingly
unlimited number of tools to help
you achieve what you want; but
where do you begin?

In this section, we look at what you will


need to take those first tentative steps
into the world of coding. You won’t
become a programmer in twenty-four
hours, learning how to code correctly
takes time and patience, but with a
little help, you can master the basics
and start your coding journey.

8 A Brief History of Coding


10 Being a Programmer
12 Choosing a Programming Language
14 Creating a Coding Platform

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 7
Coding Foundations

A Brief History of Coding


It’s easy to think that programming a machine to automate a process or calculate a value
is a modern concept that’s only really happened in the last fifty years or so. However,
that assumption is quite wrong, coding has actually been around for quite some time.

01000011 01101111 01100100 01100101


Essentially all forms of coding are made up of ones and zeros, on or off states. This works
for a modern computer and even the oldest known computational device.

~87 BC ~850 AD 1800 1842-1843 1930-1950

It’s difficult to pinpoint an exact


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

Ada Lovelace translated


the memoirs of the Italian
mathematician, Francis
Maneclang, regarding
Charles Babbage’s
Analytical Engine. She
made copious notes within
her writing, detailing a
The Banū Mūsā brothers, three Persian method of calculating
scholars who worked in the House of Bernoulli Numbers
Wisdom in Baghdad, published the Book using the engine. This is
of Ingenious Devices in around 850 recognised as the first
AD. Among the inventions listed was a computer program. Not
mechanical musical instrument, a hydro- bad, considering there
powered organ that played interchangeable were no computers
cylinders automatically. available at the time.
Your Unique Download ID Code:
0000 0919 MS26 BMD
8 www.bdmpublications.com
A Brief History of Coding

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

1951-1958 1959 1960-1970 1970-1985 1990s-Present Day

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

The Internet age brought a wealth of new


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

The first true computer code was


Assembly Language (ASM) or
Regional Assembly Language. Admiral Grace Hopper was part of
ASM was specific to the the team that developed the UNIVAC
architecture of the machine I computer and she eventually
it was being used on. In 1951 developed a compiler for it. In time,
programming languages fell under the compiler she developed became
the generic term Autocode. Soon COBOL (Common Business-oriented
languages such as IPL, FORTRAN Language), a computer language that’s
and ALGOL 58 were developed. still in use today.
Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 9
Coding Foundations

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?

Your Unique Download ID Code:


0000 0919 MS26 BMD
10 www.bdmpublications.com
Being a Programmer

MORE THAN CODE


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

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


Times have changed since programming in the ‘80s, time, many users decided they wanted to create their own content, their
but the core values still remain. own games; or simply something that could help them with their homework
or home finances. The simplicity of the 8-bit home computer meant that

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

how far to take


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

your coding
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?

The single most common trait of any programmer, regardless of what


they’re doing, is the ability to see a logical pattern. By this we mean
someone who can logically follow something from start to finish and
envisage the intended outcome. While you may not feel you’re such a
person, it is possible to train your brain into this way of thinking. Yes, it
takes time but once you start to think in this particular way you will be able
to construct and follow code.

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


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

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.

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


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

There is of course a lot more involved in being a programmer, including


learning the actual code itself. However, with time, patience and the
determination to learn, anyone can become a programmer. Whether
Being able to follow a logical pattern and you want to be part of a triple-A video game team or simply create an
see an end result is one of the most valued automated routine to make your computing life easier, it’s up to you how
skills of a programmer. far to take your coding adventure!
Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 11
Coding Foundations

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
12 www.bdmpublications.com
Choosing a Programming Language

SQL stands for Structured Query Language. SQL is a standard language


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

JavaScript (often shortened to JS) is a lightweight,


JAVASCRIPT interpreted, object-oriented language with first class
functions. JavaScript runs on the client side of the web,
that can be used to design or program how the web pages behave on the
occurrence of an event. JavaScript is an easy to learn and also powerful scripting
language, widely used for controlling web page behaviour.

Java is the foundation for virtually every type of networked application


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

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


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

Python is a widely used high level programming language used


PYTHON for general purpose programming, created by Guido van
Rossum and first released in 1991. An interpreted language,
Python has a design philosophy that emphasises code readability and a syntax that
allows programmers to express concepts in fewer lines of code. This can make it
easier for new programmers to learn.

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


C++ language. It has imperative, object-oriented and generic programming
features. It was designed with a bias toward system programming and
embedded, resource-constrained and large systems, with performance, efficiency
and flexibility of use as its design highlights.

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


RUBY Matsumoto, blended parts of his favourite languages (Perl,
Smalltalk, Eiffel, Ada and Lisp) to form a new language. From its
release in 1995, Ruby has drawn devoted coders worldwide. Ruby is seen as a
flexible language; essential parts of Ruby can be removed or redefined, at will.
Existing parts can be added to.

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


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

Swift is a powerful and intuitive programming language for macOS,


SWIFT iOS, watchOS and tvOS. Writing Swift code is interactive and fun;
the syntax is concise yet expressive and Swift includes modern
features that developers love. Swift code is safe by design, yet also produces
software that runs lightning fast. A coding tutorial app, Swift Playgrounds, is
available on the iPad. Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 13
Coding Foundations

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.

Coding can be one of those experiences that sounds fantastic, but


to get going with it, is often confusing. After all, there’s a plethora
of languages to choose from, numerous apps that will enable you
to code in a specific, or range, of languages and an equally huge
amount of third-party software to consider. Then you access the
Internet and discover that there are countless coding tutorials
available, for the language in which you’ve decided you want to
program, alongside even more examples of code. It’s all a little too
much at times.

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

OPERATING SYSTEMS VIRTUAL MACHINES


Windows 10 is the most A virtual machine is a piece of software that allows you to install a
used operating system in fully working, operating system within the confines of the software
the world, so it’s natural itself. The installed OS will allocate user-defined resources from the
that the vast majority of host computer, providing memory, hard drive space etc, as well as
coding tools are written for Microsoft’s leading operating sharing the host computer’s Internet connection.
system. However, don’t discount macOS and especially Linux.
The advantage of a virtual
macOS users enjoy an equal number of coding tools to their machine is that you can work
Windows counterparts. In fact, you will probably find that a with Linux, for example, without
lot of professional coders use a Mac over a PC, simply because it affecting your currently
of the fact that the Mac operating system is built on top of installed host OS. This means
Unix (the command-line OS that powers much of the world’s that you can have Windows 10
filesystems and servers). This Unix layer lets you test programs running, launch your virtual machine client, boot into Linux and use
in almost any language without using a specialised IDE. all the functionality of Linux while still being able to use Windows.

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

Your Unique Download ID Code:


0000 0919 MS26 BMD
16 www.bdmpublications.com
Introducing Python

Python is a fantastic programming


language for beginners but is
also powerful enough to use
in environments such as space
engineering, science, technology and
even the global stock market.

Python’s unique ability to be simple to


read but capable of coping with huge
volumes of data makes it the ideal
starting point. In this section, we’ll
ease you into the world of Python,
and how to get it on to your computer
ready to start learning.

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

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 17
Introducing Python
Pytho
n cre
Ross ator G
um n uido
readi amed V
There’s a ng sc P ython an
Pyth ripts afte
lot to like about on’s F from Mon r
lying t
Python, but don’t just Circu y
s.
take our word for it. Here are
some amazing facts and figures
surrounding one of the most popular
programming languages of recent years.

Alexa, Amazon’s Virtual Data analysis and


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

in PYTHON AND
LINUX SKILLS
N umbers

As of the end of 2018,


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

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


RECOMMENDED FACEBOOK POSTS THAT OVER 75% OF
CONTENT FROM NETFLIX ARE FILTERED NASA’S WORKFLOW
IS GENERATED FROM THROUGH PYTHON- AUTOMATION
MACHINE LEARNING – CODED MACHINE SYSTEMS ON-BOARD
CODED BY PYTHON. LEARNING. THE I.S.S. USE PYTHON.
Your Unique Download ID Code:
0000 0919 MS26 BMD
18 www.bdmpublications.com
Python in Number

16,000 PYTHON SKILL-BASED


POSITIONS ARE THE

There are over 16,000 Python jobs


posted every six months in the UK.
16MOST SOUGHT-AFTER
JOBS IN THE UK.
th

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

Python developers enjoy an average salary of

£60,000
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

Your Unique Download ID Code:


0000 0919 MS26 BMD
20 www.bdmpublications.com
Why Python?

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

Python is what’s known 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.

BASIC was once the starter language that early


8-bit home computer users learned.

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

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


Your
and makes for an ideal beginner’s Unique Download
programming language.ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 21
Introducing Python

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.

WHAT WE’RE USING


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

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

AN IDE
An IDE (Integrated Developer Environment) is used to enter and execute Python
code. It enables you to inspect your program code and the values within the code, as
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.

TIME AND PATIENCE


Despite what other books may lead you to believe, you won’t become a programmer
in 24-hours. Learning to code in Python takes time, and patience. You may become
stuck at times and other times the code will flow like water. Understand you’re learning
something entirely new, and you will get there. Your Unique Download ID Code:
0000 0919 MS26 BMD
22 www.bdmpublications.com
Equipment You Will Need

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

RASPBERRY PI
The Raspberry Pi 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

programming and even as a desktop computer.


Raspberry NEW ¦ Ra
spberry
Pi 4 ¦ Pyth Helping ixes
Raspber
imate Ser

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

tips & tricks NEW


y Pi - Th

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

Python 3 100% INDEPE


NDENT

and C++ Packed wit


h top
Volume

tips and Learn Py


tutorials thon 3,
Learn to Linux an Create am
ge d C++ azing
more fro t Pi projec
ts Master the
36

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

Packed wit NZ$20.99


h 100% INDEPE
the latest Code & bu
NDENT

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

Your Unique Download ID Code:


14/11/2019
16:30:08

0000 0919 MS26 BMD


www.bdmpublications.com 23
Introducing Python

Getting to Know Python


Python is one of the most used and popular programming languages. It’s a great
language on which to learn how to code, but it’s also powerful enough to be used by
companies when trawling through petabytes of raw data.

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

Guido van Rossum, the


designer of Python.

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com
www.bdmpublications.com 2525

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.

INSTALLING PYTHON 3.X


Microsoft Windows doesn’t come with Python preinstalled as standard, so it will be necessary to install it yourself manually.
Thankfully, it’s an easy process to follow.

STEP 1 Start by opening your web browser to www.python. STEP 3 Choosing the Customise option allows you to
org/downloads/. Look for the button detailing the specify certain parameters, and 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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
26 www.bdmpublications.com
How to Set Up Python in Windows

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 27
Introducing Python

How to Set Up
Python in Linux
While the Raspberry Pi’s operating system contains the latest, stable version of Python,
other Linux distros don’t come with Python 3 pre-installed. 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.

Next, enter: python --version into the Terminal


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

However, if you want the latest, cutting edge


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

Your Unique Download ID Code:


0000 0919 MS26 BMD
28 www.bdmpublications.com
How to Set Up Python in Linux

Open up your Linux web browser and go to the For the GUI IDLE, you’ll need to enter the following
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.

In the Terminal, go to the Downloads folder


STEP 7
by entering: cd Downloads/. Then unzip the
contents of the downloaded Python source code with: tar -xvf
Python-3.Y.Y.tar.xz (replace the Y’s with the version numbers
you’ve downloaded). Now enter the newly unzipped folder with: cd
Python-3.Y.Y/. You’ll also need PIP (Pip Installs Packages), which is
STEP 10
a tool to help you install more modules and extras.
Enter: sudo apt-get install python3-pip
Once PIP is installed, check for the latest update with:
pip3 install --upgrade pip
When complete, close the Terminal and Python 3.x will be available
via the Programming section in your distro’s menu.

Within the Python folder, enter:


STEP 8
./configure
sudo make altinstall
This could take a while, depending on the speed of your computer.
Once finished, enter: python3.7 --version to check the latest
installed version. You now have Python 3.7 installed, alongside older
Python 3.x.x and Python 2.

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

Your Unique Download ID Code:


0000 0919 MS26 BMD
30 www.bdmpublications.com
Python Foundations

Now that you have the latest version


of Python installed, you can begin
programming. These are your first
steps into the wider world of Python
and we’re here to help you write your
first piece of code, save it and run it in
the Python IDLE Shell.

We cover variables, numbers and


expressions, user input, conditions
and loops and the types of errors you
will undoubtedly come across in your
time with Python. Let’s start and see
how to get coding.

32 Starting Python for the First Time


34 Your First Code
36 Saving and Executing Your Code
38 Executing Code from the Command Line
40 Numbers and Expressions
42 Using Comments
44 Working with Variables
46 User Input
48 Creating Functions
50 Conditions and Loops
52 Python Modules
54 Python Errors
56 Combining What You Know So Far

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 31
Python Foundations

Starting Python for


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

STARTING PYTHON
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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
32 www.bdmpublications.com
Starting Python for the First Time

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

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 33
Python Foundations

Your First Code


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

PLAYING WITH PYTHON


As with most languages, computer or human, it’s all about remembering and applying the right words to the right situation.
You’re not born knowing these words, so you need to learn them.

STEP 1 If you’ve closed Python 3 IDLE, re-open it as you STEP 3 You’ll notice that instead of the number 4, the
did in the previous page. In the Shell, enter the output is the 2+2 you asked to be printed to the
familiar following: 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

Your Unique Download ID Code:


0000 0919 MS26 BMD
34 www.bdmpublications.com
Your First Code

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

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 35
Python Foundations

Saving and Executing


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

EDITING CODE
You will eventually reach a point where you have to move on from inputting single lines of code into the Shell. Instead, the
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!”)

Your Unique Download ID Code:


0000 0919 MS26 BMD
36 www.bdmpublications.com
Saving and Executing Your Code

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

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 37
Python Foundations

Executing Code from


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

COMMAND THE CODE


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

STEP 1 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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
38 www.bdmpublications.com
Executing Code from the Command Line

STEP 5 Now enter exit() to leave the command line STEP 6 From within the same folder as the code you’re going
Python session, and return back to the command to run, enter the following into the command line:
prompt. Enter the folder where you saved the code from the
python hello.py
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)

DIFFERENT VERSIONS OF PYTHON


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

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 39
Python Foundations

Numbers and Expressions


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

IT’S ALL MATHS, MAN


You can get some really impressive results from the mathematical powers of Python, as maths is the driving force behind the
code with most, if not all, programming languages.

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

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


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

Your Unique Download ID Code:


0000 0919 MS26 BMD
40 www.bdmpublications.com
Numbers and Expressions

STEP 5 You can also use STEP 8 This will be


an operation to displayed as
see the remainder left over from ‘0b11’, converting the integer
division. For example: into binary, and adding the prefix
0b to the front. If you want to
10/3
remove the 0b prefix, then you
will display 3.333333333, which can use:
is, of course, 3.3-recurring. If you
format(3, ‘b’)
now enter:
The Format command converts
10%3
a value, the number 3, to a
This will display 1, which is the formatted representation
remainder left over from dividing as controlled by the format
10 by 3. specification, the ‘b’ part.

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


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

STEP 7 Numbers and STEP 10 Execute the code from Step 9, and you’ll see a
expressions don’t series of True or False statements depending on
stop there. Python has numerous 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)

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 41
Python Foundations

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)

Your Unique Download ID Code:


0000 0919 MS26 BMD
42 www.bdmpublications.com
Using Comments

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

STEP 6 Essentially, the new code together with comments STEP 9 The comment, the hash symbol, can also be used to
could look like: comment out sections of code you don’t want to be
executed in your program. For instance, if you wanted to remove
# Set the start value of A to 10
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. ’’’

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 43
Python Foundations

Working with Variables


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

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
44 www.bdmpublications.com
Working with Variables

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

STEP 6 This is a process known as TypeCasting. The Python STEP 9 The use of TypeCasting is also important when
code is: 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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 45
Python Foundations

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.”)

Your Unique Download ID Code:


0000 0919 MS26 BMD
46 www.bdmpublications.com
User Input

STEP 5 You don’t always have to include quoted text within STEP 8 What you’ve created here is a condition, based on
the input command. For example, you can ask the the user’s input. In short, we’re using the input
user their name, and have the input in the line below: from the user and measuring it against a condition. Therefore, if the
user enters David as their name, the guard will allow them to pass
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!”)

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 47
Python Foundations

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
48 www.bdmpublications.com
Creating Functions

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

FORGING FUNCTIONS
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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 49
Python Foundations

Conditions and Loops


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

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.”)

Your Unique Download ID Code:


0000 0919 MS26 BMD
50 www.bdmpublications.com
Conditions and Loops

STEP 5 Press F5 and save the code to execute it. Enter STEP 6 Now expand the code to include other conditions.
a four-letter word in the Shell to begin with, you Eventually, it could become quite complex. We’ve
should have the returned message that the word is four letters. added a condition for three-letter words:
Now press F5 again, and re-run the program, but this time, enter a
word=input(“Please enter a four-letter word: “)
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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 51
Python Foundations

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
52 www.bdmpublications.com
Python Modules

STEP 5 Close the command prompt or Terminal, and re- STEP 8 Multiple modules can be imported within your code.
launch the IDLE Shell. When you now enter import To extend our example, use:
pygame, the module will be imported into the code without any
import random
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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 53
Python Foundations

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

Your Unique Download ID Code:


0000 0919 MS26 BMD
54 www.bdmpublications.com
Python Errors

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 55
Python Foundations

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 2 We can utilise the Chudnovsky Algorithm to create


STEP 5 You can save and execute the code at this point, if
our own Python script based on the calculation.
you like. The output will print the value of Pi to 27
We’ll begin by importing some important modules and functions
decimal places: 3.141592653589734207668453591. While pretty
within the modules:
impressive on its own, we want some user interaction, to ask the
from decimal import Decimal, getcontext user as to how many places Pi should be calculated.
import math
This uses the decimal and getcontext functions from the decimal STEP 6 We can insert an input line before the Pi calculation
module, both of which deal with large decimal place numbers, and, Def command. It’ll need to be an integer, as it will
naturally, the math module. otherwise default to a string. We can call it numberofdigits, and use
the getcontext function:

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

STEP 10 To finish our code, we need to initialise the t = Decimal(0)


colorama module, and then start the time function pi = Decimal(0)
at the point where the calculation starts, and when it finishes. The deno = Decimal(0)
end result displays, in coloured ink, how long the process took (in k = 0
the Terminal or command line): for k in range(n):
t = (Decimal(-1)**k)*(math.
from decimal import Decimal, getcontext
factorial(Decimal(6)*k))*(13591409+545140134*k)
import math
deno = math.factorial(3*k)*(math.
import time
factorial(k)**Decimal(3))*(640320**(3*k))
import colorama
pi += Decimal(t)/Decimal(deno)
from colorama import Fore
pi = pi * Decimal(12)/
colorama.init()
Decimal(640320**Decimal(1.5))
numberofdigits = int(input(“please enter the number pi = 1/pi
of decimal places to calculate Pi to: “)) return str(pi)
getcontext().prec = numberofdigits
print(calc(1))
start_time = time.time() print(Fore.RED + “\nTime taken:”, time.time() -
def calc(n): start_time)

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 57
Index

Manipulating
Data
Your Unique Download ID Code:
0000 0919 MS26 BMD
58 www.bdmpublications.com
Manipulating Data

Data is everything. It’s worth more than


gold or oil, and with it, you can elect
presidents or topple governments,
find out the secrets of the universe
or predict the money markets. Data is
power, so, to get the most from your
code, you’ll need to know how to use it
and how to manipulate it.

This section will introduce you to


Python’s ability to cope with data
and how it can be organised in your
code. We look at how graphics are
created and how to read and write
data from other sources and output to
external files.

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

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 59
Manipulating Data

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.

WORKING WITH LISTS


Lists are extremely handy in Python. A list can be strings, integers, and also variables. You can even include functions in lists,
and lists within lists.

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

Your Unique Download ID Code:


0000 0919 MS26 BMD
60 www.bdmpublications.com
Lists

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 61
Manipulating Data

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.

THE IMMUTABLE TUPLE


Reasons for having tuples vary depending on what the program is intended to do. Mostly a tuple is reserved for something
special, but they’re also used, as an example, in an adventure game where non-playing character names are stored.

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
62 www.bdmpublications.com
Tuples

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))

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 63
Manipulating Data

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”}

Your Unique Download ID Code:


0000 0919 MS26 BMD
64 www.bdmpublications.com
Dictionaries

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 65
Manipulating Data

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
66 www.bdmpublications.com
Splitting and Joining Strings

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

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 67
Manipulating Data

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))

Your Unique Download ID Code:


0000 0919 MS26 BMD
68 www.bdmpublications.com
Formatting Strings

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))

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 69
Manipulating Data

Date and Time


When working with data it’s often handy to have access to the time. For example, you may
want to time-stamp an entry, or see at what time a user logged into the system, and for
how long. Thankfully, acquiring the time and date is easy thanks to the Time module.

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’)

Your Unique Download ID Code:


0000 0919 MS26 BMD
70 www.bdmpublications.com
Date and Time

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 71
Manipulating Data

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.

OPEN, READ AND WRITE


In Python, you create a file object, similar to creating a variable, only you pass in the file using the open() function. Files are
usually categorised as text or binary.

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
72 www.bdmpublications.com
Opening Files

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 73
Manipulating Data

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.

WRITE AND CLOSE


The write() function is slightly more complex than read(). Along with the filename, you must also include an access mode that
determines whether the file in question is in read or write mode.

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
74 www.bdmpublications.com
Writing to Files

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 75
Manipulating Data

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
76 www.bdmpublications.com
Exceptions

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!”)

STEP 9 You can also use a finally: block, which works in a


similar fashion, but you cannot use else with it. Hint:
You’ll need to delete the textfile.txt file from your folder.
try:
txt = open C:\\Users\\david\\Documents\\textfile.
txt”, “r”)
try:
txt.write(“This is a test. Normal service will
shortly resume!”)
finally:
STEP 6 You can use exceptions to handle a variety of useful
print (“Content written to file successfully.
tasks. Using an example from our previous tutorials,
Have a nice day.”)
let’s assume you want to open a file and write to it:
txt.close()
try: except IOError:
txt = open(“C:\\Users\\david\\Documents\\textfile. print (“Error: unable to write the file. Check
txt”, “r”) permissions”)
txt.write(“This is a test. Normal service will
shortly resume!”)
STEP 10 As before an error will occur as we’ve used the “r”
except IOError:
read-only permission. If we change it to a “w”, then
print (“Error: unable to write the file. Check
the code will execute without the error being displayed in the IDLE
permissions”)
Shell. Needless to say, it can be a tricky getting the exception code
else:
right the first time. Practise, though, and you will get the hang of it.
print (“Content written to file successfully.
Have a nice day.”)
txt.close()

STEP 7 Obviously this won’t work due to the file textfile.txt


being opened as read only (the “r” part). So in this
case, rather than Python telling us we’re doing something wrong
we’ve created an exception, using the IOError class, informing the
user that the permissions are incorrect.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 77
Manipulating Data

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
78 www.bdmpublications.com
Python Graphics

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 79
Manipulating Data

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 4 The newUser function is next:


def newUser():
STEP 2 Next we need to define some functions. We can createLogin = input(“Create a login name: “)
begin with creating the main menu, to where, after
if createLogin in users:
selecting the available options, all users will return:
print (“\nLogin name already exists!\n”)
def mainMenu(): else:
global status createPassw = input(“Create password: “)
status = input(“Do you have a login account? users[createLogin] = createPassw
y/n? Or press q to quit.”) print(“\nUser created!\n”)
if status == “y”: logins=open(“C:\\Users\\david\\Documents\\
oldUser() logins.txt”, “a”)
elif status == “n”: logins.write(“\n” + createLogin + “ “ +
newUser() createPassw)
elif status == “q”: logins.close()
quit()
This creates a new user and password, and writes the entries into a
file called logins.txt.

Your Unique Download ID Code:


0000 0919 MS26 BMD
80 www.bdmpublications.com
Combining What You Know So Far

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()

STEP 6 Now to create the oldUser function:

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?

STEP 7 There’s a fair bit happening here. We have login


and passw variables, which are then matched to the
users dictionary. If there’s a match, then we have a successful login
and the time and date of the login is outputted. If they don’t match,
then we print an error, and the process starts again.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 81
Index

Using
Modules

Your Unique Download ID Code:


0000 0919 MS26 BMD
82 www.bdmpublications.com
Using Modules

Modules are where you can take


Python programming to new heights.
You can create your own modules,
or you can use some of the already
available modules, to help convert
a mundane piece of code into
something spectacular.

Want to see how to make better


use of these modules to add a little
something extra to your code? Then
read on and learn how they can be
used to forge fantastic programs.

84 Calendar Module
86 OS Module
88 Random Module
90 Tkinter Module
92 Pygame Module
96 Create Your Own Modules

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 83
Using 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.

WORKING WITH DATES


The Calendar module is built into Python 3. However, if, it’s not installed, you can add it using pip install calendar, as a
Windows administrator, or sudo pip install calendar for Linux and macOS.

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)

Your Unique Download ID Code:


0000 0919 MS26 BMD
84 www.bdmpublications.com
Calendar Module

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 85
Using Modules

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.

INTO THE SYSTEM


One of the primary features of the OS module is the ability to list, move, create, delete and otherwise interact with files
stored on the system; making it the perfect module for backup code.

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’)

Your Unique Download ID Code:


0000 0919 MS26 BMD
86 www.bdmpublications.com
OS Module

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”’)

STEP 9 You can also rename any directories you’ve created


by entering:
import os
os.rename(“C:\\BDM\\NEW”, “C:\\BDM\\OLD”)
Or delete them…
STEP 6 To show that the OS module works roughly the
same across all platforms, we need to specify the import os
name of the app according to the OS on which you’re working. For os.rmdir(“C:\\BDM\\OLD”)
example, on a Raspberry Pi you would enter:
import os
os.system(‘chromium-browser “http://
bdmpublications.com/”’)

STEP 10 Another module that goes together with OS is


shutil. We can use the Shutil module, together
with OS and time, to create a time-stamped backup directory, and
copy files into it:
import os, shutil, time
t=str(time.strftime(“%Y-%m-%d %H-%M”))
root_src_dir = r’C:\\BDM\\Documents\\’ #Path to
the source directory
root_dst_dir = ‘C:\\Backup\\’ + t #Path to the
backup directory
STEP 7 Note, in the previous step’s example the use of
single and double-quotes. The single quotes encase for src_dir, dirs, files in os.walk(root_src_dir):
the entire command, and launching Chromium, whereas the double dst_dir = src_dir.replace(root_src_dir, root_
quotes open the specified page. You can even use variables to dst_dir, 1)
open webpages: if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
import os
for file_ in files:
a=(‘start chrome “http://www.google.co.uk”’)
src_file = os.path.join(src_dir, file_)
os.system(a)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file)
shutil.copy(src_file, dst_dir)
print(“>>>>>>>>>>Backup complete<<<<<<<<<<”)

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 87
Using Modules

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 2 In our example


the number
three was returned. However,
enter the print function a few
more times and it will display
different integer values from the
set of numbers given, zero to STEP 5 We can extend the previous example somewhat by
five. The overall effect, although having random.choice() select from a list of mixed
pseudo-random, is adequate variables. For instance:
for the average programmer to
import random
utilise in their code.
lst=[“David”, 46, “Avengers”, 3245.32, “Pi”, True,
3.14, “Python”]
rnd=random.choice(lst)
STEP 3 For a bigger set of numbers, including floating
print(rnd)
point values, we can extend the range by using the
multiplication sign:
import random
print(random.random() *100)
Will display a floating point number, between 0 and 100, to the tune
of around fifteen decimal points.

Your Unique Download ID Code:


0000 0919 MS26 BMD
88 www.bdmpublications.com
Random Module

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”])

STEP 7 Using shuffle, we can create an entirely random list


of numbers, for example, within a given range:
import random
lst=[[i] for I in range(20)]
random.shuffle(lst) STEP 10 Here’s an interesting piece of code. Using a text
print(lst) file containing 466 thousand words, we can pluck
a user generated number of words from the file (text file found at:
Keep shuffling the list, and you’ll have a different selection of items
https://github.com/dwyl/english-words):
from 0 to 20 every time.
import random
print(“>>>>>>>>>>Random Word Finder<<<<<<<<<<”)
print(“\nUsing a 466K English word text file I can
pick any words at random.\n”)
wds=int(input(“\nHow many words shall I choose? “))
with open(“/home/pi/Downloads/words.txt”, “rt”) as f:
words = f.readlines()
words = [w.rstrip() for w in words]
print(“--------------------”)
for w in random.sample(words, wds):
STEP 8 We can also select a random number from a given
print(w)
range in steps, using the start, stop, step loop:
print(“--------------------”)
import random
for i in range(10):
print(random.randrange(0, 200, 7))
Result will vary, but you get the general idea as to how it works.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 89
Using Modules

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

Your Unique Download ID Code:


0000 0919 MS26 BMD
90 www.bdmpublications.com
Tkinter Module

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 91
Using Modules

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 2 Let’s create a simple, game ready window and give


it a title:
gamewindow=pygame.display.set_mode((800,600))
pygame.display.set_caption(“Adventure Game”)
You will notice that after the first line is entered, you’ll need to click
back into the IDLE Shell to continue entering code. In addition, you
can change the title of the window to anything you like.

Your Unique Download ID Code:


0000 0919 MS26 BMD
92 www.bdmpublications.com
Pygame Module

STEP 4 If the Pygame window still won’t


close, don’t worry, it’s just a
discrepancy between the IDLE (which is written
with Tkinter) and the Pygame module. If you
run your code via the command line, it will close
perfectly fine.

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 93
Using Modules

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
94 www.bdmpublications.com
Pygame Module

STEP 9 We can now implement a few additions, and utilise pygame.display.flip()


some previous tutorial code. The new elements are clock.tick(60)
in the Subprocess module, of which one function allows us to launch a continue
second Python script from within another, and we’re going to create a break
New File called pygametxt.py:
pygame.quit()
import pygame
import time
import subprocess
pygame.init()
screen = pygame.display.set_mode((800, 250))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 25)
pygame.time.set_timer(pygame.USEREVENT, 200)
def text_generator(text):
tmp = ‘’
for letter in text:
tmp += letter
if letter != ‘ ‘:
yield tmp
class DynamicText(object):
def __init__(self, font, text, pos,
autoreset=False):
self.done = False
self.font = font
self.text = text
self._gen = text_generator(self.text)
self.pos = pos
self.autoreset = autoreset
self.update()
def reset(self):
self._gen = text_generator(self.text)
self.done = False
self.update()
def update(self):
if not self.done:
try: self.rendered = self.font. STEP 10 When we run this code, it will display a long,
render(next(self._gen), True, (0, 128, 0)) narrow Pygame window with the intro text
except StopIteration: scrolling to the right. After a pause of ten seconds, it then launches
self.done = True the main game Python script, where we can move the warrior sprite
time.sleep(10) around. Overall, the effect is quite good, but there’s always room
subprocess.Popen(“python C:\\Users\\david\\ for improvement.
Documents\\Python\\pygame1.py 1”, shell=True)
def draw(self, screen):
screen.blit(self.rendered, self.pos)
text=(“A long time ago, a barbarian strode from the
frozen north. Sword in hand...”)
message = DynamicText(font, text, (65, 120),
autoreset=True)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: break
if event.type == pygame.USEREVENT: message.
update()
else:
screen.fill(pygame.color.Color(‘black’))
message.draw(screen) Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 95
Using Modules

Create Your Own Modules


Large programs can be much easier to manage if you break them up into smaller parts
and import the parts you need as modules. Learning to build your own modules also
makes it easier to understand how modules work.

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 7 We can now make the program a little more


advanced, by utilising the newly created module to
its full. Let’s include some user interaction. Start by creating a basic
menu from which the user can choose:
print(“Select operation.\n”)
print(“1.Times by two”)
print(“2.Times by Three”)
print(“3.Square”)
print(“4.Power of”)
choice = input(“\nEnter choice (1/2/3/4):”)

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 97
Index

Introducing
C++

Your Unique Download ID Code:


0000 0919 MS26 BMD
98 www.bdmpublications.com
Introducing C++

C++ is an amazing programming


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

C++ is an efficient and powerful


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

This section looks at the necessary


equipment and software needed to get
up and running with C++ for Windows,
Mac and Linux systems.

100 Why C++?


102 C++ Facts & Figures
104 Equipment You Will Need
106 How to Set Up C++ in Windows
108 How to Set Up C++ on a Mac
110 How to Set Up C++ in Linux
112 Other C++ IDEs to Install

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 99
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++ code is much faster than other


programming languages.

Your Unique Download ID Code:


0000 0919 MS26 BMD
100 www.bdmpublications.com
Why C++?

Microsoft’s Visual Studio is a great, free


environment in which to learn C++.

C++ puts the developer in a much wider world of coding. By improvements to the engine, or when creating a new game, if
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.

Indeed, the operating system


you’re using is written in C++.

Your Unique Download ID Code:


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

C++ IS USED FREQUENTLY C++ has


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

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

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


TO CALCULATE VAST AMOUNTS OF trading is known as
High Frequency Trading
DATA, INCLUDING THE NASA-BASED (HFT), and the software
SUPERCOMPUTING FARM THAT RUNS responsible is written in
C++ to make use of its
SIMULATIONS OF THE UNIVERSE.
high speed.
Your Unique Download ID Code:
0000 0919 MS26 BMD
102 www.bdmpublications.com
Sources: ITJobsWatch,
Google, Quora, Stack C++ Facts & Figures
Exchange, eduCBA,
StackOverflow,
stackShare, The Xbox
AppDynamics operating system
uses C++ as its
backbone.

Gaming is one of the


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

90
THE
C++ is
used in computer
networking as the
main code behind the
th
Programmable Logic Most of Adobe’s
PERCENTILE SALARY stable of products
Controller, connecting 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.

TIME AND PATIENCE


Yes, as with Python, you’re going to need to set aside significant time to spend on
learning how to code in C++. Sadly, unless you’re a genius, it’s not going to happen
overnight, or even a week. A good C++ coder has spent many years honing their
craft, so be patient, start small and keep learning. Your Unique Download ID Code:
0000 0919 MS26 BMD
104 www.bdmpublications.com
Equipment You Will Need

OS SPECIFIC NEEDS
C++ will work in any operating system, however, getting all the necessary pieces together can be confusing to a newcomer. Here’s
some OS specifics for C++.

LINUX WINDOWS
Linux users are lucky in that they already have a compiler and As we’ve mentioned previously, 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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 105
Introducing C++

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

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

STEP 1 Start by visiting the Code::Blocks download site, at STEP 3 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).

Your Unique Download ID Code:


0000 0919 MS26 BMD
106 www.bdmpublications.com
How to Set Up C++ in Windows

STEP 5 Next choose an install location for the Code::Blocks STEP 8 There’s a lot you can do in Code::Blocks, so you need
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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 107
Introducing C++

How to Set Up C++


on a Mac
To start C++ coding on a Mac you need to install Apple’s Xcode. This is a free, full
featured IDE that’s designed to create native Apple apps. However, it can also be used
to create C++ code relatively easily.

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
108 www.bdmpublications.com
How to Set Up C++ on a Mac

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 109
Introducing C++

How to Set Up C++


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

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”;

Your Unique Download ID Code:


0000 0919 MS26 BMD
110 www.bdmpublications.com
How to Set Up C++ in Linux

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 111
Introducing C++

Other C++ IDEs to Install


If you want to try a different approach to working with your C++ code, then there are
plenty of options available to you. Windows is the most prolific platform for C++ IDEs
but there are plenty for Mac and Linux users too.

DEVELOPING C++
Here are ten great C++ IDEs that are worth looking into. You can install one or all of them 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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
112 www.bdmpublications.com
Other C++ IDEs to Install

VISUAL STUDIO Microsoft’s Visual Studio is a ANJUTA The Anjuta DevStudio is a Linux-only IDE that
mammoth C++ IDE that allows you features some of the more advanced features you
to create applications for Windows, Android, iOS and the web. The 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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 113
Index

C++
Foundations

Your Unique Download ID Code:


0000 0919 MS26 BMD
114 www.bdmpublications.com
C++ Foundations

Within this section, you can begin to


understand the structure of C++ code
and how to compile and execute that
code. The fundamentals of C++ will teach
you the necessary basics, including using
comments, variables, data types, strings,
and how to use C++ mathematics.

These are the building blocks of a C++


program. With them, you can form
your own code, produce an output to
the screen and store and retrieve data.
Building a good foundation is key to
mastering C++, and learning how to
structure your C++ code will help you
further down the line.

116 Your First C++ Program


118 Structure of a C++ Program
120 Compile and Execute
122 Using Comments
124 Variables
126 Data Types
128 Strings
130 C++ Maths

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 115
C++ Foundations

Your First C++ Program


We’re going to be working exclusively in Windows with Code::Blocks for this C++
section. Let’s begin by writing your first C++ program and taking the first small steps
into a larger coding world.

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>

Your Unique Download ID Code:


0000 0919 MS26 BMD
116 www.bdmpublications.com
Your First C++ Program

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

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 117
C++ Foundations

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.

#INCLUDE <C++ STRUCTURE>


Learning the basics of programming, you begin to understand the structure of a program. The commands may be different
from one language to the next, but you will start to see how the code works.

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.

Bjarne Stroustrup, inventor


of C++.
INT MAIN()
int main() initiates the
declaration of a function, which
is a group of code statements
under the name ‘main’. All
C++ code begins at the main
function, regardless of where it
actually lies within the code.

BRACES
The open brace (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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 119
C++ Foundations

Compile and Execute


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

GREETINGS FROM C++


Compiling and executing C++ code from Code::Blocks is extraordinarily easy; just a matter of clicking an icon and seeing the
result. Here’s how it’s done.

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
120 www.bdmpublications.com
Compile and Execute

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 121
C++ Foundations

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.

THE IMPORTANCE OF COMMENTING


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

In a professional environment, comments are vital to the success


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

Place yourself in the shoes of someone whose job it is to find out


what’s wrong with a program. The program has in excess of 800,000
lines of code, spread across several different
modules. You can soon appreciate the
need for a little help from the original
programmers in the form of a good
comment.

The best comments are always concise and


link the code logically, detailing what
happens when the program
hits this line or section.
You don’t need to
comment on every
line. Something
along the lines of:
if x==0 doesn’t
require you to
comment that if x
equals zero then
do something;
that’s going to
be obvious to the
reader. However, if x
Your Unique Download ID Code:
0000 0919 MS26 BMD
122 www.bdmpublications.com
Using Comments

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 123
C++ Foundations

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.

THE DECLARATION OF VARIABLES


You can declare a C++ variable by using statements within the code. There are several distinct types of variables you can
declare. Here’s how it works.

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;

Your Unique Download ID Code:


0000 0919 MS26 BMD
124 www.bdmpublications.com
Variables

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 9 The modern C++ compiler is far more intelligent


than most programmers give it credit. While there
are numerous data types you can declare for variables, you can in
fact use the auto feature:
#include <iostream>
using namespace std;
auto pi = 3.141593;

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};

STEP 7 You can create global variables, which are variables


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

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 125
C++ Foundations

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.

THE VALUE OF DATA


There are many different data types available for the programmer incredibly accurate numbers but those numbers are only accurate
in C++, such as an integer, floating point, Boolean, character and so up to the fifteenth decimal place. There’s also the problem when
on. It’s widely accepted that there are seven basic data types, often displaying such numbers in C++ using the cout function, in that cout
called Primitive Built-in Types; however, you can create your own by default only outputs the first five decimal places. You can combat
data types should the need ever arise within your code. that by adding a cout.precision () function and adding a value inside
the brackets, but even then you’re still limited by the accuracy of the
The seven basic data types are:
double data type. For example, try this code:
#include <iostream>
TYPE COMMAND using namespace std;
Integer Integer double PI = 3.141592653589793238463;
int main()
Floating Point float {
cout << PI;
Character char }

Boolean bool

Double Floating Point double

Wide Character wchar_t

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”;
} }

Your Unique Download ID Code:


0000 0919 MS26 BMD
128 www.bdmpublications.com
Strings

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”;
}

STEP 9 Using the available operations that come with the


string function, you can manipulate the contents of a
string. For example, to remove characters from a string you could use:
STEP 6 You can see that we used greet.size() to output the
#include <iostream>
length, the number of characters there are, of the
using namespace std;
contents of the string. Naturally, if you call your string something
other than greet, then you need to change the command to reflect int main ()
this. It’s always stringname.operation. Build and run the code to see
{
the results.
string strg (“Here is a long sentence in a
string.”);
cout << strg << ‘\n’;
strg.erase (10,5);
cout << strg << ‘\n’;
strg.erase (strg.begin()+8);
cout << strg << ‘\n’;
STEP 7 You can of course add strings together, or rather
strg.erase (strg.begin()+9, strg.end()-9);
combine them to form longer strings:
cout << strg << ‘\n’;
#include <iostream>
}
using namespace std;
int main ()
STEP 10 It’s worth spending some time playing around with
{
the numbers, which are the character positions
string greet1 = “Hello”;
in the string. Occasionally, it can be hit and miss whether you get it
string greet2 = “, world!”;
right, so practice makes perfect. Take a look at the screenshot to see
string greet3 = greet1 + greet2;
the result of the code.
cout << greet3 << “\n”;
}

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 129
C++ Foundations

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 2 While simple, it does get the old maths muscle


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

Your Unique Download ID Code:


0000 0919 MS26 BMD
130 www.bdmpublications.com
C++ Maths

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”;
}

STEP 10 The value of Pi is also stored in the cmath header


library. It can be called up with the M_PI function.
Enter cout << M_PI; into the code and you get 3.14159; or you can
use it to calculate:
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
double area, radius = 1.5;
area = M_PI * radius * radius;
STEP 7 Here we created a new float called number and
used the sqrt(number) function to display the cout << area << “\n”;
square root of 134, the value of the variable, number. Build and run
}
the code, and your answer reads 11.5758.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 131
Index

C++ Input/
Output

Your Unique Download ID Code:


0000 0919 MS26 BMD
132 www.bdmpublications.com
C++ Input/Output

There’s a satisfying feeling when you


program code that asks the user for
input, before using that input to produce
something that the user can see. Even if
it’s simply asking for someone’s name,
and displaying a personal welcome
message, it’s a big leap forward.

User interaction, character literals,


defining constants and file input and
output are all covered in the following
pages. All of which help you to
understand more thoroughly how a C++
program works, and enables you to add
that personal touch with improved user
interaction in your own code.

134 User Interaction


136 Character Literals
138 Defining Constants
140 File Input/Output

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 133
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 4 If you’re asking a question, you need to store the


input as a string; to ask the user their name, you
would use:
#include <iostream>
STEP 2 The data type of the variable must also match the using namespace std;
type of input you want from the user. For example,
int main ()
to ask a user their age, you would use an integer like this:
{
#include <iostream> string name;
using namespace std; cout << “what is your name: “;
cin >> name;
int main ()
{ cout << “\nHello, “ << name << “. I hope you’re
int age; well today?\n”;
cout << “what is your age: “;
}
cin >> age;
cout <<”\nYou are “ << age << “ years old.\n”;
}

Your Unique Download ID Code:


0000 0919 MS26 BMD
134 www.bdmpublications.com
User Interaction

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.

STEP 7 Likewise, inputted data can be manipulated once


you have it stored in a variable. For instance, ask the STEP 10 Getline is usually a command that new C++
user for two numbers and do some maths on them: programmers forget to include. The terminating
white space is annoying when you can’t figure out why your code
#include <iostream>
isn’t working. In short, it’s best to use getline(cin, variable) in future:
using namespace std;
#include <iostream>
int main ()
using namespace std;
{
float num1, num2; int main ()
{
cout << “Enter two numbers: \n”;
cin >> num1 >> num2; string name;
cout << “Enter your full name: \n”;
cout << num1 << “ + “ << num2 << “ is: “ <<
getline(cin, name);
num1 + num2 << “\n”;
cout << “\nHello, “ << name << “\n”;
}
}

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 135
C++ Input/Output

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”;
}

Your Unique Download ID Code:


0000 0919 MS26 BMD
136 www.bdmpublications.com
Character Literals

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.

ESCAPE SEQUENCE CODE CHARACTER


\\ Backslash

\’ Single Quote

\” Double Quote (Speech Marks)

\? 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

\uxxxx Unicode (UTF-8)

\Uxxxxxxxx Unicode (UTF-16)

UNICODE CHARACTERS (UTF-8)


Unicode characters are symbols or characters that are standard across
all platforms. For example, the copyright symbol, that can be entered
via the keyboard by entering the Unicode code, followed by ALT+X. In
the case of the copyright symbol enter: 00A9 Alt+X. In C++ code, you
would enter:
#include <iostream>
using namespace std;
int main ()
{
cout << “\u00A9”;

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 2 Now let’s assume your code has three different


constants: length, width and height. You can define
them with:
#include <iostream>
using namespace std;
#define LENGTH 50
#define WIDTH 40
#define HEIGHT 60
int main ()
{
}
STEP 4 Build and run the code. Just as expected, it displays
the values for each of the constants created. It’s
worth noting that you don’t need a semicolon when you’re defining
a constant with the #define keyword.

Your Unique Download ID Code:


0000 0919 MS26 BMD
138 www.bdmpublications.com
Defining Constants

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;
}

STEP 9 Because you’re using const within the main block of


code, you need to finish the line with a semicolon.
You can use either, as long as the names and values don’t clash, but
it’s worth mentioning that #define requires no memory, so if you’re
coding to a set amount of memory, #define is your best bet.
STEP 6 The code, when built and executed, does exactly the
same as before, using the new constant NEWLINE
to insert a newline in the cout statement. Incidentally, creating a
newline constant isn’t a good idea unless you’re making it smaller
than \n or even the endl command.

STEP 10 Const works in much the same way as #define.


You can create static integers and even newlines:
STEP 7 Defining a constant is a good way of initialising your
base values at the start of your code. You can define #include <iostream>
that your game has three lives, or even the value of PI without using namespace std;
having to call up the C++ math library:
int main()
#include <iostream>
{
using namespace std;
const int LENGTH = 50;
#define PI 3.14159 const int WIDTH = 40;
const char NEWLINE = ‘\n’;
int main ()
int area;
{
area = LENGTH * WIDTH;
cout << “The value of Pi is: “ << PI << endl;
cout << “Area is: “ << area << NEWLINE;
}
}

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 139
C++ Input/Output

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 4 To read the contents of a file, and output it to the


screen, you need to do things slightly differently.
First you need to create a string variable to store the file’s contents
(line by line), then open the file, use getline to read the file line by
line and output those lines to the screen. Finally, close the file.

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 6 You can no


doubt see that
we’ve included a while loop, STEP 9 The code from step 8 differs again, but only where
which we cover in a few pages it comes to adding the age integer. Notice that
time. It means that while there we used cin >> age, instead of the previous getline(cin, variable).
are lines to be read from the The reason for this is that the getline function handles strings, not
text file, C++ getlines them. integers; so when you’re using a data type other than a string, use
Once all the lines are read, the standard cin.
the output is displayed on the
screen and the file is closed.

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 141
Index

Loops and
Decision Making
Your Unique Download ID Code:
0000 0919 MS26 BMD
142 www.bdmpublications.com
Loops and Decision Making

Loops and repetition are one of the


most critical factors of any programming
language. Proper use of a loop creates
a program that delivers the desired
outcome precisely as predicted, without
issues or errors.

Without loops and decision making


events within the code, your program will
never be able to offer the user any choice.
It’s this understanding of choice that
elevates your skills as a programmer and
makes for much better code.

Creating a successful loop gives the code


a beginning, middle and end ready to
start again, should the user wish to. It also
forms the basis for advanced Artificial
Intelligence routines.

144 While Loop


146 For Loop
148 Do… While Loop
150 If Statement
152 If… Else Statement

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 143
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 4 We’re introducing a few new elements here. The


first are the opening and closing braces for the
while loop. This is because our loop is a compound statement,
meaning a group of statements; note also, there’s no semicolon
after the while statement. You now also have return 0, which is a
STEP 2 Create a simple while loop. Enter the code below,
clean and preferred way of ending the code.
build and run (we’ve added comments to the
screen shot):
{
int num = 1;
while (num < 30 )
{
cout << “Number: “ << num << endl;
num = num +1;
}
STEP 5 If you didn’t need to see the continually increasing
return 0; value of num, you could have done away with the
} compound while statement and instead just added num by itself
until it reached 30, and then displayed the value:
{
int num = 1;
while (num < 30 )
num++;
cout << “Number: “ << num << endl;
return 0;
} Your Unique Download ID Code:
0000 0919 MS26 BMD
144 www.bdmpublications.com
While Loop

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 7 Naturally you can include a lot more content into a


for loop, including some user input:
int i, n, fact = 1;
cout << “Enter a whole number: “;
cin >> n;
for (i = 1; i <= n; ++i) {
fact *= i;
}
cout<< “\nFactorial of “<< n <<” = “<< fact <<
endl;
return 0;

STEP 10 The value of the integer i can be expanded from


12 to whatever number you want, displaying a
very large multiplication table in the process (or a small one). Of
course the data type within a for loop doesn’t have to be an integer;
as long as it’s valid, it works.
for ( float i = 0.00; i < 1.00; i += 0.01)
{
cout << 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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 147
Loops and Decision Making

Do… While Loop


A do… while loop differs slightly from that of a for or even a while loop. Both for and
while set and examine the state of the condition at the start of the loop, or the top of
the loop if you prefer. However, a do… while loop, is similar to a while loop but instead
checks the condition at the bottom of the loop.

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 2 Begin with a simple number count:

{
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;
}

Your Unique Download ID Code:


0000 0919 MS26 BMD
148 www.bdmpublications.com
Do… While Loop

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);

cout << “\nBlast Off!” << endl;


return 0;
}

STEP 6 The code from Step 5 works as follows: two floating


point variables are assigned, number and sum, both
with the value of 0.0. There is a brief set of instructions for the user,
then the do… while loop begins.

STEP 10 The main advantage of using a do… while loop


is because it’s an exit-condition loop; whereas a
STEP 7 The do… while loop in this instance asks the user
while loop is an entry-control loop. Therefore, if your code requires a
to input a number, which you assigned to the float
loop that needs to be executed at least once (for example, to check
variable, number. The calculation step uses the second floating
the number of lives in a game), then a do… while loop is perfect.
point variable, sum, which adds the value of number every time the
user enters a new value.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 149
Loops and Decision Making

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
150 www.bdmpublications.com
If Statement

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.

STEP 8 The first if statement checks to see if the user’s


inputted value is less than or equal to zero. If it is,
then the output is ‘Brrrr, it’s really cold!’. Otherwise, if the input is
STEP 6 You can include an if statement within a do… while
greater than zero, the code outputs ‘At least it’s not freezing!’.
loop. For example:
{
float temp;
do
{
cout << “\nEnter the temperature (or
-10000 to exit): “ << endl;
cin >> temp;
if (temp <= 0 )
{
cout << “\nBrrrr, it’s really cold!” STEP 9 Finally, if the user enters the value -10000, which is
<< endl; impossibly cold so is therefore a unrealistic value,
} the do… while loop is terminated and a friendly ‘Good bye’ is
if (temp > 0 ) displayed to the screen.
{
cout << “\nAt least it’s not
freezing!” << endl;
}
}
while ( temp != -10000 );
cout << “\nGood bye\n” << endl;
return 0;
}

STEP 10 Using if is quite powerful, if it’s used correctly. Just


remember that if the condition is true then the
code executes what’s in the braces. If not, it continues on its merry
way. See what else you can come up with using if and a combination
of loops.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 151
Loops and Decision Making

If… Else Statement


There is a much better way to use an if statement in your code, with if… else. If… else
works in much the same way as a standard if statement. If the Boolean expression
is true, the code within the braces is executed. Else, the code within the next set of
braces is used instead.

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 4 The else companion to if checks if the number


STEP 2 Let’s expand the code from the if statement on the
is greater than 30 and if so, then displays “The
previous page:
number is greater than 30!” to the console; and finally, the code is
{ terminated satisfactorily.
int num = 1;
if ( num < 30 )
{
cout << “The number is less than 30!” <<
endl;
}
else
STEP 5 You can change the value of num in the code or
{
you can improve the code by asking the user to
cout << “The number is greater than 30!”
enter a value:
<< endl;
} {
int num;
return 0;
cout << “Enter a number: “;
} cin >> num;
if ( num < 30 )
{
cout << “The number is less than 30!” <<
endl;
}
else
{
cout << “The number is greater than 30!”
<< endl;
}
return 0;
} Your Unique Download ID Code:
0000 0919 MS26 BMD
152 www.bdmpublications.com
If… Else Statement

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;

STEP 7 The new addition to the code is what’s known as a STEP 10


nested if… else statement. This allows you to check
Grab a second player, then
for multiple conditions. In this case, if the user enters a number less
build and run the code.
than 30, greater than 30 or actually 30 itself, a different outcome is
Player One enters the
presented to them.
number to be guessed,
then Player Two can take
as many guesses as they
need to get the right
number. Want to make
it harder? Maybe use
decimal numbers. Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 153
Index

Introducing
Windows 10
Batch Files
Your Unique Download ID Code:
0000 0919 MS26 BMD
154 www.bdmpublications.com
Introducing Windows 10 Batch Files

Windows batch files have been around


since the early days of Microsoft
DOS. They are simple, yet effective,
command-line scripts that can be
coded to perform a function; covering
everything from automation of system
processes to creating a command-
line based game.

Windows 10 may be the most advanced


version of Microsoft’s operating
system, but it still has the ability to
create batch files. Learning how to
code and create a batch file will help
you discover the deeper elements of
the Windows OS; leading you on to
more specific administrative concepts
such as Microsoft’s PowerShell.

156 What is a Batch File?


158 Getting Started with Batch Files
160 Getting an Output
162 Playing with Variables
164 Batch File Programming
166 Loops and Repetition
168 Creating a Batch File Game

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 155
Introducing Windows 10 Batch Files

What is a Batch File?


The Windows batch file has been around since the early days of DOS, and was once a
critical element of actually being able to boot into a working system. There’s a lot you
can do with a batch file but let’s just take a moment to see what one is.

.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

When a user powered


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

The Autoexec.bat file was


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

Your Unique Download ID Code:


0000 0919 MS26 BMD
156 www.bdmpublications.com
What is a Batch File?

BATCH FILE POWER


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

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

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


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

The Autoexec.bat was the first such file many users came across in
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.

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


Well, as long as you have Windows 10, or any older version of
Windows for that matter, you can start batch file programming
immediately. All you need is to be able to open Notepad and get to
the command prompt of Windows. We show you how it all works, so You can create complex batch files or simple ones that display
read on. ASCII images on screen. Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 157
Introducing Windows 10 Batch Files

Getting Started with


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

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
158 www.bdmpublications.com
Getting Started with Batch Files

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.

STEP 7 When saving anything in Notepad the default


extension is .txt, to denote a text file. However, you
STEP 10 The echo command displays whatever is after it
want the extension to be .bat. Click on File > Save As and navigate
to the screen. Right-click the Test.bat file from
to the newly created Batch Files directory in Documents. Click the
Windows Explorer and select Edit to add more echo commands if
drop-down menu Save as Type, and select All Files from the menu. In
you like. Try this:
File Name, call the file Test.bat.
@echo off
echo Hello World!
echo This is my first batch file
echo.
echo With a blank line between!
Remember to save each new change to the batch file.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 159
Introducing Windows 10 Batch Files

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
160 www.bdmpublications.com
Getting an Output

OUTPUT WITH VARIABLES


Variables offer a more interesting way of outputting something to the screen and create a higher level of interaction between
the user and the batch file. Try this example below.

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 2 The set /p name creates a variable called name,


with the /p part indicating that an ‘=prompt string’
is to follow. The Set command displays, sets or removes system
and environmental variables. For example, while in the command
prompt window enter: STEP 5 Save and execute the batch file changes; you can
overwrite and still use name.bat if you want. The
set
batch file takes the current system variables and reports them
To view the current system variables. Note the name= variable we accordingly, depending on the user’s login name and the name of
just created. the computer. Note: the double percent symbol means the percent
sign will be displayed, and is not a variable.

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

Playing with Variables


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

USING MORE VARIABLES


Here’s a good example of mixing system and environmental variables with some of your own creation, along with a number of
external Windows commands.

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
162 www.bdmpublications.com
Playing with Variables

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 6 The additions to the batch file simply clear the


command prompt window (using the cls command)
and delete both the view.txt and list.txt files that were created by
the batch file. The /Q flag in the del command means it deletes
the files without any user input or notification. The final message
STEP 9 This action triggers the UAC warning message,
informs the user that the files are removed.
asking you if you’re sure you want to run the
Windows command prompt with the elevated Administrator
privileges. Most of the time we wouldn’t recommend this course
of action: the UAC is there to protect your system. In this case,
however, click Yes.

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 163
Introducing Windows 10 Batch Files

Batch File Programming


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

SEARCHING FOR FILES


Here’s an interesting little batch file that you can easily extend for your own use. It asks the user for a file type to search for
and displays the results.

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
164 www.bdmpublications.com
Batch File Programming

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

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

Loops and Repetition


Looping and repeating commands are the staple diet of every programming language,
including batch file programming. For example, you can create a simple countdown or
even make numbered files or directories in the system.

COUNTERS
Creating code that counts in increasing or decreasing number sets is great for demonstrating loops. With that in mind, let’s look
at the If statement a little more, alongside more variables, and introduce the Else, Timeout and eof (End 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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
166 www.bdmpublications.com
Loops and Repetition

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

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 167
Introducing Windows 10 Batch Files

Creating a Batch File Game


@echo off
Based on what you’ve looked at Cls
so far with batch files, you can :start
set /a score=0
probably come up with your own set /a question=0
cls
simple text adventure or multiple- set /p name= What is your name?
choice game. Here’s one that we
:menu
created, that you’re free to fiddle cls
echo.
with and make your own. echo ****************************************************
**
echo.
echo Welcome %name% to the super-cool trivia game.
Make up your own questions but how about also echo.
including an introductory or loading screen? Make your echo Press 1 to get started
loading screen in a separate batch file and save it as echo.
screens.bat (for example). Then, from the main game echo Press 2 for instructions
batch file, you can load it at the beginning of the file echo.
with the ‘call’ command followed by colour to reset echo Press Q to quit
echo.
the game’s colours:
echo ****************************************************
**
@echo off
choice /C 12Q
Cls
if errorlevel 3 goto :eof
Call screens.bat
if errorlevel 2 goto Instructions
color
if errorlevel 1 goto Game
:start
set /a score=0
:Instructions
set /a question=0
cls
cls
echo.
set /p name= What is your name?
echo **************************************
echo.
echo The instructions are simple. Answer the
questions correctly.
echo.
echo **************************************
pause
cls
goto menu

:Game
set /a question=%question%+1
cls
if %question% ==5 (goto end) else (echo you are on
question %question%)
echo.
echo get ready for the question...
echo.
timeout /T 5 /nobreak > nul
if %question% ==5 (goto end) else (goto %question%)

:1
cls
echo.
echo ******************************
echo. Your Unique Download ID Code:
0000 0919 MS26 BMD
168 www.bdmpublications.com
Creating a Batch File Game

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


echo. if errorlevel 2 goto wrong
echo ****************************** if errorlevel 1 goto correct
echo.
echo. :4
echo Question %question%. cls
echo. echo.
echo Which of the following version of Windows is the echo ******************************
best? echo.
echo. echo Your current score is %score%
echo A. Windows 10 echo.
echo. echo ******************************
echo B. Windows ME echo.
echo. echo.
echo C. Windows Vista echo Question %question%.
echo. echo.
choice /C abc echo Which of the following Windows uses DirectX 12?
if errorlevel 3 goto wrong echo.
if errorlevel 2 goto wrong echo A. Windows 10
if errorlevel 1 goto correct echo.
echo B. Windows 3.11
:2 echo.
cls echo C. Windows XP
echo. echo.
echo ****************************** choice /C abc
echo. if errorlevel 3 goto wrong
echo Your current score is %score% if errorlevel 2 goto wrong
echo. if errorlevel 1 goto correct
echo ******************************
echo. :Wrong
echo. cls
echo Question %question%. echo ******************
echo. echo.
echo Which of the following version of Windows is the echo WRONG!!!!
most stable? echo.
echo. echo ******************
echo A. Windows 10 set /a score=%score%-1
echo. pause
echo B. Windows 95 goto :game
echo.
echo C. Windows ME :correct
echo. cls
choice /C abc echo ******************
if errorlevel 3 goto wrong echo.
if errorlevel 2 goto wrong echo CORRECT. YIPEE!!!
if errorlevel 1 goto correct echo.
echo ******************
:3 set /a score=%score%+1
cls pause
echo. goto :game
echo ******************************
echo. :end
echo Your current score is %score% cls
echo. echo ******************************
echo ****************************** echo.
echo. echo Well done, %name%, you have answered all the
echo. questions
echo Question %question%. echo.
echo. echo And your final score is....
echo Which of the following Windows version is the echo.
latest? echo %score%
echo. echo.
echo A. Windows 10 echo ********************************
echo. choice /M “play again? Y/N”
echo B. Windows 98 if errorlevel 2 goto :eof
echo. if errorlevel 1 goto start
echo C. Windows 7
echo.
choice /C abc Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 169
Index

Coding Projects
& Ideas
Your Unique Download ID Code:
0000 0919 MS26 BMD
170 www.bdmpublications.com
Coding Projects & Ideas

This section features some fantastic


coding projects and ideas that you
can use in your own code. Want to add
something a little extra to your code?
How about creating a loading screen,
or some amazing text animations using
ASCII characters?

There’s code here to track the ISS


in real-time, and we even look back
at some retro coding, using BBC
Micro BASIC, to give you a better
understanding of how other forms of
code come together and work.

There are always more ideas to code,


so keep learning and keep coding!

172 Passing Variables to Python


174 Retro Coding
176 Text Animations
178 Creating a Loading Screen
180 Tracking the ISS with Python
184 Using Text Files for Animation
186 Common Coding Mistakes
188 Python Beginner’s Mistakes
190 C++ Beginner’s Mistakes
192 Where Next?

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 171
Coding Projects & Ideas

Passing Variables to Python


Here’s an interesting coding tutorial: how to pass a system variable to Python. By this we
mean, if you create a variable within a Windows batch file or Linux Bash script, then you’re
able to use that same variable from inside Python.

THE WINDOWS WAY


The two systems use slightly different ways to accomplish the same task; Windows is slightly easier (by a single command) so
we’ll start with that.

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
172 www.bdmpublications.com
Passing Variables to Python

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.

THE LINUX WAY


Linux’s version of passing variables to Python is slightly different, just because it’s Linux! It’s easy, though, and here’s how
it’s done.

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 173
Coding Projects & Ideas

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.

THE GOLDEN ERA OF CODE THE BEEB


The problem with BASIC
is that there were so
many different
versions available,
across multiple
8-bit platforms,
with each
having its own unique
elements on top of the core
BASIC functions. The BASIC that was
packaged with the Commodore 64 was
different to that on the ZX Spectrum, or the Atari
home computers, due to the differing hardware of each
system. However, it’s widely recognised that one of the ‘best’, and possibly
most utilised, form of BASIC from the 80s was that of BBC BASIC.
BBC BASIC was used on the Acorn BBC Micro range of computers,
utilising the MOS 6502-based processor technologies. It was one of the
While it may seem a little counterproductive to learn how to code in a quickest examples of BASIC and, thanks to an inline assembler, it was
language that’s virtually obsolete, there are some surprising benefits to also capable of allowing the developers of the time to write code for
getting your hands dirty with a bit of retro coding. Firstly, learning old different processor types, such as the Zilog Z80 – a CPU present in the ZX
code will help you build the structure of code as, regardless of whether it Spectrum, as well as many arcade machines.
is a language that was developed yesterday, or forty years ago, code still
The BBC Micro was designed and built by Acorn Computers – a company
demands strict discipline to work correctly. Secondly, everyday coding
that is historically responsible for the creation of the ARM CPU - the
elements such as loops, sub routines and so on are a great visual aid to
processor that’s used in virtually every Android phone and tablet, as
learn in older code, especially BASIC. Lastly, it’s simply good fun.
well as smart TVs, set top boxes and so on. The BBC Micro was born in a
time when the UK government was looking for a countrywide computer
GOING BASIC platform to be used throughout education. Different companies bid,
but it was the BBC’s Computer Literacy Project (the BBC Micro) that was
The easiest retro language to play around with is, without doubt, chosen, due to its ruggedness, upgradability, and potential for education.
BASIC. Developed back in the mid-sixties, BASIC (Beginner’s All-Purpose As a result, the BBC Micro, or the Beeb as it’s affectionately known,
Symbolic Instruction Code) is a high-level programming language whose became the dominant educational computer throughout the 80s.
design was geared toward ease of use. In a time when computers were
beginning to become more accessible, designers John Kemeny and
Thomas Kurtz needed a language that students could get to grips with, BEEBEM
quickly and easily. Think of BASIC as a distant relation to Python.
Naturally, you could scour eBay and look for a working BBC Micro to
play around on, and it’ll be a lot of fun. However, for the sake of playing
around with some retro code, we’ll use one of the best BBC Micro
emulators available: BeebEm.
BeebEm was originally developed for UNIX in 1994 by Dave Gilbert and
later ported to Windows. It is now developed by Mike Wyatt and Jon
Welch, who maintain the Mac port of the emulator, and is therefore
available for Windows 10, Linux and macOS, as well as other platforms.
If you’re using Windows 10, simply navigate to http://www.mkw.
me.uk/beebem/index.html, and download the BeebEM414.exe that’s
displayed in the main screen. Your Unique Download ID Code:
0000 0919 MS26 BMD
174 www.bdmpublications.com
Retro Coding

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

#Start the countdown


for counter in range(start, 0, -1):
if counter == 10:
ten()
elif counter == 9:
nine()
elif counter == 8:
eight()
elif counter == 7:
seven()
elif counter == 6:
six()
elif counter == 5:
five()
elif counter == 4:
four()
elif counter == 3:
three()
elif counter == 2:
two()
elif counter == 1:
one()
time.sleep(1)
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
Let’s begin with some example code that will display a large countdown
from ten, then clear the screen and display a message. The code itself is And finally, we can add a display for the message:
quite simple, but lengthy. You will need to start by importing the OS and
Time modules, then start creating functions that display the numbers: #Display the message
print(“v^v^v^v^v^v^v^v^v^v^v^v^v^v^v”)
print(“< >”)
print(message)
print(“< >”)
print(“v^v^v^v^v^v^v^v^v^v^v^v^v^v^v”)
print(“\n\n\n”)

The code in its entirety can be viewed


from within our Code Repository: https://
bdmpublications.com/ code-portal, where
you’re free to copy it to your own Python IDLE
and use it as you see fit. The end effect is quite
good and it’ll be worth adding to your own
games, or presentations, in Python.
Your Unique Download ID Code:
0000 0919 MS26 BMD
176 www.bdmpublications.com
Text Animations

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

Creating a Loading Screen


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

LOAD”” 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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
178 www.bdmpublications.com
Creating a Loading Screen

percent = (loading * 100) // seconds


THE CODE print(“\n”)
print(“Loading...”)
Launch Python and enter the following code to a New File: print(“<” + (“-” * loading) + (“ “ * (seconds
loading)) + “> “ + str(percent) + “%”)
import os print(“\n”)
import time time.sleep(1)
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
def loading _ screen(seconds):
screens=open(“screens.txt”, ‘r’)
for lines in screens: #Main Code Start
print(lines, end=’’) loading _ bar(10)
time.sleep(seconds)
screens.close() print (“\nYour code begins here...”)

#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()

#Main Code Start


loading _ bar(10)
Another favourite introduction screen is that of a simple loading os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
animation, where the word loading is displayed followed by some loading _ screen(.5)
characters and a percentage of the program loaded. While it may not
take long for your Python code to load, the effect can be interesting.
print (“\nYour code begins here...”)
Create a New File in Python and enter the following code:
You can of course pull those functions up wherever and whenever you
import os
import time
want in your code and they’ll display, as they should, at the beginning.
Remember to have the ASCII text file in the same folder as the Python
def loading _ bar(seconds): code, or, at the screens=open(“screens.txt”, ‘r’) part of the code, point
for loading in range(0,seconds+1): to where the text file is located. Your Unique Download ID Code:
0000 0919 MS26 BMD
www.bdmpublications.com 179
Coding Projects & Ideas

Tracking the ISS with Python


Of the many amazing human achievements over the past decade or so, the International
Space Station tops the bill. This incredible collaboration between nations sees vital
experiments carried out in space as well as observations of our own planet.

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.

Next, look for an ISS icon. As this is going to be a graphical representation


of the location of the ISS, we need the image to be reasonably small so it
doesn’t drown out the locations on the map, but also prominent enough As we’re going to be using Turtle, a component of tkinter, the downloaded
to see when the map is loaded. We opted for an image that’s 32 x 22 images will need to be converted to GIF, since this is the default and
pixels in size. Don’t worry too much if you’re not able to find one that small, recommended image format. You can easily look up a converter online, but
you can always resize it in an image-editing app such as Paint or GIMP. using Paint in Windows 10, or GIMP, whichYour
is cross-platform, will suffice.ID Code:
Unique Download
0000 0919 MS26 BMD
180 www.bdmpublications.com
Tracking the ISS with Python

Let’s begin by breaking the code into bite-sized chunks:

import json, turtle, urllib.request, time, webbrowser


import geocoder # need to pip install geocoder for your
lat/long to work.

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.

#Retrieve the names of all the astronauts currently on


THE CODE board the ISS, and own lat/long - write to a file and display
url = “http://api.open-notify.org/astros.json”
The code we’re using here utilises an open source API (Application response = urllib.request.urlopen(url)
Programming Interface) to retrieve real-time data online regarding the result = json.loads(response.read())
status of the ISS. An API enables applications to communicate with one a=open(“iss.txt”,”w”)
another by providing the raw data that a programmer can pull out and a.write(“There are currently “ + str(result[“number”]) + “
interact with in their own code. In this case, the API in question is a web- astronauts on the ISS:\n\n”)
based collection of raw data that’s stored in a JSON (JavaScript Object
people = result[“people”]
Notation) format – an accessible and easy to use data-interchange interface.
In order for Python to interact with the JSON provided data, it needs to for p in people:
use the urllib.request and json modules. We’re also going to be using a a.write(p[“name”] + “ - on board” + “\n”)
new module called geocoder, which will pull up a users’ current latitude
and longitude based on their IP address. The two JSON API’s can be g=geocoder.ip(‘me’) # need to pip install geocoder, and
import as in the headers above
located at: http://api.open-notify.org/astros.json, and, http://api.
a.write(“\nYour current Lat/Long is: “ + str(g.latlng)) #
open-notify.org/iss-now.json. One of which contains the data regarding prints your current lat/long in the text file.
the astronauts on board the ISS, and the other contains the data a.close()
regarding the current location of the ISS in longitude and latitude. webbrowser.open(“iss.txt”)

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.

#Setup world map in Turtle


screen = turtle.Screen()
screen.setup(1280, 720)
screen.setworldcoordinates(-180, -90, 180, 90)
#Load the world map image
screen.bgpic(“map.gif”)

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.

#Retrieve the names of all the astronauts currently on


while True:
board the ISS, and own lat/long - write to a file and display
#Load the current status of the ISS in real-time
url = “http://api.open-notify.org/astros.json”
url = “http://api.open-notify.org/iss-now.json”
response = urllib.request.urlopen(url)
response = urllib.request.urlopen(url)
result = json.loads(response.read())
result = json.loads(response.read())
a=open(“iss.txt”,”w”)
a.write(“There are currently “ + str(result[“number”]) + “
#Extract the ISS location
astronauts on the ISS:\n\n”)
location = result[“iss _ position”]
lat = location[“latitude”]
people = result[“people”]
lon = location[“longitude”]

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
182 www.bdmpublications.com
Tracking the ISS with Python

#Update the ISS location on the map


screen.register _ shape(“iss.gif”) iss.goto(lon, lat)
iss = turtle.Turtle() #refresh every 5 seconds
iss.shape(“iss.gif”) time.sleep(5)
iss.setheading(45)
Create a new folder in your system, called ISSTrack (for example), and
iss.penup()
place the two graphics, as well as the Python code itself.
while True:
#Load the current status of the ISS in real-time
url = “http://api.open-notify.org/iss-now.json” RUNNING THE CODE
response = urllib.request.urlopen(url)
result = json.loads(response.read()) The code is best executed from the command line or Terminal. Clear your
desktop, enter your command line and navigate to where you’ve saved
#Extract the ISS location the code plus the two graphics. Launch the code with either: python
location = result[“iss _ position”] ISSTrack.py or Python3 ISSTrack.py (depending on your system, and what
lat = location[“latitude”]
you’ve called the Python code).
lon = location[“longitude”]
The code will launch two extra windows together with the command
#Output Latitude and Longitude to the console line window you already have open. One will be the text file containing
lat = float(lat) the named astronauts along with your current latitude and longitude,
lon = float(lon) and the other will be the world map with the ISS icon located wherever
print(“\nLatitude: “ + str(lat))
the ISS is currently orbiting. The command line window will start scrolling
print(“Longitude: “ + str(lon))
through the changing latitude and longitude of the ISS.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 183
Coding Projects & Ideas

Using Text Files


for Animation
Animation in Python can be handled with the likes of the Tkinter and Pygame modules,
however, there’s more than one way to achieve a decent end result. Using some clever, text
file reading code, we can create command-line animations.

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
184 www.bdmpublications.com
Using Text Files for Animation

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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 185
Coding Projects & Ideas

Common Coding Mistakes


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

X=MISTAKE, PRINT Y
There are many pitfalls for the programmer to be aware of, far too many to be listed here. Being
able 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.

SMALL CHUNKS EASY VARIABLES


It would be wonderful to be able to Meaningful naming for variables is a must to eliminate
work like Neo from The Matrix movies. common coding mistakes. Having letters of the alphabet
Simply ask, your operator loads it into is fine but what happens when the code states there’s
your memory and you instantly know a problem with x variable. It’s not too difficult to name
everything about the subject. Sadly variables lives, money, player1 and so on.
though, we can’t do that. The first
major pitfall is someone trying to learn
too much, too quickly. So take coding in
small pieces and take your time.

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

Your Unique Download ID Code:


0000 0919 MS26 BMD
186 www.bdmpublications.com
Common Coding Mistakes
USER ERROR
User input is often a paralysing mistake in code. For
example, when the user is supposed to enter a number for
their age and instead they enter it in letters. Often a user
can enter so much into an input that it overflows some BACKUPS
internal buffer, thus sending the code crashing. Watch those
user inputs and clearly state what’s needed from them.
Always make a backup of your work, with a secondary
backup for any changes you’ve made. Mistakes can be
rectified if there’s a good backup in place to revert to for
those times when something goes wrong. It’s much easier
to start where you left off, rather than starting from the
beginning again.

RE-INVENTING WHEELS
You can easily spend days trying to fathom out a section
SECURE DATA
of code to achieve a given result and it’s frustrating and
often time-wasting. While it’s equally rewarding to solve If you’re writing code
the problem yourself, often the same code is out there on to deal with usernames
the Internet somewhere. Don’t try and re-invent the wheel, and passwords, or
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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 187
Coding Projects & Ideas

Python Beginner’s Mistakes


Python is a relatively easy language to get started in where there’s plenty of room for
the beginner to find their programming feet. However, as with any other programming
language, it can be easy to make common mistakes that’ll stop your code from running.

DEF BEGINNER(MISTAKES=10)
Here are ten common Python programming mistakes most beginners find themselves making. Being able to identify these
mistakes will save you headaches in the future.

VERSIONS INDENTS, TABS AND SPACES


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

THE INTERNET COMMENTING


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

Your Unique Download ID Code:


0000 0919 MS26 BMD
188 www.bdmpublications.com
Python Beginner’s Mistakes

COUNTING LOOPS COLONS


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

CASE SENSITIVE
Python is a case sensitive programming language, so you will need
to check any variables you assign. For example, Lives=10 is a
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.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 189
Coding Projects & Ideas

C++ Beginner’s Mistakes


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

VOID(C++, MISTAKES)
Admittedly it’s not just C++ beginners that make the kinds of errors we outline on these pages, even hardened coders are
prone to the odd mishap here and there. Here are some common issues to try and avoid.

UNDECLARED IDENTIFIERS STD NAMESPACE


A common C++ mistake, and to be honest a common mistake with Referencing the Standard Library is common for beginners
most programming languages, is when you try and output a variable throughout their code, but if you miss the std:: element of a
that doesn’t exist. Displaying the value of x on-screen is fine but not statement, your code errors out when compiling. You can combat
if you haven’t told the compiler what the value of x is to begin with. this by adding:
using namespace std;
Under the #include part and simply using cout, cin and so on from
then on.

SEMICOLONS GCC OR G++


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

Your Unique Download ID Code:


0000 0919 MS26 BMD
190 www.bdmpublications.com
C++ Beginner’s Mistakes

COMMENTS (AGAIN) TOO MANY BRACES


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

QUOTES
Missing quotes is a common mistake to make, for every level of user.
Remember that quotes need to encase strings and anything that’s
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

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 191
Coding Projects & Ideas

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?

TWITTER OPEN PROJECTS


Twitter isn’t all trolls and antagonists, among the well-publicised Look for open source projects that you like the sound of and offer
vitriol are some genuine people who are more than willing to spread to contribute to the code to keep it alive and up to date. There are
their coding knowledge. We recommend you find a few who you can millions of projects to choose from, so contact a few and see where
relate to and follow them. Often they post great tips, hacks and fixes they need help. It may only be a minor code update but it’s a noble
for common coding problems. occupation for coders to get into.

KEEP CODING SHARE SKILLS


If you’ve mastered Python fairly well, then turn your attention to Become more active on coding and development knowledge sites,
C++ or even C#. Still keep your Python skills going but learning a new such as StackExchange. If you have the skills to start and help others
coding language keeps the old brain ticking over nicely and gives you a out, not only will you feel really good for doing so but you can also
view into another community, and how they do things differently. learn a lot yourself by interacting with other members.

Your Unique Download ID Code:


0000 0919 MS26 BMD
192 www.bdmpublications.com
Where Next?

GOING MOBILE PORTFOLIOS


The mobile market is a great place to test your coding skills and If you’ve learned how to code with an eye for a developer job in
present any games or apps you’ve created. If your app is good, then the future, then it’s worth starting to build up an online portfolio
who knows, it could be the next great thing to appear on the app of code. Look at job postings and see what skills they require,
stores. It’s a good learning experience nevertheless, and something then learn and code something with those skills and add it to the
worth considering. portfolio. When it comes to applying, include a link to the portfolio.

ONLINE LEARNING TEACH CODE


Online courses are good examples of where to take your coding Can you teach? If your coding skills are spot on, consider
skills next, even if you start from the beginner level again. Often, approaching a college or university to see if they have need for a
an online course follows a strict coding convention, so if you’re self- programming language teacher, perhaps a part-time or evening
taught then it might be worth seeing how other developers lay out course. If not teaching, then consider creating your own YouTube
their code, and what’s considered acceptable. how to code channel.

SHARE CODE HARDWARE PROJECTS


Get sharing, even if you think your code isn’t very good. The Contributing to hardware projects is a great resource for proving your
criticism, advice and comments you receive back help you iron out code with others and learning from other contributors. Many of the
any issues with your code, and you add them all to your checklist. developer boards have postings for coders to apply to for hardware
Alternatively your code might be utterly amazing but you won’t projects, using unique code to get the most from the hardware that’s
know unless you share it. being designed.

Your Unique Download ID Code:


0000 0919 MS26 BMD
www.bdmpublications.com 193
A5 Readly BDM Ad.qxp_OFC.qxd 15/10/2019 13:00 Page 2

Black Dog Media

Master Your Tech From Beginner to Expert


To continue learning more about your tech visit us at:
www.bdmpublications.com
FREE Tech Guides

PC & Windows 10 Samsung & Android

Apple iPhone, iPad, Photography, Coding Python,


Mac, MacBook & Watch Photoshop & Lightroom Raspberry Pi & Linux

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.

Projects & Ideas


Sink your coding teeth into some cool projects
and interesting ideas available for you. Utilise your
new-found skills to track the ISS in real-time, create
animations using ASCII characters, learn some retro
coding, and add effects to your code such as a
loading screen.
Learning to code is fun and fascinating with
The Complete Coding Manual, so unleash your
imagination and start coding!

Your Unique Download ID Code:


0000 0919 MS26 BMD

Manual Series - The Complete Coding Manual - Vol 21.indd 3 03/01/2020 11:13:47

You might also like