30% found this document useful (10 votes)
2K views

The Ultimate Python Coding

The ultimate Python coding
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
30% found this document useful (10 votes)
2K views

The Ultimate Python Coding

The ultimate Python coding
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 194

W

 


NE

PYTHON
 



  
   

60 GFRRAEMES
PRTOODOWNLOAD
e
Details insid
















PAGES 

Learn the latest Featuring Python Packed with top


version of Python program listings tips and tutorials
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
G Print & digital editions
G Featuring the very latest updates
G Step-by-step tutorials and guides
G Created by BDM experts
Check out our latest titles today!

PLUS

SPECIAL DEALS
and Bonus Content
Sign up to our monthly newsletter
bdmpublications.com/ultimate-photoshop and get the latest updates, offers
Buy our Photoshop guides and download tutorial and news from BDM. We are here
images for free! Simply sign up and get creative. to help you Master Your Tech!
 


PYTHON
   

 

   
 %##%# %"!%$%!%%#%!$$%# $%#!%!$%!%"$%$ "%
!#%##$ %# ##$% "!% "!% %#%#"# "%!#%
##$%"#"%# %"#$%"$%!%% "!%
" %$# %"!% $%!$% $%
#%%
"%! %"%!"$%!#%##$ %#%"%#%"$%#!%
!"$%!$#"%  "$ %#%#"! %# ##$%"!#%
" %"$%$#%!$%
!%$"$ $%!#$ %!%#"%"!%$#%#%$% %!% %#"%"!%
 ! $%!%"$%#%$#"$% !$"%!%"$%!"$%"#"%! %!%"$%
#%" % $%%#"#% $" " %#%$$$ %!%$#%!$"%#%!$

"%"$ $%#$ %#$%"$%$ $"#%""!# %"#"%%$%!%!$ %"!%


"$%!$ %!%%!% "%$$%!%!$%"!%"#% ##$ %$ %#
$$ ! % $%"% "!%!$ %#%%#%##"% " %!
#"#% $#% "!% %$#"%% !%#"%#$%!%#"%!% $" %$"%!
Contents

Contents
out
Check Portal
Code
BDM’s

FR E E
60 programs
n
Pytho nes of code
li
21,500 https://
Visit: ions.co
m/
b licat
bdmpu e-portal
c d
o

36
First Steps into Python
38 Starting Python for the First Time
40 Your First Code
6 42 Saving and Executing Your Code
44 Executing Code from the Command Line
Print (“The World of Code”) 46 Numbers and Expressions
48 Using Comments
8 Being a Programmer
50 Working with Variables
10 A Brief History of Coding
52 User Input
12 Choosing a Programming Language
54 Creating Functions
14 Creating a Coding Platform
56 Conditions and Loops
16 Using Virtual Machines
58 Python Modules
18 Equipment You Will Need
60 Python Errors
62 Combining What You Know So Far

64
Manipulating Data
20 66 Lists
68 Tuples

Welcome to Python 70 Dictionaries


72 Splitting and Joining Strings
22 Why Python? 74 Formatting Strings
24 What can You Do with Python? 76 Date and Time
26 Python in Numbers 78 Opening Files
28 How to Set Up Python in Windows 80 Writing to Files
30 How to Set Up Python in Linux 82 Exceptions
32 Python on the Pi 84 Python Graphics
34 Getting to Know Python 86 Combining What You Know So Far

4 www.bdmpublications.com
Contents

Master Python with the help of our fantastic Code


Repository, featuring code for games, tools and
more. See page 148 for more details.

88 148
Working with Modules Code Repository
90 Calendar Module 150 Python File Manager
92 OS Module 152 Number Guessing Game
94 Using the Math Module 154 Polygon Circles
96 Random Module 155 Random Number Generator
98 Tkinter Module 156 Random Password Generator
100 Pygame Module 157 Keyboard Drawing Script
104 Basic Animation 158 Pygame Text Examples
106 Create Your Own Modules 159 Google Search Script
160 Text to Binary Convertor
162 Text Adventure Script

108 164
165
Mouse Controlled Turtle
Python Alarm Clock
166 Vertically Scrolling Text
Learning Linux 168 Python Digital Clock
170 Python Scrolling Ticker Script
110 What is Linux?
171 Simple Python Calculator
112 Why Linux?
172 Playing Music with the Winsound Module
114 Using the Filesystem
174 Hangman Game Script
116 Listing and Moving Files
118 Creating and Deleting Files
120 Create and Remove Directories
122 Copying, Moving and Renaming Files
124 Using the Man Pages
126 Editing Text Files 176
128 Getting to Know Users
130 Ownership and Permissions Coding Projects & Tips
132 Useful System and Disk Commands
134 Managing Programs and Processes 178 Creating a Loading Screen
136 Input, Output and Pipes 180 Text Animations
138 Fun Things to Do in the Terminal 182 Tracking the ISS with Python
140 More Fun Things to Do in the Terminal 186 Using Text Files for Animation
142 Linux Tips and Tricks 188 Passing Variables to Python
144 Command Line Quick Reference 190 Python Beginner’s Mistakes
146 A-Z of Linux Commands 192 Glossary of Python Terms

www.bdmpublications.com 5
Index

Print (“The
World of Code”)

6 www.bdmpublications.com
Print (“The World of Code”)

Where to start learning how to code?


5emarNably this is the most diƯcult
step. There are plenty of programming
languages out there and a seemingly
unlimited number of tools to help you
achieYe what you want but where do
you begin?
,n this section we looN at what you will
need to taNe those Ƭrst tentatiYe steps
into the world of coding. <ou wonot
suddenly become a programmer in
twenty-four hours learning how to code
properly taNes time and patience. %ut
with a little help you can master the
basics and start your coding Mourney.

8 Being a Programmer
10 A Brief History of Coding
12 Choosing a Programming Language
14 Creating a Coding Platform
16 Using Virtual Machines
18 Equipment You Will Need

www.bdmpublications.com 7
Print (“The World of Code”)

Being a Programmer
Programmer, developer, coder, they’re all titles for the same occupation, someone who
creates code. What they’re creating the code for can be anything from a video game
to a critical element on-board the International Space Station. How do you become a
programmer though?

8 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 diƪerent 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 stuƪ
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 oƪered, moreover it was the fact that for the Ƭrst 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 Ƭnances. 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 Ƭrst 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 Ƭnish 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 beneƬcial 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 Ƭnal product. While you may only
be expected to create a small element of that Ƭnal 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!

www.bdmpublications.com 9
Print (“The World of Code”)

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 Ƭfty 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 ]eros, on or oƪ states. This works
for a modern computer and even the oldest known computational device.

~87 BC ~850 AD 1800 184Ǖ184 190Ǖ1950

It’s diƯcult to pinpoint an exact


start of when humans began to
‘program’ a device. However,
it’s widely accepted that the
Antikythera Mechanism is possibly
the Ƭrst ‘coded’ artefact. It’s Joseph Marie Jacquard invents a
dated to about 87 BC and is an programmable loom, which used cards with
ancient Greek analogue computer punched holes to create the textile design.
and orrery used to predict However, it is thought that he based his
astronomical positions. design on a previous automated weaving
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 using the engine. This is
Book of Ingenious Devices in around recognised as the Ƭrst
850 AD. Among the inventions listed computer program. Not
was a mechanical musical instrument: bad, considering there
a hydro-powered organ that played were no computers
interchangeable cylinders automatically. available at the time.

10 www.bdmpublications.com
A Brief History of Coding

During the Second World From the 1970s, the development of the likes of C, SQL, C with
War, signiƬcant 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 for
cryptographic machines used ordinary folk to buy. This led to a boom in home/bedroom coders
to decipher military codes 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,
they could also freely share their code and
source other code to improve their own.

The Ƭrst true computer code was


Assembly Language (ASM) or
Regional Assembly Language. ASM Admiral Grace Hopper was part of
was speciƬc to the architecture the team that developed the UNIVAC
of the machine on which it was I computer and she eventually
being used. In 1951, programming developed a compiler for it. In time,
languages fell under the generic the compiler she developed became
term Autocode. Soon languages COBOL (Common Business-oriented
such as IPL, FORTRAN and ALGOL Language), a computer language that’s
58 were developed. still in use today.

www.bdmpublications.com 11
Print (“The World of Code”)

Choosing a
Programming
/anguage
It would be impossible to properly
explain every programming language in
a single book of this size. New languages
and ways in which to ‘talk’ to a computer
or device and set it instructions are being
invented almost daily; and with the
onset of quantum computing, even more
complex methods are being born. Here
is a list of the more common languages
along with their key features.

12 www.bdmpublications.com
Choosing a Programming Language

SQL SQL stands for Structured Query Language. SQL is a standard language
for accessing and manipulating databases. Although SQL is an ANSI
(American National Standards Institute) standard, there are diƪerent 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 JavaScript (often shortened to JS) is a lightweight,


interpreted, object-oriented language with Ƭrst 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 Java is the foundation for virtually every type of networked application
and is the global standard for developing enterprise software, web-
based content, games and mobile apps. The two main components of the Java
platform are the Java Application Programming Interface (API) and the Java Virtual
Machine (JVM) that translates Java code into machine language.

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


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

PYTHON Python is a widely used high level programming language used


for general purpose programming, created by Guido van
Rossum and Ƭrst 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++ C++ (pronounced cee plus plus) is a general purpose programming


language. It has imperative, object-oriented and generic programming
features. It was designed with a bias toward system programming and embedded,
resource-constrained and large systems, with performance, eƯciency and Ʈexibility
of use as its design highlights.

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


Matsumoto, blended parts of his favourite languages (Perl,
Smalltalk, Eiƪel, Ada and Lisp) to form a new language. From its release in 1995,
Ruby has drawn devoted coders worldwide. Ruby is seen as a Ʈexible language;
essential parts of Ruby can be removed or redeƬned, at will. Existing parts can be
added to.

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


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

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


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

www.bdmpublications.com 1
Print (“The World of Code”)

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 speciƬc, 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 Ƭrst tentative
steps into the wider world of coding.

HARDWARE SOFTWARE
Thankfully, coding at the In terms of software,
foundation level doesn’t most of the development
require specialist equipment, environments - the tools
or a top of the range, liquid that allow you to code,
hydrogen-cooled PC. If you compile the code and
own a computer, no matter execute it - are freely available to download and install. There
how basic, you can begin to learn how to code. Naturally, if are some specialist tools available that will cost, but at this level
your computer in question is a Commodore 64 then you may they’re not necessary; so don’t be fooled into thinking you need to
have some diƯculty following a modern language tutorial, but purchase any extra software in order to start learning how to code.
some of the best programmers around today started on an
8-bit machine, so there’s hope yet. Over time, you may Ƭnd yourself changing from the mainstream
development environment and using a collection of your own,
Access to the Internet is necessary to download, install and discovered, tools to write your code in. It’s all personal preference
update the coding development environment, alongside a in the end and as you become more experienced, you will start
computer with either: Windows 10, macOS, or Linux installed. to use diƪerent tools to get the Mob done. Some environments
You can use other operating systems, but these are the ‘big will enhance sections of code, making it easier to read, others will
three’ and you will Ƭnd that most code resources are written allow quick compiling and execution. It’s all a matter of testing
with one, or all of these, in mind. and experience.

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 conƬnes of the software
the world, so it’s natural itself. The installed OS will allocate user-deƬned resources from the
that the vast maMority 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 enMoy an equal number of coding tools to their machine is that you can work
Windows counterparts. In fact, you will probably Ƭnd that a with Linux, for example, without
lot of professional coders use a Mac over a PC, simply because it aƪecting 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
Ƭlesystems 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 diƪerent 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 diƪerent 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 conƬguration 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 speciƬcally 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 Ƭnd, 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 aƪecting 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 MINI; 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 Must 13 x 13 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
diƪerent hardware, in the form of robotics and electronics and memory available, you’re able to create a computer that can
proMects, as well as oƪering 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 Ƭfty, or so, to increase the speciƬcations, but
consider that a license for Windows 10 Pro alone costs £21
Whichever method you choose, remember that your coding
from the Microsoft Store and you can begin to see the beneƬts
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.

www.bdmpublications.com 15
Print (“The World of Code”)

Using Virtual Machines


A Virtual Machine allows you to run an entire operating system from within an app
on your desktop. This way, you’re able to host multiple systems in a secure, safe and
isolated environment. In short, it’s an ideal way to code.

