The Ultimate Python Coding
The Ultimate Python Coding
NE
PYTHON
60 GFRRAEMES
PRTOODOWNLOAD
e
Details insid
PAGES
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
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
4 www.bdmpublications.com
Contents
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”)
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
“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.
your coding
game. This of course led to the programmer becoming more than simply
someone who could fashion a sprite on the screen and make it move at the
press of a key.
adventure!” Naturally, time has moved on and with it the technology that we use.
However, the fundamentals of programming remain the same; but what
exactly does it take to be a programmer?
Being able to see the big picture is certainly 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.
www.bdmpublications.com 9
Print (“The World of Code”)
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.
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.
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.
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.
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.
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
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”)
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.
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
16 www.bdmpublications.com
Using Virtual Machines
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.
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.
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.
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
Pi
BD
Ultimate M s the Rasp
Serie b s erry Pi
Raspberry
Raspb
P i4
ners Guid
Tricks
Upd a
Editio te
Unleash
e
& Fixes
the codin n
g power
of the am
Volume
Projects!
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
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
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.
Java is a powerful
language that’s used in
web pages, set-top boxes,
TVs and even cars.
www.bdmpublications.com 23
Welcome to Python
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.
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.
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.
in PYTHON AND
LINUX SKILLS
N UMBERS
26 www.bdmpublications.com
Python in Numbers
Python Data Science is Google is the top Data Science, Blockchain New York and San
thought to become the company for hiring Python and Machine Learning Francisco are the top
most sought-after job in developers, closely are the fastest growing Python developer cities
the coming years. followed by Microsoft. Python coding skills. in the world.
£60,000
95% OF ALL BEGINNER 75% OF ALL PYTHON 79% OF ALL 49% OF WINDOWS
CODERS START WITH DEVELOPERS USE PROGRAMMERS 10 DEVELOPERS
AND STILL USE, PYTHON 3, WHEREAS USE PYTHON USE PYTHON 3
PYTHON AS THEIR 25% STILL USE THE REGULARLY, 21% USE AS THEIR MAIN
PRIMARY OR OUTDATED PYTHON 2 IT AS A SECONDARY PROGRAMMING
SECONDARY LANGUAGE. VERSION. LANGUAGE. LANGUAGE.
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.
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.
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.
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.
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.
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 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.
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
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
www.bdmpublications.com 37
First Steps into Python
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
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
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
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)
www.bdmpublications.com 45
First Steps into Python
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)
46 www.bdmpublications.com
Numbers and Expressions
STEP 7 Numbers and STEP 10 Execute the code from Step 9, and you’ll see a
expressions don’t series of True or False statements depending on
stop there. Python has numerous 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
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 ÁRDWLQSXW´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 ÁRDWLQSXW´'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
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:
SULQWZRUG´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:
SULQWZRUG´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:
SULQWZRUG´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 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
www.bdmpublications.com 63
Index
Manipulating
Data
64 www.bdmpublications.com
Manipulating Data
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.
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.
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
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.
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.
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 LQWLQSXW´(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!”)
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ÀOOZKLWH
VFUHHQÀOOZKLWH
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 = “”
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()
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?
www.bdmpublications.com 87
Index
Working with
Modules
88 www.bdmpublications.com
Working with Modules
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.
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
\ LQWLQSXW´(QWHUWKHÀUVW\HDU´
for Monday if you prefer.
\ LQWLQSXW´(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 LQWLQSXW´(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.
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µ·
www.bdmpublications.com 93
Working with Modules
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
ÁRRUUHWXUQV
FHLOUHWXUQV
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
PWUXQF7UXQFDWHUHPRYHVWKHIUDFWLRQ
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[SH²YDOXHDFFXUDWHWRSODFHV
IURPPDWKLPSRUWÁRRUDVI H[SPHUHVXOWDFFXUDWHWRIXOOSUHFLVLRQ
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.
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ÁHOVW import random
print(lst) RXWSXW ^´+HDGVµ´7DLOVµ`
FRLQ OLVWRXWSXWNH\V
This way, you can keep shuưing the list before displaying a random
item from it. IRULLQUDQJH
RXWSXW>UDQGRPFKRLFHFRLQ@
SULQW´+HDGVµRXWSXW>´+HDGVµ@
SULQW´7DLOVµRXWSXW>´7DLOVµ@
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 SDFNDQFKRU :
Radiobutton(root,
WH[W µ&µ
padx = 20,
YDULDEOH Y
STEP 6 We can also display both text and images within a YDOXH SDFNDQFKRU :
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 /DEHOURRWURRWWLWOH´5DVSEHUU\3Lµ GHIYDUBVWDWHV
LPDJH ORJRSDFNVLGH µULJKWµ SULQW´:DUULRUG?Q0DJHGµYDUJHW
FRQWHQW ´µµ7KH5DVSEHUU\3L)RXQGDWLRQLVD YDUJHW
8.EDVHGFKDULW\WKDWZRUNVWRSXWWKHSRZHURI
/DEHOURRWURRWWLWOH´$GYHQWXUH*DPHµ
FRPSXWLQJDQGGLJLWDOPDNLQJLQWRWKHKDQGVRI
WH[W µ!!!!!!!!!!<RXUDGYHQWXUHUROHµ
SHRSOHDOORYHUWKHZRUOG:HGRWKLVVRWKDWPRUH
JULGURZ VWLFN\ 1
people are able to harness the power of computing
YDU ,QW9DU
DQGGLJLWDOWHFKQRORJLHVIRUZRUNWRVROYH
&KHFNEXWWRQURRWWH[W µ:DUULRUµYDULDEOH YDU
problems that matter to them, and to express
JULGURZ VWLFN\ :
WKHPVHOYHVFUHDWLYHO\´µµ
YDU ,QW9DU
w2 = Label(root,
&KHFNEXWWRQURRWWH[W µ0DJHµYDULDEOH YDU
MXVWLI\ /()7
JULGURZ VWLFN\ :
padx = 10,
%XWWRQURRWWH[W ·4XLW·FRPPDQG URRWGHVWUR\
WH[W FRQWHQWSDFNVLGH µOHIWµ
JULGURZ VWLFN\ :SDG\
root.mainloop()
%XWWRQURRWWH[W ·6KRZ·FRPPDQG YDUBVWDWHV
JULGURZ 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()
100 www.bdmpublications.com
Pygame Module
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ÀOOZKLWH
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ÀOOZKLWH
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
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.
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 &DQYDVJXLZLGWK KHLJKW EJ ·ZKLWH·
FDQYDVSDFN
EDOO FDQYDVFUHDWHBRYDOÀOO ·UHG·
gui.mainloop()
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
FDQYDVPRYHEDOO[D\D Simulation”)
SRV FDQYDVFRRUGVEDOO 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.
PRYHBDQGBGUDZBVWDUVVFUHHQ
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 FDQYDVFRRUGVEDOO 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.
www.bdmpublications.com 105
Working with Modules
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 LQWLQSXW´(QWHUVHFRQGQXPEHU´
print(power(num1, num2))
HOVH
SULQW´,QYDOLGLQSXWµ
STEP 8 Now we can add the user input to get the number
the code will work on:
QXP LQWLQSXW´?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
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.
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.
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.
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
112 www.bdmpublications.com
Why Linux?
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.
www.bdmpublications.com 113
Learning Linux
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.
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
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”.
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 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
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.
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
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.
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
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.
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.
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
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
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.
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.
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.
www.bdmpublications.com 131
Learning Linux
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.
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.
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.
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
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).
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
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.
www.bdmpublications.com 141
Learning Linux
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.
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
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 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 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
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
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
148 www.bdmpublications.com
Code Repository
www.bdmpublications.com 149
Code Repository
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
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
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
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
156 www.bdmpublications.com
Random Password Generator/Keyboard Drawing Script
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
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()
screen¿ll(W+,7E)
158 www.bdmpublications.com
Pygame Text Examples/Google Search Script
www.bdmpublications.com 159
Code Repository
160 www.bdmpublications.com
Text to Binary Convertor
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()
www.bdmpublications.com 161
Code Repository
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.
www.bdmpublications.com 163
Code Repository
screen = Screen()
yertle = 7urtle()
def k0():
screenonscreenclick(click B handler)
screenlisten()
screenmainloop()
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
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
, 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
µ¶¶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 update(self):
if pgtimeget B ticks()selftimer ! selfdelay:
selftimer = pgtimeget B ticks()
for text rect in selftext:
recty =
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
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)
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
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
print(“Select operation?n´)
print(“Add´)
print(“Subtract´)
print(“Multiply´)
print(“4DiYide´)
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
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
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.
www.bdmpublications.com 173
Code Repository
| |
O |
|
|
|
=========¶¶¶ µ¶¶
| |
O |
| |
|
|
=========¶¶¶ µ¶¶
| |
O |
| |
|
|
=========¶¶¶ µ¶¶
| |
O |
|? |
|
|
=========¶¶¶ µ¶¶
| |
O |
|? |
|
174 www.bdmpublications.com
Hangman Game Script
www.bdmpublications.com 175
Index
Coding
Projects & Tips
176 www.bdmpublications.com
Coding Projects & Tips
www.bdmpublications.com 177
Coding Projects & Tips
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
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.
#Initialise settings
start = 10
message = “> BLAST OFF!! <”
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
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.
182 www.bdmpublications.com
Tracking the ISS with Python
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.
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
www.bdmpublications.com 185
Coding Projects & Tips
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
ZLWKRSHQQDPH´UµHQFRGLQJ µXWIµDVI IRUQDPHLQÀOHQDPHV
IUDPHVDSSHQGIUHDGOLQHV ZLWKRSHQQDPH´UµHQFRGLQJ µXWIµDVI
IUDPHVDSSHQGIUHDGOLQHV
IRULLQUDQJH
IRUIUDPHLQIUDPHV
SULQW´µMRLQIUDPH
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
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.
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.
190 www.bdmpublications.com
Python Beginner’s Mistakes
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
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.
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
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
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