Sounds good, but what e[actly is a Virtual Machine and how


does it work?
The oƯcial deƬnition of a virtual machine is ‘an eƯcient, isolated
duplicate of a real computer machine’. This basically means that a
virtual machine is an emulated computer system that can operate in
exactly the same way as a physical machine, but within the conƬnes
of a dedicated virtual machine operator, or Hypervisor.

The Hypervisor itself, is an app that will allow you to install a


separate operating system, creating a virtual computer system
within itself complete with access to the Internet, your home
network and so on.

The Hypervisor will take resources from the host system - your
physical computer, to create the virtual computer. This means that
part of your physical computer’s: memory, CPU, hard drive space
and other shared resources, will be set aside for use in the virtual Youore able to install Linu[, and code inside a virtual
machine and therefore won’t be available to the physical computer machine on a Windows 10 host.
until the hypervisor has been closed down.

Black Dog This resource overhead


VIRTUAL OS
NEW Linux Mint 19.1 ¦ Scripting ¦ Python & C++
i-Tech Series
can be crippling for the From within a hypervisor you’re able to run a number of diƪerent

Coding for physical machine if you


don’t already have enough
operating systems. The type of OS depends greatly on the
hypervisor you’re running, as some are better at emulating a

Linux
Master Linux and expand your programming skills

FREE
memory, or hard drive
space available, or your
computer has a particularly
slow processor. While it’s
particular system over others. For example, VirtualBox, a free and
easy to use hypervisor from Oracle, is great at running Windows
and Linux virtual machines, but isn’t so good at Android or macOS.
QEMU is good for emulating ARM processors, therefore ideal for
FULLY
UPDATED Code
Downlo entirely possible to run Android and such, but it can be diƯcult to master.
EDITION ad
virtual machines on as little
With th
is issue

as 2GB of memory, it’s not There are plenty of hypervisors available to try for free, with an
advisable. Ideally, you will equal amount commercially available that are signiƬcantly more
need a minimum of 8GB
£9.99
Volume 38
US$19.99
powerful and oƪer better features. However, for most users, both
of memory (you can get beginner and professional, VirtualBox does a good enough Mob.
Can$24.50
Aus$20.25
NZ$19.99
100% INDEPENDENT

away with 4GB, but again,


your physical computer Within a hypervisor, you’re able to set up and install any of the
e.
..
will begin to suƪer with newer distributions of Linux, or if you feel the need, you’re also able
Packed with
sid
Learn Python 3 Start to learn Discover the world
In top tips and
tutorials
and apply it to real
world programs
the basics
of C++
of free software
with Linux
the loss of memory to the to install some of the more antiquated versions. You can install early
virtual machine), at least 25 versions of Windows, even as far back as Windows 3 complete with
Our Linu[ titles contain to 50GB of free space on DOS 6.22 – although you may Ƭnd some functionality of the VM lost
steps on how to install a your hard drive and a quad- due to the older drivers (such as access to the network).
hypervisor and OS. core processor (again, you
can have a dual-core CPU, With this in mind then, you’re able to have an installation of Linux
but that can cause a bottleneck on your physical computer). Mint, or the latest version of Ubuntu, running in an app on your
Windows 10 PC. This is the beauty of using a virtual machine.
The limit to how many diƪerent virtual machines you host on your Conversely, if your physical computer has Linux as its installed
physical computer is restricted, therefore, by the amount of physical operating system, then with a hypervisor you’re able to create a
system resources you can allocate to each, while still leaving enough Windows 10 virtual machine – although you will need to have a
for your physical computer to operate on. licence code available to register and activate Windows 10.

16 www.bdmpublications.com
Using Virtual Machines

Using virtual machines removes the need to dual-boot. Dual-booting


is having two, or more, physical operating systems installed on
ADVANTAGES FOR CODERS
the same, or multiple, hard drives on a single computer. As the For the coder, having a virtual machine setup oƪers many
computer powers up, you’re given the option to choose which OS advantages, the most popular being cross-platform code. Meaning if
you want to boot into. While this sounds like a more ideal scenario you write code within Windows 10, then with an installation of a
it isn’t always as straight forward as it sounds, as all the operating Linux distro in a hypervisor, you’re able to quickly and eƪortlessly
systems that are booted into will have full access to the computer’s power up the virtual machine and test your code in a completely
entire system resources. diƪerent operating system. From this, you’re able to iron out any
bugs, tweak the code so it works better on a diƪerent platform and
The problems with dual-booting come when one of the operating expand the reach of your code to non-Windows users.
systems is updated. Most updates cover security patching, or bug
Ƭxing, however, some updates can alter the core - the kernel, of The advantage of being able to conƬgure a development
the OS. When these changes are applied, the update may alter the environment, in speciƬc ways for speciƬc proMects, is quite
way in which the OS starts up, meaning the initial boot choice you invaluable. Using a virtual machine setup greatly reduces the
made could be overwritten, leaving you without the ability to access uncertainties that are inherent to having multiple versions of
the other operating systems installed on the computer. To rectify programming languages, libraries, IDEs and modules installed, to
this, you’ll need to access the Master Boot Record and alter the support the many diƪerent proMects you may become involved in as
conƬguration to re-allow booting into the other systems. There’s a coder. Elements of code that ‘talk’ directly to speciƬcs of an
also the danger of possibly overwriting the Ƭrst installed OS, or operating system can easily be overcome, without the need to
overwriting data and more often than not, most operating systems clutter up your main, host system with cross-platform libraries,
don’t play well when running side-by-side. Indeed, while good, dual- which in turn may have an aƪect on other libraries within the IDE.
booting has more than its fair share of problems. In contrast, using a
virtual machine environment, while still problematic at times, takes Another element to consider is stability. If you’re writing code that
out some of the more nasty and disastrous aspects of using multiple could potentially cause some instability to the core OS during its
operating systems on a single computer. development phase, then executing and testing that code on a
virtual machine makes more sense than testing it on your main
computer; where having to repeatedly reboot, or reset something
Even old operating systems can be run inside a
due to the code’s
virtual machine.
instabilities, can
become
ineƯcient and
Must plain
annoying.

The virtual
machine
environment can
be viewed as a
sandbox, where Coding in Python on the Raspberry
you’re able to test Pi Desktop OS inside a VM on
unsecure, or Windows 10!
unstable code
without it causing harm, or doing damage, to your main, working
computer. Viruses and malware can be isolated within the VM
without infecting the main computer, you’re able to set up
anonymity Internet use within the VM and you’re able to install
third-party software without it slowing down your main computer.
Virtual machines can be as simple, or as comple[ as your
needs reTuire.

GOING VIRTUAL
While you’re at the early stages of coding, using a virtual machine
may seem a little excessive. However, it’s worth looking into because
coding in Linux can often be easier than coding in Windows, as some
versions of Linux have IDEs pre-installed. Either way, virtualisation of
an operating system is how many of the professional and successful
coders and developers work, so getting used to it early on in your
skill set is advantageous.

To start, look at installing VirtualBox. Then consider taking a look


at our Linux titles, https://bdmpublications.com/?s linu[ postB
type product, to learn how to install Linux in a virtual environment
and how best to utilise the operating system.

www.bdmpublications.com 17
Print (“The World of Code”)

Equipment You
Will Need
You can learn Python with very little hardware or initial Ƭnancial investment. You
don’t need an incredibly powerful computer and any software that’s required is
freely{available.

WHAT WEoRE USING


Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linu[, 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 oƪering advanced features. There are many diƪerent IDEs available, so Ƭnd
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++, oƪers 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
eƯcient 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 Ʈow like water. Understand you’re learning
something entirely new, and you will get there.

18 www.bdmpublications.com
Equipment You Will Need

THE RASPBERRY PI
Why use a Raspberry Pi? The Raspberry Pi is a tiny computer thatos very cheap to purchase, but oƪers the user a fantastic learning
platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many modules and e[tras.

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 Ƭnd 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 Ƭrst Raspberry Pi,
set it up and use NEW ¦ Py
thon 3 ¦ C+
+ ¦ Raspbe
it; there are some great step- rry Pi 4 ¦
Projects
The Raspberry Pi’s main operating system is a Debian-based
by-step proMect examples
BD
Ultimate M s

Raspber
Series

Linux distribution that comes with everything you need in


a simple to use package. It’s streamlined for the Pi and is an
and guides to get the most
from the Tips, ry Pi
ideal platform for hardware and software proMects, Python Tricks & F
ixes
Raspberry
Raspberry NEW! ¦ R
aspberry
programming and even as a desktop computer. Pi 3 ¦ Lin
ux ¦ Codin Helping
you to un
Pi too. g lock the
power of

Pi
BD
Ultimate M s the Rasp
Serie b s erry Pi
Raspberry

Raspb

The Begin erry


Pi - Tips,

P i4
ners Guid
Tricks

Upd a
Editio te
Unleash
e
& Fixes

the codin n
g power
of the am
Volume

Featuring azing Ras


Python, pberry Pi
C++, and Pi
35

Projects!

tips & tricks


£9.99
Volume
35
US$19.9
9
Can$25.50
Aus$21.25
NZ$20.9
9
100% INDEP
ENDENT

Create am
azing
Pi projec Master th
ts e
Raspberry
Pi

160
PA
packe GES
dw
... prograith project
ide m
and m ming
s,
Ins Packed w ore
ith top tip
and tuto s Featurin
rials g
Learn co
ding with tutorials in-depth
Python an for Rasp
D iscover so bian Volume
d C++ US$19.9
9/Ca n$24.50
33 £9.99

fantastic me
/Aus$20
.25/NZ$
19.99

Packed w Pi projec
ts
ENDENT

ith top tip


and tuto s
100% INDEP

rials Featurin
g
Learn co
ding with tutorials in-depth
Python an for Rasp
d C++ Discover bian
some

www.bdmpublications.com 19
Index

Welcome
to Python

20 www.bdmpublications.com
Welcome to Python

Python is a fantastic programming


language. With it, you can create
everything from a simple program to
backup the pictures on your computer,
through to analysing petabytes of data.
Not only is Python the programming
language of choice for some of the
biggest companies in the world, it’s also
one of the easiest to learn.
This chapter will help you get Python set
up on your computer, and introduce you to
this remarkable and powerful language.

22 Why Python?
24 What can You Do with Python?
26 Python in Numbers
28 How to Set Up Python in Windows
30 How to Set Up Python in Linux
32 Python on the Pi
34 Getting to Know Python

www.bdmpublications.com 21
Welcome to Python

Why Python?
There are many diƪerent 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 scientiƬc 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-deƬnition 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 diƪer 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

22 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 Ƭve 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, eƪective 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 beneƬt 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


and makes for an ideal beginner’s programming language.

www.bdmpublications.com 23
Welcome to Python

What can You


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

Python’s ability to create highly readable code within a small set You’ll Ƭnd lots of examples of this, where Python is acting behind
of instructions has a considerable impact on our modern digital the scenes. This is why it’s such an important language to learn.
world. From the ideal, Ƭrst programmers’ choice to it’s ability to
create interactive stories and games; from scientiƬc applications to
artiƬcial Intelligence and web-based applications, the only limit to
Python is the imagination of the person coding in it.

It’s Python’s malleable design that makes it an ideal language for


many diƪerent situations and roles. Even certain aspects of the
coding world, that require more eƯcient code, still use Python.
For example, NASA utilises Python both as a stand-alone language
and as a bridge between other programming languages. This way,
NASA scientists and engineers are able to get to the data they
need without having to cross multiple language barriers; Python
Ƭlls the gaps and provides the means to get the job done.

BIG DATA
Big data is a buzzword you’re likely to have come across in the last couple of years.
Basically, it means extremely large data sets that are available for analysis to reveal
patterns, trends and interactions between humans, society and technology. Of course,
it’s not just limited to those areas, big data is currently being used in a variety of
industries, from social media to health and welfare, engineering to space exploration
and beyond.

Python plays a substantial role in the world of big data. It’s extensively used to
analyse huge chunks of the available big data and extract speciƬc information based
on what the user/company requires from the wealth of numbers present. Thanks to an
impressive set of data processing libraries, Python makes the act of getting to the data,
in amongst the numbers, that counts and presenting it in a fashion that’s readable and
useable for humans.

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

24 www.bdmpublications.com
What can You Do with Python?

ARTIFICIAL INTELLIGENCE
ArtiƬcial Intelligence and Machine Learning are two of the most
groundbreaking aspects of modern computing. AI is the umbrella
term used for any computing process wherein the machine is
doing something intelligent, working and reacting in similar ways
to humans. Machine Learning is a subset of AI and provides the
overall AI system with the ability to learn from
its experiences.

However, AI isn’t simply the creation of autonomous robots


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

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


Instagram and so on. Have you ever looked up a celebrity on
Instagram and then discovered that your searches within other
social media platforms are now speciƬcally targeted toward
similar celebrities? This is a prime example of using AI in
targeted advertising and behind the code and algorithms that
predict what you’re looking for, is Python. GAMING
Spotify, for example, uses Python based code, among Although you won’t Ƭnd too many triple-A rated games coded using
other things, to analyse your musical habits and Python, you may be surprised to learn that Python is used as an
oƪer playlists based on what you’ve listened to extra on many of the high-ranking modern games.
in the past. It’s all clever stuƪ and, moving
forward, Python is at the forefront of the way The main use of Python in gaming comes in the form of scripting,
the Internet will work in the future. where a Python script can add customisations to the core game
engine. Many map editors are Python compatible and you will also
come across it if you build any mods for games, such as The Sims.

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


WEB DEVELOPMENT Playing Games) available utilise Python as a companion language for
the server-side elements. These include: code to search for potential
cheating, load balancing across the game’s servers, player skill
Web development has moved on considerably since the early
matchmaking and to check whether the player’s client-side game
days of HTML scripting in a limited text editor. The many
matches the server’s versions. There’s also a Python module that
frameworks and web management services available now
can be included in a Minecraft server, enabling the server admin to
means that building a page has become increasingly complex.
add blocks, send messages and automate a lot of the background
complexities of the game.
With Python, the web developer has the ability to create
dynamic and highly secure web apps, enabling interaction with
other web services and apps such as Instagram and Pinterest.
Python also allows the collection of data from other websites
and even apps built within other websites.
PYTHON EVERYWHERE
As you can see, Python is quite a versatile
programming language. By learning Python,
you are creating a well-rounded skillset that’s
able to take you into the next generation of
computing, either professionally or simply as
a hobbyist.

Whatever route you decide to take on your


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

www.bdmpublications.com 25
Welcome to Python
Pytho
n cre
Ross ator G
um n uido
amed
There’s a readi
ng sc Pytho Van
ripts n afte
lot to like about Pyth from M r
on’s F ont
lying
Python, but don’t just Circu y
s.
take our word for it. Here are
some ama]ing facts and Ƭgures
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.

26 www.bdmpublications.com
Python in Numbers

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

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.

www.bdmpublications.com 27
Welcome to 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 you’re going to have to install it yourself manually.
Thankfully, it’s an easy process to follow.

STEP 1 Start by opening your web browser to www.python. STEP 3 Choosing the Customise option allows you to
org/downloads/. Look for the button detailing the specify certain parameters, and 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 Ƭx and update. Therefore, don’t worry if with Python, thankfully) installers can include unwanted additional
you see Python 3.7.3, or more, as long as it’s Python 3, the code in features. On the Ƭrst screen available, ensure all boxes are ticked
this book will work Ƭne. 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 Ƭle to your Downloads folder. When the additions to Python. Ensure the Associate Ƭle with
Ƭle 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.

28 www.bdmpublications.com
How to Set Up Python in Windows

STEP 5 You may need to conƬrm the installation with the STEP 8 Clicking on the IDLE (Python 3.7 32-bit) link will
Windows authentication notiƬcation. Simply click launch the Python Shell, where you can begin
Yes and Python will begin to install. Once the installation is complete your Python programming journey. Don’t worry if your version is
the Ƭnal Python wizard page will allow you to view the latest release newer as long as it’s Python 3.x our code works inside your
notes, and follow some online tutorials. Python 3 interface.

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 the
shield detailed Disable Path Length Limit. This will allow Python Command Prompt link. Click it to get to the Windows command line
to bypass the Windows 260 character limitation, enabling you to environment. To enter Python within the command line, you need
execute Python programs stored in deep folders arrangements. to type: python and press Enter.
Again, click Yes to authenticate the process; then you can Close the
installation window.

STEP 7 STEP 10 The command line version of Python works in


much the same way as the Shell you opened in
Windows 10 users can now Step 8; note the three left-facing arrows (>>>). Whilst it’s a perfectly
Ƭnd the installed Python Ƭne environment, it’s not too user-friendly, so leave the command
3.x within the Start button line for now. Enter: exit() to leave and close the Command
Recently Added section. Prompt window.
The Ƭrst link, Python 3.7
(32-bit) will launch the
command line version of
Python when clicked (more
on that in a moment). To
open the IDLE, type IDLE
into Windows start.

www.bdmpublications.com 29
Welcome to 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  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 diƯcult to nail down just one-way of doing something. Diƪerent
distributions go about installing software in diƪerent 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.

30 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 diƪerent 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
FRQÀJXUH
sudo make altinstall
This could take a while, depending on the speed of your computer.
Once Ƭnished, 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.

www.bdmpublications.com 31
Welcome to Python

Python on the Pi
If you’re considering on which platform to install and use Python, then give some
thought to one of the best coding bases available: the Raspberry Pi. The Pi has many
advantages for the coder: it’s cheap, easy to use, and extraordinarily Ʈexible.

THE POWER OF PI
While having a far more powerful coding platform on which to write and test your code is ideal, it’s not often feasible. Most of
us are unable to jump into a several hundred-pound investment when we’re starting oƪ and this is where the Raspberry Pi can
help out.

While having a far more powerful coding platform on which to for space and money, then for around ~60, buying one of the many
write and test your code is ideal, it’s not often feasible. Most of us kits available will provide the Pi with a pre-loaded SD card (with the
are unable to jump into a several hundred-pound investment when latest Raspbian OS), a case, power socket and cables, this is a good
we’re starting oƪ and this is where the Raspberry Pi can help out. idea as you could, with very little eƪort, leave the Pi plugged into the
wall under a desk, while still being able to connect to it and code.
The Raspberry Pi is a fantastic piece of modern hardware that
has created, or rather re-created, the fascination we once all had The main advantage is, of course, the extra content that the
about computers, how they work, how to code and foundation Raspberry Pi Foundation has included out of the box. The reason
level electronics. Thanks to its unique mix of hardware and custom for this is that the Raspberry Pi’s goal is to help educate the
software, it has proved itself to be an amazing platform on which to user, whether that’s coding, electronics, or some other aspect of
learn how to code; speciƬcally, using Python. computing. To achieve that goal the Pi Foundation includes diƪerent
IDEs for the user to compile Python code on; as well as both Python
While you’re able, with ease, to use the Raspberry Pi to learn to 2 and Python , there’s even a Python library that allows you to
code with other programming languages, it’s Python that has been communicate with Minecraft.
Ƭrmly pushed to the forefront. The Raspberry Pi uses Raspbian
as its recommended, default operating system. Raspbian is a There are other advantages, such as being able to combine Python
Linux OS, or to be more accurate, it’s a Debian-based distribution code with Scratch (an Object-Oriented programming language
of Linux. This means that there’s already a built-in element developed by MIT, for children to understand how coding works) and
of Python programming, as opposed to a fresh installation of being able to code the GPIO connection on the Pi to further control
Windows 10, which has no Python-speciƬc base. However, the any attached robotics or electronics projects. Raspbian also includes
Raspberry Pi Foundation has gone the extra mile to include a vast a Sense HAT Emulator (a HAT is a hardware attached piece of
range of Python modules, extensions and even examples, out of circuitry that oƪers diƪerent electronics, robotics and motorisation
the box. So, essentially, all you need to do is buy a Raspberry Pi, projects to the Pi), which can be accessed via Python code.
follow the instructions on how to set one up (by using one of our
excellent Raspberry Pi guides found at https://bdmpublications. Consequently, the Raspberry Pi is an excellent coding base, as well
com/?s=raspberry+pi&post_type=product) and you can start as a superb project foundation. It is for these, and many other,
coding with Python as soon as the desktop has loaded. reasons we’ve used the Raspberry Pi as our main Python codebase
throughout this title. While the code is written and performed on a
SigniƬcantly, there’s a lot more to the Raspberry Pi, which makes Pi, you’re also able to use it in Windows, other versions of Linux and
it an excellent choice for someone who is starting to learn how to macOS. If the code requires a speciƬc operating system, then, don’t
code in Python. The Pi is remarkably easy to set up as a headless worry; we will let you know in the text.
node. This means that, with a few tweaks here and there, you’re able
to remotely connect to the Raspberry Pi from any other computer,
Everything you need to learn to code with Python is
or device, on your home network. For example, once you’ve set up
included with the OS!
the remote connectivity options, you can simply plug the Pi into the
power socket anywhere in your house within range of your wireless
router. As long as the Pi is connected, you will be able to remotely
access the desktop from Windows or macOS as easily as if you were
sitting in front of the Pi with a keyboard and mouse.

Using this method saves a lot of money, as you don’t need another
keyboard, mouse and monitor, plus, you won’t need to allocate
suƯcient space to accommodate those extras either. If you’re pushed

32 www.bdmpublications.com
Python on the Pi

PI 4ǕEVER!
Introduced on 24th June 2019, the Raspberry Pi 4 Model B is
a signiƬcant leap in terms of Pi performance and hardware
speciƬcations. It was also one of the quickest models, aside from
the original Pi, to sell out.

With a new 1.5GHz, 64-bit, quad-core ARM Cortex-A72


processor, and a choice of 1GB, 2GB, or 4GB memory
versions, the Pi 4 is one-step closer to becoming
a true desktop computer. In addition, the Pi 4 was
launched with the startling decision to include dual-
monitor support, in the form of a pair of two micro-
HDMI ports. You’ll also Ƭnd a pair of USB .0 ports,
Bluetooth 5.0, and a GPU that’s capable of handing 4K
resolutions and OpenGL ES .0 graphics.

There’s no In short, the Pi 4 is the most powerful of the current Raspberry


such thing as too Pi models. However, the diƪerent memory versions have an
much Pi! increased cost. The 1GB version costs ~4, 2GB is ~44, and the
4GB version will set you back ~54. Remember to also factor in one
or two micro-HDMI cables with your order.

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

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


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

In short, what you see in this book will work with the Raspberry Pi
4 and Raspbian Buster!

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

www.bdmpublications.com 33
Welcome to Python

Getting to
Know Python
P

WHAT IS PROGRAMMING?
It helps to understand what a programming language is before you try to learn one, and Python is no diƪerent. Let’s take a
look at how Python came about and how it relates to other languages.

PYTHON PROGRAMMING RECIPES


Programs are like recipes for computers. A
A programming language recipe to bake a cake could go like this:
is a list of instructions that
a computer follows. These Put 100 grams of self-raising Ʈour in a bowl.
instructions can be as simple Add 100 grams of butter to the bowl.
as displaying your name Add 100 millilitres of milk.
or playing a music Ƭle, or Bake for half an hour.
as complex as building a
whole virtual world. Python
is a programming language
conceived in the late 1980s
CODE
by Guido van Rossum Just like a recipe, a program consists of instructions that you follow
at Centrum Wiskunde & in order. A program that describes a cake might run like this:
Informatica (CWI) in the
bowl = []
Netherlands as a successor to
ÁRXU 
the ABC language.
EXWWHU 
PLON 
Guido van Rossum, the
ERZODSSHQG >ÁRXUEXWWHUPLON@ 
father of Python.
cake.cook(bowl)

PROGRAM COMMANDS
You might not understand some of the Python commands, like bowl.append and cake.cook(bowl).
The Ƭrst is a list, the second an object; we’ll look at both in this book. The main thing to know is
that it’s easy to read commands in Python. Once you learn what the commands do, it’s easy to
Ƭgure out how a program works.

34 www.bdmpublications.com
Getting to Know Python

HIGHǕLEVEL LANGUAGES ZEN OF PYTHON


Computer languages that are easy to read are known as “high-level”. Python lets you access all the power of a computer in a language
This is because they Ʈy high above the hardware (also referred to as that humans can understand. Behind all this is an ethos called “The
“the metal”). Languages that “Ʈy close to the metal,” like Assembly, Zen of Python.” This is a collection of 20 software principles that
are known as “low-level”. Low-level languages commands read a bit inƮuences the design of the language. Principles include “Beautiful
like this: PVJGE[DOHQHTXPVJ. is better than ugly” and “Simple is better than complex.” Type
import this into Python and it will display all the principles.

PYTHON 3 VS PYTHON 2
In a typical computing scenario, Python is complicated somewhat by the existence of two active versions of the language:
Python 2 and Python 3.

WORLD OF PYTHON Python 3.7 is the newest release PYTHON 3.X In 2008 Python 3 arrived with several new
of the programming language. and enhanced features. These features
However, if you dig a little deeper into the Python site, and investigate provide a more stable, eƪective and eƯcient programming
Python code online, you will undoubtedly come across Python 2. environment but sadly, most (if not all) of these new features are
Although you can run Python 3 and Python 2 alongside each other, it’s not compatible with Python 2 scripts, modules and tutorials. Whilst
not recommended. Always opt for the latest stable release as posted not popular at Ƭrst, Python 3 has since become the cutting edge of
by the Python website. Python programming.

PYTHON 2.X So why two? Well, Python 2 was originally 3.X WINS Python 3’s growing popularity has meant that
launched in 2000 and has since then it’s now prudent to start learning to develop
adopted quite a large collection of modules, scripts, users, tutorials with the new features and begin to phase out the previous version.
and so on. Over the years Python 2 has fast become one of the Ƭrst Many development companies, such as SpaceX and NASA use
go to programming languages for beginners and experts to code Python 3 for snippets of important code.
in, which makes it an extremely valuable resource.

www.bdmpublications.com 35
Index

First Steps
into Python

36 www.bdmpublications.com
First Steps into Python

Now that you have the latest version of


Python installed, you can begin to get
programming. These are your Ƭrst steps in
the wider world of Python and we’re here
to help you write your Ƭrst 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.

38 Starting Python for the First Time


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

www.bdmpublications.com 37
First Steps into Python

Starting Python for


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

STARTING PYTHON
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 inƬnite
to try out some simple code and processes. sequence of whole numbers, can easily be added, subtracted,
multiplied, and so on.

38 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 conƬgurable environment. If
exciting. Instead, try this: you don’t like the way the colours are represented,
then you can always change them via Options ! ConƬgure 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 Ƭrst 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 > ConƬgure 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 diƪerent 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

www.bdmpublications.com 39
First Steps into Python

Your First Code


Essentially, you’ve already written your Ƭrst 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 deƬning 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

40 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 Ƭrst 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, deƬning 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 diƪerent 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 Ƭrst steps into the wide
world of Python,

www.bdmpublications.com 41
First Steps into Python

Saving and Executing


Your Code
While working in the IDLE Shell is perfectly Ƭne 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 Ƭrst 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 Ƭle system,
though, it’ll help you out in the future.
print(“Hello everyone!”)

42 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 Ƭle again, as it’s been
modiƬed from before.

STEP 6 This is how the vast majority of your Python code STEP 9 If you click the OK button the Ƭle 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 diƪer, depending on whether you’ve requested a separate if you were to edit a larger Ƭle 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 Ƭle location of the saved Python STEP 10 Now create a new Ƭle. 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 Ƭlename, 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.

www.bdmpublications.com 43
First Steps into Python

Executing Code from


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

COMMAND THE CODE


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

STEP 1 When you Ƭrst 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.

44 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 Ƭles within; you should see
the hello.py Ƭle. 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 Ƭle 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 diƪerent 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.

www.bdmpublications.com 45
First Steps into Python

Numbers and Expressions


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

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 Ʈoats, or Ʈoating 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.

46 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 preƬx
0b to the front. If you want to
10/3
remove the 0b preƬx, 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. speciƬcation, 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 deƬning 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)

www.bdmpublications.com 47
First Steps into Python

Using Comments
When writing your code, the Ʈow, 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
diƯcult 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 Ƭle, 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)

48 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 Ƭrst 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 diƪerent 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. ’’’

www.bdmpublications.com 49
First Steps into Python

Working with Variables


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

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 diƪerent
variables:
age=44
Type (age)
Which, as we know, are integers.

50 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 Ʈoating 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 ‘Ʈoat’, 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 Ʈoats Python
for input from the user, such as a number. for usually converts the integer to a Ʈoat, but should
example, enter: the reverse ever be applied, it’s worth remembering that Python
doesn’t return the exact value. When converting a Ʈoat 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.

www.bdmpublications.com 51
First Steps into Python

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

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”) SULQW ´:HOFRPHµÀUVWQDPHVXUQDPH´,KRSH
ÀUVWQDPH LQSXW ´:KDWLV\RXUÀUVWQDPH"´ you’re well today.”)
print(“Thanks.”)
surname=input(“And what is your surname? “)

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

52 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
SULQW ´+HOOR:KDW·V\RXUQDPH"µ
unhindered. If, however, they enter a name other than David, the
name=input()
guard challenges them to a Ƭght.

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

STEP 7 It’s a good start to a text adventure game, perhaps? STEP 10 And to Ƭnalise the rate and distance code, we can add:
Now we can expand on it, and use the raw input
GLVWDQFH ÁRDW LQSXW ´'LVWDQFH´
from the user to Ʈesh out the game a little:
print(“Time:”, (distance / rate))
if name==”David”:
Save and execute the code, and enter some numbers. Using the
SULQW ´:HOFRPHJRRGVLU<RXPD\SDVVµ
Ʈoat(input element, we’ve told Python that anything entered is a
else:
Ʈoating point number rather than a string.
print(“I know you not. Prepare for battle!”)

www.bdmpublications.com 53
First Steps into Python

Creating Functions
Now that you’ve mastered the use of variables and user input, the next step is to tackle
functions. You’ve already used a few functions, such as the print command, but Python
enables you to deƬne 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-deƬned functions, but since users have created
len(“antidisestablishmentarianism”), and the number 28 many more, they’re not the only ones available.
would return.

54 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 diƪerent 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 Ƭle (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.

www.bdmpublications.com 55
First Steps into Python

Conditions and Loops


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

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:
SULQW ZRUG´LVDIRXUOHWWHUZRUG:HOOGRQHµ
The double equal sign (==) check if something is equal to
something else.

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

56 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: “)
Ƭve-letter word. The Shell will display that it’s not a four-letter word.
word_length=len(word)
if word_length == 4:
SULQW ZRUG´LVDIRXUOHWWHUZRUG:HOO
done.”)
elif word_length == 3:
print (word, “is a three-letter word. Try again.”)
else:
print (word, “is not a four-letter word.”)

LOOPS
Although a loop looks Tuite similar to a condition, they are somewhat diƪerent 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 diƪerence 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 Ƭrst and last numbers used.

www.bdmpublications.com 57
First Steps into Python

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

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 diƪerent 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.

58 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 Ƭnd 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 deƬned 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.

www.bdmpublications.com 59
First Steps into Python

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 rectiƬed with a little patience. The import thing
is to keep looking, experimenting, and testing. Eventually your code will be bug free.

STEP 1 Code isn’t as Ʈuid 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 deƬne 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 Ƭnd 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”.

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

www.bdmpublications.com 61
First Steps into Python

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 deƬnes 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 Ƭnd 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)

62 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 diƪerent 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 diƪerent
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 Ƭnish 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 Ƭnishes. 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() SULQW )RUH5('´?Q7LPHWDNHQµWLPHWLPH 
def calc(n): start_time)

www.bdmpublications.com 63
Index

Manipulating
Data

64 www.bdmpublications.com
Manipulating Data

Data is everything. It’s more valuable


than gold or oil. With data, governments
can change the world, politicians can rise
or fall, and companies, large or small,
can impact our future in ways we
wouldn’t have imagined just a few years
ago. Data is power, and learning how to
manipulate and control it are essential
aspects of any coding language.
Here we’ll take a look at how you can
use date and time functions, write to
Ƭles in your system, and even create
graphical user interfaces that will take
your coding skills to new levels and open
more doors for you.

66 Lists
68 Tuples
70 Dictionaries
72 Splitting and Joining Strings
74 Formatting Strings
76 Date and Time
78 Opening Files
80 Writing to Files
82 Exceptions
84 Python Graphics
86 Combining What You Know So Far

www.bdmpublications.com 65
Manipulating Data

Lists
Lists are one of the most common types of data structures you will comes 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 deƬned 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 Ƭrst 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).

66 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
P\WKLFDOBFUHDWUHV P\WKLFDOBFUHDWXUHV>´*ULIÀQµ@
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 Ƭrst 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.

www.bdmpublications.com 67
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 Ƭxed 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.

68 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 diƪerent 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 Ƭnd 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 Ʈoats. To output the highest and
lowest, use:
print(max(numbers))
print(min(numbers))

www.bdmpublications.com 69
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 Ƭrst,
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 beneƬt 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”}

70 www.bdmpublications.com
Dictionaries

STEP 5 Adding to a dictionary is easy too. You can include STEP 8 Next, we need to deƬne 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.

www.bdmpublications.com 71
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.

72 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

www.bdmpublications.com 73
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 diƪerent 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 signiƬcantly 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 Ƭnd tons of help.
print(“{} hailed from the North, in a cold land
known as {}”.format(name, place))

74 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 Ƭrst 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)) SULQW ´7KHÀUVWOHWWHURI\RXUQDPHLVD^`µ
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))

www.bdmpublications.com 75
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’)

76 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 Ƭle
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.

www.bdmpublications.com 77
Manipulating Data

Opening Files
In Python, you can read text and binary Ƭles 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 Ƭle object, similar to creating a variable, only you pass in the Ƭle 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 Ƭle 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 Ƭle:
by Robert E Howard, and we’ve saved the Ƭle 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 Ƭle into a STEP 4 If you enter poem.read() a second time, you will
variable as an object. You can name the Ƭle object notice that the text has been removed from the
anything you like, but you will need to tell Python the name and Ƭle. You will need to enter poem=open(“C:\\Users\\david\\
location of the text Ƭle you’re opening: Documents\\poem.txt”) again to recreate the Ƭle. 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.

78 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 Ƭrst Ƭve characters, while entering:
lines[0]
poem.read(5) lines[1]
lines[2]
Will display the next Ƭve. 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 Ƭrst 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.

www.bdmpublications.com 79
Manipulating Data

Writing to Files
Being able to read external Ƭles within Python is certainly handy, but writing to a Ƭle
can be even more useful. Using the write() function, you’re able to output the results
of a program to a Ƭle, which you can then use to read() back into Python, or as a text
Ƭle for perusal later.

WRITE AND CLOSE


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

STEP 1 Start by opening IDLE and enter the following STEP 3 However, the actual text Ƭle 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 Ƭle object, but not committed it to the
t=open(“C:\\Users\\david\\Documents\\text.txt”, “w”)
Ƭle itself. Part of the write() function is that we need to commit the
This code will create a text Ƭle, called text.txt in write mode, using changes to the Ƭle, we can do this by entering:
the variable ‘t’. If there’s no Ƭle 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 Ƭle using the write() STEP 4 If you now open the text Ƭle 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: Ƭle. This gives us the foundation for some interesting possibilities,
perhaps the creation of your own log Ƭle, 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.

80 www.bdmpublications.com
Writing to Files

STEP 5 To expand this code, we can re-open the Ƭle using STEP 8 We can pass variables to a Ƭle 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 Ƭle and creating written to a Ƭle. We can call Pi from the Math module, create a new
a new one. For example: Ƭle, and pass the output of Pi into the new Ƭle:
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. SULQW ´?Q:ULWLQJWRDÀOHQRZ«µ 
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, Ƭnish the code with t.close(), and open the Ƭle in a text
pi=math.pi
editor to see the results:
We also need to create a new Ƭle 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 Ƭle location to your own particular
t.close()
system setup.

STEP 7 There are various types of Ƭle access to consider STEP 10 To Ƭnish, we can use string formatting to call the
using the open() function. Each depends on how the variable and write it to the Ƭle, then commit the
Ƭle is accessed, and even the position of the cursor. For example, r+ changes and close the Ƭle:
opens a Ƭle in read and write, and places the cursor at the start of
t.write(“Value of Pi is: {}”.format(pi))
the Ƭle.
t.close()
As you can see from the results, you’re able to pass any variable to
a Ƭle.

www.bdmpublications.com 81
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 Ʈow 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.

82 www.bdmpublications.com
Exceptions

STEP 5 For example, using the divide by zero error, we can STEP 8 Naturally, we can quickly Ƭx 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 Ƭle and write the content then
commit the changes to the Ƭle. The end result will report a diƪerent
try:
set of circumstances, in this case, a successful execution of the code.
D LQW LQSXW ´(QWHUWKHÀUVWQXPEHU´
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 Ƭnally: block, which works in a


similar fashion, but you cannot use else with it. Hint:
You’ll need to delete the textƬle.txt Ƭle from your folder.
try:
W[W RSHQ&??8VHUV??GDYLG??'RFXPHQWV??WH[WÀOH
txt”, “r”)
try:
txt.write(“This is a test. Normal service will
shortly resume!”)
ÀQDOO\
STEP 6 You can use exceptions to handle a variety of useful
SULQW ´&RQWHQWZULWWHQWRÀOHVXFFHVVIXOO\
tasks. Using an example from our previous tutorials,
Have a nice day.”)
let’s assume you want to open a Ƭle and write to it:
txt.close()
try: except IOError:
W[W RSHQ ´&??8VHUV??GDYLG??'RFXPHQWV??WH[WÀOH SULQW ´(UURUXQDEOHWRZULWHWKHÀOH&KHFN
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
SULQW ´(UURUXQDEOHWRZULWHWKHÀOH&KHFN
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 Ƭrst time. Practise, though, and you will get the hang of it.
SULQW ´&RQWHQWZULWWHQWRÀOHVXFFHVVIXOO\
Have a nice day.”)
txt.close()

STEP 7 Obviously this won’t work due to the Ƭle textƬle.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.

www.bdmpublications.com 83
Manipulating Data

Python Graphics
While dealing with text on the screen, either as a game or in a program, is perfectly Ƭne,
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 eƪects.

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 Ʈoor. 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() SULQW ´'UDZLQJDVTXDUH«µ
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.

84 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_Ƭll(), and turtle.end_
h = 450
Ƭll() to Ƭll in the square with the chosen colours; in this case, red
screen = pygame.display.
outline, and yellow Ƭll.
set_mode((w, h))
VFUHHQÀOO ZKLWH
VFUHHQÀOO ZKLWH
screen.blit(img,(0,0))
S\JDPHGLVSOD\ÁLS
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
deƬned 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.
EHJLQBÀOO
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
HQGBÀOO
done()
It’s a diƪerent method,
but very eƪective.

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-deƬned image. Start by opening a up the many functions within the Pygame module too.
browser and Ƭnding an image, then save it to the folder where you
save your Python code.

www.bdmpublications.com 85
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
deƬned 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 deƬne 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
Ƭle called logins.txt.

86 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 Ƭle. 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
Ƭle 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.

www.bdmpublications.com 87
Index

Working with
Modules

88 www.bdmpublications.com
Working with Modules

Modules are where you can take Python


programming to new heights; they are
the key ingredients to better code. You
can create your own modules, or you can
use some of those already available, 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.

90 Calendar Module
92 OS Module
94 Using the Math Module
96 Random Module
98 Tkinter Module
100 Pygame Module
104 Basic Animation
106 Create Your Own Modules

www.bdmpublications.com 89
Working with 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 speciƬc 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 Ƭrst line
print(“>>>>>>>>>>Leap Year Calculator<<<<<<<<<<\n”)
conƬgures TextCalendar to start its weeks on a Sunday; you can opt
\ LQW LQSXW ´(QWHUWKHÀUVW\HDU´
for Monday if you prefer.
\ LQW LQSXW ´(QWHUWKHVHFRQG\HDU´
leaps=calendar.leapdays(y1, y2)
print(“Number of leap years between”, y1, “and”,
\´LVµOHDSV

90 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
\HDU LQW LQSXW ´(QWHUWKH\HDUWRGLVSOD\´ IRUQDPHLQFDOHQGDUPRQWKBQDPH
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. IRUQDPHLQFDOHQGDUGD\BQDPH
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 Ƭle:
import calendar
cal=calendar.TextCalendar(calendar.SUNDAY) import calendar
IRULLQFDOLWHUPRQWKGD\V   FDO RSHQ ´&??8VHUV??GDYLG??'RFXPHQWV??FDOKWPOµ´Zµ
print(i) c=calendar.HTMLCalendar(calendar.SUNDAY)
cal.write(c.formatmonth(2019, 1))
cal.close()
This code will create an HTML Ƭle 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
ZHESDJH´
FDO RSHQ ´&??8VHUV??GDYLG??'RFXPHQWV??FDOKWPOµ´Zµ
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 Ƭle destination.

www.bdmpublications.com 91
Working with 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 Ƭles
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 diƪerent 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 diƪerent 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’)

92 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 Ƭle name for it to work
import os
successfully. However, you can also use the following:
RVPNGLU ´&??%'0??1(:µ
import os
This creates a new directory within the speciƬed Directory (C:\BDM\),
RVV\VWHP ¶¶VWDUWFKURPH´KWWSVZZZ\RXWXEHFRP
named according to the object in the mkdir function (C:\BDM\NEW).
IHHGPXVLFµ·

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


by entering:
import os
RVUHQDPH ´&??%'0??1(:µ´&??%'0??2/'µ
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 RVUPGLU ´&??%'0??2/'µ
example, on a Raspberry Pi you would enter:
import os
RVV\VWHP ¶FKURPLXPEURZVHU´KWWS
EGPSXEOLFDWLRQVFRPµ·

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 Ƭles into it:
import os, shutil, time
t=str(time.strftime(“%Y-%m-%d %H-%M”))
URRWBVUFBGLU U·&??%'0??'RFXPHQWV??·3DWKWR
the source directory
URRWBGVWBGLU ¶&??%DFNXS??·W3DWKWRWKH
EDFNXSGLUHFWRU\
STEP 7 Note, in the previous step’s example the use of
single and double-quotes. The single quotes encase IRUVUFBGLUGLUVÀOHVLQRVZDON URRWBVUFBGLU 
the entire command, and launching Chromium, whereas the double dst_dir = src_dir.replace(root_src_dir, root_
quotes open the speciƬed page. You can even use variables to dst_dir, 1)
open webpages: LIQRWRVSDWKH[LVWV GVWBGLU 
RVPDNHGLUV GVWBGLU
import os
IRUÀOHBLQÀOHV
D ¶VWDUWFKURPH´KWWSZZZJRRJOHFRXNµ·
VUFBÀOH RVSDWKMRLQ VUFBGLUÀOHB
os.system(a)
GVWBÀOH RVSDWKMRLQ GVWBGLUÀOHB
LIRVSDWKH[LVWV GVWBÀOH 
RVUHPRYH GVWBÀOH
VKXWLOFRS\ VUFBÀOHGVWBGLU
SULQW ´!!!!!!!!!!%DFNXSFRPSOHWHµ 

www.bdmpublications.com 93
Working with Modules

Using the Math Module


One of the more used modules you will come across is the Math module. As we’ve
mentioned previously in this book, Mathematics is the backbone of programming and
there’s an incredible number of uses the Math module can have in your code.

E = MC2
The Math module provides access to a plethora of Mathematical functions, from simply displaying the value of Pi, to helping
you create complex 3D shapes.

STEP 1 The Math module is built-in to Python 3; so there’s STEP 3 As you will no doubt be aware by now, if you know
no need to PIP install it. As with the other modules the name of the individual functions within the
present, you can import the module’s function by simply entering module you can speciƬcally import them. For instance, the Ʈoor and
import math into the Shell, or as part of your code in the Editor. ceil functions round a Ʈoat down, or up:
IURPPDWKLPSRUWÁRRUFHLO
ÁRRU  UHWXUQV
FHLO  UHWXUQV

STEP 2 Importing the Math module, as such, will give you STEP 4 The Math module can also be renamed as you
access to the module’s code. From there, you can import it, as with the other modules on oƪer within
call up any of the available functions within Math, by using math, Python. This often saves time, but don’t forget to make a comment
followed by the name of the function in question. For example, enter: to show someone else looking at your code what you’ve done:
math.sin(2) import math as m
PWUXQF  7UXQFDWHUHPRYHVWKHIUDFWLRQ
This will display the sine of 2.

94 www.bdmpublications.com
Using the Math Module

STEP 5 Although it’s not common practise, it is possible to STEP 8 For further accuracy when it comes to numbers, the
import functions from a module and rename them. exp and expm1 functions can be used to compute
In this example, we’re importing Ʈoor from Math and renaming it to precise values:
f. This process can quickly become confusing though, where lengthy
from math import exp, expm1
code is in use:
H[S H ²YDOXHDFFXUDWHWRSODFHV
IURPPDWKLPSRUWÁRRUDVI H[SP H UHVXOWDFFXUDWHWRIXOOSUHFLVLRQ
f(1.2)

STEP 6 Importing all the functions of the Math module can STEP 9 This level of accuracy is really quite impressive, but
be achieved by entering: quite niche for the most part. Probably the two
most used functions are e and Pi, where e is the numerical constant
from math import *
equal to 2.71828 (where the circumference of a circle is divided by
While certainly handy, this is often frowned upon by the developer its diameter):
community as it takes up unnecessary resources and isn’t an
import math
eƯcient way of coding. However, if it works for you then go ahead.
print(math.e)
print(math.pi)

STEP 7 Interestingly, some functions within the Math STEP 10 The wealth of Mathematical functions available
module are more accurate, or to be more precise, are through the Math module is vast, and covers
designed to return a more accurate value, than others. For example: everything from factors to inƬnity, powers to trigonometry, and
angular conversion to constants. Look up https://docs.python.org/3/
sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
library/math.html# for a list of available Math module functions.
Will return the value of 0.999999999. Whereas:
fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
Returns the value of 1.0.

www.bdmpublications.com 95
Working with 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 suƯce 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 UDQGRPFKRLFH >´&RQDQµ´9DOHULDµ´%HOLWµ@ 
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
diƪerent integer values from the
set of numbers given, zero to STEP 5 We can extend the previous example somewhat by
Ƭve. The overall eƪect, 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.
OVW >´'DYLGµ´$YHQJHUVµ´3Lµ7UXH
´3\WKRQµ@
rnd=random.choice(lst)
STEP 3 For a bigger set of numbers, including Ʈoating
print(rnd)
point values, we can extend the range by using the
multiplication sign:
import random
print(random.random() *100)
Will display a Ʈoating point number, between 0 and 100, to the tune
of around Ƭfteen decimal points.

96 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 Ʈips a
Random module to shuưe 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:
UDQGRPVKXIÁH OVW import random
print(lst) RXWSXW ^´+HDGVµ´7DLOVµ`
FRLQ OLVW RXWSXWNH\V
This way, you can keep shuưing the list before displaying a random
item from it. IRULLQUDQJH  
RXWSXW>UDQGRPFKRLFH FRLQ @ 
SULQW ´+HDGVµRXWSXW>´+HDGVµ@
SULQW ´7DLOVµRXWSXW>´7DLOVµ@

STEP 7 Using shuưe, we can create an entirely random list


of numbers, for example, within a given range:
import random
lst=[[i] for I in range(20)]
UDQGRPVKXIÁH OVW STEP 10 Here’s an interesting piece of code. Using a text
print(lst) Ƭle containing 466 thousand words, we can pluck
a user generated number of words from the Ƭle (text Ƭle found at:
Keep shuưing the list, and you’ll have a diƪerent selection of items
https://github.com/dwyl/english-words):
from 0 to 20 every time.
import random
SULQW ´!!!!!!!!!!5DQGRP:RUG)LQGHUµ
SULQW ´?Q8VLQJD.(QJOLVKZRUGWH[WÀOH,FDQ
SLFNDQ\ZRUGVDWUDQGRP?Qµ
wds=int(input(“\nHow many words shall I choose? “))
ZLWKRSHQ ´KRPHSL'RZQORDGVZRUGVW[Wµ´UWµ DVI
words = f.readlines()
words = [w.rstrip() for w in words]
print(“--------------------”)
IRUZLQUDQGRPVDPSOH ZRUGVZGV 
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
IRULLQUDQJH  
print(random.randrange(0, 200, 7))
Result will vary, but you get the general idea as to how it works.

www.bdmpublications.com 97
Working with Modules

Tkinter Module
While running your code from the command line, or even in the Shell, is perfectly Ƭne,
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: LPSRUWWNLQWHU, 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 diƪerently than before, to save on several more we can play around with:
typing, by importing all their contents:
EWQ %XWWRQ
LPSRUWWNLQWHUDVWN EWQSDFN
IURPWNLQWHULPSRUW EWQ>´WH[Wµ@ µ+HOORHYHU\RQHµ
The Ƭrst 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
LPSRUWWNLQWHUDVWN
do any harm. Let’s begin by creating a basic GUI window, enter:
IURPWNLQWHULPSRUW
ZLQG 7N EWQ %XWWRQ
EWQSDFN
This creates a small, basic window. At this point, there’s not much
EWQ>´WH[Wµ@ µ+HOORHYHU\RQHµ
else to do but click the X in the corner to close the window.
Then add some button interactions:
GHIFOLFN 
SULQW ´<RXMXVWFOLFNHGPHµ
EWQ>´FRPPDQGµ@ FOLFN

98 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.
IURPWNLQWHULPSRUW
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 URRW 7N
achieved with a few lines of code.
Y ,QW9DU
Label(root, root.title(“Options”), text=”””Choose
DSUHIHUUHGODQJXDJHµµµ
MXVWLI\ /()7SDG[  SDFN
Radiobutton(root,
WH[W µ3\WKRQµ
padx = 20,
YDULDEOH Y
YDOXH  SDFN DQFKRU :
Radiobutton(root,
WH[W µ&µ
padx = 20,
YDULDEOH Y
STEP 6 We can also display both text and images within a YDOXH  SDFN DQFKRU :
Tkinter window. However, only GIF, PGM, or PPM
mainloop()
formats are supported. So Ƭnd 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
IURPWNLQWHULPSRUW
output to the Shell:
URRW 7N
IURPWNLQWHULPSRUW
ORJR 3KRWR,PDJH ÀOH µ&??8VHUV??GDYLG??'RZQORDGV??
URRW 7N
3L/RJRJLIµ
Z /DEHO URRWURRWWLWOH ´5DVSEHUU\3Lµ  GHIYDUBVWDWHV 
LPDJH ORJR SDFN VLGH µULJKWµ SULQW ´:DUULRUG?Q0DJHGµ YDUJHW 
FRQWHQW ´µµ7KH5DVSEHUU\3L)RXQGDWLRQLVD YDUJHW
8.EDVHGFKDULW\WKDWZRUNVWRSXWWKHSRZHURI
/DEHO URRWURRWWLWOH ´$GYHQWXUH*DPHµ 
FRPSXWLQJDQGGLJLWDOPDNLQJLQWRWKHKDQGVRI
WH[W µ!!!!!!!!!!<RXUDGYHQWXUHUROHµ 
SHRSOHDOORYHUWKHZRUOG:HGRWKLVVRWKDWPRUH
JULG URZ VWLFN\ 1
people are able to harness the power of computing
YDU ,QW9DU
DQGGLJLWDOWHFKQRORJLHVIRUZRUNWRVROYH
&KHFNEXWWRQ URRWWH[W µ:DUULRUµYDULDEOH YDU 
problems that matter to them, and to express
JULG URZ VWLFN\ :
WKHPVHOYHVFUHDWLYHO\´µµ
YDU ,QW9DU
w2 = Label(root,
&KHFNEXWWRQ URRWWH[W µ0DJHµYDULDEOH YDU 
MXVWLI\ /()7
JULG URZ VWLFN\ :
padx = 10,
%XWWRQ URRWWH[W ·4XLW·FRPPDQG URRWGHVWUR\ 
WH[W FRQWHQW SDFN VLGH µOHIWµ
JULG URZ VWLFN\ :SDG\ 
root.mainloop()
%XWWRQ URRWWH[W ·6KRZ·FRPPDQG YDUBVWDWHV 
JULG URZ VWLFN\ (SDG\ 
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.

www.bdmpublications.com 99
Working with 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))
S\JDPHGLVSOD\VHWBFDSWLRQ ´$GYHQWXUH*DPHµ
running=True
ZKLOHUXQQLQJ
IRUHYHQWLQS\JDPHHYHQWJHW 
LIHYHQWW\SH 48,7
UXQQLQJ )DOVH
pygame.quit()

STEP 2 Let’s create a simple, game ready window and give


it a title:
gamewindow=pygame.display.set_mode((800,600))
S\JDPHGLVSOD\VHWBFDSWLRQ ´$GYHQWXUH*DPHµ
You will notice that after the Ƭrst 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.

100 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 Ƭne.

STEP 5 We’re going to shift the code around a bit now, LPJ S\JDPHLPDJHORDG ´&??8VHUV?GDYLG??
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
GHIVSULWH [\ 
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
JDPHZLQGRZÀOO ZKLWH
ZKLOHUXQQLQJ sprite(x,y)
pygame.display.update()
gamewindow=pygame.display.set_mode((800,600))
S\JDPHGLVSOD\VHWBFDSWLRQ ´$GYHQWXUH*DPHµ IRUHYHQWLQS\JDPHHYHQWJHW 
EODFN  LIHYHQWW\SH S\JDPH48,7
white=(255,255,255) UXQQLQJ )DOVH

STEP 6 Let’s quickly go through the code changes. We’ve downloaded image called sprite.png, and allocated it to the variable
deƬned two colours, black and white, together img. We’ve also deƬned 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.

www.bdmpublications.com 101
Working with Modules

STEP 7 Now we can change the code around again, this imgspeed=0
time containing a movement option within the
ZKLOHUXQQLQJ
while loop, and adding the variables needed to move the sprite
IRUHYHQWLQS\JDPHHYHQWJHW 
around the screen:
LIHYHQWW\SH 48,7
import pygame UXQQLQJ )DOVH
from pygame.locals import *
LIHYHQWW\SH S\JDPH.(<'2:1
pygame.init()
LIHYHQWNH\ S\JDPH.B/()7
running=True xchange=-5
HOLIHYHQWNH\ S\JDPH.B5,*+7
gamewindow=pygame.display.set_mode((800,600))
xchange=5
S\JDPHGLVSOD\VHWBFDSWLRQ ´$GYHQWXUH*DPHµ
LIHYHQWW\SH S\JDPH.(<83
EODFN 
LIHYHQWNH\ S\JDPH.B/()7RUHYHQW
white=(255,255,255)
NH\ S\JDPH.B5,*+7
LPJ S\JDPHLPDJHORDG ´&??8VHUV??GDYLG??
xchange=0
Downloads\\sprite.png”)
[ [FKDQJH
GHIVSULWH [\ 
gamewindow.blit(img, (x,y)) JDPHZLQGRZÀOO ZKLWH
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.

102 www.bdmpublications.com
Pygame Module

STEP 9 We can now implement a few additions, and utilise S\JDPHGLVSOD\ÁLS


some previous tutorial code. The new elements are FORFNWLFN 
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 EUHDN
New File called pygametxt.py:
pygame.quit()
import pygame
import time
import subprocess
pygame.init()
screen = pygame.display.set_mode((800, 250))
FORFN S\JDPHWLPH&ORFN
IRQW S\JDPHIRQW)RQW 1RQH
pygame.time.set_timer(pygame.USEREVENT, 200)
GHIWH[WBJHQHUDWRU WH[W 
tmp = ‘’
IRUOHWWHULQWH[W
WPS OHWWHU
LIOHWWHU ¶¶
yield tmp
FODVV'\QDPLF7H[W REMHFW 
def __init__(self, font, text, pos,
DXWRUHVHW )DOVH 
VHOIGRQH )DOVH
self.font = font
self.text = text
self._gen = text_generator(self.text)
self.pos = pos
self.autoreset = autoreset
self.update()
GHIUHVHW VHOI 
self._gen = text_generator(self.text)
VHOIGRQH )DOVH
self.update()
GHIXSGDWH VHOI 
LIQRWVHOIGRQH
WU\VHOIUHQGHUHG VHOIIRQW 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
H[FHSW6WRS,WHUDWLRQ 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 eƪect is quite good, but there’s always room
VXESURFHVV3RSHQ ´S\WKRQ&??8VHUV??GDYLG?? for improvement.
'RFXPHQWV??3\WKRQ??S\JDPHS\µVKHOO 7UXH
GHIGUDZ VHOIVFUHHQ 
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)
ZKLOH7UXH
IRUHYHQWLQS\JDPHHYHQWJHW 
LIHYHQWW\SH S\JDPH48,7EUHDN
LIHYHQWW\SH S\JDPH86(5(9(17PHVVDJH
update()
HOVH
VFUHHQÀOO S\JDPHFRORU&RORU ¶EODFN·
message.draw(screen)

www.bdmpublications.com 103
Working with Modules

Basic Animation
Python’s modules make it relatively easy to create shapes, or display graphics, and
animate them accordingly. Animation, though, can be a tricky element to get right in
code. There are so many diƪerent ways of achieving the same end result. Here’s one
such example.

LIGHTS, CAMERA, ACTION


The Tkinter module is an ideal starting point to learning animation within Python. Naturally, there are better custom modules
out there, but Tkinter does the job well enough to get a grasp on what’s needed.

STEP 1 Let’s make a bouncing ball animation. First, we will STEP 3 Insert the new code between the ball1
need to create both a canvas (window) and the ball FDQYDVFUHDWHBRYDO 
to animate: ÀOO ·UHG· line, and the gui.mainloop() line. Save it and
Run. You will now see the ball move from the top left corner of the
IURPWNLQWHULPSRUW
animation window, down to the bottom right corner. You can alter
import time
the speed in which the ball traverses the window by altering the
JXL 7N time.sleep(.01) line. Try (.05).
gui.geometry(“800x600”)
JXLWLWOH ´3L$QLPDWLRQµ
FDQYDV &DQYDV JXLZLGWK KHLJKW EJ ·ZKLWH·
FDQYDVSDFN
EDOO FDQYDVFUHDWHBRYDO ÀOO ·UHG·
gui.mainloop()

STEP 2 Save and Run the code. A blank window will


appear, with a red ball sitting in the upper left
corner of the window. While great, it’s not very animated. Let’s add
the following code:
a = 5
b = 5
IRU[LQUDQJH  
FDQYDVPRYH EDOODE
gui.update()
time.sleep(.01)

STEP 4 The FDQYDVPRYH EDOODE line is what moves


the ball from one corner to the other; obviously
with both a and b equalling 5. We can change things around a bit
already, such as the size and colour of the ball, with the line: ball1 =
FDQYDVFUHDWHBRYDO ÀOO ·UHG· , and we can
change the values of a and b to something else.

104 www.bdmpublications.com
Basic Animation

STEP 5 Let’s see if we can animate the ball so that it bounces STEP 9 Now add the following:
around the window until you close the program.
GHIPDLQ 
xa = 5
pygame.init()
ya = 10
screen = pygame.display.set_mode((640,480))
ZKLOH7UXH S\JDPHGLVSOD\VHWBFDSWLRQ ´6WDUÀHOG
FDQYDVPRYH EDOO[D\D Simulation”)
SRV FDQYDVFRRUGV EDOO FORFN S\JDPHWLPH&ORFN
LISRV>@! RUSRV>@ 
init_stars(screen)
ya = -ya
LISRV>@! RUSRV>@  ZKLOH7UXH
xa = -xa /RFNWKHIUDPHUDWHDW)36
gui.update() FORFNWLFN 
time.sleep(.025)
+DQGOHHYHQWV
IRUHYHQWLQS\JDPHHYHQWJHW 
STEP 6 Remove the code you entered in Step 2, and insert LIHYHQWW\SH S\JDPH48,7
the code from Step 5 in its place; again, between the return
EDOO FDQYDVFUHDWHBRYDO ÀOO ·UHG· ,
VFUHHQÀOO 
and the gui.mainloop() lines. Save the code, and Run it as normal.
PRYHBDQGBGUDZBVWDUV VFUHHQ
If you’ve entered the code correctly, you will see the red ball bounce
S\JDPHGLVSOD\ÁLS
oƪ the edges of the window until you close the program.
LIBBQDPHBB ´BBPDLQBBµ
main()
STEP 7 The bouncing animation
takes place within the While
True loop. First, we have the values of xa
and xy before the loop, both of 5 and 10.
The SRV FDQYDVFRRUGV EDOO line
takes the value of the ball’s location in the
window. When it reaches the limits of the
window, 800, or 600, it will make the values
negative; moving the ball around the screen.

STEP 8 Pygame, however, is a much better module at


producing higher-end animations. Begin by creating
a New File, and entering:
import pygame
from random import randrange
MAX_STARS = 250
67$5B63((' 
GHILQLWBVWDUV VFUHHQ  STEP 10 Save and Run the code. You will agree that the
´µµ&UHDWHWKHVWDUÀHOG´µµ simulated starƬeld code looks quite impressive.
global stars Imagine this as the beginning of some game code, or even the start
stars = [] to a presentation? Using a combination of Pygame and Tkinter, your
IRULLQUDQJH 0$;B67$56  Python animations will look fantastic.
$VWDULVUHSUHVHQWHGDVDOLVWZLWKWKLV
IRUPDW>;<@
star = [randrange(0,screen.get_width() - 1),
randrange(0,screen.get_height() - 1)]
stars.append(star)
GHIPRYHBDQGBGUDZBVWDUV VFUHHQ 
´µµ0RYHDQGGUDZWKHVWDUV´µµ
global stars
IRUVWDULQVWDUV
VWDU>@ 67$5B63(('
LIVWDU>@! VFUHHQJHWBKHLJKW 
star[1] = 0
star[0] = randrange(0,639)
screen.set_at(star,(255,255,255))

www.bdmpublications.com 105
Working with 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 Ƭles, 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 deƬnitions
functions. Multiply a number by two or three, and out of the program and into a separate Ƭle.
square or raise a number to an exponent (power). Create a New File Highlight the function deƬnitions 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 Ƭles, one with the function deƬnitions, and the
GHIWLPHVWZR [ 
other with the function calls.
return x * 2
GHIWLPHVWKUHH [ 
return x * 3
GHIVTXDUH [ 
return x * x
GHISRZHU [\ 
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 deƬned’ will be displayed. This is due to the code no longer
print (timestwo(2))
having access to the function deƬnitions.
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 deƬnitions, 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.

106 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 deƬnitions:
from minimath import *
LIFKRLFH ¶·
This will import the function deƬnitions as a module. Press F5 to
print(timestwo(num1))
save and execute the program, and see it in action.
HOLIFKRLFH ¶·
print(timesthree(num1))
HOLIFKRLFH ¶·
print(square(num1))
HOLIFKRLFH ¶·
QXP LQW LQSXW ´(QWHUVHFRQGQXPEHU´
print(power(num1, num2))
HOVH
SULQW ´,QYDOLGLQSXWµ

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”)
SULQW ´3RZHURIµ
FKRLFH LQSXW ´?Q(QWHUFKRLFH  µ

STEP 8 Now we can add the user input to get the number
the code will work on:
QXP LQW LQSXW ´?Q(QWHUQXPEHU´
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 deƬnition called
power. Save and execute the program to see it in action.

www.bdmpublications.com 107
Index

Learning
Linux

108 www.bdmpublications.com
Learning Linux

Linux is a Ʈexible and powerful


operating system but it also has a unique
Ƭlesystem and way of doing things.
Therefore, learning how Linux works is
essential to creating better Python code.
You’ll Ƭnd that Linux already has Python
elements built-in and if you’re working
on a Raspberry Pi 4, then everything you
need to code with Python is ready from
the start. In this section we will mainly
focus on using the Raspberry hardware
with Linux but regardless of whether
you’re using an RPi, Linux Mint, or
Ubuntu, these pages will prove
invaluable for your Python learning.

110 What is Linux?


112 Why Linux?
114 Using the Filesystem
116 Listing and Moving Files
118 Creating and Deleting Files
120 Create and Remove Directories
122 Copying, Moving and Renaming Files
124 Using the Man Pages
126 Editing Text Files
128 Getting to Know Users
130 Ownership and Permissions
132 Useful System and Disk Commands
134 Managing Programs and Processes
136 Input, Output and Pipes
138 Fun Things to Do in the Terminal
140 More Fun Things to Do in the Terminal
142 Linux Tips and Tricks
144 Command Line Quick Reference
146 A-Z of Linux Commands

www.bdmpublications.com 109
Learning Linux

What is Linux?
The Raspberry Pi operating system is Raspbian, which is a Linux operating system. But,
what exactly is Linux, where did it come from, and what does it do? In a world where
Windows and macOS have supremacy of the desktop, it’s easy to overlook Linux; but
there’s more here than you might imagine.

Linux is a surprisingly powerful, fast, secure, and capable operating system. It’s used as the OS of choice for the Raspberry Pi,
in the form of Raspbian OS, as well as in some of the most unlikely places.

Despite only enjoying 1.96% (according to netmarketshare.com) of Torvalds needed a system that could mirror UNIX’s performance and
the total desktop operating system market, Linux has a dedicated features, without the licensing cost. Thus was born Linux, a UNIX-like
following of enthusiasts, users, and contributors. It was created in operating system using freely available code from the GNU project.
1991 by then University of Helsinki student, Linus Torvalds, who had This enabled users around the world to utilise the power of a
become frustrated with the limitations and licensing of the popular UNIX-like system, completely free of charge – an ethos that still
educational system in use called Minix; a miniature version of the holds today. Linux is free to download, install, and use.
UNIX operating system.
Essentially, Linux is much like any other operating system, such as
UNIX itself was released in the early ‘70s, as a multi-tasking, Windows or macOS. It manages the computer hardware, provides
modular-designed operating system, originally developed for an interface for the user to access that hardware, and provides
programmers who needed a stable platform on which to code. programs for productivity, communications, gaming, science,
However, its performance, power, and portability meant that it soon education and more. As an operating system, Linux can be broken
became the system of choice for companies, and universities, where up into a number of signiƬcant elements:
high-end computing tasks were needed.

BOOTLOADER GRAPHICAL SERVER


The bootloader is the software that initialises and boots up This is a module within Linux that provides a graphical output
your computer. It loads up the various modules the OS uses to to your monitor. It’s referred to as the X server, or simply X. X
begin to access the hardware in the system. You can modify a is an application that manages one or more graphical displays,
bootloader to load more than one OS installed on the system. and one or more input devices (keyboard, mouse, etc.)
connected to the computer.

DAEMONS
KERNEL
Daemons are background services that will start as the
operating system is booting. These can enable printing, The kernel is the core of the system, and the single element
sound, networking and so on. They run unobtrusively rather that is actually called Linux. The Linux kernel manages the
than under the direct control of the user; often waiting to be computer processor, memory, storage, and any peripherals
activated by an event or condition. you have attached to your computer. It provides the basic
services for all other parts of the OS.

DESKTOP ENVIRONMENTAL
PROGRAMSǖAPPLICATIONS
The Desktop Environment, or DE, is the main Graphical User
Interface (GUI) with which users interact. It’s the desktop With Linux, begins not only an open source, and free,
that includes Internet browsers, productivity, games, and operating system, it also makes use of the tens of thousands
whatever program or app you’re using. There are countless of freely available applications too. The likes of LibreOƯce,
DEs available, Raspbian uses PIXEL. GIMP, and Python are just the tip of the iceberg.

110 www.bdmpublications.com
What is Linux?

SHELL
The Linux shell is a command-line interface environment that a
Linux user can use to enter commands to the OS that directly
aƪect it. Within the shell, you can add new users, reboot the
system, create, and delete Ƭles and folders, and much more.
BASH (Bourne-Again Shell) is the
most popular shell used in
Linux, although more are
available. The shell is also
known as the Terminal,
and it’s where we’re going
to work from through this
Linus Torvalds, the creator of the
section of the book.
Linux kernel.

Linux is used throughout the world, in several basic, and quite


unique, situations. While it may look radically diƪerent from one
Tux, the environment to the next, the actual Linux kernel can be found
Linux in modern smart TVs, in-car entertainment systems and GPS,
mascot supercomputers, IoT devices, and the Raspberry Pi. NASA uses it,
(Linus likes both in the command centre and on board the ISS. Linux servers
penguins). power the backbone of the Internet, along with most of the
websites you visit daily. Android utilises components of the Linux
kernel, as do set-top boxes, games consoles, and even some fridges,
freezers, ovens, and washing machines.

Linux isn’t just a free to use operating system. It’s stable,


powerful, fast, can easily be customised, and requires very little
maintenance. However, it’s more than just a set of on-paper
performance stats. Linux means freedom from the walled-garden
approach of other operating systems. It’s a lively community of like-
Raspbian on the Raspberry Pi, is the minded individuals who want more from their computers, without
Linux distribution of choice. the shackles of price or conformity. Linux means choice.

A Desktop Environment can


be as complex or as simple as
the user desires.

www.bdmpublications.com 111
Learning Linux

Why Linux?
Linux, like its parental UNIX, is a fantastic platform on which to code. Not only does
Linux come pre-installed with Python modules and command-line execution, but it also
has a wealth of other programming languages built-in to its framework.

FREE AND OPEN


Linux is a fantastic Ƭt for those who want something diƪerent. The eƯciency of the system, the availability of applications, and
its stability are just a few reasons why it’s a great Python coding resource.

The Ƭrst thing we need to address is that there is no such operating Linux works considerably diƪerently to Windows or macOS. It’s free for
system called Linux. Linux is, in fact, the operating system kernel, the a start, free to download, free to install on as many computers as you
core component of an OS. When talking about Linux, what we, and like, free to use for an unlimited amount of time, and free to upgrade
others, are referring to is one of the many distributions, or distros, and extend with, equally, free programs and applications. This free
that use the Linux kernel. No doubt you’ve heard of at least one of to use element is one of the biggest draws for the developer. While a
the current popular distros: Ubuntu, Linux Mint, Fedora, openSUSE, Windows license can cost up to £100, and a Mac considerably more,
Debian, Raspbian… the list goes on. Each one of these distros oƪers a user, be they a developer, gamer, or someone who wants to put an
the user something a little diƪerent. While each has the Linux kernel at older computer to use, can quickly download a distro and get to work in
its core, they provide diƪerent looking desktop environments, diƪerent a matter of minutes.
pre-loaded applications, diƪerent ways in which to update the system
and get more apps installed, and a slightly diƪerent look and feel Alongside the free to use aspect, comes a level of freedom to
throughout the entire system. However, at the centre lies Linux; which customise and mould the system to your own uses. Each of the distros
is why we say, Linux. available on the Internet have a certain ‘spin’, in that some oƪer

Linux is a great operating system in


which to start coding.

112 www.bdmpublications.com
Why Linux?

increased security, a fancy-looking desktop, a gaming speciƬc spin, or


something directed toward students. This extensibility makes Linux a
more desirable platform to use, as you can quickly mould the system
into a development base, including many diƪerent kinds of IDEs for the
likes of Python, web development, C++, Java and so on; or even a base
for online anonymity, perhaps as a Minecraft server, media centre and
much more.

Another remarkable advantage for those looking to learning how


to code, is that Linux comes with most of the popular coding
environments built-in. Both Python and C++ are pre-installed in a high
percentage of Linux distros, which means you can start to program
almost as soon as you install the system and boot it up for the Ƭrst time.

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


Each distro oƪers something unique to the
Windows or macOS. By system resources, we mean memory, hard drive
user but all have Linux at the core.
space, and CPU load, as the Linux code has been streamlined and is free
from third-party ‘bloatware’, which hogs other systems resources. Of
course, a more eƯcient system means more resources are available run the latest versions of Windows or macOS. So rather than throwing
for the coding and testing environment, and the programs you will away an old computer, it can be reused with a Linux distro.
eventually create. Less use of resources also means you can use Linux
on older hardware that would normally struggle, or even refuse, to It’s not all about C++, Python, or any of the other more popular
programming languages, however. Using the command line of Linux,
also called the Terminal, you’re able to create Shell scripts, which are
programs designed to run from the command line and are made up of
scripting languages. They are used mainly to automate tasks, or oƪer
the user some form of input and output for a certain operation.

Finally, although there are many more advantages we could list, there
are thousands and thousands of free programs and apps available
that cover virtually every aspect of computing. Known as packages,
there are (at the time of writing) over 8,700 speciƬc programming
applications just on Linux Mint alone, and an incredible 62,000+ overall
packages catering from Amateur Radio to WWW tools.

Linux, therefore, is a great resource and environment in which to


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

A Linux programming environment can be


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

www.bdmpublications.com 113
Learning Linux

Using the Filesystem


To master Linux, it’s important to understand how the Ƭlesystem works. What’s more,
it’s also important to become familiar with the Terminal, or shell. This command line
environment may appear daunting at Ƭrst, but with practise, it soon becomes easy to use.

GETTING AROUND
To drop into the Terminal, click on the fourth icon from the left along the top of the Raspberry Pi desktop, the one with a right-
facing arrow and an underscore. This is the shell, or Terminal.

STEP 1 First, you’re going to look at directories and the STEP 3 Enter: ls to view the contents of the current
directory path. A directory is the same thing as a directory. You should see Desktop, Documents,
folder, however in Linux it’s always called a directory. These are and Downloads and Scratch in Blue. You may also see other items
placed inside each other using a “/” character. So when you see / depending on how much you have used your Raspberry Pi. The
home/pi it means the pi directory is inside the home directory. colour code is worth knowing: directories are blue while most Ƭles
Enter: clear and press return to clean the screen. Now enter: pwd. are white. As you go on you’ll see other colours: executable Ƭles
This stands for Print Working Directory and displays /home/pi.. (programs) are bright green, archived Ƭles are red and so on. Blue
and white are the two you need to know to get started.

STEP 2 When you log in to your Raspberry Pi, you don’t STEP 4 Now you’re going to move from the pi directory into
start at the base of the hard drive, known as the the Documents directory. Enter: cd Documents.
‘root’ (also known as the topmost directory). Instead you begin Note the capital “D”. Linux is case sensitive, which means you have
inside your user directory, which is named ‘pi’ by default and is to enter the exact name including correct capitalisation. The cd
itself in a directory called ‘home’. Directories are indicated by the ‘/’ command stands for change directory. Now enter: pwd again to
symbol. So, “‘/home/pi’” tells you that in the root is a directory called view the directory path. It will display /home/pi/ Documents. Enter:
home, and the next “‘/’” says that inside “home” is a directory called ls to view the Ƭles inside the Documents directory.
“pi”. That’s where you start.

114 www.bdmpublications.com
Using the Filesystem

STEP 5 How do you get back up to the pi directory? By using STEP 6 The “ls” and “cd” commands can also be used with
a command “cd ..”. In Linux two dots means the more complex paths. Enter: ls Documents/
directory above, also known as the parent directory. Incidentally, a Pictures to view the contents of a Pictures directory inside
single dot “.” is used for the same directory. You never use “cd .” to your Documents directory. You can switch to this directory using
switch to the same directory but it’s worth knowing because some cd Documents/Pictures; use cd ../.. to move back up two
commands need you to specify the current directory. parent directories.

ABSOLUTE VS RELATIVE PATHS


It is important to know the diƪerence between the working directory, root directory and home. There are also two types of
path: Absolute and Relative. These are easier to understand than they sound. Let’s take a lookf

STEP 1 By default, commands like “ls” use the working STEP 3 The second command (“ls /Documents/Pictures”)
directory. This is the current directory that you’re attempts to list the content of Pictures in a
looking at and is set to your home directory by default (/users/ directory called Documents inside the root directory (because the
pi). Using “pwd” (Print Working Directory) lets you know what the path started with ‘/’, which is root). There is typically no Documents
working directory is, and using “cd” changes the working directory. directory in root, so you will get a “No such Ƭle or directory”
error. Starting a path with ‘/’ is known as an “absolute path”, while
starting without the ‘/’ is known as a “relative path” because it is
relative to your working directory.

STEP 2 The root directory is always ‘/’. Entering: ls / STEP 4 There is also an absolute path shortcut to your
lists the contents of root, and entering: cd / user directory, and that is the tilde “~” character.
switches to the root directory. This is important because there is a Entering: ls ~ always lists the contents of your home directory,
diƪerence between “ls Documents/Pictures” and “ls /Documents/ while “cd ~” moves straight to your home directory, no matter
Pictures”. The Ƭrst command lists the contents of the Pictures what your working directory is. You can also use this shortcut
directory in Documents inside the working directory (which, if you wherever you are: enter: ls ~/Documents/Pictures to display
are in the home directory, will work). the contents of the Pictures.

www.bdmpublications.com 115
Learning Linux

Listing and Moving Files


Admittedly, using the desktop GUI to list and move Ƭles is much easier than using the
Terminal and keyboard. However, it’s an important skill that you will appreciate as you
advance with the Raspberry Pi and Linux.

LOOKING AT FILES
Operating systems are built on Ƭles and folders, or directories if you prefer. While you’re used to viewing your own Ƭles, most
operating systems keep other Ƭles out of sight. In Raspbian, you have access to every Ƭle in the system.

STEP 1 We’ve already looked at “ls”, which lists the Ƭles in STEP 3 After the permission letters come a single number.
the working directory, but you are more likely to This is the number of Ƭles in the item. If it’s a Ƭle
use a command like “ls –l”. The bit after the command (the ‘-lah’) then it’ll be 1, but if it’s a directory it’ll be at least 2. This is because
is known as the argument. This is an option that modiƬes the each directory contains two hidden Ƭles; one with a single dot (.)
behaviour of the command. and one with two dots (..). Directories containing Ƭles or other
directories will have a higher number.

STEP 2 The “-l” argument lists Ƭles and directories in long STEP 4 Next you’ll see the word “pi” listed twice on each
format. Each Ƭle and directory is now on a single line. This refers to the user rather than the name of
line, and before each Ƭle is a lot of text. First you’ll see lots of letters your computer (your default username is “pi”). The Ƭrst is the owner
and dashes, like ‘drwxr-xr-x’. Don’t worry about these for now; they of the Ƭle, and the second is the group. Typically these will both be
are known as ‘permissions’ and we’ll come to those later. the same and you’ll see either ‘pi’ or ‘root’. You can enter: ls -l /
to view the Ƭles and directories in the root directory that belong to
the root account.

116 www.bdmpublications.com
Listing and Moving Files

STEP 5 The next number relates to the size of the Ƭle, in STEP 6 Finally, you should be aware that there are many
bytes. In Linux each text Ƭle is made up of letters hidden Ƭles in Linux. These are listed using the “-a”
and each letter takes up a byte, so our names.txt Ƭle has 37 bytes argument. Hidden Ƭles and directories begin with a dot (.), so you
and 37 characters in the document. Files and directories can be should never start a Ƭle or directory with a dot, unless you want to
extremely large and hard to determine, so use “ls – lh”. The “h” hide it. Typically, you can combine all three arguments together into
argument humanises the number, making it easier to read. the command ‘”s –lah”.

SOME COMMON DIRECTORIES


Now that you know how to view the contents of your hard drive you’ll start to notice a lot of directories with names like bin, sbin,
var and dev. These are the Ƭles and directories that you are kept away from on a Mac, and won’t encounter on a Windows PC.

STEP 1 Enter: ls -lah / to view all of the Ƭles and STEP 3 Entering: ls /home displays the contents of your
directories, including the hidden items, in the root home directory, which contains pi; the directory
directory of your hard drive. Here you will see all the items that that you start in. So, entering: ls/home/pi is the same as just “ls”
make up your Raspbian OS (which is a version of Linux). It’s worth from the default home directory. This is where you are expected
taking the time to know some of them. to place most of the documents you create. Don’t confuse home
with “usr”; the /usr directory is where Ƭnd you Ƭnd program tools
and libraries.

STEP 2 Bin is a directory that stores binaries. This is the STEP 4 Lib is a directory that contains libraries of code
Linux way of saying programs or applications. that are referred to by other programs (diƪerent
Sbin is for system binaries, which are the programs that make programs share Ƭles in Lib). “Var” is short for various, which is
up your system. Dev contains references to your devices: hard mostly Ƭles used by the system, but you may need to work with
drive, keyboard, mouse and so on. Etc contains your system items here. Finally there is a directory called “tmp”, which is for
conƬguration Ƭles. temporary Ƭles; Ƭles placed here are on your system for the short
term and can be deleted from the system.

www.bdmpublications.com 117
Learning Linux

Creating and Deleting Files


Being able to create and delete a Ƭle is an everyday computing skill. However, when
using the Linux Terminal, there’s an element of care required, chieƮy because any
deleted Ƭles aren’t placed in the system recycle bin.

CREATING FILES
Once you learn to recognise the Ƭles and directories that make up Raspbian OS, it’s time to discover how to make your own.
Knowing how to make, edit and delete Ƭles and directories is essential if you want to make your own projects.

STEP 1 We’re going to create a Ƭle using a command called STEP 3 If you try to touch a Ƭle that doesn’t exist, you
Touch. Touch is an interesting command that reaches create a blank Ƭle with that name. Try it now. Type
out to a Ƭle, or directory, and updates it (this changes the system time WRXFKWHVWÀOH and ls –l to view the Ƭles. You’ll now have a
as if you’d just opened the Ƭle). You can see Touch in access using “ls new Ƭle in your home directory called “testƬle”. Notice that the size
–l” and checking the time next to a directory (such as Scratch). of the Ƭle is 0, because it has nothing in it.

STEP 2 Now enter: touch Scratch and ls –l again and STEP 4 A quick word about Ƭle names: remember that
notice that the time has changed. It now matches Linux is case sensitive, so if you now enter: touch
the current time. You might be wondering what this has to do with 7HVWÀOH (with a capital T), it doesn’t update ‘testƬle’; instead, it
creating Ƭles or directories. Touch has a second, more popular, use, creates a second Ƭle called ‘TestƬle’. Enter: ls –l to see both Ƭles.
which is to create Ƭles. This is confusing, so most people stick with using lowercase letters
at all times.

118 www.bdmpublications.com
Creating and Deleting Files

STEP 5 Another important thing to know is never to use a STEP 6 Here are some other Ƭles names to avoid:
space in your Ƭle names. If you try to enter: touch #%&^`\> ?/!’”:#+C_=. The full stop (.) is used to
WHVWÀOH, you create a document called “test” and another called create an extension to a Ƭle; usually used to indicate a Ƭle type,
“Ƭle”. Technically there are ways to create Ƭles containing a space such as textƬle.txt or compressedƬle.zip, and starting a Ƭle with
but you should always use an underscore character (“_”) instead of a a full stop makes it invisible. Don’t use full stop in place of a space
space, such as “touch test_Ƭle”. though; stick to underscores.

REMOVING FILES
We’ve created some Ƭles that we don’t want, so how do we go about removing them? It turns out that deleting Ƭles in your
Raspberry Pi is really easy, which may be a problem, so be careful.

STEP 1 Enter: ls –l to view the Ƭles in your home directory. STEP 3 We’re going to use a wildcard (*) to delete our next
If you’ve followed the steps before then you should two Ƭles, but again this is something you really
have three Ƭles: “test”, “testƬle”, and “TestƬle”. We’re going to get rid need to do with care. First use “ls” to list the Ƭles and make sure
of these items because they were created as an example. it’s the one you want to delete. Enter: ls test* to view Ƭles that
match the word “test” and any other characters. The “*” character
is called a “wildcard” and it means any characters here.

STEP 2 To get rid of Ƭles you use the “rm” command. STEP 4 We see that “ls test*” matches two Ƭles: “test” and
Enter: UP7HVWÀOH to delete the Ƭle called “testƬle”, but not the Ƭle called “Ƭle”. That’s because
“TestƬle” (with the uppercase “t”). Enter: ls –l and you’ll Ƭnd it’s it didn’t match the “test” part of “test*”. Check carefully over groups
gone. Where is it? It’s not in the Trash or Recycle Bin, like on a Mac of Ƭles you want to remove (remember you can’t recover them) and
or Windows PC. It’s deleted completely and cannot be recovered. replace the “ls” with “rm”. Enter: rm test* to remove both Ƭles.
Bear this in mind and always think before deleting Ƭles. Finally enter: UPÀOH to get rid of the confusing Ƭle.

www.bdmpublications.com 119
Learning Linux

Create and Remove


Directories
Creating, moving and deleting directories isn’t as easy in the Terminal as it is within a
desktop interface. You need to tell Linux to move the directories inside other directories, a
process known as recursion. Sounds complex but you should quickly get the hang of it.

MANAGING FILES AND DIRECTORIES


Now that you know how to create Ƭles, you’ll want to learn how to make directories, which are the same thing as folders, as
well as move items around. If you are more used to working with a desktop interface, this can take a bit of getting used to.

STEP 1 Enter: ls to quickly view all the directories currently STEP 3 Like touch, you can create multiple directories
in in the home location. Directories are created at once with the mkdir command. Enter: mkdir
using the “mkdir” command (make directory). Enter: mkdir testdir2 testdir3 and enter: ls. You’ll now Ƭnd several
testdir to create a new directory in your home directory. Enter: directories called testdir. Also, like Ƭles, you should know this means
ls again to see it. you can’t (and really shouldn’t) create directories with spaces. As
with Ƭles, use an underscore (“_”) character instead of a space.

STEP 2 The “mkdir” command is diƪerent to touch, in that STEP 4 You can create directories inside of each other using
it doesn’t update the timestamp if you use it with a the directory path. Enter: mkdir Documents/
directory that already exists. Enter: mkdir testdir again and you’ll photos to create a new directory called “photos” inside your
get the error “mkdir: cannot create directory ‘testdir: File exists”. documents directory. The directory has to already exist, though,
try to enter: mkdir articles/reports and you’ll get an error
because there is no articles directory.

120 www.bdmpublications.com
Create and Remove Directories

STEP 5 To create a directory path you need to pass in the STEP 6 Now you’re starting to get a bit more advanced,
“p” option to mkdir (which stands for “parents”). we’re going to just reiterate something. In Linux
Options, if you remember, come after the command and start with the command structure is always: command, option and argument,
a ‘-’. So enter: mkdir -p articles/reports. Enter: ls to view in that order. The command is the function, next are the options
the articles directory, or “ls articles” to view the reports directory (typically single letters starting with “-”) and Ƭnally the argument
sitting inside. (often a Ƭle, or directory structure). It’s always command, option
then argument.

GETTING RID OF DIRECTORIES


Deleting directories is pretty easy in Linux, along with Ƭles, and this can be a problem. It’s too easy to delete entire directories
containing Ƭles and these are instantly removed, not sent to a trash directory. Tread carefully.

STEP 1 We’re going to remove one of the directories we STEP 3 To delete a directory containing Ƭles or other
created earlier using the “rmdir” command. Enter: directories, you return to the “rm” command used
ls to view the Ƭles and directories in the current directory. We’ll to remove Ƭles, only now we need to use the “-R” option (which
start by getting rid of one of the test directories. Enter: rmdir stands for “recursive”.) Using “rm sR” removes all the Ƭles and
testdir3 and ls again to conƬrm the directory has been removed. directories to whatever you point it at. Enter: rm -R articles to
remove the articles directory.

STEP 2 Now we’ll try to get rid of the articles directory STEP 4 As with multiple Ƭles, you can delete multiple
(containing the reports directory). Enter: rmdir directories inside the same directory using the “rm”
articles and press return. You’ll get an error saying “rmdir: failed command with the wildcard character (*). This should be done with
to remove ‘articles’: Directory not empty”. This is a puzzler; the care though so use the -I option (which stands for “interactive”).
rmdir command only removes directories that having nothing in This will prompt you before each deletion. Enter: rm -Ri test*
them (no Ƭles or other directories). and press Y and return to each prompt. It’s a good idea to use the
-i option whenever using the rm command.

www.bdmpublications.com 121
Learning Linux

Copying, Moving and


Renaming Files
Taking command of the Terminal is essential when learning how your Raspberry
Pi’s operating system works. The copying, moving and renaming of Ƭles is equally
important, as you’ll be doing a lot of this throughout your Pi projects.

USING THE MOVE COMMAND


In Linux, renaming a Ƭle is simply moving it from one name to another and copying a Ƭle is moving it without deleting the
original. Don’t panic, it’s quite easy to master.

STEP 1 Before we can move anything around, we need to STEP 3 Enter: PYWHVWÀOHWHVWGLU and press return
have a few test items in our home directory. Enter: to move the testƬle document into the testdir
WRXFKWHVWÀOH and mkdir testdir to create a test Ƭle and test directory. Enter: ls to see that it’s no longer in the home directory,
directory in your home directory. Enter: ls to check that they are and ls testdir to see the testƬle now sitting in the testdir
both present. directory. Now enter: mkdir newparent to create a new directory.

STEP 2 Files and directories are moved using the mv STEP 4 Directories with Ƭles are moved in the same way.
command. This is diƪerent to the commands we’ve Enter: mv testdir newparent to move the
looked at so far because it has two arguments (remember Linux testdir directory inside the newparent directory. Let’s move into the
command line is command, option, argument). The Ƭrst argument directory to Ƭnd the Ƭle. Enter: cd /newparent/testdir and
is the source (the Ƭle or directory to be moved) and the second is enter: ls to view the testƬle sitting inside the directory.
the destination.

122 www.bdmpublications.com
Copying, Moving and Renaming Files

STEP 5 Files and directories can be moved up using the STEP 6 You can also move Ƭles using longer paths. Enter:
double dot (“..”) as an argument. Enter: ls –la to cd ~ to return to the home directory and
view your testƬle and the single and double dot Ƭles. The single dot PYQHZSDUHQWWHVWÀOHQHZSDUHQWWHVWGLUWHVWÀOH to
is the current directory and the double dot is the parent directory. move the testƬle from its current location back inside the testdir
Enter: PYWHVWÀOH to move the testƬle up into the newparent directory. Enter: ls newparent/testdir to view the Ƭle back in
directory. Enter: cd .. to move up to the parent directory. its current directory.

RENAMING FILES AND DIRECTORIES


The mv command isn’t used just to move Ƭles; it also serves the purpose of renaming Ƭles (eƪectively it moves it from its old
name to a new name). Let’s see how to use mv to rename items.

STEP 1 Let’s start by making a new test Ƭle called “names”. STEP 3 You can rename directories inside other directories
Enter: WRXFKWHVWÀOH and then ls to make sure using paths. Let’s rename the testdir directory,
the testƬle is present. We’re going to turn this into a Ƭle that which is now inside the people directory. Enter: mv names/
contains the names of some people. So let’s call it something more testdir names/friends. Now enter: mv names people/
appropriate, like “names”. friends to move the names Ƭle inside the friends directory.

STEP 2 Enter: PYWHVWÀOHQDPHV and ls. Now we can STEP 4 It is easy to overwrite Ƭles using the mv
see the new “names” Ƭle in our directory. The mv command, so if you have Ƭles with the same
command can also be used to rename directories. We should still name use the “-n” option, which stands for “no overwrite”.
have our newparent directory in our home directory. Enter: mv Enter: WRXFKWHVWÀOH to create a new Ƭle and mv -n
newparent people to rename the newparent directory. Enter: WHVWÀOHSHRSOHIULHQGV. There’s no error report though,
ls to view it. enter: ls and you’ll Ƭnd testƬle still there.

www.bdmpublications.com 123
Learning Linux

Using the Man Pages


Linux comes with man (manual) pages that explain each command and show you all the
options you can use. Once you get the hang of reading the man pages, you’ll be able to
Ƭnd and do just about anything in Linux.

HEY, MAN!
The man pages are one of the best features of Linux, and as a built-in tool it’s invaluable for both beginner and senior level
Linux administrators. Let’s see how it works

STEP 1 Linux has a built-in manual, known as man for STEP 3 Most commands are pretty easy to Ƭgure out how
short. Using the man command you can obtain to use, so what you spend most of the time in the
information on all the Linux commands we’ve talked about. Simply man pages is looking under the Description. Here you will see all the
enter: man and the name of the command you want to learn more options and the letters used to activate them. Most man pages are
about. Start by entering: man ls in the command line. longer than a single page, so press any key, such as the space bar, to
move to the next page of content.

STEP 2 The man pages are a bit more detailed than you
might be used to. First you have a name, which tells
you what the command is called; in this case “list directory contents”
and then the synopsis shows you how it works. In this case: “ls
[OPTION].. [FILE..]”. So you enter: ls followed by options (such as
-la) and the Ƭle or directory to list.

STEP 4 Press the H key while looking at a man page to view


the commands you can use to control the view.
This is called the Summary of Less Commands (the less command
is something we’ll come to when we look at editing text). For now
realise that you can move back and forward with Z and W. Press Q to
quit this help screen and return to the man page.

124 www.bdmpublications.com
Using the Man Pages

STEP 5 Scroll to the bottom of the man page to discover STEP 6 The man command can be used for just about every
more information. Typically you will Ƭnd the command you use in Linux. You can even enter:
author’s name and information on reporting bugs, including web man man to get information on using the man tool. From now on,
links that can be useful for more information. Press Q to exit the whenever you come across a new command in this book, such as
man page and return to the command line. “nano” or “chmod”, take time to enter: man nano or man chmod
and read the instructions.

USING MAN OPTIONS


Because man doesn’t change anything, like mv or mkdir, it is tempting not to see it as a command. But it is, and like all other
commands it has options. These can be very handy to learn.

STEP 1 Entering: man man enables you to view some of STEP 3 One of the most powerful man options is the -k
the options, but sometimes you’ll just want a quick option, which is for “apropos”. This enables you
overview. Fortunately man has a built-in help option that quickly to search a wider range of man pages than the exact command.
lists the options. Press Q if you’re in a man page and enter: man –h Enter: man -k directory to view all of the man pages relating
at the command line. to directories “(man -k directory | less” to view one page at a time).
Here you’ll Ƭnd commands like “ls”, “mkdir” and “cd” along with
their description.

STEP 2 If you’re fast you may have noticed the start of the STEP 4 Entering the man page for all the commands
text Ʈew up oƪ the page. This is because the “man you come across can be a little long-winded,
–h” option doesn’t use the less command by default (less is what although ultimately productive. If you simply want to know what a
enables you to move down text one screen at a time). We’ll look command does you can read just the description using the “whatis”
into pipes (“|”) later on, but for now just use “man -h | less” to read command. Enter: whatis pwd to read the description of the
long text one page at a time. “pwd” command (“print name of current/working directory”).

www.bdmpublications.com 125
Learning Linux

Editing Text Files


A text Ƭle in Linux can be anything from a simple set of instructions on how to use an
app, to some complex Python, C++ or other programming language code. Text Ƭles can
be used for scripting, automated executable Ƭles, as well as conƬguration Ƭles too.

THE JOY OF TEXT


To be able to edit or create a text Ƭle, you need a good text editor. Linux has many but here are some in action on the
Raspberry Pi.

STEP 1 The Ƭrst text editor for the Raspberry Pi is the STEP 3 Vi is the original Unix command but in this case it
default desktop environment app: Leafpad. To launches VIM, the new Linux version of Vi. Although
use, you can either double-click an existing text Ƭle or click the simple looking, Vi is considered, even by today’s standards, to be
Raspberry Pi menu icon (in the top left of the desktop) and from the one of the most widely used text editors, There’s a lot you can do
Accessories menu, choose Text Editor. with it, so check out the man pages for more Vi information.

STEP 2 From the Terminal there are even more options, STEP 4 Nano is another favourite, and simple, text editor
although using the correct command, you can available for Linux. Enter: nano into the Terminal
launch any of the desktop apps via the Terminal. One of the to launch it. You can use Nano for editing code, creating scripts or
simplest, and a classic text editor that’s carried over from the Unix writing your own help Ƭles. To exit Nano, press Ctrl + X, followed by
days, is vi. In the Terminal, enter: vi. Y to save the Ƭle or N to exit without saving.

126 www.bdmpublications.com
Editing Text Files

STEP 5 Emacs, or GNU Emacs, is an extensible and STEP 8 Emacs can oƪer an uncomplicated view of your text
customisable, self-documenting, real-time display Ƭle or one with a plethora of information regarding
editor. It’s a fantastic text editor and one that’s worth getting used the structure of the Ƭle in question; it’s up to you to work out your
to as soon as you can. Sadly, it’s not installed on the Pi by default, own preference. There’s also a hidden text adventure in Emacs,
so you’ll need to install it. In the Terminal, enter: sudo apt-get which we cover later in this book, why not see if you can Ƭnd it
install emacs without our help.

STEP 6 The previous command contacts the Debian STEP 9 Gedit is another excellent text editor for Linux.
(Raspbian is based on a Debian Linux distribution) Again, it’s not installed by default on the Raspberry
repositories and pulls down the information needed to install Pi; however, by entering: sudo apt-get install gedit and
Emacs. When the Pi asks to continue with the installation, press Y. accepting the installation, the program can be on the Pi in a matter
This installs the latest version and when it’s done, you’ll be back to of seconds. Once it’s installed, use gedit in the Terminal to launch
the command prompt. it. Gedit is a great text editor for coding.

STEP 7 Once the installation is complete, enter: emacs STEP 10 Finally, Jed is an Emacs-like, cross-platform text
into the Terminal. The Emacs splash screen opens editor that’s lightweight and comes with a wealth
in a new window, oƪering a tutorial (which we recommend you run of features. To install it, enter: sudo apt-get install jed.
through) and a guided tour amongst other information. Accept the installation and when it’s complete, use: jed to launch.

www.bdmpublications.com 127
Learning Linux

Getting to Know Users


You might think you’re the only person using your Raspberry Pi but there are several
diƪerent users and even groups of users. Your main account is normally called Pi and
there is an account above it called root, which is more powerful. You can also create
users and groups.

WHAT IS A USER?
An important part of using Linux is the concept of users and understanding which user you are and which group you belong to.
Like all modern computers, you can have multiple user accounts with each having diƪerent levels of access.

STEP 1 The Ƭrst thing you need to do is get a concept of STEP 3 To allow this, you need to use the sudo command.
which user you are. Enter: whoami into the command Sudo loosely stands for Substitute User Do;
line and press return. It should say “pi” (unless you set up your account essentially it’s the highest level of access to the system and you’ve
name diƪerently during setup). The “whoami” command might seem already installed text editors using sudo. You’ll come across sudo
a bit simplistic, but it comes in very handy sometimes. frequently in Linux, so let’s create a second account to get the hang
of it. Enter: sudo useradd -m lucy (or pick your name).

STEP 2 When you are working in Linux, from time to time a STEP 4 Now add a password for the new account. Enter:
‘Permission denied’ error will occur, typically when sudo passwd lucy and enter: a short password.
you try to create, edit or execute (run) a Ƭle or directory outside Retype the same password and you’ll now have two accounts on
of your area of privilege. If you want to see this, enter: mkdir / your Raspberry Pi. Now enter: ls -l /home to view the home
testdir. Attempting to create a new directory in your root directories for both users. Notice that the lucy directory lists lucy as
directory isn’t allowed. the owner and group; and pi directory is belongs to pi.

128 www.bdmpublications.com
Getting to Know Users

STEP 5 Let’s try switching to our new account. Enter: su STEP 6 We’ll look at permissions in the next tutorial, but
lucy and enter the password you just created for now try to create a Ƭle as before. Enter: touch
for that account. Notice that the command line now says “lucy# WHVWÀOH to create a Ƭle. It will say “touch: cannot touch ‘testƬle’:
raspberrypi” but the working directory is “still /home/pi” (check Permission denied”. This is because your new user account doesn’t
this using “pwd”). Enter: whoami to conƬrm that you are now the have the right to create Ƭles in the /home/pi directory. Enter: su
new user. pi to switch back to your pi account.

GETTING SUDO
We now have two accounts on our Raspberry Pi: lucy and pi. The lucy account can edit Ƭles in /home/lucy and the pi account can
edit Ƭles in /home/pi. But there’s also a third account, called “root”, that sits above both lucy and pi. It can edit Ƭles anywhere.

STEP 1 The root account is all-powerful. It is possible, but not STEP 3 It’s rare that you use sudo to substitute another
recommended, to switch to the root account, although user. If you don’t specify a user using the “-“u
you’ll need to give it a password Ƭrst (using “sudo passwd root”). Then option with a username it defaults to the root account, as if
just type “su” to switch to root. Please don’t do this though: knowledge you’d typed “sudo -u root”. Enter: sudo touch /home/lucy/
is a good thing but it’s safer and wiser to use sudo instead. DQRWKHUWHVWÀOHto create a Ƭle in the lucy directory while still
using the pi account.

STEP 4 This step is optional. Only the pi user can use sudo. If
we want to give the lucy account sudo privileges, it
needs to be added to the sudoers Ƭle. Enter: sudo visudo to view
the sudoers Ƭle. Add lucy ALL=(ALL) NOPASSWD: ALL to the
last line and use Control+O to output the Ƭle. Remove the “.tmp”
STEP 2 Most people think sudo stands for “super user”,
that is added to the Ƭle name as a security measure. Note that most
but it stands for “substitute user do”. It enables
accounts are not added to the sudoers Ƭle as a matter of course.
you to perform a command as another user. Enter: sudo -u
lucy touch /home/lucy/test to create a Ƭle inside the lucy
home directory. You won’t get an error because the lucy user has
permission to edit that directory.

www.bdmpublications.com 129
Learning Linux

Ownership and
Permissions
Once you’ve got the hang of users, you need to learn about ownership and
permissions. Diƪerent users have diƪerent areas of ownership and can do diƪerent
things with each Ƭle. Permissions in Linux can be quite complex but with careful
thought it’s not too diƯcult.

OWNER AND PRIVILEGE


Each user account in Linux is an owner of a section of the Ƭlesystem: their Home area. Within this area, they do what they like
(within reason), as they have owner privileges. Elsewhere though, they usually just have read-only privileges.

STEP 1 If you followed the previous tutorial you should now STEP 3 The Ƭrst letter in the permissions also indicates a
have two accounts on your Raspberry Pi. One called directory or Ƭle. Notice that all the other Ƭles start
“pi” and the other with a name (Lucy in our case). An essential aspect with a ‘d’ and our textƬle.txt Ƭle starts with a ‘-’. That’s what the Ƭrst
of Linux is the idea of Ƭle and directory ownership; who owns, and letter means. It’s either a ‘d’, in which case it’s a directory, or a ‘-’, in
has access, to what. You need a test Ƭle so enter: WRXFKWHVWÀOH. which case it’s not; it’s a Ƭle. Enter: OVOWHVWÀOHW[Wto view
the permissions for just this Ƭle.

STEP 2 Now enter: ls –l and let’s have a good look at the


default permissions Ƭle. Our testƬle.txt Ƭles starts
with the text “-rw-r--rt“. Start with the Ƭrst letter, which is a dash ‘-’.
All the other items in our home directory are directories. You can tell
because they are blue, and our testƬle.txt Ƭle is white.

STEP 4 The next nine letters of the permissions are known


as “alpha notation” because they let you know the
permissions using letters. Each permission is either on, in which case
you see a letter, or it is oƪ, in which case you see a dash. The letter
doesn’t change for each place. So the Ƭrst permission - the second
letter after the directory one - is either an ‘r’ or a ‘-’. It’s never any
other letter.

130 www.bdmpublications.com
Ownership and Permissions

STEP 5 The ‘r’ means that particular permission is read and STEP 6 The presence of r, w, or x means that this aspect is
it’s set to On. The nine letters here are divided into possible, a dash means it isn’t. Our testƬle.txt has
three groups of three letters: r, w, x. They stand for read, write and no x letter; so if it were a script it wouldn’t run. So why are there so
execute (run). Read means the Ƭle can be viewed (using cat or nano); many letters? Why not just three; read, write and execute? The three
w means the Ƭle can be edited or moved, and x means the Ƭle - blocks of three letters are for diƪerent sets of people: user, group
typically a script or program - can be run. and other.

CHANGING PERMISSIONS
Now that you know how groups of permissions work, it’s time to look at how to change them.

STEP 1 The Ƭrst block of three is the most important. STEP 3 Turning everything on is probably overkill, so you
This is the user who owns the Ƭle (typically pi); the need to target each group. Do this by putting
second is for other people in the same group as the user, and the commas between each mode option. Enter: chmod u=rwx,g=rw,o=r
third is for other people on the system. Permissions are changed testƬle.txt to give users read, write and execute privileges, user read
using the chmod (change Ƭle mode bit) command. Enter: man and write and other just read. Enter: ls –l to see your handiwork.
chmod to look at the manual.

STEP 4 Alpha notation is Ƭne, but many Linux admins


use octal notation instead. This is a three-
digit number that represents permissions. This is the formula:
read=4, write=2 and execute=1 and you add them up for each
group, therefore if a group is read, write and execute it’s 7, if it’s
STEP 2 The chmod command is one of the trickier ones
read and write it’s 6 or if it’s just execute it’s 1. A popular option
to understand. There are two ways you can adjust
is 755. Enter: FKPRGWHVWÀOHW[W to change the Ƭle
permissions; the Ƭrst is using chmod with an option to target one
using octal notation.
of the three groups: owner, group, other. For these you use u, g
or o followed by = and the letters or dashes you want. So enter:
FKPRGXJR U[WHVWÀOHW[W to make all three groups read,
write and execute.

www.bdmpublications.com 131
Learning Linux

Useful System and


Disk Commands
Understanding these core Linux commands will enable you to not only master the
inner workings of your Raspberry Pi but also to transfer those skills to other Linux
distros, such as Ubuntu or Linux Mint.

LOTS OF LINUX
Linux is a huge and versatile command line language and there are hundreds of commands you can learn and use. Here are a
few that can help you get more from your Raspberry Pi.

STEP 1 The Raspberry Pi is a great little computer, so STEP 3 Enter: uname to view the name of the operating
let’s start by getting some information. Enter: system’s kernel, this is the element that sits
cat /proc/cpuinfo to view some details on your Raspberry Pi between the interface and hardware. Just as you would suspect, the
processors. If you have a Raspberry Pi 3 you will see four processors, response from the command is Linux, as Raspbian is a Linux distro,
along with the model name and other info. which in itself is based on another Linux distro called Debian. While
it may sound complicated, it actually demonstrates how versatile
Linux is.

STEP 2 STEP 4 Enter: uname –a to view some more detailed


information. Here you’ll see the kernel name,
Remember that cat hostname and kernel version (3.18.7-v7 on ours). If you have a
is used to list the Raspberry Pi 2 you’ll see SMP (symmetric multiprocessing),
contents of a text Ƭle, followed by the system date, CPU architecture and operating
which is what cpuinfo system (GNU/Linux).
is. There are other text
Ƭles with system info
available. Try “cat /
proc/meminfo” to get
information about
your memory, “cat /
proc/partitions” for
information about your
SD card, and “cat /proc/
version” shows which
version of Raspberry Pi
you are using.

132 www.bdmpublications.com
Useful System and Disk Commands

STEP 5 Enter: vcgencmd measure_temp to view the STEP 6 One command you might be wondering about is
current operating system temperature of your how to switch oƪ or restart your Raspberry Pi from
Raspberry Pi. Enter: vcgencmd get_mem arm to view the RAM the command line. Don’t just hit the power switch. Enter: sudo
available, and vcgencmd get_mem gpu to view the memory showdown –h now to shut down the Raspberry Pi (the “-h” option
available to the graphics chip. Finally try ls usb to view a list of stands for “halt”), or enter: sudo shutdown –r now to restart
attached USB devices. your Raspberry Pi.

DISK COMMANDS
Learn the two commands that enable you to view your disk space and the Ƭles on it: df (disk free space) and du (disk usage).
With these two commands you can view the Ƭle usage on your SD card.

STEP 1 Start by entering: df in the command line. It STEP 3 Now enter: du. You should see lots of text Ʈy
returns a list of the volumes contained on your up the screen. This is the disk usage for the Ƭles
SD card. You might be wondering what a volume is. It’s best to contained in your home directory and their sub-directories. As
think of your SD card as the drive. This contains partitions, which is with df, it is better to use du with the “-h” option to humanise the
where you split one drive to act like two or more drives. And each output. If you want to slow down the output, you’ll also need to
partition can contain volumes, which are storage spaces. pipe it through less. Enter: df -h | less to view the Ƭles and
their respective usage one page at a time.

STEP 2 Enter: df –h to get the list in human readable STEP 4 You don’t typically enter: du on its own; most of the
form. The Ƭrst two lines should read “rootfs” and time you want to view the disk usage of a speciƬc
“/dev/root” and have matching Size, Used, Avail and Use% listings. directory. Enter: du -h python_games to view how much
This is the main drive, and is an indication of how much space you space the python_games directory (installed alongside Raspbian)
have used, and have free, on your Raspbian OS. The other volumes takes up. It should be 1.8M. If you want a more comprehensive
are for booting and initialising devices (you can ignore these for now). breakdown of the Ƭles contained, use the “-a” option (all). Enter:
du -ha python_games to view all the Ƭles contained and their
disk usage.

www.bdmpublications.com 133
Learning Linux

Managing Programs
and Processes
Being able to eƪectively manage the active programs and processes on your Raspberry
Pi allows you to change the way the systems work. If you have a project requiring more
memory, you can kill a process to free up the available system resources.

PROGRAMS AND PROCESSES


Linux has a trick up its sleeve when it comes to being able to manage programs and processes. When Windows closes a
program, the allocated memory often isn’t freed up again. However, Linux is far more streamlined.

STEP 1 As you get STEP 3 If you type in “ps” on its own you don’t see much.
into Linux You should see two items: bash and ps. Bash
you’ll start to hear more (Bourne Again Shell) is the command line environment you are
about processes and another typing in, and ps is the command you just entered. If that seems a
thing called the “kernel”. little light, that’s because it is. These are just the processes owned
The kernel sits beneath the by the user and are running in the foreground.
software and hardware. It
passes instructions to the
hardware running processes,
which takes up memory, and
when the process is Ƭnished
it closes it and reclaims
the{memory.

STEP 4 If you
want to
see processes used by
other users (including
those started by root)
enter: ps –a. The
option stands for all
STEP 2 You’re probably used to thinking in terms of
users. This still isn’t
programs and most OS’s tend to keep processes
everything though
out of sight. In Linux on the other hand, you’re right in at the deep
because it doesn’t
end. A process is like a program, only it’s a single task running
include background
on your computer. Programs as you know them, may be a single
processes. For this you
process, or multiple processes working together. In Linux, you
can enter either “ps –A”
should learn to manage processes. This is done using the “ps”
or “ps –e”. This will show
(process status){ command.
you every process on
the system including the
background processes.
You may need to pipe it
through less using
“ps -e _ less”.

134 www.bdmpublications.com
Managing Programs and Processes

STEP 5 The ps STEP 6 The “ps aux” command displays the processes
command in columns. The Ƭrst is the User followed by the
is one of the oldest Process ID (PID), then we see the percentage of CPU and memory.
known, and it has a lot of
legacy. Because of this,
it also has alternative
options that can be used
without the dash at the
start. The most common
way to use ps is to enter:
SVDX[. Piping this
command through less
is the best way to go
about using ps. Enter:
SVDX[_OHVV to view
your processes.

VIEWING AND QUITTING PROCESSES


Now that you’ve got a handle on processes, you need to know what to do with them. You can view processes running in real-
time, and quit ones that you no longer need, or those that are problematic.

STEP 1 While ps is a great tool for checking all the STEP 3 Now that you’ve got an idea of what processes
processes on your Raspberry Pi, sometimes you are, how do you go about stopping them? Some
need to view them in real-time. In particular you may want to check processes run in the foreground until you quit them. Enter: ping
the CPU and memory usage of processes and see if any process is www.google.com and you’ll start a ping process continuously
hogging all your computer’s resources. Use “top” to do this. contacting Google. This sort of process runs until you press Control+C.

STEP 2 Top Ƭlls the display with processes and it Ƭts as STEP 4 Processes are stopped using the kill command.
many as it can on one screen. These run in real- Enter: sleep 100 & to create a dummy process.
time so as you watch, the display items will move up and down Enter: pgrep sleep to Ƭnd its PID number (on ours it is 2192).
according to their usage. You can interact with top as it is running: Now enter: kill 2192 and the sleep process will be stopped.
use < and > to change the sort column. Press H to view a help page You can also use pkill sleep if you’re sure you know the
with all the commands you can use. process name.

www.bdmpublications.com 135
Learning Linux

Input, Output and Pipes


Most operating systems allow you to direct the output of something on the screen
to, for example, a Ƭle. Linux, with its ancestral history of Unix-like command-based
arguments, goes a step further and oƪers much more control.

IN, OUT, LINUX ALL ABOUT


Everything on a computer is about input and output. You input things into the computer (press keys, move the mouse) and it
makes calculations and outputs content (changes the display, makes a noise, for example).

STEP 1 When STEP 3 You can change the standard output to something
you enter else using the “>” character after your command. If
commands into Linux (in we wanted to see all the items in the python_games directory we
the command line), you could use “ls -l python_games”. Using “ls -l python_games > games.
are using standard input txt” outputs the list of items to a new text Ƭle called “games.txt”.
and output. This is so
obvious that most people
don’t even think about
it. You enter commands
using the keyboard (that’s
input) and it responds
to the screen (output).
STEP 4 The games.txt Ƭle now contains the output from
This is the regular way
the ls command. You can check it using “nano
of doing it, which is why
games.txt”. It’s an editable text Ƭle containing all the permissions,
it’s “standard input and
user and Ƭle size information and the names of the Ƭles. The output
output” (often called
from the ls -l command, normally displayed on the screen, was
“stdin” and “stdout”
instead sent to this Ƭle. Press Control+X to quit nano.
for short).

STEP 2 As far as the computer is concerned, input and


output can be to and from a whole range of
diƪerent sources that you might never even think about. A program
can get input from other programs, from Ƭles stored on the hard
drive and a whole host of other areas. It outputs back to the display
line, but also to Ƭles, other programs and even other commands.

136 www.bdmpublications.com
Input, Output and Pipes

STEP 5 So > enables you to output to Ƭles, but you can also STEP 6 We’re going to use this text Ƭle as input to the
get input from a Ƭle. Make a new directory called sort command. Enter: VRUWEDQGVW[W and
music (“mkdir music”) and switch to it (“cd music”). Enter: nano the content from the text Ƭle is used as input to sort. Because the
EDQGVW[W to create a new text Ƭle. Enter some band names and output isn’t speciƬed, it uses the standard output (the screen) but
press Control+O to output the Ƭle. Press Control+X to quit nano. you use input and output together. Enter: VRUWEDQGVW[W!
EDQGVBVRUWHGW[W to create a new Ƭle with the band names in
order to switch back to your pi account.

USING PIPES
As well as directing input and output to and from Ƭles, you can send the output from one command directly into another. This
is known as piping, and uses the pipe character “_”.

STEP 1 As you start to get more advanced in Linux, you begin STEP 3 You can pipe commands multiple times. Enter:
to create more powerful commands, and one way FDWEDQGVW[W_VRUW_JUHS7KH to get
you do this is by using the pipe character (“|”). Take some time to Ƭnd the bands starting with “The” in alphabetical order. The output of
this character if you haven’t already: it usually sits above or to the left the text from the bands.txt document is passed into sort, and the
of the Return key on most keyboards. output from sort is passed into grep which Ƭlters out the bands
starting with “The”. These bands form the output.

STEP 2 We’ve used the pipe a few times in the book (“ps STEP 4 You can combine pipes with input and output to
aux | less”), but you might not have understood create complex expressions. You can also use >>
what’s actually happening. Enter: FDWEDQGVW[W_ZF. The to append outputted data to a Ƭle that already exists. Enter: cat
output from the cat command (the text inside the document) EDQGVW[W_ZF!!EDQGVW[W. This takes the output from
isn’t displayed on the screen, instead it is piped into the wc (word the bands.txt Ƭle and pipes it into the wc (word count) function. The
count) function. This then tells us how many lines, words and output from wc is appended to the end of the bands.txt Ƭle. Enter:
characters are in the document. FDWEDQGVW[W to view it.

www.bdmpublications.com 137
Learning Linux

Fun Things to Do in
the Terminal
Despite the seriousness of an operating system, the Linux community are certainly no
strangers to a bit of fun. Over the years, the developers have created and inserted all
manner of quirky and entertaining elements into the Terminal.

TERMINAL FUN
All these commands are Linux-based, so not only can you use them on the Raspberry Pi but also on any of the Debian-based
Linux distributions.

STEP 1 The Ƭrst command we’re going to use is sl, it’s STEP 3 If you’ve ever fancied having the computer read
not installed by default so enter: sudo apt-get a random fortune out to you then you’re in luck.
install sl. The command can be run with sl and when executed Raspbian requires you to install the Terminal app, Fortune, Ƭrst.
displays a Steam Locomotive travelling across the screen (hence ‘sl’). Enter: sudo apt-get install fortune, then simply enter:
Entering: LS (note the upper case) also works. fortune, into the Terminal to see what comes up.

STEP 2 Fans of Star Wars even get a Ƭx when it comes STEP 4 The rev command is certainly interesting, and at
to the Terminal. By linking to a remote server via Ƭrst what seems a quite useless addition to the
the telnet command, you can watch Episode IV: A New Hope being OS can, however, be used to create some seemingly unbreakable
played out, albeit in ASCII. To view this spectacle, enter: sudo passwords. Enter: rev and then type some text. Then press Enter
apt-get install telnet, followed by: telnet towel. and everything you typed in is reversed. Press Ctrl+C to exit.
blinkenlights.nl

138 www.bdmpublications.com
Fun Things to Do in the Terminal

STEP 5 If you’re stuck trying to work out all the possible STEP 8 If you really want to expand the whole cow thing,
factors for any particular number, simply enter: for whatever reason, then pipe the fortune
factor followed by the number. For example, factor 7 doesn’t command through it, with: fortune | cowsay; and for the
oƪer much output, whereas factor 60 displays more. graphical cow equivalent: IRUWXQH_[FRZVD\. Plus, there’s
always cowthink. Try: cowthink ...This book is awesome.

STEP 6 There’s a Ƭne line between the rather cool and STEP 9 Admittedly, the command ‘toilet’ doesn’t inspire
the really quite weird. Having an ASCII cow repeat much conƬdence. However, it’s not as bad as it
text to you could potentially fall into the latter. Start by installing Ƭrst sounds. Start by installing it with: sudo apt-get install
cowsay: sudo apt-get install cowsay, then enter: cowsay toilet, then when it’s installed, type something along the lines of:
Raspberry Pi is Ace!. In fact, you can even output the ls toilet David; or perhaps list the contents of the current folder
command through the cow, by entering: ls | cowsay. through it, with: ls | toilet.

STEP 7 To further the cow element, there’s even a STEP 10 Expanding the toilet command, you can actually
graphical, i.e. non-Terminal, cow available. Install generate some decent looking graphics through
it with: VXGRDSWJHWLQVWDOO[FRZVD\, then when it’s it. For example, try this: toilet -f mono12 -F metal David.
installed enter something similar to cowsay, such as: [FRZVD\%'0 You can enter: toilet --help, for a list of the command line
Publications are ace!. arguments to expand further.

www.bdmpublications.com 139
Learning Linux

More Fun Things to Do in


the Terminal
If the previous list of bizarre, and fun things to do in the Terminal has you wanting
more, you’re in luck. We’ve put together another batch of both useful, and not so
useful, commands for you to try out.

MORE FUN, YAY


Since the Terminal session is already open, and your keyboard digits are nicely warmed up, here are another two pages of
Terminal nonsense.

STEP 1 Remember the old ZX Spectrum days of computing, STEP 3 Having a little white cat chase your mouse pointer
when you could type in 10 print “Hello”, 20 goto around the desktop may sound like a terrible waste
10 and Hello would list down the screen? Well, in Raspbian you can of time. Oddly though, it isn’t. Enter: sudo apt-get install
do the same. Simply enter: yes followed by some text, i.e. yes oneko, then type: oneko to have the cat appear. Move your ‘mouse’
Raspberry Pi is ace. It keeps going until you press Ctrl+C. cursor around the screen and the cat chases it. Use Ctrl+C to exit
the action.

STEP 2 The Matrix was one of the most visually copied STEP 4 This entry is a little more serious than the previous.
Ƭlms ever released and there’s even a version of Fork Bomb is a command that continually replicates
the Matrix code available for Linux. Install it with: sudo apt-get itself until it has used up all the available system resources,
LQVWDOOFPDWUL[. When it’s done enter: cmatrix and follow the eventually causing your computer to crash. You don’t have to try it,
white rabbit, Neo. Unlike the real Matrix though, you can press but it’s interesting nonetheless. Simply enter: :(){ :|:& }: and
Ctrl+C to exit. be prepared to reboot.

140 www.bdmpublications.com
More Fun Things to Do in the Terminal

STEP 5 Stringing several commands and piping them STEP 8 Used as a music demo from the old Amiga and DOS
through other commands is what makes scripting days, the bb command evokes memories of three and
such a powerful element to an OS. For example, using the while a half inch Ʈoppies crammed with all manner of demo scene goodies.
command, together with toilet, can yield some impressive results. You’ve already installed bb from the previous step, so just enter: bb.
Enter: while true; do echo “$(date ‘+%D %T’ | toilet Follow the onscreen instructions and turn up your volume.
-f term -F border --metal)”; sleep 1; done.

STEP 6 Talking computers were the craze of the ‘80s. To STEP 9 This entry is in two parts. First you need to get
re-live the fun enter: sudo apt-get install hold of the necessary packages: sudo apt-
espeak, then: espeak “This is a Raspberry Pi” to have get install libcurses-perl. When that’s done enter: cd
the computer repeat the text inside the quotes to you. Make sure Downloads/ && wget http://search.cpan.org/CPAN/
your volume is turned up and try the following: OV!IROGHUV DXWKRUVLG..%.%$8&207HUP$QLPDWLRQWDUJ]
W[W HVSHDNIIROGHUVW[W. This gets Raspbian to read WDU[I7HUP$QLPDWLRQWDUJ] FG7HUP
back the contents of the ls command. $QLPDWLRQ)ROORZHGE\SHUO0DNHÀOH3/ 
make && make test && sudo make install.

STEP 7 A roaring ASCII Ƭre isn’t the most useful command


to have at your disposal but it’s fun. Install it with:
sudo apt-get install libaa-bin, then use: DDÀUH. It’s not
exactly warming but you get the idea. To expand the above, enter:
sudo apt-get install bb caca-utils, then: FDFDÀUH.

STEP 10 With that little lot completed, onto the next


part. Enter: cd .. && wget http://www.
robobunny.com/projects/asciiquarium/asciiquarium.
WDUJ] WDU[IDVFLLTXDULXPWDUJ] FG
DVFLLTXDULXPB FKPRG[DVFLLTXDULXP. Providing
all went well, enter: ./asciiquarium and enjoy your very own
ASCII-based aquarium.

www.bdmpublications.com 141
Learning Linux

Linux Tips and Tricks


The Linux Terminal, you’ll no doubt agree, is an exceptional environment and with a
few extra apps installed along with a smidgen of command knowledge, incredible and
often quite strange things can be accomplished.

TAKING COMMAND
There are countless Linux tips, secrets, hacks and tricks out there. Some are very old, originating from Linux’s Unix heritage,
while others are recent additions to Linux lore. Here are our ten favourite tips and tricks.

EASTER EGGS Emacs text editor, is a great piece of TERMINAL BROWSING Ever fancied being able to
software but did you know it also contains browse the Internet from
a hidden Easter Egg? With Emacs installed (sudo apt-get install the Terminal? While not particularly useful, it is a fascinating thing to
emacs24), drop to a Terminal session and enter: behold. To do so, enter:
emacs -batch -l dunnet sudo apt-get install elinks
Dunnet is a text adventure written by Ron Schnell in 1982, and Then:
hidden in Emacs since 1994.
elinks
Enter the website you want to visit.

MOON BUGGY Based on the classic 1982 arcade game, LET IT SNOW Snowing in the Terminal console isn’t
Moon Patrol, Moon Buggy appeared something you come across every day. If
on home computers in 1985 amid much praise. It’s a cracking Atari you’re interested, however, enter:
game available in the Linux Terminal by entering:
wget
sudo apt-get install moon-buggy
KWWSVJLVWJLWKXEXVHUFRQWHQWFRPVRQWHN
Then: UDZGHDHIEIHHIFD
snowjob.sh
moon-buggy
FKPRG[VQRZMREVK
Enjoy.
./snowjob.sh

142 www.bdmpublications.com
Linux Tips and Tricks

MEMORY HOGS Memory Hogs – If you need to see BBS Back in the days of dial-up connections, the online world
which apps are consuming the most was made up of Bulletin Board Systems. These remote
memory on your Raspberry Pi, simple enter: servers provided hangouts for users to chat, swap code, play games
and more. Using Telnet in Linux, you can still connect to some active
SVDX[_VRUWUQN
BBSes:
This sorts the output by system memory use.
telnet battlestarbbs.dyndns.org
There are countless operational BBSes available; check out
www.telnetbbsguide.com/bbs/list/detail/ for more.

SHREDDER When you delete a Ƭle, there’s still a chance of


someone with the right software being able to
retrieve it. However, Ƭles can be securely and permanently deleted
using Shred:
DIRECTORY TREES If you want to create an entire
VKUHG]YX1$0(2)),/(W[W directory (or folder) tree with a
single command, you can use:
Replace NAMEOFFILE with the name of the Ƭle to delete.
mkdir -p New-Dir/
^VXEIROGHUVXEIROGHUVXEIROGHUVXEIROGHU`
This creates a New-Dir with four sub folders within.

ASCII ART ASCII art can be quite striking when applied to


some images. However, it’s often diƯcult to FORGOTTEN COMMANDS It’s not easy trying
get just right. You can create some great ASCII art from the images to remember all the
you already have on the Raspberry Pi by using img2txt: available Linux commands. Thankfully, you can use apropos to help.
Simply use it with a description of the command:
LPJW[W1$0(2),0$*(),/(SQJ
DSURSRV´FRS\ÀOHVµ
Replace NAMEOFIMAGEFILE with the actual name of the image Ƭle
DSURSRV´UHQDPHÀOHVµ
on your system.

www.bdmpublications.com 143
Learning Linux

Command Line
Quick Reference
When you start using Linux full time, you will quickly realise that the graphical
interfaces of Ubuntu, Mint, etc. are great for many tasks but not great for all tasks.
Understanding how to use the command line not only builds your understanding of
Linux but also improves your knowledge of coding and programming in general. Our
command line quick reference guide is designed to help you master Linux quicker.

TOP 10 COMMANDS
These may not be the most common commands used by everyone but they will certainly feature frequently for many users of
Linux and the command line.

The cd command is one of the commands you The mv command moves a Ƭle to a diƪerent
will use the most at the command line in Linux. It location or renames a Ƭle. For example PYÀOH
cd allows you to change your working directory. You mv sub renames the original Ƭle to sub. mv sub
use it to move around within the hierarchy of your ~/Desktop moves the Ƭle ‘sub’ to your desktop
Ƭle system. You can also use chdir. directory but does not rename it. You must specify
a new Ƭlename to rename a Ƭle.

The ls command shows you the Ƭles in your The chown command changes the user and/
current directory. Used with certain options, it lets or group ownership of each given Ƭle. If only an
ls you see Ƭle sizes, when Ƭles where created and Ƭle chown owner (a user name or numeric user ID) is given,
permissions. For example, ls ~ shows you the Ƭles that user is made the owner of each given Ƭle, and
that are in your home{directory. the Ƭles’ group is not changed.

The cp command is used to make copies of Ƭles The chmod command changes the permissions on
and directories. For example, FSÀOHVXE makes the Ƭles listed. Permissions are based on a fairly
cp an exact copy of the Ƭle whose name you entered cmod simple model. You can set permissions for user,
and names the copy sub but the Ƭrst Ƭle will still group and world and you can set whether each can
exist with its original{name. read, write and or execute the Ƭle.

The pwd command prints the full pathname of The rm command removes (deletes) Ƭles or
the current working directory (pwd stands for directories. The removal process unlinks a Ƭlename
pwd “print working directory”). Note that the GNOME rm in a Ƭlesystem from data on the storage device
terminal also displays this information in the title and marks that space as usable by future writes. In
bar of its window. other words, removing Ƭles increases the amount
of available space on your disk.

The clear command clears your screen if this Short for “make directory”, mkdir is used to
is possible. It looks in the environment for the create directories on a Ƭle system, if the speciƬed
clear terminal type and then in the terminfo database mkdir directory does not already exist. For example,
to Ƭgure out how to clear the screen. This is mkdir work creates a work directory. More than
equivalent to typing Control-L when using the one directory may be speciƬed when calling mkdir.
bash shell.

144 www.bdmpublications.com
Command Line Quick Reference

C:\Commonly_Used_Commands

USEFUL HELPǖINFO COMMANDS


The following commands are useful for when
you are trying to learn more about the system or
program you are working with in Linux. You might
not need them every day, but when you do, they
will be invaluable.

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

The df command displays Ƭlesystem disk space


The adduser command adds a new user to the
df usage for all partitions. The command df-h adduser system. Similarly, the addgroup command adds a
is probably the most useful (the -h means
new group to the {system.
human-readable).

The top program provides a dynamic real-time The deluser command removes a user from
view of a running system. It can display the system. To remove the user’s Ƭles and
top system summary information, as well as a list deluser home directory, you need to add the -remove-
of processes. home option.

The uname command with the -a option prints The delgroup command removes a group from
uname-a all system information, including machine name, delgroup the system. You cannot remove a group that is the
kernel name, version and a few other details. primary group of any users.

The ps command allows you to view all the


The man man command brings up the manual
processes running on the machine. Every
ps operating system’s version of ps is slightly man man entry for the man command, which is a great place
to start when using it.
diƪerent but all do the same thing.

The grep command allows you to search inside a The man intro command is especially useful.
number of Ƭles for a particular search pattern and It displays the Introduction to User Commands,
grep then print matching lines. An example would be: man intro which is a well written, fairly brief introduction to
JUHSEODKÀOH. the Linux command line.

www.bdmpublications.com 145
Learning Linux

A-Z of Linux Commands


There are literally thousands of Linux commands, so while this is not a complete A-Z, it
does contain many of the commands you will most likely need. You will probably Ƭnd
that you end up using a smaller set of commands over and over again but having an
overall knowledge is still very useful.

A
adduser Add a new user dd Data Dump, convert and
G
gawk Find and Replace text
copy a Ƭle within Ƭle(s)
arch Print machine architecture
diff Display the diƪerences grep Search Ƭle(s) for lines that
awk Find and replace text
between two Ƭles match a given pattern
within Ƭle(s)
dirname Convert a full path name groups Print group names a user

B
to just a path is in
du Estimate Ƭle space usage gzip Compress or decompress
bc An arbitrary precision named Ƭle(s)
calculator language

E H
C
cat Concatenate Ƭles and print
echo
ed
Display message on screen
A line oriented text editor
head Output the Ƭrst part
of Ƭle(s)
on the standard output (edlin)
hostname Print or set system name
chdir Change working directory egrep Search Ƭle(s) for lines
that match an

I
chgrp Change the group
extended expression
ownership of Ƭles
env Display, set or remove
chroot Change root directory id Print user and group ids
environment variables
cksum Print CRC checksum and info Help info
H[SDQG Convert tabs to spaces
byte counts
install Copy Ƭles and
H[SU Evaluate expressions
cmp Compare two Ƭles set attributes

F
comm Compare two sorted Ƭles

cp
line by line
Copy one or more Ƭles to factor Print prime factors
J
join Join lines on a
another location
fdisk Partition table common Ƭeld
crontab Schedule a command to manipulator for Linux

K
run at a later time
fgrep Search Ƭle(s) for lines that
csplit Split a Ƭle into context- match a Ƭxed string
determined pieces kill Stop a process
ÀQG Search for Ƭles that meet
from running
cut Divide a Ƭle into a desired criteria
several parts

L
fmt Reformat paragraph text

D
fold Wrap text to Ƭt a
speciƬed width less Display output one screen
at a time
date Display or change the format Format disks or tapes
date & time ln Make links between Ƭles
fsck Filesystem consistency
dc Desk calculator check and repair locate Find Ƭles

146 www.bdmpublications.com
A-Z of Linux Commands

logname
lpc
Print current login name
Line printer
rm
rmdir
Remove Ƭles
Remove folder(s) U
umount Unmount a device
control program rpm Remote Package Manager
XQH[SDQG Convert spaces to tabs
lpr Oƪ line print rsync Remote Ƭle copy
(synchronise Ƭle trees) uniq Uniquify Ƭles
lprm Remove jobs from the
print queue units Convert units from one

S
scale to another

M
man See Help manual
screen Terminal window manager
unshar
useradd
Unpack shell archive scripts
Create new user account
sdiff Merge two Ƭles interactively
usermod Modify user account
mkdir Create new folder(s) select Accept keyboard input
users List users currently
PNÀIR Make FIFOs (named pipes) seq Print numeric sequences logged in
mknod Make block or character shutdown Shutdown or restart Linux

V
special Ƭles
sleep Delay for a speciƬed time
more Display output one screen
at a time sort Sort text Ƭles vdir Verbosely list directory
mount Mount a Ƭle system split Split a Ƭle into contents (Cls -l -b’)
Ƭxed-size pieces

N
SSH Connects to a remote host
computer as a speciƬed
user, using secure
W
watch Execute or display a
nice Set the priority of a
encrypted protocols. program periodically
command or job
su Substitute user identity wc Print byte, word, and
nl Number lines and
sudo Execute a command as line counts
write Ƭles
another user, primarily as whereis Report all known
nohup Run a command immune the Root level, instances of a command
to hangups administrator user.
which Locate a program Ƭle in
sum Print a checksum for a Ƭle

P
the user’s path
symlink Make a new name for who Print all usernames
a Ƭle currently logged in
passwd Modify a user password
paste Merge lines of Ƭles sync Synchronise data on disk whoami Print the current user id
with memory and name
pathchk Check Ƭle name portability
pr

printcap
Convert text Ƭles
for printing
Printer capability database
T
tac Concatenate and write
X
[DUJV Execute utility, passing
Ƭles in reverse
printenv Print environment variables constructed argument list(s)
tail Output the last part
printf Format and print data

Y
of Ƭles
tar Tape Archiver

Q tee Redirect output to


multiple Ƭles
yes Print a string
until interrupted
quota Display disk usage test Evaluate a
and limits conditional expression

quotacheck Scan a Ƭle system for time Measure Program


disk usage Resource Use

quotactl Set disk quotas touch Change Ƭle timestamps


top List processes running on

R
the system
traceroute Trace Route to Host
ram Ram disk device tr Translate, squeeze and or
rcp Copy Ƭles between delete characters
two machines tsort Topological sort

www.bdmpublications.com 147
Index

Code
Repository

SHARE YOUR CODE!


The code listed within this section can be downloaded
as a Python Ƭle, so you don’t have to type it out. Simply
visit www.bdmpublications.com/code-portal, sign up
for access to the portal and the code is available as a
compressed Ƭle for you to download and execute.
Maybe you’ve written something amazing and want to
show it oƪ; if so, why not send it in and we can add it
to the Code Portal as well as mention it via our social
media accounts.
Tell us what the code does, how it works (don’t forget
to include comments in the code) and what platform to
run it on.
Send it in to: enquiries:bdmpublications.com. We look
forward to seeing what you’ve done.

148 www.bdmpublications.com
Code Repository

We’ve included a unique Python code


repository for you to freely use in your
own programs. There’s everything you can
think of in here to help you create a superb
piece of programming.
We’ve got code that covers number
guessing games, random number
generators, Google search code, game
code, animation code, graphics code, text
adventure code, and even code that plays
music stored on your computer.
This is an excellent resource that you
won’t Ƭnd in any other Python book. So
use it, take it apart, adapt it to your own
programs, and see what you can create.

150 Python File Manager


152 Number Guessing Game
154 Polygon Circles
155 Random Number Generator
156 Random Password Generator
157 Keyboard Drawing Script
158 Pygame Text Examples
159 Google Search Script
160 Text to Binary Convertor
162 Text Adventure Script
164 Mouse Controlled Turtle
165 Python Alarm Clock
166 Vertically Scrolling Text
168 Python Digital Clock
170 Python Scrolling Ticker Script
171 Simple Python Calculator
172 Playing Music with the Winsound Module
174 Hangman Game Script

www.bdmpublications.com 149
Code Repository

Python File Manager


This Ƭle manager program displays FILEMAN.PY
a list of options that allow you to Copy the code below into a New > File and save it as FileMan.py.
read a Ƭle, write to a Ƭle, append to Once executed it will display the program title, along with the
current time and date and the available options.
a Ƭle, delete a Ƭle, list the contents
of a directory and much more. It’s
remarkably easy to edit and insert import shutil
import os
into your own code, or add to. import time 1
import subprocess

def Read():
path=iQput(³(Qter the ¿le path to read:´)
¿le=opeQ(path´r´)
priQt(¿leread()) 2
iQput(µ3ress (Qter¶)
¿leclose()

def Write():
path=iQput(³(Qter the path of ¿le to Zrite or create:´)
if ospathis¿le(path):
priQt(µRebuildiQJ the e[istiQJ ¿le¶)
else:
priQt(µCreatiQJ the QeZ ¿le¶)
te[t=iQput(³(Qter te[t:´)
¿le=opeQ(path´Z´)
¿leZrite(te[t)

def Add():
path=iQput(³(Qter the ¿le path:´)
te[t=iQput(³(Qter the te[t to add:´)
¿le=opeQ(path´a´)
¿leZrite(µ?Q¶te[t)

def Delete():
This part of the code imports the necessary modules. path=iQput(³(Qter the path of ¿le for deletioQ:´)
1 The OS and Subprocess modules deal with the if ospathe[ists(path):
priQt(µ)ile )ouQd¶)
operating system elements of the program.
osremoYe(path)
priQt(µ)ile has beeQ deleted¶)
Each def XXX() functions store the code for each
2 of the menu’s options. Once the code within the
else:
priQt(µ)ile Does Qot e[ist¶)
function is complete, the code returns to the main
menu for another option. def Dirlist():
path=iQput(³(Qter the Director\ path to displa\:´)
This is part of the code that checks to see what OS sortlist=sorted(oslistdir(path))
3 the user is running. In Windows the CLS command i=0
clears the screen, whereas in Linux and macOS, the Zhile(ileQ(sortlist)):
priQt(sortlist>i@¶?Q¶)
Clear command wipes the screen. If the code tries
i=
to run CLS when being used in Linux or macOS, an
error occurs, which then prompts it to run the Clear def Check():
command instead. fp=iQt(iQput(µCheck e[isteQce of ?Q)ile ?Q
Director\?Q¶))
These are the options, from 1 to 12. Each executes if fp==:
4 the appropriate function when the relevant number path=iQput(³(Qter the ¿le path:´)
is entered. ospathis¿le(path)

150 www.bdmpublications.com
Python File Manager

if ospathis¿le(path)==7rue: 5/ist ¿les iQ a directory


priQt(µ)ile )ouQd¶) 6Check ¿le existeQce
else: 7MoYe a ¿le
priQt(µ)ile Qot fouQd¶) 8Copy a ¿le
if fp==: 9Create a directory
path=iQput(³EQter the directory path:´) 0Delete a directory
ospathisdir(path) OpeQ a proJram
if ospathisdir(path)==)alse: Exit
priQt(µDirectory )ouQd¶)
else: µ¶¶))
priQt(µDirectory 1ot )ouQd¶) if dec==:
Read()
def MoYe(): if dec==:
path=iQput(µEQter the source path of ¿le to moYe:¶) Write()
mr=iQt(iQput(µReQame ?QMoYe ?Q¶)) if dec==:
if mr==: Add()
path=iQput(µEQter the destiQatioQ path aQd ¿le Qame:¶) if dec==4:
shutilmoYe(pathpath) Delete()
priQt(µ)ile reQamed¶) if dec==5:
if mr==: Dirlist()
path=iQput(µEQter the path to moYe:¶) if dec==6:
shutilmoYe(pathpath) Check()
priQt(µ)ile moYed¶) if dec==7: 4
MoYe()
def Copy(): if dec==8:
path=iQput(µEQter the path of the ¿le to copy or reQame:¶) Copy()
path=iQput(µEQter the path to copy to:¶) if dec==9:
shutilcopy(pathpath) Makedir()
priQt(µ)ile copied¶) if dec==0:
RemoYedir()
def Makedir(): if dec==:
path=iQput(³EQter the directory Qame Zith path to make OpeQ¿le()
?QeJ C:??+ello??1eZdir ?QWhere 1eZdir is QeZ if dec==:
directory:´) exit()
osmakedirs(path) ruQ=iQt(iQput(³ReturQ to meQu?QExit ?Q´))
priQt(µDirectory Created¶) if ruQ==:
exit()
def RemoYedir():
path=iQput(µEQter the path of Directory:¶)
treedir=iQt(iQput(µDeleted Directory ?QDelete
Directory 7ree ?QExit ?Q¶))
if treedir==:
osrmdir(path)
if treedir==:
shutilrmtree(path)
priQt(µDirectory Deleted¶)
if treedir==:
exit()

def OpeQ¿le():
path=iQput(µEQter the path of proJram:¶)
try:
osstart¿le(path)
except:
priQt(µ)ile Qot fouQd¶)

ruQ= Imports
Zhile(ruQ==): There are three modules to import here: Shutil, OS and
try: Time. The Ƭrst two deal with the operating system and Ƭle
ossystem(µclear¶)
except OSError: 3 management and manipulation; and the Time module simply
displays the current time and date.
ossystem(µcls¶)
priQt(µ?Q!!!!!!!!!!3ythoQ  )ile MaQaJer?Q¶)
priQt(µ7he curreQt time aQd date is:¶timeasctime()) Note how we’ve included a try and except block to check if
priQt(µ?QChoose the optioQ Qumber: ?Q¶) the user is running the code on a Linux system or Windows.
dec=iQt(iQput(µ¶¶Read a ¿le Windows uses CLS to clear the screen, while Linux uses clear.
Write to a ¿le The try block should work well enough but it’s a point of
AppeQd text to a ¿le possible improvement depending on your own system.
4Delete a ¿le

www.bdmpublications.com 151
Code Repository

Number Guessing Game


This is a simple little piece of NUMBERGUESS.PY
code but it makes good use of the Copy the code and see if you can beat the computer within
Random module, print and input, Ƭve guesses. It’s an interesting bit of code that can be quite
handy when your implementing a combination of the Random
and a while loop. The number of module alongside a while loop.
guesses can be increased from 5
and the random number range can import random 1
easily be altered too. guessesUsed = 0
1ame=input(µ+ello What is your name" µ)
number = randomrandint( 0)
print(µ*reetings µ  1ame  µ ,?¶m thinking of a
number betZeen  and 0¶)
Zhile guessesUsed  5:
guess=int(input(µ*uess the number Zithin 5 guesses¶))
guessesUsed = guessesUsed  
if guess  number:
print(µ7oo loZ try again¶)
if guess ! number: 2
print(µ7oo high try again¶)
if guess == number:
break
if guess == number:
guessesUsed = str(guessesUsed)
print(µWell done µ  1ame  µ <ou guessed
correctly in µ  guessesUsed  µ guesses¶)
3
if guess = number:
number = str(number)
print(µSorry out of guesses 7he number , Zas
thinking of is µ  number)

Although this is a reasonably easy to follow program, there are


1 some elements to the code that are worth pointing out. To begin
with, you need to import the Random module, as you’re using
random numbers within the code.
This section of the code creates the variables for the number
2 of guesses used, along with the name of the player, and also
sets up the random number between 1 and 30. If you want a
wider range of random number selection, then increase the
number=random.randint(1, 30) end value of 30; don’t make
it too high though or the player will never be able to guess it.
If the player guesses too low or too high, they are given the
appropriate output and asked to try again, while the number
of guesses is less than Ƭve. You can also increase the number of
guesses from 5 by altering the while guessesUsed  5: value.
If the player guessed the correct number then they are given a
3 ‘well done’ output, along with how many guesses they used up.
If the player runs out of guesses, then the game over output is
displayed instead, along with revealing the number the computer
was thinking of. Remember, if you do alter the values of the
random number chosen by the computer, or the number of
guesses the player can take, then along with the variable values,
you also need to amend the instructions given in the print
statements at the start of the code.

152 www.bdmpublications.com
Number Guessing Game

Code Improvements
Since this is such as simple script to apply to a situation, there’s For example, as per the screenshot provided, you could use
plenty of room to mess around with it and make it more something along the lines of:
interesting. Perhaps you can include an option to take score, the
best out of three rounds. Maybe an elaborate way to congratulate Endurance=0
the player for getting a ‘hole in one’ correct guess on their Ƭrst try. CR=0
/uck=0
Moreover, the number guessing game code does oƪer some room Endurance = randomrandint( 5)
CR = randomrandint( 0)
for implementing into your code in a diƪerent manner. What
/uck = randomrandint( 0)
we mean by this is, the code can be used to retrieve a random 3rint(³<our character¶s stats are as folloZs:?n´)
number between a range, which in turn can give you the start of a 3rint(³Endurance:´ Endurance)
character creation deƬned function within an adventure game. 3rint(³Combat Rating:´ CR)
3rint(³/uck:´ /uck)
Imagine the start of a text adventure written in Python, where
the player names their character. The next step is to roll the
The player can then decide to either stick with their roll or try again
virtual random dice to decide what that character’s combat
for the hope of better values being picked. There’s ample ways in
rating, strength, endurance and luck values are. These can then be
which to implement this code into a basic adventure game.
carried forward into the game under a set of variables that can be
reduced or increased depending on the circumstances the player’s
character ends up in.

www.bdmpublications.com 153
Code Repository

Polygon Circles
Here’s a fun, and mathematical, POLYGONCIRCLES.PY
look at making a circle from There’s lots of mathematics used here along with some
straight lines. Using the Math intricate coordinate manipulation with the Turtle module.
Enter the code and execute it to see how it turns out.
module, in particular sin, cos and
Pi, this code will draw a series from turtle import*
from math import sin cos pi
of straight lines using the Turtle r=00
module. The end result is quite inc=*pi00
t=0n=5
remarkable and has plenty of for i in range(00):
x=r*sin(t) y=r*cos(t)
scope for further exploration. x=r*sin(tn)y=r*cos(tn)
penup() goto(xy)
pendoZn()goto(xy)
t=inc

Graphical Enhancements
There are several ways in which you can improve this code to make For example:
it more interesting. You can insert colours, perhaps a diƪerent
colour for every line. You can display a message inside the circle for i in range(00):
and have the Turtle draw around it. Let your imagination run wild x=r*sin(t) y=r*cos(t)
on this one. x=r*sin(tn)y=r*cos(tn)
speed(µfastest¶)
penup() goto(xy)
Turtle’s graphics can take a while to map out and draw, depending
pendoZn()goto(xy)
on how big and how intricate an image it is you’re designing. Whilst t=inc
the eƪect can be quite stunning, it is limited by the amount of
time it takes to display an image. Therefore it’s worth seeing if the
This will run through the code at the ‘fastest’ speed possible for
function turtle.speed() will quicken things up.
the Turtle. It certainly makes a diƪerence and is worth considering
if you’re drawing Turtle images for games or presentations.
Turtle.speed() comes in various values:

sloZest
sloZ
normal
fast
fastest

You can experiment with the various speeds by adding the function
in the for loop, just before the penup line.

154 www.bdmpublications.com
Polygon Circles/Random Number Generator

Random Number Generator


User input and the ability to RNDNUMGEN.PY
manipulate that input are important It might be simple but this little piece of code will ask the user
for two sets of numbers, a start and a Ƭnish. The code will then
elements with any programming pluck out a random number between the two sets and display it.
language. It’s what separates a good
program from a great program, one from random import *

that allows the user to interact and print(“?n!!!!!!!!!!Random 1umber *enerator?n´)


nmb=int(input(“Enter the start number: “))
see the results of that interaction. nmb=int(input(“Enter the last number: “))

x = randint(nmb nmb)
print(“?n7he random number betZeen´nmb´and´nmb´is:?n´)
print(x)

More Input
While an easy code to follow, it could be more interesting if you For example, the code could be edited to this:
prompt the user for more input. Perhaps you can provide them
with addition, subtraction, multiplication elements with their from random import *
numbers. If you’re feeling clever, see if you can pass the code import turtle
through a Tkinter window or even the Ticker window that’s
available on Page 128. print(“?n!!!!!!!!!!Random 7urtle ,mage?n´)
nmb=int(input(“Enter the start number: “))
nmb=int(input(“Enter the second number: “))
Furthermore, the core of the code can be used in a text adventure nmb=int(input(“Enter the third number: “))
game, where the character Ƭghts something and their health, nmb4=int(input(“Enter the fourth number: “))
along with the enemy’s, is reduced by a random number. This
can be mixed with the previous code from Page 90’s Number
Guessing Game, where we deƬned the stats for the adventure turtleforZard(nmb)
game’s character. turtleleft(90)
turtleforZard(nmb)
You can also introduce the Turtle module into the code and turtleleft(90)
perhaps set some deƬned rules for drawing a shape, object or turtleforZard(nmb)
turtleleft(90)
something based on a user inputted random value from a range
turtleforZard(nmb4)
of numbers. It takes a little working out but the eƪect is certainly turtleleft(90)
really interesting.
Whilst it’s a little rough around the edges, you can easily make it
more suitable.

www.bdmpublications.com 155
Code Repository

Random Password
Generator
We’re always being told that our RNDPASSWORD.PY
passwords aren’t secure enough; Copy the code and run it; each time you’ll get a random string
well here’s a solution for you to of characters that can easily be used as a secure password
which will be incredibly diƯcult for a password cracker to hack.
implement into your own future
programs. The random password import string
import random
generator code below will create
def randompassZord():
a 12-letter string of words (both chars=stringascii B uppercase  stringascii B
cases) and numbers each time loZercase  stringdigits
size= 8
it’s executed. return µ¶Moin(randomchoice(chars) for x in
range(size0))

print(randompassZord())

Secure Passwords
There’s plenty you can do to modify this code and improve it Adding a loop to print a password Ƭfty times is extremely easy, for
further. For one, you can increase the number of characters the example:
generated password displays and perhaps you can include special
characters too, such as signs and symbols. Then, you can output import string
the chosen password to a Ƭle, then securely compress it using the import random
previous random number generator as a Ƭle password and send it
to a user for their new password.
def randompassZord():
chars=stringascii B uppercase  stringascii B
An interesting aspect to this code is the ability to introduce a loop loZercase  stringdigits
and print any number of random passwords. Let’s assume you have size= 4
a list of 50 users for a company and you’re in charge of generating return µ¶Moin(randomchoice(chars) for x in
a random password for them each month. range(size0))

n=0
Zhile n50:
print(randompassZord())
n=n

This will output Ƭfty random passwords based on the previous


random selection of characters.

156 www.bdmpublications.com
Random Password Generator/Keyboard Drawing Script

Keyboard Drawing Script


The Turtle module is an excellent resource
for the Python programmer. However,
what makes it more interesting, is its
ability to enable the user to control the
turtle on the screen. This piece of code
does exactly that, allowing the user to
unleash their inner artist.
KEYBDRAW.PY
There are two modules in this script: Turtle and Tkinter. The
Turtle module is the main display, where the user controls the
drawing, whereas Tkinter simply displays the user controls.
“´´
All moYements and turns are by increments of 5
Right arroZ key = moYe forZard
/eft arroZ key = moYe backZard
r = turn right
l = turn left
1
u = pen up
d = pen doZn
h = go home
c = clear
“´´ Artwork
from tkinter import * Just as with all code, there’s always room for improvement
from turtle import * somewhere. Here you could change the colours or ask the user
which colour they want to start with and then include a key in
root = 7k() the controls to change the pen colour whilst drawing. There’s
7 = 7ext(root root title(“Controls´)height=8 Zidth=60) also room to increase or decrease the speed of the pen, again
7pack() that could be a user-deƬned speed. You can also expand the
7insert(E1D “Right arroZ key = moYe forZard? controls thoroughly to include a lot more detail and options.
n/eft arroZ key = moYe backZard?nr = turn right?nl
= turn left?nu = pen up?nd = pen doZn?nh = go home?
nc = clear´)

def main():
Zidth()
speed(0) 2
pencolor(“blue´)
onkey(up “u´)
onkey(doZn “d´)
onkey(clear “c´) An initial set of comments to display the controls, which can
onkey(home “h´) 1 also be outputted as a separate tkinter window if you want,
onkey(lambda: forZard(5) “Right´)
and importing the necessary modules: tkinter and turtle.
onkey(lambda: back(5) “/eft´)
onkey(lambda: left(5) “l´)
Setting up the separate tkinter window displaying the controls
onkey(lambda: right(5) “r´)
listen() 2 and creating a function to deƬne the width, speed and colour
return “Done´ of the line being drawn; also setting up the onkey functions for
if B B name B B == “ B B main B B ´: the controls of the pen.
msg = main()
print(msg) 3 A neat way to Ƭnalise the code and loop it so you can continue
mainloop() 3 drawing with the pen.

www.bdmpublications.com 157
Code Repository

Pygame Text Examples


There’s a lot you can do using the text = fontrender(“Upside doZn text´ 7rue %/AC.)
text = pygametransformrotate(text 80)
Pygame module that’s not related screenblit(text >0 0@)

to displaying graphics. The module text = fontrender(“Flipped text´ 7rue %/AC.)


contains many functions which can text = pygametransformÀip(text False 7rue)
screenblit(text >0 0@)
manipulate text, such as Ʈipping it,
text = fontrender(“Rotating text´ 7rue %/AC.)
displaying it sideways, upside down text = pygametransformrotate(text text B
and even rotating it with animations. rotate B degrees)
text B rotate B degrees = 
screenblit(text >00 50@)
TXTROT.PY
pygamedisplayÀip()
Here we’ve introduced several examples of
displaying text within the Pygame module. Each is clocktick(60)
easily recognised within the code, so you can pull it
out and use it in your code. pygameTuit()

import pygame
pygameinit()
The Joy Of Text
%/AC. = (0 0 0)
Here, you can see that we’ve started by deƬning the colours
W+,7E = (55 55 55)
but left the text black throughout the rest of the code; then,
%/UE = (0 0 55)
*REE1 = (0 55 0) also left the display window with a white background. The code
RED = (55 0 0) itself is fairly easy to follow and you can improve it by using
diƪerent colours, changing the font for each text example, and
3, = 45965 its size too.

size = (400 500) Try using some of the text examples individually in your code as
screen = pygamedisplayset B mode(size) an introduction to your program perhaps. Either way you use
it, it will help make it stand out a little more than the standard
pygamedisplayset B caption(“7ext Examples´)
Python code you will likely come across during your time as
a programmer.
done = False
clock = pygametimeClock()

text B rotate B degrees = 0

Zhile not done:

for eYent in pygameeYentget():


if eYenttype == pygame4U,7:
done = 7rue

screen¿ll(W+,7E)

pygamedraZline(screen %/AC. >0050@


>00 50@)
pygamedraZline(screen %/AC. >0050@
>00 50@)

font = pygamefontSysFont(µCalibri¶ 5


7rue False)
text = fontrender(“SideZays text´ 7rue %/AC.)
text = pygametransformrotate(text 90)
screenblit(text >0 0@)

158 www.bdmpublications.com
Pygame Text Examples/Google Search Script

Google Search Script


Using the OS and Urllib modules, this GOOGLESEARCH.PY
small snippet of code will display a You will need to pip install the Urllib module, unless it’s
window for the user’s input, then pass already installed. It also uses Zenity, which is a Linux-based
(GNOME) tool for creating dialog boxes.
the input to a Google search in their
browser. It’s really quite a handy script import os
import urllibparse
and one that’s easily introduced into google = ospopen(µzenity entry text=´Enter your
your own code. *oogle search: “ title=´*oogle Search´¶)read()
google = urllibparseTuote(google)
ossystem(µchromiumbroZser http:ZZZgooglecom
search"T=s¶  (google))

Searching For More


Here we’ve used the Zenity command to create the dialog box, The last two for Chrome and Internet Explorer respectively.
which as we mentioned is only available to Linux machines (such as
Ubuntu, Raspberry Pi, Linux Mint and so on). If you want to execute There is a Zenity for Windows project available on GitHub at www.
it in Windows you have a couple of possibilities: you can Ƭnd a github.com/kvaps/zenity-windows. It’s a good working version
Windows version of Zenity and pass the user’s query through it; or but you do need to install it to a folder on your system where you
you can create a Tkinter dialog box to pass the information. won’t require administrator access to be able to run the Zenity
program. When you have Zenity installed, you can modify the
You can see that this particular code uses the Chromium browser Windows version of this code in Python to read:
which comes preinstalled on the Raspberry Pi, and some versions
of Linux. To use your favourite browser in Windows, for example, import os
you will need to change the command in the last line of the code import urllibparse
to read Firefox, or whatever you use, together with the Start
command. So essentially, one of the following: google = ospopen(µstart c:?7emp?=enity??bin?
zenity entry text=´Enter your *oogle search: “
title=´*oogle Search´¶)read()
ossystem(µstart ¿refox http:ZZZgooglecom
google = urllibparseTuote(google)
search"T=s¶  (google))
ossystem(µstart ¿refox http:ZZZgooglecom
search"T=s¶  (google))
ossystem(µstart chrome http:ZZZgooglecom
search"T=s¶  (google))

ossystem(µstart iexplore http:ZZZgooglecom


search"T=s¶  (google))

www.bdmpublications.com 159
Code Repository

Text to Binary Convertor


While it may not seem too exciting, TXT2BIN.PY
this text to binary convertor is Naturally we’re using the format function to convert the
actually quite good fun. It also user’s entered text string into its binary equivalent. If you
want to check its accuracy, you can plug the binary into an
only uses two lines of code, so it’s online convertor.
extremely easy to insert into your
own script. text=input(“Enter text to conYert to %inary: “)

print(µ µMoin(format(ord(x) µb¶) for x in text))

160 www.bdmpublications.com
Text to Binary Convertor

1000010 1101001 1101110 1100001 1110010


1111001
The text to binary convertor does oƪer some room for
pygamedisplayset B caption(“%inary ConYersion´)
improvement and enhancement. There are many uses: it could be
utilised in a password or secret word script, as part of an adventure done = False
game or just a novel way to display someone’s name. clock = pygametimeClock()

With regards to improvements, you could display the binary text B rotate B degrees = 0
conversion in a Pygame window, using the animated text options
from page 100. You could also ask the user if they wanted to have %inary=(µ µMoin(format(ord(x) µb¶) for x
another go, or even ask if they wanted the binary output to be in conYersion))
saved to a Ƭle.
Zhile not done:

With regards to rendering the outputted binary conversion to a for eYent in pygameeYentget():
Pygame window, complete with rotating text, you can use: if eYenttype == pygame4U,7:
done = 7rue
import pygame
pygameinit() screen¿ll(W+,7E)
font = pygamefontSysFont(µCalibri¶ 5 7rue False)
%/AC. = (0 0 0)
W+,7E = (55 55 55) text = fontrender(%inary 7rue %/AC.)
%/UE = (0 0 55) text = pygametransformrotate(text text B
*REE1 = (0 55 0) rotate B degrees)
RED = (55 0 0) text B rotate B degrees = 
screenblit(text >00 50@)
print(“!!!!!!!!!!7ext to %inary ConYertor?n´) pygamedisplayÀip()

conYersion=input(“Enter text to conYert to %inary: “) clocktick(60)

size = (600 400) pygameTuit()


screen = pygamedisplayset B mode(size)
print(µ µMoin(format(ord(x) µb¶) for x in conYersion))

www.bdmpublications.com 161
Code Repository

Text Adventure Script


Text adventures are an excellent ADVENTURE.PY
way to build your Python coding The Adventure game uses just the Time module to begin
skills and have some fun at the with, creating pauses between print functions. There’s a help
system in place to expand upon, as well as the story itself.
same time. This example that we
created will start you on the path
to making a classic text adventure; import time

where it will end is up to you. print(“?n´ * 00)


print(“!!!!!!!!!!AZesome AdYenture?n´)
print(“?n´ * )
timesleep()
print(“?nA long time ago a Zarrior strode forth from
the frozen north´)
timesleep()
print(“Does this Zarrior haYe a name"´)
name=input(“! “)
print(name “the barbarian sZord in hand and looking
for adYenture´)
timesleep()
print(“+oZeYer eYil is lurking nearby´)
timesleep()
print(“A pair of bulbous eyes regards the hero´)
timesleep()
print(“Will´ name “preYail and Zin great fortune´)
timesleep()
print(“Or die by the hands of great eYil"´)
timesleep()
print(“?n´ *)
print(“Only time Zill tell´)
timesleep()
print(µ¶)
timesleep()
print(µ¶)
timesleep()
print(µ¶)
timesleep()
print(µ¶)
timesleep(5)
print(“?n´ *00)

print(µ¶¶ <ou ¿nd yourself at a small inn 7here¶s


little gold in your purse but your sZord is sharp
and you¶re ready for adYenture
With you are three other customers
A ragged looking man and a pair of dangerous
looking guards¶¶¶)

def start():
print(“?n ´)
print(“Do you approach the´)
print(“?n´)
print(“ Ragged looking man´)
print(“ Dangerous looking guards´)

cmdlist=>“´ “´@
cmd=getcmd(cmdlist)

162 www.bdmpublications.com
Text Adventure Script

if cmd == “´:
ragged() def getcmd(cmdlist):
elif cmd == “´: cmd = input(name´!´)
guards() if cmd in cmdlist:
return cmd
def ragged(): elif cmd == “help´:
print(“?n´ * 00) print(“?nEnter your choices as detailed in
print(µ¶¶<ou Zalk up to the ragged looking man and the game´)
greet him print(“or enter µTuit¶ to leaYe the game´)
+e smiles a toothless grin and Zith a strange return getcmd(cmdlist)
accent says elif cmd == “Tuit´:
“%uy me a cup of Zine and ,¶ll tell you of print(“?n´)
great treasure¶¶¶) timesleep()
timesleep() print(“Sadly you return to your homeland Zithout
fame or fortune´)
def guards(): timesleep(5)
print(“?n´ *00) exit()
print(µ¶¶<ou Zalk up to the dangerous looking guards
and greet them
7he guards look up from their drinks and if B B name B B ==´ B B main B B ´:
snarl at you start()
“What do you Zant barbarian"´ One guard reaches
for the hilt of his sZord¶¶¶)
timesleep()

Adventure Time
This, as you can see, is just the beginning of the adventure and
takes up a fair few lines of code. When you expand it, and weave
the story along, you’ll Ƭnd that you can repeat certain instances
such as a chance meeting with an enemy or the like.

We’ve created each of the two encounters as a deƬned set


of functions, along with a list of possible choices under the
cmdlist list, and cmd variable, of which is also a deƬned function.
Expanding on this is quite easy, just map out each encounter and
choice and create a deƬned function around it. Providing the user
doesn’t enter quit into the adventure, they can keep playing.

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


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

Finally, how about introducing the Random module. This will


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

Needless to say, your text adventure can grow exponentially


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

www.bdmpublications.com 163
Code Repository

Mouse Controlled Turtle


We’ve already seen the Turtle MOUSETURTLE.PY
module being controlled by the The Ƭrst piece of code presents the standard Turtle window.
user via the keyboard but now we Press Space and then click anywhere on the screen for the
Turtle to draw to the mouse pointer. The second allows you to
thought we’d see how the user click the Turtle and drag it around the screen; but be warned,
can use their mouse as a drawing it can crash Python.
tool within Python. We have two 1st Code Example:
possible code examples here, pick
which works best for you. from turtle import Screen 7urtle

screen = Screen()
yertle = 7urtle()

def k0():
screenonscreenclick(click B handler)

def click B handler(x y):


screenonscreenclick(1one)  disable eYent inside
eYent handler
yertlesetheading(yertletoZards(x y))
yertlegoto(x y)
screenonscreenclick(click B handler)  reenable
eYent on eYent handler exit

screenonkey(k0 “ “)  space turns on mouse draZing

screenlisten()

screenmainloop()

2nd Code Example:

from turtle import *


shape(“circle´)
pencolor(“blue´)
Zidth()
ondrag(goto)
listen()

Ninja TurtleMouse
This code utilises some interesting skills. Obviously it will stretch
your Python Turtle skills to come up with any improvements,
which is great, but it could make for a nice piece of code to
insert into something a young child will use. Therefore it can be
a fantastic project for a younger person to get their teeth into;
or perhaps even as part of a game where the main character is
tasked to draw a skull and crossbones or something similar.

164 www.bdmpublications.com
Mouse Controlled Turtle/Python Alarm Clock

Python Alarm Clock


Ever taken a quick break from working try:
at the computer, then suddenly realised if minutes ! 0:
print (“Sleeping for “  str(minutes)  unit B Zord)
many minutes later that you’ve spent sleep(seconds)
all that time on Facebook? Introducing print (“Wake up´)
for i in range(5):
the Python alarm clock code, where you print (chr(7))
sleep()
can drop into the command prompt and except .eyboard,nterrupt:
tell the code how many minutes until print (“,nterrupted by user´)
sysexit()
the alarm goes oƪ.
Wakey Wakey
ALARMCLOCK.PY There’s some good use of try and except blocks here, alongside
some other useful loops that can help you get a Ƭrmer
This code is designed for use in the command prompt, be that
understanding of how they work in Python. The code itself
Windows, Linux or macOS. There are some instructions on how
can be used in a variety of ways: in a game where something
to use it in the main print section but essentially it’s: python3
happens after a set amount of time or simply as a handy
AlarmClock.py 10 (to go oƪ in ten minutes).
desktop alarm clock for your tea break.

import sys Linux users, try making the alarm clock code into an alias, so
import string you can run a simple command to execute it. Then, why not
from time import sleep integrate a user input at the beginning to ask the user for the
length of time they want until the alarm goes oƪ, rather than
sa = sysargY having to include it in the command line.
lsa = len(sysargY)
if lsa = :
print (“Usage: > python @ AlarmClockpy duration B
in B minutes´)
print (“Example: > python @ AlarmClockpy 0´)
print (“Use a Yalue of 0 minutes for testing the
alarm immediately´)
print (“%eeps a feZ times after the duration is oYer´)
print (“3ress CtrlC to terminate the alarm
clock early´)
sysexit()

try:
minutes = int(sa>@)
except ValueError:
print (“,nYalid numeric Yalue (s) for minutes´  sa>@)
print (“Should be an integer != 0´)
sysexit()

if minutes  0:
print (“,nYalid Yalue for minutes should be != 0´) Windows users, if Python 3 is the only version installed on your
sysexit() system then you will need to execute the code without adding
the 3 to the end of the Python command. For example:
seconds = minutes * 60
python AlarmClockpy 0
if minutes == :
unit B Zord = “ minute´
Again, you could easily incorporate this into a Windows batch
else:
unit B Zord = “ minutes´ Ƭle and even set a schedule to activate the alarm at certain
times of the day.

www.bdmpublications.com 165
Code Repository

Vertically Scrolling Text


What’s not to like about vertically EPICSCROLL.PY
scrolling text? Its uses are many: We’ve used the poem Cimmeria by Robert E. Howard for the
the beginning of a game or code’s scrolling text, along with a dramatic black background
and red text. We think you’ll agree, it’s quite epic.
introduction to something epic,
like the beginning of every Star
Wars movie; a list of credits at the
import pygame as pg
end of something, such as a Python from pygamelocals import *
presentation. The list goes on. pginit()

text B list = µ¶¶

, remember
7he dark Zoods masking slopes of sombre hills;
7he grey clouds¶ leaden eYerlasting arch;
7he dusky streams that ÀoZed Zithout a sound
And the lone Zinds that Zhispered doZn the passes

Vista on Yista marching hills on hills


Slope beyond slope each dark Zith sullen trees
Our gaunt land lay So Zhen a man climbed up
A rugged peak and gazed his shaded eye
SaZ but the endless Yista ± hill on hill
Slope beyond slope each hooded like its brothers

,t Zas a gloomy land that seemed to hold


All Zinds and clouds and dreams that shun the sun
With bare boughs rattling in the lonesome Zinds
And the dark Zoodlands brooding oYer all
1ot eYen lightened by the rare dim sun
Which made sTuat shadoZs out of men; they called it
Cimmeria land of Darkness and deep 1ight

,t Zas so long ago and far aZay


, haYe forgot the Yery name men called me
7he axe and Àinttipped spear are like a dream
And hunts and Zars are shadoZs , recall
Only the stillness of that sombre land;
7he clouds that piled foreYer on the hills
7he dimness of the eYerlasting Zoods
Cimmeria land of Darkness and the 1ight

Oh soul of mine born out of shadoZed hills


7o clouds and Zinds and ghosts that shun the sun
+oZ many deaths shall serYe to break at last
7his heritage Zhich Zraps me in the grey
Apparel of ghosts" , search my heart and ¿nd
Cimmeria land of Darkness and the 1ight

µ¶¶split(µ?n¶)

166 www.bdmpublications.com
Vertically Scrolling Text

class Credits:
def B B init B B (self screen B rect lst): A Long Time Agof
selfsrect = screen B rect The obvious main point of enhancement is the actual text
selflst = lst itself. Replace it with a list of credits, or an equally epic opening
selfsize = 6
storyline to your Python game, and it will certainly hit the
selfcolor = (5500)
selfbuff B centery = selfsrectheight  5 mark with whoever plays it. Don’t forget to change the screen
selfbuff B lines = 50 resolution if needed; we’re currently running it at 800 x 600.
selftimer = 00
selfdelay = 0
selfmake B surfaces()

def make B text(selfmessage):


font = pgfontSysFont(µArial¶ selfsize)
text = fontrender(message7rueselfcolor)
rect = textget B rect(center = (selfsrect
centerx selfsrectcentery  selfbuff B centery) )
return textrect

def make B surfaces(self):


selftext = >@
for i line in enumerate(selflst):
l = selfmake B text(line)
l>@y = i*selfbuff B lines
selftextappend(l)

def update(self):
if pgtimeget B ticks()selftimer ! selfdelay:
selftimer = pgtimeget B ticks()
for text rect in selftext:
recty = 

def render(self surf):


for text rect in selftext:
surfblit(text rect)

screen = pgdisplayset B mode((800600))


screen B rect = screenget B rect()
clock = pgtimeClock()
running=7rue
cred = Credits(screen B rect text B list)

Zhile running:
for eYent in pgeYentget():
if eYenttype == 4U,7:
running = False
screen¿ll((000))
credupdate()
credrender(screen)
pgdisplayupdate()
clocktick(60)

www.bdmpublications.com 167
Code Repository

Python Digital Clock


There is already a clock displayed DIGCLOCK.PY
on the desktop of most operating This is a surprisingly handy little script and one that we’ve
systems but it’s always handy to used in the past instead of relying on a watch or even the
clock in the system tray of the operating system.
have one on top of the currently
open window. To that end, why not import time
import tkinter as tk
create a Python digital clock that
def tick(time=¶¶):
can be a companion desktop widget  get the current time from the 3C
for you. time = timestrftime(µ+:M:S¶)
if time = time:
time = time
clockcon¿g(text=time)

clockafter(00 tick)

root = tk7k()
clock = tk/abel(root font=(µarial¶ 0 µbold¶)
bg=¶green¶)
clockpack(¿ll=¶both¶ expand=)
tick()
rootmainloop()

168 www.bdmpublications.com
Python Digital Clock

Tick Tock
This is a piece of code we’ve used many times in the past to keep
track of time while working on multiple monitors and with just a roottitle(µStop Watch¶)
quick glance to where we’ve placed it on the screen. rootresizable(7rue False)
rootgrid B columncon¿gure(0 Zeight=)
The Tkinter box can be moved around without aƪecting the time, padding = dict(padx=5 pady=5)
Zidget = StopWatch(root **padding)
maximised or closed by the user at will. We haven’t given the
Zidgetgrid(sticky=tkinter1SEW **padding)
Tkinter clock window a title, so you can add to that easily enough
rootmainloop()
by snipping the code from other examples in this book.
def B B init B B (self master=1one cnf=^` **kZ):
Another area of improvement is to include this code when padding = dict(padx=kZpop(µpadx¶ 5) pady=kZ
Windows or Linux starts, so it automatically pops up on the pop(µpady¶ 5))
desktop. See also, if you’re able to improve its functionality by super() B B init B B (master cnf **kZ)
including diƪerent time zones: Rome, Paris, London, New York, selfgrid B columncon¿gure( Zeight=)
Moscow and so on. selfgrid B roZcon¿gure( Zeight=)
self B B total = 0
self B B label = tkinter/abel(self
text=¶7otal 7ime:¶)
self B B time = tkinterStringVar(self
µ0000000¶)
self B B display = tkinter/abel(self
textYariable=self B B time)
self B B button = tkinter%utton(self
text=¶Start¶ command=self B B click)
self B B labelgrid(roZ=0 column=0
sticky=tkinterE **padding)
self B B displaygrid(roZ=0 column=
sticky=tkinterEW **padding)
self B B buttongrid(roZ= column=0
columnspan=sticky=tkinter1SEW **padding)

def B B click(self):
if self B B button>µtext¶@ == µStart¶:
self B B button>µtext¶@ = µStop¶
self B B start = timeclock()
self B B counter = selfafter B idle(self B B update)
else:
self B B button>µtext¶@ = µStart¶
selfafter B cancel(self B B counter)

def B B update(self):
noZ = timeclock()
Another example, expanding on the original code, could be a diff = noZ  self B B start
digital stopwatch. For that you could use the following: self B B start = noZ
self B B total = diff
import tkinter self B B timeset(µ^:6f`¶format(self B B total))
import time self B B counter = selfafter B idle(self B B update)

class StopWatch(tkinterFrame): if B B name B B == µ B B main B B ¶:


StopWatchmain()
@classmethod
def main(cls):
tkinter1oDefaultRoot()
root = tkinter7k()

www.bdmpublications.com 169
Code Repository

Python Scrolling
Ticker Script
You may be surprised to hear TICKER.PY
that one of the snippets of code We’re using Tkinter here along with the Time module to
determine the speed the text is displayed across the window.
we’re often asked for is some
form of scrolling ticker. Whilst
we’ve covered various forms of import time
scrolling text previously, the ticker import tkinter as tk
is something that seems to keep root = tk7k()
cropping up. So, here it is. canYas = tkCanYas(root roottitle(“7icker Code´)
height=80 Zidth=600 bg=´yelloZ´)
canYaspack()
font = (µcourier¶ 48 µbold¶)
Ticker Time text B Zidth = 5

The obvious improvements to the Ticker code lie in 7ext blocks insert here
the speed of the text and what the text will display.
Otherwise you can change the background colour of s = “7his is a scrolling ticker example As you
the ticker window, the font and the font colour, along can see it¶s Tuite long but can be a lot longer if
with the geometry of the Tkinter window if you want to. necessary “
s = “We can eYen extend the length of the ticker
Yet another interesting element that could be message by including more Yariables “
s = “7he Yariables are Zithin the sYalues in
introduced is one of the many text to Speech modules
the code “
available for Python 3. You could pip install one, import it, s4 = “Don¶t forget to concatenate them all before the
then as the ticker displays the text, the text to speech For loop and rename the µspacer¶ sYariable too´
function will read out the variable at the same time, since
the entire text is stored in the variable labelled ‘s’.  pad front and end of text Zith spaces
s5 = µ µ * text B Zidth
 concatenate it all
s = s5  s  s  s  s4  s5
x = 
y = 
text = canYascreate B text(x y anchor=¶nZ¶ text=s
font=font)
dx = 
dy = 0  use horizontal moYement only

 the pixel Yalue depends on dx font and length of text


pixels = 9000

for p in range(pixels):
 moYe text obMect by increments dx dy
 dx ! right to left
canYasmoYe(text dx dy)
The ticker example can be used for system warnings,
canYasupdate()
perhaps something that will display across your work or  shorter delay ! faster moYement
home network detailing the shutting down of a server timesleep(0005)
over the weekend for maintenance; or even just to print(k)  test helps Zith pixel Yalue
inform everyone as to what’s happening. We’re sure
you will come up with some good uses for it. rootmainloop()

170 www.bdmpublications.com
Python Scrolling Ticker Script/Simple Python Calculator

Simple Python Calculator


Sometimes the simplest code can be
the most eƪective. Take for example,
this Simple Python Calculator script.
It’s based on the Create Your Own
Modules section seen earlier but
doesn’t utilise any external modules.
CALCULATOR.PY
We created some function deƬnitions to begin with, then lead
on to the user menu and inputs. It’s an easy piece of code to
follow and as such can also be expanded well too.

print(“Simple 3ython Calculator?n´)

def add(x y):


return x  y

def subtract(x y):


return x  y

def multiply(x y):


return x * y

def diYide(x y):


return x  y

print(“Select operation?n´)
print(“Add´)
print(“Subtract´)
print(“Multiply´)
print(“4DiYide´)

choice = input(“?nEnter choice (4):´)

num = int(input(“?nEnter ¿rst number: “))


num = int(input(“Enter second number: “))

if choice == µ¶:
print(num´´num´=´ add(numnum))
Improved Calculations
elif choice == µ¶: The obvious contender for improvement here is using the
print(num´´num´=´ subtract(numnum)) Create Your Own Modules route and extracting the function
deƬnitions as a module. You can then call the module and focus
elif choice == µ¶:
on the body of the code.
print(num´*´num´=´ multiply(numnum))

elif choice == µ4¶: The other area of improvement is code itself. Where there’s
print(num´´num´=´ diYide(numnum)) just a single shot at making a calculation, you could encase it in
else: a while loop, so once a value is presented the user is sent back
print(“,nYalid input´) to the main menu. Perhaps, improvement to the Invalid Input
section is worth looking into as well.

www.bdmpublications.com 171
Code Repository

Playing Music with the


Winsound Module
Of course, instead of playing an MUSIC.PY
existing MP3, you can always The code utilises both the Time and Winsound modules,
make your own music. The code deƬning the tone and pitch and inserting small pauses of .5
of a second.
below will play out Pachelbel’s
Canon in D, no less. import Zinsound
import time
1
t = 50
p = 50

llC = 65

lC = 
lDb = 9
lD = 47
lEb = 56
lE = 65
lF = 75
lGb = 85
lG = 96
lAb = 08
lA = 0
lBb = 
lB = 47

C = 6
Db = 77
D = 94
Eb = 
E = 0
F = 49 2
Gb = 70
G = 9
Ab = 45
A = 440
Bb = 466
B = 494

hC = 5
hDb = 554
hD = 587
hEb = 6
hE = 659
hF = 698
hGb = 740
hG = 784
hAb = 8
hA = 880
hBb = 9
hB = 988

timesleep(000)

172 www.bdmpublications.com
Playing Music with the Winsound Module

for i in range (5): Sweet Music


Obviously the Winsound module is a Windows-only set of
ZinsoundBeep( lC *t) functions for Python. Open your IDLE in Windows and copy the
ZinsoundBeep( hC t)
code in. Press F5 to save and execute, then press the Enter key,
ZinsoundBeep( hE t)
as instructed in the code, to start the music.
ZinsoundBeep( hG t)
timesleep(p)
Naturally you can swap out the winsound.Beep frequency and
ZinsoundBeep( lG *t) durations to suit your own particular music; or you can leave it as
ZinsoundBeep( G t) is and enjoy. Perhaps play around with the various methods to
ZinsoundBeep( B t) make other music.
ZinsoundBeep( hD t)
timesleep(p) For example, players of the Nintendo classic game, The Legend
of Zelda: Ocarina of Time, can enjoy the game’s titular musical
ZinsoundBeep( lA *t)
intro by entering:
ZinsoundBeep( A t)
ZinsoundBeep( hC t)
import Zinsound
ZinsoundBeep( hE t)
beep = ZinsoundBeep
timesleep(p)
c = [
ZinsoundBeep( lE *t)
(880 700)
ZinsoundBeep( E t)
(587 000)
ZinsoundBeep( G t)
(698 500)
ZinsoundBeep( B t)
(880 500)
timesleep(p)
3 (587 000)
(698 500)
ZinsoundBeep( lF *t)
(880 50)
ZinsoundBeep( F t)
(046 50)
ZinsoundBeep( A t)
(988 500)
ZinsoundBeep( hC t)
(784 500)
timesleep(p)
(699 0)
(784 50)
ZinsoundBeep( llC *t)
(880 500)
ZinsoundBeep( C t)
(587 500)
ZinsoundBeep( E t)
(5 50)
ZinsoundBeep( G t)
(659 50)
timesleep(p)
(587 750)
]
ZinsoundBeep( lF *t)
ZinsoundBeep( F t)
s = c  c
ZinsoundBeep( A t)
ZinsoundBeep( hC t)
for f d in s:
timesleep(p)
beep(f d)
ZinsoundBeep( lG *t)
ZinsoundBeep( G t)
ZinsoundBeep( B t)
ZinsoundBeep( hD t)
timesleep(p)

The start of the code imports the Winsound and Tie modules;
1 remember, this is a Windows-only Python script. The variable t
is setting the duration, while p equals .5, which you can use for
the time.sleep function.

These variables set the frequencies, with the corresponding


2 numbers, which can be used in the next section of the code.

Winsound.beep requires a frequency and duration within the


3 brackets. The frequencies come from the large set of variables
called in the second section of the code and the duration is
through the t variable set at the start of the code. There’s a
half-second, using the variable p, pause between blocks of
winsound.beep statements.

www.bdmpublications.com 173
Code Repository

Hangman Game Script


Hangman is a great game to HANGMAN.PY
program into Python. It can be We’ve made a Hangman game board (the gallows) out of
extremely complex, displaying characters that can be displayed in the IDLE Shell, along with
a huge bank of words to randomly choose from.
graphics, the number of guesses left
in the secret word, a huge bank of
available words picked at random import random

and countless other elements. It can board = [µ¶¶


also be quite simple. Here we have a !!!!!!!!!!+angman
mix between the two.

| |
|
|
|
|
=========¶¶¶ µ¶¶


| |
O |
|
|
|
=========¶¶¶ µ¶¶


| |
O |
| |
|
|
=========¶¶¶ µ¶¶


| |
O |
| |
|
|
=========¶¶¶ µ¶¶


| |
O |
|? |
|
|
=========¶¶¶ µ¶¶


| |
O |
|? |
 |

174 www.bdmpublications.com
Hangman Game Script

| luggage responsible ambassador circumstance


=========¶¶¶ µ¶¶ congratulate freTuent¶split()
return bank[randomrandint(0len(bank))]

| | def main():
O | game = +angman(rand B Zord())
|? | Zhile not gamehangman B oYer():
 ? | gameprint B game B status()
| user B input = input(µ?nEnter a letter: µ)
=========¶¶¶] gameguess(user B input)

gameprint B game B status()


class +angman: if gamehangman B Zon():
def B B init B B (selfZord): print (µ?nCongratulations <ou haYe Zon¶)
selfZord = Zord else:
selfmissed B letters = [] print (µ?nSorry you haYe lost¶)
selfguessed B letters = [] print (µ7he Zord Zas µ  gameZord)

def guess(selfletter): print (µ?nGoodbye?n¶)


if letter in selfZord and letter not in self
guessed B letters: if B B name B B == “ B B main B B ´:
selfguessed B lettersappend(letter) main()
elif letter not in selfZord and letter not in
selfmissed B letters:
selfmissed B lettersappend(letter)
else:
return False
QUIT()
return 7rue Since this is the last example in our Python code repository, we
thought we’d go out with a bang and feature the hangman
def hangman B oYer(self): gallows being drawn with each incorrect guess of the word.
return selfhangman B Zon() or (len(selfmissed B Don’t worry if it looks misaligned in the text here, this is merely
letters) == 6)
due to the diƪerences between using the Python IDLE editor
def hangman B Zon(self): and pasting the code into a word processor (which formats
if µ B ¶ not in selfhide B Zord(): things diƪerently).
return 7rue
return False There’s plenty you can do to improve, enhance and expand on
what we’ve presented here. You can include a routine that
def hide B Zord(self): returns an error if the user enters a number or character. You
rtn = µ¶ can include extra points for someone who guesses the entire
for letter in selfZord: word in one go rather than one letter at a time and you could
if letter not in selfguessed B letters:
perhaps add Chopin’s Funeral March should you lose the game;
rtn = µ B ¶
or something celebratory if you win.
else:
rtn = letter
return rtn

def print B game B status(self):


print (board[len(selfmissed B letters)])
print (µWord: µ  selfhide B Zord())
print (µ/etters Missed: µ)
for letter in selfmissed B letters:
print (letter)
print ()
print (µ/etters Guessed: µ)
for letter in selfguessed B letters:
print (letter) Consider replacing the bank of words too. They’re found under
print () the bank list, and could easily be swapped out for something
more diƯcult. If you download www.github.com/dwyl/english-
def rand B Zord(): words you can Ƭnd a text document with over 466,000 words.
bank = µability about aboYe absolute accessible Perhaps you could swap the words in the bank to instead read
accommodation accounting beautiful bookstore the contents of the text Ƭle:
calculator cleYer engaged engineer enough
handsome refrigerator opposite socks interested def rand B Zord():
straZberry backgammon anniYersary confused Zith open(“homepiDoZnloadsZordstxt´ “rt´) as f:
dangerous entertainment exhausted impossible bank=freadlines()
oYerZeight temperature Yacation scissors return bank[randomrandint(0len(bank))]
accommodation appointment decrease deYelopment
earthTuake enYironment brand enYironment necessary

www.bdmpublications.com 175
Index

Coding
Projects & Tips

176 www.bdmpublications.com
Coding Projects & Tips

We’re going to Ƭnish oƪ by looking at


some interesting coding elements that
you can incorporate into your own
unique projects and code. In this section
you’ll Ƭnd code for creating a loading
screen for your content, text animations
using ASCII art, clever ways in which you
can include animated sections at the
command prompt, and even code that
can track the International Space Station
in realtime, while displaying both the
astronauts on board and its current
latitude and longitude.
There are also pages of common, and
language speciƬc, mistakes to help you
avoid, and create, error-free and
eƪective code in the future.

178 Creating a Loading Screen


180 Text Animations
182 Tracking the ISS with Python
186 Using Text Files for Animation
188 Passing Variables to Python
190 Python Beginner’s Mistakes
192 Glossary of Python Terms

www.bdmpublications.com 177
Coding Projects & Tips

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 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, or use an image to ASCII Art converter to convert any images you
have to ASCII. When you have your ASCII art, drop it into a newly created
folder inside a normal text Ƭle.
Save the Ƭle, call it screens.txt for now.

Back in the 80s, in the 8-bit home computing era, loading screens were
often used to display the cover of a game as it loaded from tape. The
image would load itself in, usually one-line-at-a-time, then proceed to
colour itself in while the loading raster bars danced around in the borders
of the screen.
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
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:

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
deƬnitely add a little something else extra.

178 www.bdmpublications.com
Creating a Loading Screen

THE CODE percent = (loading * 100) // seconds


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

#Main Code Start


os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
loading _ screen(.5) The code works in much the same way as the previous except, instead
of reading from a text Ƭle, it’s running through a for loop that prints
print (“\nYour code begins here...”)
Loading… followed by an animation of sorts, along with a percentage
counter; clearing the screen every second and displaying the new results.
The code is quite simple: import the OS and Time modules and then create It’s simple, yes, but quite eƪective in its design.
a Python function called loading_screen with a (seconds) option. Within
the function, open the text Ƭle with the ASCII art as read-only and create
a For loop that’ll read the text Ƭle one-line-at-a-time. Next, print the lines
COMBINING THE TWO
– incidentally, the lines, end=’’ element will strip the newline from the How about combining the two elements we’ve looked at? Let’s begin with
text document, without it you’ll end up with a double-line spaced display. a Loading… progress bar, followed by the loading screen. After that, you
Include the timing in seconds and close the text Ƭle buƪer. can include your own code and continue your program. Here’s the code:
The Ƭnal part of the code, #Main Code Start, is where you’ll clear the
import os
screen (CLS for Windows, Clear for Linux and macOS) and call the import time
function, together with the output number of seconds to wait for each
line to be written to the screen – in this case, .5 of a second. def loading _ bar(seconds):
for loading in range(0,seconds+1):
Save the code as screens.
percent = (loading * 100) // seconds
py, drop into a Command print(“\n”)
Prompt or Terminal and print(“Loading...”)
execute it. The screen print(“<” + (“-” * loading) + (“ “ * (seconds-
will clear and your ASCII loading)) + “> “ + str(percent) + “%”)
art inside the text Ƭle print(“\n”)
will load in line-by-line, time.sleep(1)
creating a loading os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
screen eƪect.

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)
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
loading _ screen(.5)
Another favourite introduction screen is that of a simple loading
animation, where the word loading is displayed followed by some
characters and a percentage of the program loaded. While it may not print (“\nYour code begins here...”)
take long for your Python code to load, the eƪect can be interesting.
Create a New File in Python and enter the following code:

import os You can of course pull those functions up wherever and whenever you
import time want in your code and they’ll display, as they should, at the beginning.
Remember to have the ASCII text Ƭle 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 Ƭle is located.

www.bdmpublications.com 179
Coding Projects & Tips

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
eƪects 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 diƪerent 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:
¿ve()
elif counter == 4:
four()
elif counter == 3:
three()
elif counter == 2:
two()
elif counter == 1:
one()
Let’s begin with some example code that will display a large countdown time.sleep(1)
from ten, then clear the screen and display a message. The code itself is os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
quite simple, but lengthy. You will need to start by importing the OS and
Time modules, then start creating functions that display the numbers:
And Ƭnally, we can add a display for the message:

#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 Ƭt. The end eƪect is quite
good and it’ll be worth adding to your own
games, or presentations, in Python.

180 www.bdmpublications.com
Text Animations

To extend the code, or make it easier to use, you can always BLAST OFF!!
create the number functions in their own Python code, call it
Building on the previous countdown example, we can create an
Count.py for example, then import Count at the beginning of
animated rocket that’ll launch after the Blast Oƪ!! message has
a new Python Ƭle called Countdown.py, along with the OS and
been printed. The code for this would look something like this:
Time modules:
def Rocket():
import os
distanceFromTop = 20
import time
while True:
import count
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
print(“\n” * distanceFromTop)
From there, you will need to specify the imported code in the print(“ /\ “)
Countdown section: print(“ || “)
print(“ || “)
#Start the countdown print(“ /||\ “)
for counter in range(start, 0, -1): time.sleep(0.2)
if counter == 10: os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
count.ten() distanceFromTop -= 1
elif counter == 9: if distanceFromTop <0:
count.nine() distanceFromTop = 20
elif counter == 8:
count.eight()
elif counter == 7: #Launch Rocket
count.seven() Rocket()
elif counter == 6:
count.six() Here we’ve created a new function called Rocket, which
elif counter == 5: produces the eƪect of an ASCII-like rocket taking oƪ and
count.¿ve() scrolling upwards; using the distanceFromTop variable.
elif counter == 4:
count.four() To use this, add it to the end of the previous countdown code and
elif counter == 3: at the end of the Blast Oƪ!! message, add the following lines:
count.three()
elif counter == 2: print(“\n\n\n\n”)
count.two() input(“Press Enter to launch rocket...”
elif counter == 1:
count.one()
This will allow your message to be displayed and then, when the
user has hit the Enter button, the rocket will launch.
This will pull the functions from the imported Count.py and print Again, the code in its entirety can be found in the Code
them to the screen. Repository at: https://bdmpublications.com/ code-portal.

ROLLING DIE
Aside from the rocket animation, together with its countdown,
def dice():
another fun bit of text-based animation is that of a rolling dice.
for roll in range(0,15):
A rolling dice can be a great animation to include in an os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
adventure game, where the player rolls to see what their score print(“\n”)
is compared to that of an enemy. The highest roller wins the number = randint(0,5)
print(die[number])
round and the losers’ health drops as a result. It’s an age-old
time.sleep(0.2)
combat sequence, used mainly in the Dungeon and Dragons
board games and Fighting Fantasy novels, but it works well. #Main Code Begins
The code you’ll need to animate a dice roll is: dice()

import os
You may need to tweak the
import time O entries, to line up the
from random import randint dots on the virtual dice.
Once it’s done, though,
die = [“ \n O \n “] #1 you’ll be able to add this
die.append(“ O\n \nO “) #2 function to your adventure
die.append(“O \n O \n O”) #3 game code and call it up
die.append(“O O\n \nO O”) #4 whenever your character, or
die.append(“O O\n O \nO O”) #5 the situation, requires some element of luck, combat or chance
die.append(“O O\nO O\nO O”) #6
roll of the dice.

www.bdmpublications.com 181
Coding Projects & Tips

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 GOf
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 onboard 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.
cluttered, so in this instance we’re going to look at spreading all those
While we’re not able to Ƭll you in on all the details, regarding the
details over three screens: a text document window -displaying the
code the ISS utilises, we can look at a fun Python script that will track
astronauts and your current latitude and longitude, a command line
the ISS, display the number of astronauts on board, update the
(or Terminal window) - displaying the continually updating latitude
station’s current latitude and longitude every Ƭve seconds, while also
and longitude of the ISS as it orbits Earth, and a Ƭnal, large window
displaying your current latitude and longitude.
displaying a map of the world, together with an icon representing the
Displaying all that information in a single screen can become a little ISS, that’s 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 Ƭnd 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, which is cross-platform, will suƯce.

182 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 Ƭles
in the default text Ƭle application – despite what its name may suggest.
The geocoder module is a new element, and you will need to install it
Simply load the image up in your image editor app and choose Save As, with: pip install geocoder. Geocoder can retrieve a users’ location based
call them map and iss respectively, and click GIF as the image format. on their IP address, as each ISP will have a geo-speciƬc IP.
Remember to also resize the ISS image before saving it as a GIF.
#Retrieve the names of all the astronauts currently on
board the ISS, and own lat/long - write to a ¿le and display
THE CODE url = “http://api.open-notify.org/astros.json”
response = urllib.request.urlopen(url)
The code we’re using here utilises an open source API (Application
result = json.loads(response.read())
Programming Interface) to retrieve real-time data online regarding the
a=open(“iss.txt”,”w”)
status of the ISS. An API enables applications to communicate with one a.write(“There are currently “ + str(result[“number”]) + “
another by providing the raw data that a programmer can pull out and astronauts on the ISS:\n\n”)
interact with in their own code. In this case, the API in question is a web-
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.
for p in people:
In order for Python to interact with the JSON provided data, it needs to a.write(p[“name”] + “ - on board” + “\n”)
use the urllib.request and json modules. We’re also going to be using a
new module called geocoder, which will pull up a users’ current latitude g=geocoder.ip(‘me’) # need to pip install geocoder, and
and longitude based on their IP address. The two JSON API’s can be 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 ¿le.
the astronauts onboard 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 onboard the ISS.
It then creates a new text Ƭle 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 Ƭle that contains the names of
the astronauts. The last line, webbrowser.open(“iss.txt”) will use the
webbroser module to open and display the newly written text Ƭle in the
system’s default text Ƭle 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
mark the boundaries of the screen, creating the x and y coordinates of

www.bdmpublications.com 183
Coding Projects & Tips

the four corners of the canvas, so that the ISS icon can freely travel across Here’s the code in its entirety:
the map of the world and wrap itself back to the opposite side when it
reaches an edge. The ISS icon is set as the turtle pen shape, giving it an import json, turtle, urllib.request, time, webbrowser
angle of 45 degrees when moving. import geocoder # need to pip install geocoder for your
lat/long to work.
while True:
#Load the current status of the ISS in real-time #Retrieve the names of all the astronauts currently on
url = “http://api.open-notify.org/iss-now.json” board the ISS, and own lat/long - write to a ¿le and display
response = urllib.request.urlopen(url) url = “http://api.open-notify.org/astros.json”
result = json.loads(response.read()) response = urllib.request.urlopen(url)
result = json.loads(response.read())
#Extract the ISS location a=open(“iss.txt”,”w”)
location = result[“iss _ position”] a.write(“There are currently “ + str(result[“number”]) + “
lat = location[“latitude”] astronauts on the ISS:\n\n”)
lon = location[“longitude”]
people = result[“people”]
#Output Latitude and Longitude to the console
lat = Àoat(lat) for p in people:
lon = Àoat(lon) a.write(p[“name”] + “ - on board” + “\n”)
print(“\nLatitude: “ + str(lat))
print(“Longitude: “ + str(lon)) g=geocoder.ip(‘me’) # need to pip install geocoder, and
import
#Update the ISS location on the map as in the headers above
iss.goto(lon, lat) a.write(“\nYour current Lat/Long is: “ + str(g.latlng)) #
#refresh every 5 seconds prints
time.sleep(5) your current lat/long in the text ¿le.
a.close()
webbrowser.open(“iss.txt”)
Now for the Ƭnal 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 Ƭle. The code then prints the latitude and longitude data to the screen.setup(1280, 720)
console/Terminal, transferring the data from a Ʈoat to a string in order screen.setworldcoordinates(-180, -90, 180, 90)
to print it correctly. The last section will use the latitude and longitude as #Load the world map image
variables lat and lon, to update the ISS icon on the map every Ƭve seconds. screen.bgpic(“map.gif”)

184 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 Ƭle containing
lat = Àoat(lat) the named astronauts along with your current latitude and longitude,
lon = Àoat(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.

www.bdmpublications.com 185
Coding Projects & Tips

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
Ƭle 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 Ƭle 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 suƯce). Save
an online Text to ASCII generator, created by Patrick Gillespie. Start the Ƭle 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 Ƭle 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.

186 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 Ƭles we want to open, and then we need to
LPSRUWRVWLPH
open them for display in the Terminal.
RVV\VWHP ¶FOV·LIRVQDPH ¶QW·HOVH¶FOHDU·
ÀOHQDPHV >´W[Wµ´W[Wµ@
IUDPHV >@ ÀOHQDPHV >´W[Wµ´W[Wµ@
IUDPHV >@
IRUQDPHLQÀOHQDPHV
ZLWKRSHQ QDPH´UµHQFRGLQJ µXWIµ DVI IRUQDPHLQÀOHQDPHV
IUDPHVDSSHQG IUHDGOLQHV  ZLWKRSHQ QDPH´UµHQFRGLQJ µXWIµ DVI
IUDPHVDSSHQG IUHDGOLQHV
IRULLQUDQJH  
IRUIUDPHLQIUDPHV
SULQW ´µMRLQ IUDPH 
WLPHVOHHS 
RVV\VWHP ¶FOV·LIRVQDPH ¶QW·HOVH 
 ¶FOHDU·

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 Ƭles, as ASCII art as text, within a text Ƭle, command will work correctly. If you want, you could use a Try/
often requires you to save the Ƭle as UTF compliant – due to the Except statement instead.
characters used. Now we can add a loop to display the Ƭles as 1.txt,
then 2.txt, creating the illusion of animation while clearing the
screen after each Ƭle 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/
Ƭles 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
S\WKRQ1$0(S\
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.

www.bdmpublications.com 187
Coding Projects & Tips

Passing Variables
to Python

THE WINDOWS WAY


The two systems use moderately diƪerent ways to accomplish the same task, Windows is slightly easier (by a single command),
and so we’ll start there.

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 Ƭle and enter the following:
LPSRUWRV
#HFKRRII
Q RVHQYLURQ>¶QDPH·@
VHWSQDPH :KDWLV\RXUQDPH"
SULQW ´<RXUQDPHLV´Q 
HFKR/HW·VWU\DQGSDVVWKLVWRD3\WKRQVFULSW
S\WKRQEDWS\S\
HFKR,WZRUNHG

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
Ƭles here. SuƯce 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 Ƭle (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 Ƭle as a batch Ƭle, 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 Ƭle. Save the
code as batpy1.py.

188 www.bdmpublications.com
Passing Variables to Python

STEP 5 To recap: we have a batch Ƭle called batpy1.bat, STEP 8 Drop into a Windows command prompt, and
which asks the user their name and stores the navigate to the folder Batpy. To run a Windows
info as a system variable called name. It will then print a message batch Ƭle, simply enter the command:
to the screen, run the Python code, and Ƭnally 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 Ƭle to end.

THE LINUX WAY


Linux’s version of passing variables to Python is slightly diƪerent, 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 Ƭle, and enter the following:
and entering the following:
LPSRUWRV
ELQEDVK
Q RVHQYLURQ>¶ÀUVWQDPH·@
HFKRQ´+HOORZKDWLV\RXUQDPH"´
UHDGÀUVWQDPH SULQW ´<RXUQDPHLV´Q
H[SRUWÀUVWQDPH Save the Python code as batpy1.py.
S\WKRQEDWS\S\
HFKR
HFKR
HFKRQ´,WZRUNHGµ
HFKR

STEP 2 Drop into a Terminal session and make a new STEP 4 Back in the Terminal, enter: EDWS\VK to run
directory called batpy (mkdir batpy). Save the the Bash script. As you can see, the results are the
Bash script as batpy.sh, and from the Terminal enable the script as same as in Windows. The major diƪerences are: making the Bash
executable with: FKPRG[EDWS\VK. script executable, and adding the export Ƭrstname command to
the Bash Ƭle. In Linux, you need to export system variables before
they can be accessed by the subsystem, in this case the Python code.

www.bdmpublications.com 189
Coding Projects & Tips

Python Beginner’s
Mistakes
Python is a relatively easy language to get started in where there’s plenty of room for
the beginner to Ƭnd 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 Ƭnd 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.

190 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:
FODVV+DQJPDQ
Q OLVW UDQJH   GHIJXHVV VHOIOHWWHU 
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, /LYHV  is a
diƪerent 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 diƯcult, 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 FOV. Whereas, for Linux you need to use
FOHDU. You need to solve this by capturing the error and issuing it
with an alternative command.

www.bdmpublications.com 191
Coding Projects & Tips

Glossary of Python Terms


Just like most technology, Python contains many confusing words and acronyms. Here
then, for your own sanity, is a handy glossary to help you keep on top of what’s being
said when the conversation turns to Python programming.

Argument Expression
The detailed extra information used by Python to perform more Essentially, Python code that produces a value of something.
detailed commands. Can also be used in the command prompt to
specify a certain runtime event. Float
An immutable Ʈoating point number used in Python.
Block
Used to describe a section or sections of code that are Function
grouped together. Used in Python to deƬne a sequence of statements that can be
called or referenced at any time by the programmer.
Break
A command that can be used to exit a for or while loop. For example, GitHub
if a key is pressed to quit the program, Break will exit the loop. A web-based version control and collaboration portal designed for
software developers to better manage source code.
Class
A class provides a means of bundling data and functionality together. Global Variable
They are used to encapsulate variables and functions into a single entity. A variable that is useable anywhere in the program.

Comments Graphics
A comment is a section of real world wording inserted by the The use of visual interaction with a program, game or operating
programmer to help document what’s going on in the code. They
system. Designed to make it easier for the user to manage the
can be single line or multi-line and are deƬned by a # or ‘’’.
program in question.

Debian GUI
A Linux-based distro or distribution that forms the Debian Project.
Graphical User Interface. The interface which most modern
This environment oƪers the user a friendly and stable GUI to
operating systems use to enable the user to interact with the
interact with along with Terminal commands and other forms of
core programming of the system. A friendly, easy to use graphical
system level administration.
desktop environment.
Def
Used to deƬne a function or method in Python.
High-Level Language
A programming language that’s designed to be easy for people to read.
Dictionaries
A dictionary in Python is a data structure that consists of key and IDLE
value pairs. Stands for Integrated Development Environment or Integrated
Development and Learning Environment.
Distro
Also Distribution, an operating system that uses the Linux Kernel as its Immutable
core but oƪers something diƪerent in its presentation to the end user. Something that cannot be changed after it is created.

Editor Import
An individual program, or a part of the graphical version of Python, Used in Python to include modules together with all the
that enables the user to enter code ready for execution. accompanying code, functions and variables they contain.

Exceptions Indentation
Used as a means of breaking from the normal Ʈow of a code block in Python uses indentation to delimit blocks of code. The indents are
order to handle any potential errors or exceptional conditions within four spaces apart, and are often created automatically after a colon
the program. is used in the code.

192 www.bdmpublications.com
Glossary of Python Terms

Integer Python
A number data type that must be a whole number and not An awesome programming language that’s easy to learn and use,
a decimal. whilst still being powerful enough to enjoy.

Interactive Shell Random


The Python Shell, which is displayed whenever you launch the A Python module that implements a pseudo-random character
graphical version of Python. generator using the Mersenne Twister PRNG.

Kernel Range
The core of an operating system, which handles data processing, A function that used to return a list of integers, deƬned by the
memory allocation, input and output, and processes information arguments passed through it.
between the hardware and programs.
Root
Linux The bottom level user account used by the system itself. Root is the
An open source operating system that’s modelled on UNIX. overall system administrator and can go anywhere, and do anything,
Developed in 1991 by Finnish student Linus Torvalds. on the system.

Lists Sets
A Python data type that contains collections of values, which can be Sets are a collection of unordered but unique data types.
of any type and can readily be modiƬed.
Strings
Local Variable Strings can store characters that can be modiƬed. The contents of
A variable that’s deƬned inside a function and is only useable inside a string are alphanumerical and can be enclosed by either single or
that function. double quote marks.

Loop Terminal
A piece of code that repeats itself until a certain condition is met. Also Console or Shell. The command line interface to the operating
Loops can encase the entire code or just sections of it. system, namely Linux, but also available in macOS. From there you
can execute code and navigate the Ƭlesystem.
Module
A Python Ƭle that contains various functions that can be used within Tkinter
another program to further extend the eƪectiveness of the code. A Python module designed to interact with the graphical
environment, speciƬcally the tk-GUI (Tool Kit Graphical User
Operating System Interface).
Also OS. The program that’s loaded into the computer after the
initial boot sequence has completed. The OS manages all the other Try
programs, graphical user interface (GUI), input and output and A try block allows exceptions to be raised, so any errors can be
physical hardware interactions with the user. caught and handled according to the programmer’s instructions.

Output Tuples
Data that is sent from the program to a screen, printer or other An immutable Python data type that contains an ordered set of
external peripheral. either letters or numbers.

PIP UNIX
Pip Installs Packages. A package management system used to install A multitasking, multiuser operating system designed in the ‘70s at
and manage modules and other software written in Python. the Bell Labs Research Centre. Written in C and assembly language

Print Variables
A function used to display the output of something to the screen. A data item that has been assigned a storage location in the
computer’s memory.
Prompt
The element of Python, or the Command Line, where the user X
enters their commands. In Python it’s represented as >>> in the Also X11 or X-windows. The graphical desktop used in Linux-based
interactive shell. systems, combining visual enhancements and tools to manage the
core operating system.
Pygame
A Python module that’s designed for writing games. It includes Zen of Python
graphics and sound libraries and was Ƭrst developed in When you enter: LPSRUWWKLV into the IDLE, the Zen of Python
October 2000. is displayed.

www.bdmpublications.com 193
Black Dog Media

Master Your Tech From Beginner to Expert


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

Raspberry Pi 4 Programming with Python

Coding Guides, Tips & Tricks Learn & Master C++ Testing Linux Distros

Exclusive Offers
on Tech Guidebooks
G Print & digital editions ultimatephotoshop.com
G Featuring the latest updates Buy our Photoshop guides and
download tutorial images for free!
G Step-by-step tutorials & guides
Simply sign up and get creative.
G Created by BDM experts

When you sign up to our


PLUS Special Deals and Bonus Content monthly newsletter!

BDM’s Manual Series Editorial and design are the copyright © Papercut Limited and are BDM’s Manual Series s 5th Edition is an independent publication and as
5th Edition s ISSN 20566662 reproduced under licence to Black Dog Media. No part of this publication such does not necessarily reƮect the views or opinions of the producers
Published by: . . . . . . . . . . . . . . . .Black Dog Media Limited (BDM) may be reproduced in any form, stored in a retrieval system, or integrated contained within. This publication is not endorsed or associated in any way
Editor: . . . . . . . . . . . . . . . . . . . . . . .James Gale into any other publication, database, or commercial programs without with Microsoft, The Linux Foundation, The Raspberry Pi Foundation, ARM
Art Director Production: . . .Mark Ayshford the express written permission of the publisher. Under no circumstances
Production Manager: . . . . . . . .Karl Linstead Holding, Canonical Ltd, Python, Debian Project, Lenovo, Dell, Hewlett-
should this publication and its contents be resold, loaned out, or used
Design: . . . . . . . . . . . . . . . . . . . . . .Robin Drew, Lena Whitaker Packard, Apple and Samsung or any associate or aƯliate company. All
in any form by way of trade without the publisher’s written permission.
Editorial:. . . . . . . . . . . . . . . . . . . . .David Hayward copyrights, trademarks and registered trademarks for the respective
While we pride ourselves on the quality of the information we provide,
Sub Editor: . . . . . . . . . . . . . . . . . . .Alison Drew companies are acknowledged. Relevant graphic imagery reproduced
Black Dog Media Limited reserves the right not to be held responsible for
Printed and bound in Great Britain by: Acorn Web Oƪset Ltd any mistakes or inaccuracies found within the text of this publication. with courtesy of Lenovo, Hewlett- Packard, Dell, Samsung, Microsoft
Newsstand distribution by: Seymour Distribution Limited Due to the nature of the software industry, the publisher cannot and Apple.
2, East Poultry Avenue, London EC1A 9PT guarantee that all tutorials will work on every version of Windows,
International distribution by: Pineapple Media Limited Additional images contained within this publication are reproduced under
macOS, or the Raspbian OS. It remains the purchaser’s sole responsibility
www.pineapple-media.com licence from Shutterstock.com.
to determine the suitability of this book and its content for whatever
Digital distribution by: Readly AB, Zinio, Magzter, Cafeyn, PocketMags
purpose. Images reproduced on the front and back cover are solely for Prices, international availability, ratings, titles and content are subject to
For all advertising and promotional opportunities contact:
design purposes and are not representative of content. We advise all change. All information was correct at time of print. Some content may
enquiries@bdmpublications.com
potential buyers to check listing prior to purchase for conƬrmation of have been previously published in other volumes or BDM titles. We advise
Copyright © 2020 Black Dog Media. All rights reserved. actual content. All editorial opinion herein is that of the reviewer as an potential buyers to check the suitability of contents prior to purchase.
INTERNATIONAL LICENSING – Black Dog Media has many great publications and all are individual and is not representative of the publisher or any of its aƯliates.
available for licensing worldwide. For more information go to: www.brucesawfordlicensing. Therefore, the publisher holds no responsibility in regard to editorial Black Dog Media Limited (BDM)
com; email: bruce@brucesawfordlicensing.com; telephone: 0044 7831 567372 opinion and content. Registered in England & Wales No: 5311511

You might also like