The Complete Python Coding Manual - 3rd Edition, 2023
The Complete Python Coding Manual - 3rd Edition, 2023
The Complete
Coding Manual
The essential manual for improving
your Python programming skills
OVER
820GUIDES
&TIPS
Coding Manual
Unlock your imagination with Python...
There are few coding languages that have enjoyed the success of
Python. Thanks to Python’s unique development, everyone can learn
the code that is: helping to drive such technological projects as the
Large Hadron Collider, collating the petabytes of data that made up
the first image of a Black Hole and creating the next generation of
Artificial Intelligence. It doesn’t take long to get to grips with Python,
but you need to start small.
This guide will help you form the foundation of your Python coding
future, from installing the language on to your computer, through to
forming user interaction and complex variables. There’s so much you
can do with Python and within these pages you’ll find everything you
need to know to become a Python programmer, ready for the
next level of advanced coding.
www.pclpublications.com
Contents
Check out
PCL’s Code Portal
50 FREE
Contents
COMPLETE PROGRAM
S!
Over 20,000 lines of
code!
Visit: pclpublications
.com/
exclusives
Please note: Sign up is
required
for download
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.SFOpublications.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
164 Mouse Controlled Turtle
108 165 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.SFOpublications.com 5
Index
6 www.SFOpublications.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.SFOpublications.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.SFOpublications.com
Being a Programmer
“It’s up to you
creating something from a few lines of BASIC code was achievable and so
WKHƬUVWJHQHUDWLRQRIKRPHEUHGSURJUDPPHUZDVERUQ
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?
%HLQJDEOHWRVHHWKHELJSLFWXUHLVFHUWDLQO\EHQHƬFLDOIRUWKHPRGHUQ
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
RIGHVLJQHUVDOORIZKRPDUHFUHDWLQJDƬQDOSURGXFW:KLOH\RXPD\RQO\
EHH[SHFWHGWRFUHDWHDVPDOOHOHPHQWRIWKDWƬQDOSURGXFWEHLQJDEOHWR
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.SFOpublications.com 9
Print (“The World of Code”)
,WoVGLƯFXOWWRSLQSRLQWDQH[DFW
start of when humans began to
‘program’ a device. However,
it’s widely accepted that the
Antikythera Mechanism is possibly
WKHƬUVWnFRGHGoDUWHIDFW,WoV Joseph Marie Jacquard invents a
dated to about 87 BC and is an programmable loom, which used cards with
ancient Greek analogue computer punched holes to create the textile design.
and orrery used to predict However, it is thought that he based his
astronomical positions. design on a previous automated weaving
process from 1725, by Basile Bouchon.
10 www.SFOpublications.com
A Brief History of Coding
During the Second World From the 1970s, the development of the likes of C, SQL, C with
:DUVLJQLƬFDQWDGYDQFHV 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.
7KHƬUVWWUXHFRPSXWHUFRGHZDV
Assembly Language (ASM) or
Regional Assembly Language. ASM Admiral Grace Hopper was part of
ZDVVSHFLƬFWRWKHDUFKLWHFWXUH the team that developed the UNIVAC
of the machine on which it was I computer and she eventually
being used. In 1951, programming developed a compiler for it. In time,
languages fell under the generic the compiler she developed became
term Autocode. Soon languages COBOL (Common Business-oriented
such as IPL, FORTRAN and ALGOL Language), a computer language that’s
58 were developed. still in use today.
www.SFOpublications.com 11
Print (“The World of Code”)
Choosing a
Programming
/DQJXDJH
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.SFOpublications.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
$PHULFDQ1DWLRQDO6WDQGDUGV,QVWLWXWH VWDQGDUGWKHUHDUHGLƪHUHQWYHUVLRQVRI
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.SFOpublications.com
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
OHDUQLQJIRXQGDWLRQZKLOH\RXEHJLQWRWDNH\RXUƬUVWWHQWDWLYH
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
KDYHVRPHGLƯFXOW\IROORZLQJDPRGHUQODQJXDJHWXWRULDOEXW 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. 2YHUWLPH\RXPD\ƬQG\RXUVHOIFKDQJLQJIURPWKHPDLQVWUHDP
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. WRXVHGLƪHUHQWWRROVWRJHWWKHMREGRQH6RPHHQYLURQPHQWV
You can use other operating systems, but these are the ‘big will enhance sections of code, making it easier to read, others will
WKUHHoDQG\RXZLOOƬQGWKDWPRVWFRGHUHVRXUFHVDUHZULWWHQ allow quick compiling and execution. It’s all a matter of testing
with one, or all of these, in mind. and experience.
14 www.SFOpublications.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 KDYHGLƪHUHQWLQVWDOODWLRQVRIRSHUDWLQJV\VWHPVUXQQLQJIURP
does it have a Unix-like backbone, but also it’s also free to WKHKRVWFRPSXWHUZKLOHXVLQJGLƪHUHQWFRGLQJODQJXDJHV
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 DQGLWoVHDV\WRUHWXUQWRDSUHYLRXVFRQƬJXUDWLRQZLWKRXWWKH
the servers that make up the Internet. It’s used on nearly all of need to reinstall everything again.
WKHWRSVXSHUFRPSXWHUVDVZHOODVVSHFLƬFDOO\LQRUJDQLVDWLRQV
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, SUREDEO\ƬQGIRUH[DPSOHUDWKHUWKDQKDYLQJDVLQJOHVHUYHU
as a coding platform, is an excellent idea and it can be installed with an installation of Windows Server, the IT team have
LQVLGHDYLUWXDOPDFKLQHZLWKRXWHYHUDƪHFWLQJWKHLQVWDOODWLRQ 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 0,1,;1(21&Ǖ
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 0,1,;0HDVXULQJMXVW[[PPWKLV,QWHO1&38
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
GLƪHUHQWKDUGZDUHLQWKHIRUPRIURERWLFVDQGHOHFWURQLFV and memory available, you’re able to create a computer that can
SURMHFWVDVZHOODVRƪHULQJDFRPSOHWHGHVNWRSH[SHULHQFH 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 KXQGUHGDQGƬIW\RUVRWRLQFUHDVHWKHVSHFLƬFDWLRQVEXW
FRQVLGHUWKDWDOLFHQVHIRU:LQGRZV3URDORQHFRVWV~
Whichever method you choose, remember that your coding
IURPWKH0LFURVRIW6WRUHDQG\RXFDQEHJLQWRVHHWKHEHQHƬWV
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.SFOpublications.com
Print (“The World of Code”)
6RXQGVJRRGEXWZKDWH[DFWO\LVD9LUWXDO0DFKLQHDQGKRZ
does it work?
7KHRƯFLDOGHƬQLWLRQRIDYLUWXDOPDFKLQHLVnDQHƯFLHQWLVRODWHG
duplicate of a real computer machine’. This basically means that a
virtual machine is an emulated computer system that can operate in
H[DFWO\WKHVDPHZD\DVDSK\VLFDOPDFKLQHEXWZLWKLQWKHFRQƬQHV
of a dedicated virtual machine operator, or Hypervisor.
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 <RXoUHDEOHWRLQVWDOO/LQX[DQGFRGHLQVLGHDYLUWXDO
machine and therefore won’t be available to the physical computer machine on a Windows 10 host.
until the hypervisor has been closed down.
16 www.SFOpublications.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.
9LUWXDOPDFKLQHVFDQEHDVVLPSOHRUDVFRPSOH[DV\RXU
QHHGVUHTXLUH
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.SFOpublications.com 17
Print (“The World of Code”)
Equipment You
Will Need
<RXFDQOHDUQ3\WKRQZLWKYHU\OLWWOHKDUGZDUHRULQLWLDOƬQDQFLDOLQYHVWPHQW<RX
don’t need an incredibly powerful computer and any software that’s required is
IUHHO\{DYDLODEOH
:+$7:(o5(86,1*
7KDQNIXOO\3\WKRQLVDPXOWLSODWIRUPSURJUDPPLQJODQJXDJHDYDLODEOHIRU:LQGRZVPDF26/LQX[5DVSEHUU\3LDQGPRUH,I
\RXKDYHRQHRIWKRVHV\VWHPVWKHQ\RXFDQHDVLO\VWDUWXVLQJ3\WKRQ
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
ZHOODVRƪHULQJDGYDQFHGIHDWXUHV7KHUHDUHPDQ\GLƪHUHQW,'(VDYDLODEOHVRƬQG
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,
VXFKDV6XEOLPH7H[WRU1RWHSDGRƪHUVPRUHDGYDQFHGIHDWXUHVDQGFRORXUFRGLQJ
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
HƯFLHQWODQJXDJH+DYLQJDFFHVVWRWKH,QWHUQHWZLOONHHS\RXXSWRGDWHKHOS\RX
out when you get stuck and give access to Python’s immense number of modules.
18 www.SFOpublications.com
Equipment You Will Need
THE RASPBERRY PI
:K\XVHD5DVSEHUU\3L"7KH5DVSEHUU\3LLVDWLQ\FRPSXWHUWKDWoVYHU\FKHDSWRSXUFKDVHEXWRƪHUVWKHXVHUDIDQWDVWLFOHDUQLQJ
SODWIRUP,WVPDLQRSHUDWLQJV\VWHP5DVSELDQFRPHVSUHLQVWDOOHGZLWKWKHODWHVW3\WKRQDORQJZLWKPDQ\PRGXOHVDQGH[WUDV
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
WREXLOGDQGSURJUDP<RXFDQƬQGPRUHLQIRUPDWLRQRQWKH
FUZE at www.fuze.co.uk.
BOOKS
We have several great Raspberry Pi titles available via www.
SFOSXEOLFDWLRQVFRP. Our Pi books cover how to buy your
RASPBIAN ILUVW5DVSEHUU\3L
set it up and use ¦C
it; there are some great step- r
rojec
The Raspberry Pi’s main operating system is a Debian-based
E\VWHSSURMHFWH[DPSOHV
Linux distribution that comes with everything you need in
and guides to get the most
a simple to use package. It’s streamlined for the Pi and is an
from the
LGHDOSODWIRUPIRUKDUGZDUHDQGVRIWZDUHSURMHFWV3\WKRQ
Raspberry
programming and even as a desktop computer.
Pi too.
www.SFOpublications.com 19
Index
20 www.SFOpublications.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.SFOpublications.com 21
Welcome to Python
Why Python?
7KHUHDUHPDQ\GLƪHUHQWSURJUDPPLQJODQJXDJHVDYDLODEOHIRUWKHPRGHUQFRPSXWHU
DQGVRPHVWLOODYDLODEOHIRUROGHUDQGELWFRPSXWHUVWRR6RPHRIWKHVHODQJXDJHV
DUHGHVLJQHGIRUVFLHQWLƬFZRUNRWKHUVIRUPRELOHSODWIRUPVDQGVXFK6RZK\FKRRVH
3\WKRQRXWRIDOOWKHUHVW"
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’
WKDWoVXVHGWRXOWUDKLJKGHƬQLWLRQJUDSKLFVDQGRSHQZRUOGPXOWL 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 7KHODQJXDJHVLQXVHWRGD\GLƪHUGHSHQGLQJRQWKHVLWXDWLRQWKH
billion pound gaming empire that continually amazes us. platform, the device’s use and how the device will interact with its
22 www.SFOpublications.com
:K\3\WKRQ"
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 HYHQ5,6&26,WKDVEHHQYRWHGRQHRIWKHWRSƬYHSURJUDPPLQJ
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, OHDUQH[FHSWLRQDOO\SRZHUIXOXQLYHUVDOO\DFFHSWHGHƪHFWLYHDQGD
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
VWDFNVDQGUHJLVWHUVLWVEHQHƬWLVWKDWLWoVXQLYHUVDOO\DFFHVVLEOH
and easy to learn.
Java is a powerful
language that’s used in
web pages, set-top boxes,
TVs and even cars.
www.SFOpublications.com 23
Welcome to Python
3\WKRQoVDELOLW\WRFUHDWHKLJKO\UHDGDEOHFRGHZLWKLQDVPDOOVHW <RXoOOƬQGORWVRIH[DPSOHVRIWKLVZKHUH3\WKRQLVDFWLQJEHKLQG
RILQVWUXFWLRQVKDVDFRQVLGHUDEOHLPSDFWRQRXUPRGHUQGLJLWDO WKHVFHQHV7KLVLVZK\LWoVVXFKDQLPSRUWDQWODQJXDJHWROHDUQ
ZRUOG)URPWKHLGHDOƬUVWSURJUDPPHUVoFKRLFHWRLWoVDELOLW\WR
FUHDWHLQWHUDFWLYHVWRULHVDQGJDPHVIURPVFLHQWLƬFDSSOLFDWLRQVWR
DUWLƬFLDO,QWHOOLJHQFHDQGZHEEDVHGDSSOLFDWLRQVWKHRQO\OLPLWWR
3\WKRQLVWKHLPDJLQDWLRQRIWKHSHUVRQFRGLQJLQLW
,WoV3\WKRQoVPDOOHDEOHGHVLJQWKDWPDNHVLWDQLGHDOODQJXDJHIRU
PDQ\GLƪHUHQWVLWXDWLRQVDQGUROHV(YHQFHUWDLQDVSHFWVRIWKH
FRGLQJZRUOGWKDWUHTXLUHPRUHHƯFLHQWFRGHVWLOOXVH3\WKRQ
)RUH[DPSOH1$6$XWLOLVHV3\WKRQERWKDVDVWDQGDORQHODQJXDJH
DQGDVDEULGJHEHWZHHQRWKHUSURJUDPPLQJODQJXDJHV7KLVZD\
1$6$VFLHQWLVWVDQGHQJLQHHUVDUHDEOHWRJHWWRWKHGDWDWKH\
QHHGZLWKRXWKDYLQJWRFURVVPXOWLSOHODQJXDJHEDUULHUV3\WKRQ
ƬOOVWKHJDSVDQGSURYLGHVWKHPHDQVWRJHWWKHMREGRQH
BIG DATA
%LJGDWDLVDEX]]ZRUG\RXoUHOLNHO\WRKDYHFRPHDFURVVLQWKHODVWFRXSOHRI\HDUV
%DVLFDOO\LWPHDQVH[WUHPHO\ODUJHGDWDVHWVWKDWDUHDYDLODEOHIRUDQDO\VLVWRUHYHDO
SDWWHUQVWUHQGVDQGLQWHUDFWLRQVEHWZHHQKXPDQVVRFLHW\DQGWHFKQRORJ\2IFRXUVH
LWoVQRWMXVWOLPLWHGWRWKRVHDUHDVELJGDWDLVFXUUHQWO\EHLQJXVHGLQDYDULHW\RI
LQGXVWULHVIURPVRFLDOPHGLDWRKHDOWKDQGZHOIDUHHQJLQHHULQJWRVSDFHH[SORUDWLRQ
and beyond.
3\WKRQSOD\VDVXEVWDQWLDOUROHLQWKHZRUOGRIELJGDWD,WoVH[WHQVLYHO\XVHGWR
DQDO\VHKXJHFKXQNVRIWKHDYDLODEOHELJGDWDDQGH[WUDFWVSHFLƬFLQIRUPDWLRQEDVHG
RQZKDWWKHXVHUFRPSDQ\UHTXLUHVIURPWKHZHDOWKRIQXPEHUVSUHVHQW7KDQNVWRDQ
LPSUHVVLYHVHWRIGDWDSURFHVVLQJOLEUDULHV3\WKRQPDNHVWKHDFWRIJHWWLQJWRWKHGDWD
LQDPRQJVWWKHQXPEHUVWKDWFRXQWVDQGSUHVHQWLQJLWLQDIDVKLRQWKDWoVUHDGDEOHDQG
XVHDEOHIRUKXPDQV
7KHUHDUHFRXQWOHVVOLEUDULHVDQGIUHHO\DYDLODEOHPRGXOHVWKDWHQDEOHIDVWVHFXUH
DQGPRUHLPSRUWDQWO\DFFXUDWHSURFHVVLQJRIGDWDIURPWKHOLNHVRIVXSHUFRPSXWLQJ
FOXVWHUV)RUH[DPSOH&(51XVHVDFXVWRP3\WKRQPRGXOHWRKHOSDQDO\VHWKHPLOOLRQ
FROOLVLRQVSHUVHFRQGWKDWWKH/+&SURGXFHV$GLƪHUHQWODQJXDJHKDQGOHVWKHUDZGDWD
EXW3\WKRQLVSUHVHQWWRKHOSVLIWWKURXJKWKHGDWDVRVFLHQWLVWVFDQJHWWRWKHFRQWHQW
WKH\ZDQWZLWKRXWWKHQHHGWROHDUQDIDUPRUHFRPSOH[SURJUDPPLQJODQJXDJH
24 www.SFOpublications.com
:KDWFDQ<RX'RZLWK3\WKRQ"
ARTIFICIAL INTELLIGENCE
$UWLƬFLDO,QWHOOLJHQFHDQG0DFKLQH/HDUQLQJDUHWZRRIWKHPRVW
JURXQGEUHDNLQJDVSHFWVRIPRGHUQFRPSXWLQJ$,LVWKHXPEUHOOD
WHUPXVHGIRUDQ\FRPSXWLQJSURFHVVZKHUHLQWKHPDFKLQHLV
GRLQJVRPHWKLQJLQWHOOLJHQWZRUNLQJDQGUHDFWLQJLQVLPLODUZD\V
WRKXPDQV0DFKLQH/HDUQLQJLVDVXEVHWRI$,DQGSURYLGHVWKH
RYHUDOO$,V\VWHPZLWKWKHDELOLW\WROHDUQIURP
its experiences.
+RZHYHU$,LVQoWVLPSO\WKHFUHDWLRQRIDXWRQRPRXVURERWV
LQWHQWRQZLSLQJRXWKXPDQFLYLOLVDWLRQ,QGHHG$,FDQEH
IRXQGLQDYDULHW\RIGD\WRGD\FRPSXWLQJDSSOLFDWLRQVZKHUH
WKHnPDFKLQHoRUPRUHDFFXUDWHO\WKHFRGHQHHGVWROHDUQ
IURPWKHDFWLRQVRIVRPHIRUPRILQSXWDQGDQWLFLSDWHZKDW
WKHLQSXWLVOLNHO\WRUHTXLUHRUGRQH[W
7KLVPRGHOFDQEHDSSOLHGWR)DFHERRN*RRJOH7ZLWWHU
,QVWDJUDPDQGVRRQ+DYH\RXHYHUORRNHGXSDFHOHEULW\RQ
,QVWDJUDPDQGWKHQGLVFRYHUHGWKDW\RXUVHDUFKHVZLWKLQRWKHU
VRFLDOPHGLDSODWIRUPVDUHQRZVSHFLƬFDOO\WDUJHWHGWRZDUG
VLPLODUFHOHEULWLHV"7KLVLVDSULPHH[DPSOHRIXVLQJ$,LQ
WDUJHWHGDGYHUWLVLQJDQGEHKLQGWKHFRGHDQGDOJRULWKPVWKDW
SUHGLFWZKDW\RXoUHORRNLQJIRULV3\WKRQ GAMING
6SRWLI\IRUH[DPSOHXVHV3\WKRQEDVHGFRGHDPRQJ $OWKRXJK\RXZRQoWƬQGWRRPDQ\WULSOH$UDWHGJDPHVFRGHGXVLQJ
RWKHUWKLQJVWRDQDO\VH\RXUPXVLFDOKDELWVDQG Python, you may be surprised to learn that Python is used as an
RƪHUSOD\OLVWVEDVHGRQZKDW\RXoYHOLVWHQHGWR extra on many of the high-ranking modern games.
LQWKHSDVW,WoVDOOFOHYHUVWXƪDQGPRYLQJ
IRUZDUG3\WKRQLVDWWKHIRUHIURQWRIWKHZD\ The main use of Python in gaming comes in the form of scripting,
WKH,QWHUQHWZLOOZRUNLQWKHIXWXUH where a Python script can add customisations to the core game
engine. Many map editors are Python compatible and you will also
come across it if you build any mods for games, such as The Sims.
www.SFOpublications.com 25
Welcome to Python
Pytho
n cre
Ross ator G
um n uido
amed V
There’s a readi
ng sc P ython an
Pyth ripts afte
lot to like about on’s F from Mon r
lying t
Python, but don’t just Circu y
s.
take our word for it. Here are
VRPHDPD]LQJIDFWVDQGƬJXUHV
surrounding one of the most popular
programming languages of recent years.
in PYTHON AND
LINUX SKILLS
N UMBERS
26 www.SFOpublications.com
3\WKRQLQ1XPEHUV
16,000 3<7+216.,//Ǖ%$6('
POSITIONS ARE THE
th
0267628*+7Ǖ$)7(5
There are over 16,000 Python jobs
posted every six months in the UK. JOBS IN THE UK.
Python Data Science is Google is the top Data Science, Blockchain New York and San
thought to become the company for hiring Python and Machine Learning Francisco are the top
most sought-after job in developers, closely are the fastest growing Python developer cities
the coming years. followed by Microsoft. Python coding skills. in the world.
£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.SFOpublications.com 27
Welcome to Python
How to Set Up
Python in Windows
:LQGRZVXVHUVFDQHDVLO\LQVWDOOWKHODWHVWYHUVLRQRI3\WKRQYLDWKHPDLQ3\WKRQ
'RZQORDGVSDJH:KLOVWPRVWVHDVRQHG3\WKRQGHYHORSHUVPD\VKXQ:LQGRZVDVWKH
SODWIRUPRIFKRLFHIRUEXLOGLQJWKHLUFRGHLWoVVWLOODQLGHDOVWDUWLQJSRLQWIRUEHJLQQHUV
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
WKHODVWGLJLWIRUHDFKEXJƬ[DQGXSGDWH7KHUHIRUHGRQoWZRUU\LI 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 IHDWXUHV2QWKHƬUVWVFUHHQDYDLODEOHHQVXUHDOOER[HVDUHWLFNHG
WKLVERRNZLOOZRUNƬQH 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
VDYHWKHƬOHWR\RXU'RZQORDGVIROGHU:KHQWKH DGGLWLRQVWR3\WKRQ(QVXUHWKH$VVRFLDWHƬOHZLWK
ƬOHLVGRZQORDGHGGRXEOHFOLFNWKHH[HFXWDEOHDQGWKH3\WKRQ 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.SFOpublications.com
+RZWR6HW8S3\WKRQLQ:LQGRZV
STEP 5 <RXPD\QHHGWRFRQƬUPWKHLQVWDOODWLRQZLWKWKH STEP 8 Clicking on the IDLE (Python 3.7 32-bit) link will
:LQGRZVDXWKHQWLFDWLRQQRWLƬFDWLRQ6LPSO\FOLFN 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
WKHƬQDO3\WKRQZL]DUGSDJHZLOODOORZ\RXWRYLHZWKHODWHVWUHOHDVH 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.SFOpublications.com 29
Welcome to Python
How to Set Up
Python in Linux
:KLOHWKH5DVSEHUU\3LoVRSHUDWLQJV\VWHPFRQWDLQVWKHODWHVWVWDEOHYHUVLRQRI3\WKRQ
RWKHU/LQX[GLVWURVGRQoWFRPHZLWK3\WKRQSUHLQVWDOOHG,I\RXoUHQRWJRLQJGRZQ
WKH3LURXWHWKHQKHUHoVKRZWRFKHFNDQGLQVWDOO3\WKRQIRU/LQX[
PYTHON PENGUIN
/LQX[LVVXFKDYHUVDWLOHRSHUDWLQJV\VWHPWKDWLWoVRIWHQGLƯFXOWWRQDLOGRZQMXVWRQHZD\RIGRLQJVRPHWKLQJ'LƪHUHQW
GLVWULEXWLRQVJRDERXWLQVWDOOLQJVRIWZDUHLQGLƪHUHQWZD\VVRIRUWKLVSDUWLFXODUWXWRULDOZHZLOOVWLFNWR/LQX[0LQW
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.SFOpublications.com
+RZWR6HW8S3\WKRQLQ/LQX[
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
,'/(UXQVDGLƪHUHQWYHUVLRQWRWKHRQH\RXLQVWDOOHGIURPVRXUFH
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.SFOpublications.com 31
Welcome to Python
Python on the Pi
,I\RXoUHFRQVLGHULQJRQZKLFKSODWIRUPWRLQVWDOODQGXVH3\WKRQWKHQJLYHVRPH
WKRXJKWWRRQHRIWKHEHVWFRGLQJEDVHVDYDLODEOHWKH5DVSEHUU\3L7KH3LKDVPDQ\
DGYDQWDJHVIRUWKHFRGHULWoVFKHDSHDV\WRXVHDQGH[WUDRUGLQDULO\ƮH[LEOH
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
XVDUHXQDEOHWRMXPSLQWRDVHYHUDOKXQGUHGSRXQGLQYHVWPHQWZKHQZHoUHVWDUWLQJRƪDQGWKLVLVZKHUHWKH5DVSEHUU\3LFDQ
help out.
:KLOHKDYLQJDIDUPRUHSRZHUIXOFRGLQJSODWIRUPRQZKLFKWR IRUVSDFHDQGPRQH\WKHQIRUDURXQG~EX\LQJRQHRIWKHPDQ\
ZULWHDQGWHVW\RXUFRGHLVLGHDOLWoVQRWRIWHQIHDVLEOH0RVWRIXV NLWVDYDLODEOHZLOOSURYLGHWKH3LZLWKDSUHORDGHG6'FDUG ZLWKWKH
DUHXQDEOHWRMXPSLQWRDVHYHUDOKXQGUHGSRXQGLQYHVWPHQWZKHQ ODWHVW5DVSELDQ26 DFDVHSRZHUVRFNHWDQGFDEOHVWKLVLVDJRRG
ZHoUHVWDUWLQJRƪDQGWKLVLVZKHUHWKH5DVSEHUU\3LFDQKHOSRXW LGHDDV\RXFRXOGZLWKYHU\OLWWOHHƪRUWOHDYHWKH3LSOXJJHGLQWRWKH
ZDOOXQGHUDGHVNZKLOHVWLOOEHLQJDEOHWRFRQQHFWWRLWDQGFRGH
7KH5DVSEHUU\3LLVDIDQWDVWLFSLHFHRIPRGHUQKDUGZDUHWKDW
KDVFUHDWHGRUUDWKHUUHFUHDWHGWKHIDVFLQDWLRQZHRQFHDOOKDG 7KHPDLQDGYDQWDJHLVRIFRXUVHWKHH[WUDFRQWHQWWKDWWKH
DERXWFRPSXWHUVKRZWKH\ZRUNKRZWRFRGHDQGIRXQGDWLRQ 5DVSEHUU\3L)RXQGDWLRQKDVLQFOXGHGRXWRIWKHER[7KHUHDVRQ
OHYHOHOHFWURQLFV7KDQNVWRLWVXQLTXHPL[RIKDUGZDUHDQGFXVWRP IRUWKLVLVWKDWWKH5DVSEHUU\3LoVJRDOLVWRKHOSHGXFDWHWKH
VRIWZDUHLWKDVSURYHGLWVHOIWREHDQDPD]LQJSODWIRUPRQZKLFKWR XVHUZKHWKHUWKDWoVFRGLQJHOHFWURQLFVRUVRPHRWKHUDVSHFWRI
OHDUQKRZWRFRGHVSHFLƬFDOO\XVLQJ3\WKRQ FRPSXWLQJ7RDFKLHYHWKDWJRDOWKH3L)RXQGDWLRQLQFOXGHVGLƪHUHQW
,'(VIRUWKHXVHUWRFRPSLOH3\WKRQFRGHRQDVZHOODVERWK3\WKRQ
:KLOH\RXoUHDEOHZLWKHDVHWRXVHWKH5DVSEHUU\3LWROHDUQWR DQG3\WKRQWKHUHoVHYHQD3\WKRQOLEUDU\WKDWDOORZV\RXWR
FRGHZLWKRWKHUSURJUDPPLQJODQJXDJHVLWoV3\WKRQWKDWKDVEHHQ FRPPXQLFDWHZLWK0LQHFUDIW
ƬUPO\SXVKHGWRWKHIRUHIURQW7KH5DVSEHUU\3LXVHV5DVSELDQ
DVLWVUHFRPPHQGHGGHIDXOWRSHUDWLQJV\VWHP5DVSELDQLVD 7KHUHDUHRWKHUDGYDQWDJHVVXFKDVEHLQJDEOHWRFRPELQH3\WKRQ
/LQX[26RUWREHPRUHDFFXUDWHLWoVD'HELDQEDVHGGLVWULEXWLRQ FRGHZLWK6FUDWFK DQ2EMHFW2ULHQWHGSURJUDPPLQJODQJXDJH
RI/LQX[7KLVPHDQVWKDWWKHUHoVDOUHDG\DEXLOWLQHOHPHQW GHYHORSHGE\0,7IRUFKLOGUHQWRXQGHUVWDQGKRZFRGLQJZRUNV DQG
RI3\WKRQSURJUDPPLQJDVRSSRVHGWRDIUHVKLQVWDOODWLRQRI EHLQJDEOHWRFRGHWKH*3,2FRQQHFWLRQRQWKH3LWRIXUWKHUFRQWURO
:LQGRZVZKLFKKDVQR3\WKRQVSHFLƬFEDVH+RZHYHUWKH DQ\DWWDFKHGURERWLFVRUHOHFWURQLFVSURMHFWV5DVSELDQDOVRLQFOXGHV
5DVSEHUU\3L)RXQGDWLRQKDVJRQHWKHH[WUDPLOHWRLQFOXGHDYDVW D6HQVH+$7(PXODWRU D+$7LVDKDUGZDUHDWWDFKHGSLHFHRI
UDQJHRI3\WKRQPRGXOHVH[WHQVLRQVDQGHYHQH[DPSOHVRXWRI FLUFXLWU\WKDWRƪHUVGLƪHUHQWHOHFWURQLFVURERWLFVDQGPRWRULVDWLRQ
WKHER[6RHVVHQWLDOO\DOO\RXQHHGWRGRLVEX\D5DVSEHUU\3L SURMHFWVWRWKH3L ZKLFKFDQEHDFFHVVHGYLD3\WKRQFRGH
IROORZWKHLQVWUXFWLRQVRQKRZWRVHWRQHXS E\XVLQJRQHRIRXU
H[FHOOHQW5DVSEHUU\3LJXLGHVIRXQGDWhttps://bdmpublications. &RQVHTXHQWO\WKH5DVSEHUU\3LLVDQH[FHOOHQWFRGLQJEDVHDVZHOO
com/?s=raspberry+pi&post_type=product) and you can start DVDVXSHUESURMHFWIRXQGDWLRQ,WLVIRUWKHVHDQGPDQ\RWKHU
FRGLQJZLWK3\WKRQDVVRRQDVWKHGHVNWRSKDVORDGHG UHDVRQVZHoYHXVHGWKH5DVSEHUU\3LDVRXUPDLQ3\WKRQFRGHEDVH
WKURXJKRXWWKLVWLWOH:KLOHWKHFRGHLVZULWWHQDQGSHUIRUPHGRQD
6LJQLƬFDQWO\WKHUHoVDORWPRUHWRWKH5DVSEHUU\3LZKLFKPDNHV 3L\RXoUHDOVRDEOHWRXVHLWLQ:LQGRZVRWKHUYHUVLRQVRI/LQX[DQG
LWDQH[FHOOHQWFKRLFHIRUVRPHRQHZKRLVVWDUWLQJWROHDUQKRZWR PDF26,IWKHFRGHUHTXLUHVDVSHFLƬFRSHUDWLQJV\VWHPWKHQGRQoW
FRGHLQ3\WKRQ7KH3LLVUHPDUNDEO\HDV\WRVHWXSDVDKHDGOHVV ZRUU\ZHZLOOOHW\RXNQRZLQWKHWH[W
QRGH7KLVPHDQVWKDWZLWKDIHZWZHDNVKHUHDQGWKHUH\RXoUHDEOH
WRUHPRWHO\FRQQHFWWRWKH5DVSEHUU\3LIURPDQ\RWKHUFRPSXWHU
Everything you need to learn to code with Python is
RUGHYLFHRQ\RXUKRPHQHWZRUN)RUH[DPSOHRQFH\RXoYHVHWXS
included with the OS!
WKHUHPRWHFRQQHFWLYLW\RSWLRQV\RXFDQVLPSO\SOXJWKH3LLQWRWKH
SRZHUVRFNHWDQ\ZKHUHLQ\RXUKRXVHZLWKLQUDQJHRI\RXUZLUHOHVV
URXWHU$VORQJDVWKH3LLVFRQQHFWHG\RXZLOOEHDEOHWRUHPRWHO\
DFFHVVWKHGHVNWRSIURP:LQGRZVRUPDF26DVHDVLO\DVLI\RXZHUH
VLWWLQJLQIURQWRIWKH3LZLWKDNH\ERDUGDQGPRXVH
8VLQJWKLVPHWKRGVDYHVDORWRIPRQH\DV\RXGRQoWQHHGDQRWKHU
NH\ERDUGPRXVHDQGPRQLWRUSOXV\RXZRQoWQHHGWRDOORFDWH
VXƯFLHQWVSDFHWRDFFRPPRGDWHWKRVHH[WUDVHLWKHU,I\RXoUHSXVKHG
32 www.SFOpublications.com
Python on the Pi
3,Ǖ(9(5
Introduced on 24th June 2019, the Raspberry Pi 4 Model B is
DVLJQLƬFDQWOHDSLQWHUPVRI3LSHUIRUPDQFHDQGKDUGZDUH
VSHFLƬFDWLRQV,WZDVDOVRRQHRIWKHTXLFNHVWPRGHOVDVLGHIURP
WKHRULJLQDO3LWRVHOORXW
:LWKDQHZ*+]ELWTXDGFRUH$50&RUWH[$
SURFHVVRUDQGDFKRLFHRI*%*%RU*%PHPRU\
YHUVLRQVWKH3LLVRQHVWHSFORVHUWREHFRPLQJ
DWUXHGHVNWRSFRPSXWHU,QDGGLWLRQWKH3LZDV
ODXQFKHGZLWKWKHVWDUWOLQJGHFLVLRQWRLQFOXGHGXDO
PRQLWRUVXSSRUWLQWKHIRUPRIDSDLURIWZRPLFUR
+'0,SRUWV<RXoOODOVRƬQGDSDLURI86%SRUWV
%OXHWRRWKDQGD*38WKDWoVFDSDEOHRIKDQGLQJ.
UHVROXWLRQVDQG2SHQ*/(6JUDSKLFV
There’s no ,QVKRUWWKH3LLVWKHPRVWSRZHUIXORIWKHFXUUHQW5DVSEHUU\
such thing as too 3LPRGHOV+RZHYHUWKHGLƪHUHQWPHPRU\YHUVLRQVKDYHDQ
much Pi! LQFUHDVHGFRVW7KH*%YHUVLRQFRVWV~*%LV~DQGWKH
*%YHUVLRQZLOOVHW\RXEDFN~5HPHPEHUWRDOVRIDFWRULQRQH
RUWZRPLFUR+'0,FDEOHVZLWK\RXURUGHU
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.
,QVKRUWZKDW\RXVHHLQWKLVERRNZLOOZRUNZLWKWKH5DVSEHUU\3L
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.SFOpublications.com 33
Welcome to Python
Getting to
Know Python
WHAT IS PROGRAMMING?
,WKHOSVWRXQGHUVWDQGZKDWDSURJUDPPLQJODQJXDJHLVEHIRUH\RXWU\WROHDUQRQHDQG3\WKRQLVQRGLƪHUHQW/HWoVWDNHD
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).
7KHƬUVWLVDOLVWWKHVHFRQGDQREMHFWZHoOOORRNDWERWKLQWKLVERRN7KHPDLQWKLQJWRNQRZLV
that it’s easy to read commands in Python. Once you learn what the commands do, it’s easy to
ƬJXUHRXWKRZDSURJUDPZRUNV
34 www.bdmpublications.com
*HWWLQJWR.QRZ3\WKRQ
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 ,Q3\WKRQDUULYHGZLWKVHYHUDOQHZ
RIWKHSURJUDPPLQJODQJXDJH DQGHQKDQFHGIHDWXUHV7KHVHIHDWXUHV
+RZHYHULI\RXGLJDOLWWOHGHHSHULQWRWKH3\WKRQVLWHDQGLQYHVWLJDWH SURYLGHDPRUHVWDEOHHƪHFWLYHDQGHƯFLHQWSURJUDPPLQJ
3\WKRQFRGHRQOLQH\RXZLOOXQGRXEWHGO\FRPHDFURVV3\WKRQ HQYLURQPHQWEXWVDGO\PRVW LIQRWDOO RIWKHVHQHZIHDWXUHVDUH
$OWKRXJK\RXFDQUXQ3\WKRQDQG3\WKRQDORQJVLGHHDFKRWKHULWoV QRWFRPSDWLEOHZLWK3\WKRQVFULSWVPRGXOHVDQGWXWRULDOV:KLOVW
QRWUHFRPPHQGHG$OZD\VRSWIRUWKHODWHVWVWDEOHUHOHDVHDVSRVWHG QRWSRSXODUDWƬUVW3\WKRQKDVVLQFHEHFRPHWKHFXWWLQJHGJHRI
by the Python website. 3\WKRQSURJUDPPLQJ
www.bdmpublications.com 35
Index
36 www.SFOpublications.com
First Steps into Python
www.SFOpublications.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 LQWHUDFWLRQVZLWKWKHV\VWHP,QWHJHUVZKLFKDUHWKHLQƬQLWH
to try out some simple code and processes. sequence of whole numbers, can easily be added, subtracted,
multiplied, and so on.
38 www.SFOpublications.com
Starting Python for the First Time
STEP 5 While that’s very interesting, it’s not particularly STEP 8 7KH3\WKRQ,'/(LVDFRQƬJXUDEOHHQYLURQPHQW,I
exciting. Instead, try this: you don’t like the way the colours are represented,
then you can always change them via 2SWLRQV!&RQƬJXUH,'/(, 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
\RXUƬUVWELWRIFRGH7KH3ULQWFRPPDQGLVIDLUO\ 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 !&RQƬJXUH,'/(DQGXQGHUWKHKeys 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
3\WKRQ,'/(7KHFRORXUVUHSUHVHQWGLƪHUHQW 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.SFOpublications.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: VFUHHQ7KHTXRWDWLRQPDUNVDUHGHƬQLQJZKDWoVEHLQJRXWSXWWHG
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.SFOpublications.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:
:HQRZKDYHWZRYDULDEOHVFRQWDLQLQJERWKDƬUVWQDPHDQGD
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)
:HQHHGDVSDFHEHWZHHQWKHWZRGHƬQLQJWKHPDVWZRVHSDUDWH
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.
www.SFOpublications.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. FRGHKRZHYHU\RXQHHGWRƬUVWVDYHLW3UHVVF5 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: MXVWGXPSLWZKHUHYHU\RXOLNH5HPHPEHUWRNHHSDWLG\ƬOHV\VWHP
though, it’ll help you out in the future.
print(“Hello everyone!”)
42 www.SFOpublications.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 F5QRZ\RXoOOEHDVNHGWRVDYHWKHƬOHDJDLQDVLWoVEHHQ
PRGLƬHGIURPEHIRUH
STEP 6 This is how the vast majority of your Python code STEP 9 If you click the OKEXWWRQWKHƬOHZLOOEHRYHUZULWWHQ
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
ZLOOGLƪHUGHSHQGLQJRQZKHWKHU\RXoYHUHTXHVWHGDVHSDUDWH LI\RXZHUHWRHGLWDODUJHUƬOHRYHUZULWLQJFDQEHFRPHDQLVVXH
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.
www.SFOpublications.com 43
First Steps into Python
STEP 1 :KHQ\RXƬUVWLQVWDOOHG3\WKRQWKHLQVWDOODWLRQ 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.SFOpublications.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
SUHYLRXVWXWRULDODQGOLVWWKHDYDLODEOHƬOHVZLWKLQ\RXVKRXOGVHH
the hello.pyƬOH This will execute the code we created, which to remind you is:
a=”Python”
b=”is”
c=”cool!”
print(a, b, c)
www.SFOpublications.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.SFOpublications.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 WKHUHVXOWRIWKHWZRGHƬQLQJYDOXHVDQG,WoVDQH[WHQVLRQRI
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.SFOpublications.com 47
First Steps into Python
Using Comments
:KHQZULWLQJ\RXUFRGHWKHƮRZZKDWHDFKYDULDEOHGRHVKRZWKHRYHUDOOSURJUDP
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
GLƯFXOWWRUHDG
#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)
6DYHWKHƬOHDQGH[HFXWHWKHFRGH
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.SFOpublications.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
WKHƬUVWSULQWVWDWHPHQW\RXZRXOGXVH
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 <RXFDQXVHFRPPHQWVLQGLƪHUHQWZD\V)RU 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.SFOpublications.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)
1XPEHUVDUHVWRUHGDVGLƪHUHQW
variables:
age=44
Type (age)
Which, as we know, are integers.
50 www.SFOpublications.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: GHDOLQJZLWKƮRDWLQJSRLQWDULWKPHWLFUHPHPEHU
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
WKHQXPEHUDVDnƮRDWoEHFDXVHWKHYDOXHFRQWDLQVDGHFLPDOSRLQW
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.
www.SFOpublications.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.
IRU\RXUƬUVWQDPHVWRULQJLWDVWKHYDULDEOHƬUVWQDPH, 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.SFOpublications.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()
JXDUGFKDOOHQJHVWKHPWRDƬJKW
STEP 6 The code from the previous step is often regarded STEP 9 As you learned previously, any input from a user
as being a little neater than having a lengthy is automatically a string, so you’ll need to apply a
amount of text in the input command, but it’s not a rule that’s set in TypeCast in order to turn it into something else. This creates some
stone, so do as you like in these situations. Expanding on the code, interesting additions to the input command. For example:
try this:
# Code to calculate rate and distance
SULQW ´+DOW:KRJRHVWKHUH"µ print(“Input a rate and a distance”)
name=input() UDWH ÁRDW LQSXW ´5DWH´
STEP 7 It’s a good start to a text adventure game, perhaps? STEP 10 $QGWRƬQDOLVHWKHUDWHDQGGLVWDQFHFRGHZHFDQDGG
Now we can expand on it, and use the raw input
GLVWDQFH ÁRDW LQSXW ´'LVWDQFH´
IURPWKHXVHUWRƮHVKRXWWKHJDPHDOLWWOH
print(“Time:”, (distance / rate))
if name==”David”:
Save and execute the code, and enter some numbers. Using the
SULQW ´:HOFRPHJRRGVLU<RXPD\SDVVµ
ƮRDW LQSXW element, we’ve told Python that anything entered is a
else:
ƮRDWLQJSRLQWQXPEHUUDWKHUWKDQDVWULQJ
print(“I know you not. Prepare for battle!”)
www.SFOpublications.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
HQDEOHV\RXWRGHƬQH\RXURZQIXQFWLRQ
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: 7KHVHDUHWKHSUHGHƬQHGIXQFWLRQVEXWVLQFHXVHUVKDYHFUHDWHG
len(“antidisestablishmentarianism”), and the number 28 many more, they’re not the only ones available.
would return.
54 www.SFOpublications.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
7KHUHDUHPDQ\GLƪHUHQWIXQFWLRQVFUHDWHGE\RWKHU3\WKRQSURJUDPPHUVZKLFK\RXFDQLPSRUWDQG\RXoOOXQGRXEWHGO\FRPH
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,
FUHDWHDIXQFWLRQFDOOHG+HOORWKDWZLOOJUHHWD the last line in the script, and press Ctrl+S to save
user. Enter: WKHQHZVFULSW&ORVHWKH(GLWRUDQGFUHDWHDQHZƬOH File > New
File). Enter the following:
def Hello():
print (“Hello”) from Hello import Hello
Hello() Hello(“David”)
Press F5WRVDYHDQGUXQWKHVFULSW<RXoOOVHH+HOORLQWKH6KHOO 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 :KDW\RXoYHMXVWGRQHLVLPSRUWWKH+HOORIXQFWLRQ
the user’s name for example. Edit your script to read: IURPWKHVDYHG+HOORS\SURJUDPDQGWKHQXVHGLW
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):
7KLVZLOOQRZDFFHSWWKHYDULDEOHQDPHRWKHUZLVHLWZLOOSULQW+HOOR
result = a + b
David. In the Shell, enter: name=(“Bob”), then, Hello(name). Your
return result
function can now pass variables through it.
www.SFOpublications.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:
SULQW ZRUG´LVDIRXUOHWWHUZRUG:HOOGRQHµ
The double equal sign (==) check if something is equal to
something else.
STEP 2 Now we can create a new variable, then use the len STEP 4 The colon at the end of if tells Python that if this
function and pass the word variable through it to statement is true, do everything after the colon
get the total number of letters the user has just entered: that’s indented. Next, move the cursor back to the beginning of
the Editor:
word=input(“Please enter a four-letter word: “)
word_length=len(word) word=input(“Please enter a four-letter word: “)
word_length=len(word)
if word_length == 4:
SULQW ZRUG´LVDIRXUOHWWHUZRUG:HOO
done.”)
else:
print (word, “is not a four-letter word.”)
56 www.SFOpublications.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: “)
ƬYHOHWWHUZRUG7KH6KHOOZLOOGLVSOD\WKDWLWoVQRWDIRXUOHWWHUZRUG
word_length=len(word)
if word_length == 4:
SULQW ZRUG´LVDIRXUOHWWHUZRUG:HOO
done.”)
elif word_length == 3:
print (word, “is a three-letter word. Try again.”)
else:
print (word, “is not a four-letter word.”)
LOOPS
$OWKRXJKDORRSORRNVTXLWHVLPLODUWRDFRQGLWLRQWKH\DUHVRPHZKDWGLƪHUHQWLQWKHLURSHUDWLRQ$ORRSZLOOUXQWKURXJKWKH
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 7KHGLƪHUHQFHEHWZHHQif 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
FUHDWHVDOLVWEHWZHHQWKHƬUVWDQGODVWQXPEHUVXVHG
www.SFOpublications.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 WRLWLQVWDOOLQJFRPSRQHQWVDWGLƪHUHQWORFDWLRQV
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.SFOpublications.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
SUREOHPV<RXoOOƬQGWKDWPRVWFRGHGRZQORDGHGRUFRSLHGIURP
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 ZKLFKZLOOLPSRUWHYHU\WKLQJGHƬQHGZLWKLQWKHQDPHGPRGXOH
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.SFOpublications.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
(UURUVLQFRGHDUHFDOOHGEXJVWKH\oUHSHUIHFWO\QRUPDODQGFDQRIWHQEHHDVLO\UHFWLƬHGZLWKDOLWWOHSDWLHQFH7KHLPSRUWWKLQJ
is to keep looking, experimenting, and testing. Eventually your code will be bug free.
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.SFOpublications.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.SFOpublications.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 7KHSUHYLRXVVWHSGHƬQHVWKHUXOHVWKDWPDNHXS
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
FDQƬQGPRUHLQIRUPDWLRQDERXWLWDWen.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.SFOpublications.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 ZKLFKZLOORXWSXWWH[WLQGLƪHUHQWFRORXUV DORQJ
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,
DQGSUHVHQWWKHLQIRUPDWLRQLQDGLƪHUHQW
colour. For this, drop into the command line
and import the colorama module (RPi users
already have it installed):
pip install colorama
www.SFOpublications.com 63
Index
64 www.SFOpublications.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.SFOpublications.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 2QFH\RXoYHGHƬQHG\RXUOLVW\RXFDQFDOOHDFKE\ 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
VWDUWWKHƬUVWLWHPHQWU\DVIROORZHGE\DQGVRRQ 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
ZRXOGQXPEHUV>@WRUHWXUQDQG
numbers[3]
To call the item third from zero in the list (21 in this case).
66 www.SFOpublications.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
www.SFOpublications.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
SHUIHFWIRUVWRULQJƬ[HGGDWDLWHPV
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.SFOpublications.com
Tuples
STEP 5 It’s worth noting that when referencing multiple STEP 8 Now unpack the tuple into two c
WXSOHVZLWKLQDOLVWWKHLQGH[LQJLVVOLJKWO\GLƪHUHQW 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.
www.SFOpublications.com 69
Manipulating Data
Dictionaries
Lists are extremely useful, but dictionaries in Python are by far the more technical way
RIGHDOLQJZLWKGDWDLWHPV$OWKRXJKWKH\FDQEHWULFN\WRJHWWRJULSVZLWKDWƬUVW
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 7KHEHQHƬWRIXVLQJDGLFWLRQDU\LVWKDW\RX
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.SFOpublications.com
Dictionaries
STEP 5 Adding to a dictionary is easy too. You can include STEP 8 1H[WZHQHHGWRGHƬQHWKHXVHULQSXWVDQG
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.SFOpublications.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.SFOpublications.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.SFOpublications.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 7KHUHDUHPDQ\GLƪHUHQWZD\VWRDSSO\VWULQJ
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 \RXKHUHDQGRWKHUVFDQEHVLJQLƬFDQWO\PRUHFRPSOH[,WDOO
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.htmO+HUH\RXZLOOƬQGWRQVRIKHOS
print(“{} hailed from the North, in a cold land
known as {}”.format(name, place))
74 www.SFOpublications.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 GLVSOD\WKHƬUVWOHWWHULQDSHUVRQoVHQWHUHGQDPH
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.SFOpublications.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
WKDWoVEXLOWLQWR3\WKRQVR\RXVKRXOGQoWQHHGWR 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.SFOpublications.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)WRGLVSOD\WKHFXUUHQW3\WKRQYHUVLRQKHOSƬOH
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.SFOpublications.com 77
Manipulating Data
Opening Files
,Q3\WKRQ\RXFDQUHDGWH[WDQGELQDU\ƬOHVLQ\RXUSURJUDPV7KLVHQDEOHV\RXWR
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 VRPHLQIRUPDWLRQUHJDUGLQJWKHWH[WƬOH\RXoYHMXVW
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, FRQWHQWVRIWKHƬOH
E\5REHUW(+RZDUGDQGZHoYHVDYHGWKHƬOHDVpoem.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()IXQFWLRQWRSDVVWKHƬOHLQWRD STEP 4 If you enter poem.read() a second time, you will
YDULDEOHDVDQREMHFW<RXFDQQDPHWKHƬOHREMHFW notice that the text has been removed from the
anything you like, but you will need to tell Python the name and ƬOH<RXZLOOQHHGWRHQWHUpoem=open(“C:\\Users\\david\\
ORFDWLRQRIWKHWH[WƬOH\RXoUHRSHQLQJ Documents\\poem.txt”)DJDLQWRUHFUHDWHWKHƬOH7KLVWLPH
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.SFOpublications.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()
'LVSOD\VWKHƬUVWƬYHFKDUDFWHUVZKLOHHQWHULQJ
lines[0]
poem.read(5) lines[1]
lines[2]
:LOOGLVSOD\WKHQH[WƬYH(QWHULQJ ZLOOGLVSOD\RQHFKDUDFWHUDW
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)
:LOOGLVSOD\WKHƬUVWOLQHRIWKHWH[W$QG 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.SFOpublications.com 79
Manipulating Data
Writing to Files
%HLQJDEOHWRUHDGH[WHUQDOƬOHVZLWKLQ3\WKRQLVFHUWDLQO\KDQG\EXWZULWLQJWRDƬOH
can be even more useful. Using the write() function, you’re able to output the results
RIDSURJUDPWRDƬOHZKLFK\RXFDQWKHQXVHWRUHDG EDFNLQWR3\WKRQRUDVDWH[W
ƬOHIRUSHUXVDOODWHU
STEP 1 Start by opening IDLE and enter the following STEP 3 +RZHYHUWKHDFWXDOWH[WƬOHLVVWLOOEODQN \RXFDQ
(obviously entering your own username location): check by opening it up). This is because you’ve
ZULWWHQWKHOLQHRIWH[WWRWKHƬOHREMHFWEXWQRWFRPPLWWHGLWWRWKH
t=open(“C:\\Users\\david\\Documents\\text.txt”, “w”)
ƬOHLWVHOI3DUWRIWKHZULWH IXQFWLRQLVWKDWZHQHHGWRFRPPLWWKH
7KLVFRGHZLOOFUHDWHDWH[WƬOHFDOOHGWH[WW[WLQZULWHPRGHXVLQJ FKDQJHVWRWKHƬOHZHFDQGRWKLVE\HQWHULQJ
WKHYDULDEOHnWo,IWKHUHoVQRƬOHRIWKDWQDPHLQWKHORFDWLRQLWZLOO
t.close()
create one. If one already exits, it will overwrite it – so be careful.
80 www.SFOpublications.com
Writing to Files
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:
GRQHƬQLVKWKHFRGHZLWKWFORVH DQGRSHQWKHƬOHLQDWH[W
pi=math.pi
editor to see the results:
:HDOVRQHHGWRFUHDWHDQHZƬOHWRZULWH3LWR
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”)
5HPHPEHUWRFKDQJH\RXUƬOHORFDWLRQWR\RXURZQSDUWLFXODU
t.close()
system setup.
www.SFOpublications.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
5DWKHUWKDQVWRSWKHƮRZRI\RXUFRGH3\WKRQLQFOXGHVH[FHSWLRQREMHFWVZKLFKKDQGOHXQH[SHFWHGHUURUVLQWKHFRGH:H
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.SFOpublications.com
Exceptions
STEP 5 For example, using the divide by zero error, we can STEP 8 1DWXUDOO\ZHFDQTXLFNO\Ƭ[WKHLVVXHE\FKDQJLQJ
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: DV\RXDOUHDG\NQRZZLOOFUHDWHWKHƬOHDQGZULWHWKHFRQWHQWWKHQ
FRPPLWWKHFKDQJHVWRWKHƬOH7KHHQGUHVXOWZLOOUHSRUWDGLƪHUHQW
try:
set of circumstances, in this case, a successful execution of the code.
D LQW LQSXW ´(QWHUWKHÀUVWQXPEHU´
b=int(input(“Enter the second number: “))
print(a/b)
except ZeroDivisionError:
print(“You have tried to divide by zero!”)
else:
print(“You didn’t divide by zero. Well done!”)
STEP 7 2EYLRXVO\WKLVZRQoWZRUNGXHWRWKHƬOHWH[WƬOHW[W
being opened as read only (the “r” part). So in this
case, rather than Python telling us we’re doing something wrong
we’ve created an exception, using the IOError class, informing the
user that the permissions are incorrect.
www.SFOpublications.com 83
Manipulating Data
Python Graphics
:KLOHGHDOLQJZLWKWH[WRQWKHVFUHHQHLWKHUDVDJDPHRULQDSURJUDPLVSHUIHFWO\ƬQH
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
VRPHVSHFWDFXODUHƪHFWV
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,
SDSHURQWKHƮRRU7KH7XUWOHPRGXOHFDQEHLPSRUWHGZLWK 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.SFOpublications.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 WXUWOHEHJLQBƬOO , and turtle.end_
h = 450
ƬOO WRƬOOLQWKHVTXDUHZLWKWKHFKRVHQFRORXUVLQWKLVFDVHUHG
screen = pygame.display.
RXWOLQHDQG\HOORZƬOO
set_mode((w, h))
VFUHHQÀOO ZKLWH
VFUHHQÀOO ZKLWH
screen.blit(img,(0,0))
S\JDPHGLVSOD\ÁLS
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
STEP 6 As you can see, the Turtle module can draw out STEP 9 In the previous step we’ve imported pygame,
some pretty good shapes, and become a little more initiated the pygame engine, and asked it to import
complex, as you begin to master the way it works. Enter this example: our saved Raspberry Pi logo image, saved as RPi.png. Next, we
GHƬQHGWKHEDFNJURXQGFRORXURIWKHZLQGRZWRGLVSOD\WKHLPDJH
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()
,WoVDGLƪHUHQWPHWKRG
EXWYHU\HƪHFWLYH
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
QRZOHWoVORRNDWGLVSOD\LQJDSUHGHƬQHGLPDJH6WDUWE\RSHQLQJD up the many functions within the Pygame module too.
EURZVHUDQGƬQGLQJDQLPDJHWKHQVDYHLWWRWKHIROGHUZKHUH\RX
save your Python code.
www.SFOpublications.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
GHƬQHGIXQFWLRQVROG8VHUDQGQHZ8VHUZKLFKZHoOOJHWWRQH[W
import time
users = {}
status = “”
86 www.SFOpublications.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
VSHFLI\\RXURZQORFDWLRQIRUWKHORJLQVW[WƬOH 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
ƬOHEHLQJFUHDWHGWRVWRUHWKHORJLQGDWDDQGVXFFHVVIXOORJLQVEHLQJ
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.SFOpublications.com 87
Index
88 www.SFOpublications.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.SFOpublications.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
OHDS\HDUVEHWZHHQWZRVSHFLƬF\HDUV
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
PRQWK\RXZDQWDELUWKGD\IRUH[DPSOH 7KHƬUVWOLQH
print(“>>>>>>>>>>Leap Year Calculator<<<<<<<<<<\n”)
FRQƬJXUHV7H[W&DOHQGDUWRVWDUWLWVZHHNVRQD6XQGD\\RXFDQRSW
\ LQW LQSXW ´(QWHUWKHÀUVW\HDU´
for Monday if you prefer.
\ LQW LQSXW ´(QWHUWKHVHFRQG\HDU´
leaps=calendar.leapdays(y1, y2)
print(“Number of leap years between”, y1, “and”,
\´LVµOHDSV
90 www.SFOpublications.com
Calendar Module
STEP 5 You can also create a program that will display all STEP 8 You’re also able to print the individual months or
the days, weeks, and months within a given year: days of the week:
import calendar import calendar
\HDU LQW LQSXW ´(QWHUWKH\HDUWRGLVSOD\´ IRUQDPHLQFDOHQGDUPRQWKBQDPH
print(calendar.prcal(year)) print(name)
We’re sure you’ll agree that’s quite a handy bit of code to have import calendar
to hand. IRUQDPHLQFDOHQGDUGD\BQDPH
print(name)
STEP 6 Interestingly we can also list the number of days in a STEP 9 The Calendar module also allows us to write the
month by using a simple for loop: functions in HTML, so that you can display it on a
ZHEVLWH/HWoVVWDUWE\FUHDWLQJDQHZƬOH
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()
7KLVFRGHZLOOFUHDWHDQ+70/ƬOHFDOOHGFDORSHQLWZLWKDEURZVHU
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
ZHESDJH5HPHPEHUWRFKDQJH\RXUƬOHGHVWLQDWLRQ
www.SFOpublications.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 7KH:LQGRZVRXWSXWLVGLƪHUHQWDVWKDWoVWKH
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/piLWZLOOEHGLƪHUHQWGHSHQGLQJRQ 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.SFOpublications.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:
QHHGWRNQRZWKHIXOOSDWKDQGSURJUDPƬOHQDPHIRULWWRZRUN
import os
successfully. However, you can also use the following:
RVPNGLU ´&??%'0??1(:µ
import os
7KLVFUHDWHVDQHZGLUHFWRU\ZLWKLQWKHVSHFLƬHG'LUHFWRU\ &?%'0?
RVV\VWHP ¶¶VWDUWFKURPH´KWWSVZZZ\RXWXEHFRP
QDPHGDFFRUGLQJWRWKHREMHFWLQWKHPNGLUIXQFWLRQ &?%'0?1(:
IHHGPXVLFµ·
www.SFOpublications.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 7KH0DWKPRGXOHLVEXLOWLQWR3\WKRQVRWKHUHoV 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 PRGXOH\RXFDQVSHFLƬFDOO\LPSRUWWKHP)RULQVWDQFHWKHƮRRUDQG
import mathLQWRWKH6KHOORUDVSDUWRI\RXUFRGHLQWKH(GLWRU FHLOIXQFWLRQVURXQGDƮRDWGRZQRUXS
IURPPDWKLPSRUWÁRRUFHLO
ÁRRU UHWXUQV
FHLO UHWXUQV
STEP 2 Importing the Math module, as such, will give you STEP 4 The Math module can also be renamed as you
access to the module’s code. From there, you can LPSRUWLWDVZLWKWKHRWKHUPRGXOHVRQRƪHUZLWKLQ
call up any of the available functions within Math, by using math, Python. This often saves time, but don’t forget to make a comment
followed by the name of the function in question. For example, enter: to show someone else looking at your code what you’ve done:
math.sin(2) import math as m
PWUXQF 7UXQFDWHUHPRYHVWKHIUDFWLRQ
This will display the sine of 2.
94 www.SFOpublications.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 ƮRRU from Math and renaming it to precise values:
f. This process can quickly become confusing though, where lengthy
from math import exp, expm1
code is in use:
H[S H ²YDOXHDFFXUDWHWRSODFHV
IURPPDWKLPSRUWÁRRUDVI H[SP H UHVXOWDFFXUDWHWRIXOOSUHFLVLRQ
f(1.2)
STEP 6 Importing all the functions of the Math module can STEP 9 This level of accuracy is really quite impressive, but
be achieved by entering: quite niche for the most part. Probably the two
most used functions are e and Pi, where e is the numerical constant
from math import *
equal to 2.71828 (where the circumference of a circle is divided by
While certainly handy, this is often frowned upon by the developer its diameter):
community as it takes up unnecessary resources and isn’t an
import math
HƯFLHQWZD\RIFRGLQJ+RZHYHULILWZRUNVIRU\RXWKHQJRDKHDG
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: HYHU\WKLQJIURPIDFWRUVWRLQƬQLW\SRZHUVWRWULJRQRPHWU\DQG
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.SFOpublications.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
LWLWZLOOVXƯFHIRUPRVWQHHGV
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 UDQGRPDQGWKHOLVWFDQFRQWDLQDQ\WKLQJ
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.SFOpublications.com
Random Module
STEP 6 Interestingly, we can also use a function within the STEP 9 /HWoVXVHDQH[DPSOHSLHFHRIFRGHZKLFKƮLSVD
5DQGRPPRGXOHWRVKXưHWKHLWHPVLQWKHOLVWWKXV virtual coin ten thousand times and counts how
adding a little more randomness into the equation: many times it’ll land on Heads or Tails:
UDQGRPVKXIÁH OVW import random
print(lst) RXWSXW ^´+HDGVµ´7DLOVµ`
FRLQ OLVW RXWSXWNH\V
7KLVZD\\RXFDQNHHSVKXưLQJWKHOLVWEHIRUHGLVSOD\LQJDUDQGRP
item from it. IRULLQUDQJH
RXWSXW>UDQGRPFKRLFH FRLQ @
SULQW ´+HDGVµRXWSXW>´+HDGVµ@
SULQW ´7DLOVµRXWSXW>´7DLOVµ@
STEP 7 8VLQJVKXưHZHFDQFUHDWHDQHQWLUHO\UDQGRPOLVW
of numbers, for example, within a given range:
import random
lst=[[i] for I in range(20)]
UDQGRPVKXIÁH OVW STEP 10 Here’s an interesting piece of code. Using a text
print(lst) ƬOHFRQWDLQLQJWKRXVDQGZRUGVZHFDQSOXFN
DXVHUJHQHUDWHGQXPEHURIZRUGVIURPWKHƬOH WH[WƬOHIRXQGDW
.HHSVKXưLQJWKHOLVWDQG\RXoOOKDYHDGLƪHUHQWVHOHFWLRQRILWHPV
https://github.com/dwyl/english-words):
from 0 to 20 every time.
import random
SULQW ´!!!!!!!!!!5DQGRP:RUG)LQGHUµ
SULQW ´?Q8VLQJD.(QJOLVKZRUGWH[WÀOH,FDQ
SLFNDQ\ZRUGVDWUDQGRP?Qµ
wds=int(input(“\nHow many words shall I choose? “))
ZLWKRSHQ ´KRPHSL'RZQORDGVZRUGVW[Wµ´UWµ DVI
words = f.readlines()
words = [w.rstrip() for w in words]
print(“--------------------”)
IRUZLQUDQGRPVDPSOH ZRUGVZGV
STEP 8 We can also select a random number from a given
print(w)
range in steps, using the start, stop, step loop:
print(“--------------------”)
import random
IRULLQUDQJH
print(random.randrange(0, 200, 7))
Result will vary, but you get the general idea as to how it works.
www.SFOpublications.com 97
Working with Modules
Tkinter Module
:KLOHUXQQLQJ\RXUFRGHIURPWKHFRPPDQGOLQHRUHYHQLQWKH6KHOOLVSHUIHFWO\ƬQH
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
:HFDQVWDUWWRLPSRUWPRGXOHVGLƪHUHQWO\WKDQEHIRUHWRVDYHRQ several more we can play around with:
typing, by importing all their contents:
EWQ %XWWRQ
LPSRUWWNLQWHUDVWN EWQSDFN
IURPWNLQWHULPSRUW EWQ>´WH[Wµ@ µ+HOORHYHU\RQHµ
7KHƬUVWOLQHIRFXVHVRQWKHQHZO\FUHDWHGZLQGRZ&OLFNEDFNLQWR
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.SFOpublications.com
Tkinter Module
STEP 5 Save and execute the code from Step 5, and a STEP 8 We can create radio buttons too. Try:
window will appear with ‘Hello everyone!’ inside.
IURPWNLQWHULPSRUW
If you click the Hello everyone! button, the Shell will output the
text ‘You just clicked me!’. It’s simple, but shows you what can be URRW 7N
achieved with a few lines of code.
Y ,QW9DU
Label(root, root.title(“Options”), text=”””Choose
DSUHIHUUHGODQJXDJHµµµ
MXVWLI\ /()7SDG[ SDFN
Radiobutton(root,
WH[W µ3\WKRQµ
padx = 20,
YDULDEOH Y
YDOXH SDFN DQFKRU :
Radiobutton(root,
WH[W µ&µ
padx = 20,
YDULDEOH Y
STEP 6 We can also display both text and images within a YDOXH SDFN DQFKRU :
Tkinter window. However, only GIF, PGM, or PPM
mainloop()
IRUPDWVDUHVXSSRUWHG6RƬQGDQLPDJHDQGFRQYHUWLWEHIRUHXVLQJ
the code. Here’s an example using the Raspberry Pi logo:
STEP 9 And we can create check boxes, with buttons, and
IURPWNLQWHULPSRUW
output to the Shell:
URRW 7N
IURPWNLQWHULPSRUW
ORJR 3KRWR,PDJH ÀOH µ&??8VHUV??GDYLG??'RZQORDGV??
URRW 7N
3L/RJRJLIµ
Z /DEHO URRWURRWWLWOH ´5DVSEHUU\3Lµ GHIYDUBVWDWHV
LPDJH ORJR SDFN VLGH µULJKWµ SULQW ´:DUULRUG?Q0DJHGµ YDUJHW
FRQWHQW ´µµ7KH5DVSEHUU\3L)RXQGDWLRQLVD YDUJHW
8.EDVHGFKDULW\WKDWZRUNVWRSXWWKHSRZHURI
/DEHO URRWURRWWLWOH ´$GYHQWXUH*DPHµ
FRPSXWLQJDQGGLJLWDOPDNLQJLQWRWKHKDQGVRI
WH[W µ!!!!!!!!!!<RXUDGYHQWXUHUROHµ
SHRSOHDOORYHUWKHZRUOG:HGRWKLVVRWKDWPRUH
JULG URZ VWLFN\ 1
people are able to harness the power of computing
YDU ,QW9DU
DQGGLJLWDOWHFKQRORJLHVIRUZRUNWRVROYH
&KHFNEXWWRQ URRWWH[W µ:DUULRUµYDULDEOH YDU
problems that matter to them, and to express
JULG URZ VWLFN\ :
WKHPVHOYHVFUHDWLYHO\´µµ
YDU ,QW9DU
w2 = Label(root,
&KHFNEXWWRQ URRWWH[W µ0DJHµYDULDEOH YDU
MXVWLI\ /()7
JULG URZ VWLFN\ :
padx = 10,
%XWWRQ URRWWH[W ·4XLW·FRPPDQG URRWGHVWUR\
WH[W FRQWHQW SDFN VLGH µOHIWµ
JULG URZ VWLFN\ :SDG\
root.mainloop()
%XWWRQ URRWWH[W ·6KRZ·FRPPDQG YDUBVWDWHV
JULG URZ VWLFN\ (SDG\
STEP 7 The previous code is quite weighty, mostly due to
mainloop()
the content variable holding a part of Raspberry Pi’s
About page, from the company website. You can obviously change
the content, the root.title, and the image to suit your needs. STEP 10 The code from Step 9 introduced some new
geometry elements into Tkinter. Note the
VWLFN\ 1(DQG:DUJXPHQWV"7KHVHGHVFULEHWKHORFDWLRQVRIWKH
FKHFNER[HVDQGEXWWRQV 1RUWK(DVW6RXWKDQG:HVW 7KHURZ
argument places them on separate rows. Have a play around and
see what you get.
www.SFOpublications.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. ZLQGRZZLWKRXWFORVLQJWKH3\WKRQ,'/(6KHOO
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.SFOpublications.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ÀOO ZKLWH
ZKLOHUXQQLQJ sprite(x,y)
pygame.display.update()
gamewindow=pygame.display.set_mode((800,600))
S\JDPHGLVSOD\VHWBFDSWLRQ ´$GYHQWXUH*DPHµ IRUHYHQWLQS\JDPHHYHQWJHW
EODFN LIHYHQWW\SH S\JDPH48,7
white=(255,255,255) UXQQLQJ )DOVH
STEP 6 Let’s quickly go through the code changes. We’ve downloaded image called sprite.png, and allocated it to the variable
GHƬQHGWZRFRORXUVEODFNDQGZKLWHWRJHWKHU LPJ:HoYHDOVRGHƬQHGDVSULWHIXQFWLRQDQGWKH%OLWIXQFWLRQ
with their respective RGB colour values. Next, we’ve loaded the which will allow us to eventually move the image.
www.SFOpublications.com 101
Working with Modules
STEP 7 Now we can change the code around again, this imgspeed=0
time containing a movement option within the
ZKLOHUXQQLQJ
while loop, and adding the variables needed to move the sprite
IRUHYHQWLQS\JDPHHYHQWJHW
around the screen:
LIHYHQWW\SH 48,7
import pygame UXQQLQJ )DOVH
from pygame.locals import *
LIHYHQWW\SH S\JDPH.(<'2:1
pygame.init()
LIHYHQWNH\ S\JDPH.B/()7
running=True xchange=-5
HOLIHYHQWNH\ S\JDPH.B5,*+7
gamewindow=pygame.display.set_mode((800,600))
xchange=5
S\JDPHGLVSOD\VHWBFDSWLRQ ´$GYHQWXUH*DPHµ
LIHYHQWW\SH S\JDPH.(<83
EODFN
LIHYHQWNH\ S\JDPH.B/()7RUHYHQW
white=(255,255,255)
NH\ S\JDPH.B5,*+7
LPJ S\JDPHLPDJHORDG ´&??8VHUV??GDYLG??
xchange=0
Downloads\\sprite.png”)
[ [FKDQJH
GHIVSULWH [\
gamewindow.blit(img, (x,y)) JDPHZLQGRZÀOO ZKLWH
sprite(x,y)
x=(800*0.45)
pygame.display.update()
y=(600*0.8)
pygame.quit()
xchange=0
STEP 8 Copy the code down and, using the left and right arrow keys on the keyboard, you will be able to move your sprite across
the bottom of the screen. It looks like we have the makings of a classic arcade 2D scroller in the works.
102 www.SFOpublications.com
Pygame Module
www.SFOpublications.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
FRGH7KHUHDUHVRPDQ\GLƪHUHQWZD\VRIDFKLHYLQJWKHVDPHHQGUHVXOW+HUHoVRQH
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 &DQYDV JXLZLGWK KHLJKW EJ ·ZKLWH·
FDQYDVSDFN
EDOO FDQYDVFUHDWHBRYDO ÀOO ·UHG·
gui.mainloop()
104 www.SFOpublications.com
Basic Animation
STEP 5 Let’s see if we can animate the ball so that it bounces STEP 9 Now add the following:
around the window until you close the program.
GHIPDLQ
xa = 5
pygame.init()
ya = 10
screen = pygame.display.set_mode((640,480))
ZKLOH7UXH S\JDPHGLVSOD\VHWBFDSWLRQ ´6WDUÀHOG
FDQYDVPRYH EDOO[D\D Simulation”)
SRV FDQYDVFRRUGV EDOO FORFN S\JDPHWLPH&ORFN
LISRV>@! RUSRV>@
init_stars(screen)
ya = -ya
LISRV>@! RUSRV>@ ZKLOH7UXH
xa = -xa /RFNWKHIUDPHUDWHDW)36
gui.update() FORFNWLFN
time.sleep(.025)
+DQGOHHYHQWV
IRUHYHQWLQS\JDPHHYHQWJHW
STEP 6 Remove the code you entered in Step 2, and insert LIHYHQWW\SH S\JDPH48,7
WKHFRGHIURP6WHSLQLWVSODFHDJDLQEHWZHHQWKH return
EDOO FDQYDVFUHDWHBRYDO ÀOO ·UHG· ,
VFUHHQÀOO
and the gui.mainloop() lines. Save the code, and Run it as normal.
PRYHBDQGBGUDZBVWDUV VFUHHQ
If you’ve entered the code correctly, you will see the red ball bounce
S\JDPHGLVSOD\ÁLS
RƪWKHHGJHVRIWKHZLQGRZXQWLO\RXFORVHWKHSURJUDP
LIBBQDPHBB ´BBPDLQBBµ
main()
STEP 7 The bouncing animation
takes place within the While
True loop. First, we have the values of xa
and xy before the loop, both of 5 and 10.
The SRV FDQYDVFRRUGV EDOO line
takes the value of the ball’s location in the
window. When it reaches the limits of the
window, 800, or 600, it will make the values
QHJDWLYHPRYLQJWKHEDOODURXQGWKHVFUHHQ
www.SFOpublications.com 105
Working with Modules
BUILDING MODULES
0RGXOHVDUH3\WKRQƬOHVFRQWDLQLQJFRGHWKDW\RXVDYHXVLQJDS\H[WHQVLRQ7KHVHDUHWKHQLPSRUWHGLQWR3\WKRQXVLQJWKH
now familiar import command.
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
QRWGHƬQHGo will be displayed. This is due to the code no longer
print (timestwo(2))
KDYLQJDFFHVVWRWKHIXQFWLRQGHƬQLWLRQV
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
WKHIXQFWLRQGHƬQLWLRQVDQG
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.SFOpublications.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
XWLOLVHWKHQHZO\FUHDWHGIXQFWLRQGHƬQLWLRQV
from minimath import *
LIFKRLFH ¶·
7KLVZLOOLPSRUWWKHIXQFWLRQGHƬQLWLRQVDVDPRGXOH3UHVVF5 to
print(timestwo(num1))
save and execute the program, and see it in action.
HOLIFKRLFH ¶·
print(timesthree(num1))
HOLIFKRLFH ¶·
print(square(num1))
HOLIFKRLFH ¶·
QXP LQW LQSXW ´(QWHUVHFRQGQXPEHU´
print(power(num1, num2))
HOVH
SULQW ´,QYDOLGLQSXWµ
STEP 8 Now we can add the user input to get the number
the code will work on:
QXP LQW LQSXW ´?Q(QWHUQXPEHU´
This will save the user-entered number as the variable num1.
STEP 10 Note that for the last available options, the Power
of choice, we’ve added a second variable: num2.
7KLVSDVVHVDVHFRQGQXPEHUWKURXJKWKHIXQFWLRQGHƬQLWLRQFDOOHG
power. Save and execute the program to see it in action.
www.SFOpublications.com 107
Index
108 www.SFOpublications.com
Learning Linux
/LQX[LVDƮH[LEOHDQGSRZHUIXO
RSHUDWLQJV\VWHPEXWLWDOVRKDVDXQLTXH
ƬOHV\VWHPDQGZD\RIGRLQJWKLQJV
7KHUHIRUHOHDUQLQJKRZ/LQX[ZRUNVLV
HVVHQWLDOWRFUHDWLQJEHWWHU3\WKRQFRGH
<RXoOOƬQGWKDW/LQX[DOUHDG\KDV3\WKRQ
HOHPHQWVEXLOWLQDQGLI\RXoUHZRUNLQJ
RQD5DVSEHUU\3LWKHQHYHU\WKLQJ\RX
QHHGWRFRGHZLWK3\WKRQLVUHDG\IURP
WKHVWDUW,QWKLVVHFWLRQZHZLOOPDLQO\
IRFXVRQXVLQJWKH5DVSEHUU\KDUGZDUH
ZLWK/LQX[EXWUHJDUGOHVVRIZKHWKHU
\RXoUHXVLQJDQ53L/LQX[0LQWRU
8EXQWXWKHVHSDJHVZLOOSURYH
LQYDOXDEOHIRU\RXU3\WKRQOHDUQLQJ
www.SFOpublications.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.
/LQX[LVDVXUSULVLQJO\SRZHUIXOIDVWVHFXUHDQGFDSDEOHRSHUDWLQJV\VWHP,WoVXVHGDVWKH26RIFKRLFHIRUWKH5DVSEHUU\3L
LQWKHIRUPRI5DVSELDQ26DVZHOODVLQVRPHRIWKHPRVWXQOLNHO\SODFHV
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 XSLQWRDQXPEHURIVLJQLƬFDQWHOHPHQWV
high-end computing tasks were needed.
%227/2$'(5 *5$3+,&$/6(59(5
The bootloader is the software that initialises and boots up This is a module within Linux that provides a graphical output
your computer. It loads up the various modules the OS uses to to your monitor. It’s referred to as the X server, or simply X. X
begin to access the hardware in the system. You can modify a is an application that manages one or more graphical displays,
bootloader to load more than one OS installed on the system. and one or more input devices (keyboard, mouse, etc.)
connected to the computer.
'$(0216
.(51(/
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.
'(6.723(19,5210(17$/
352*5$06ǖ$33/,&$7,216
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 RIIUHHO\DYDLODEOHDSSOLFDWLRQVWRR7KHOLNHVRI/LEUH2ƯFH
DEs available, Raspbian uses PIXEL. GIMP, and Python are just the tip of the iceberg.
110 www.SFOpublications.com
What is Linux?
6+(//
The Linux shell is a command-line interface environment that a
Linux user can use to enter commands to the OS that directly
DƪHFWLW:LWKLQWKHVKHOO\RXFDQDGGQHZXVHUVUHERRWWKH
V\VWHPFUHDWHDQGGHOHWHƬOHVDQGIROGHUVDQGPXFKPRUH
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
/LQXV7RUYDOGVWKHFUHDWRURIWKH
section of the book.
/LQX[NHUQHO
$'HVNWRS(QYLURQPHQWFDQ
EHDVFRPSOH[RUDVVLPSOHDV
WKHXVHUGHVLUHV
www.SFOpublications.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.
)5(($1'23(1
/LQX[LVDIDQWDVWLFƬWIRUWKRVHZKRZDQWVRPHWKLQJGLƪHUHQW7KHHƯFLHQF\RIWKHV\VWHPWKHDYDLODELOLW\RIDSSOLFDWLRQVDQG
LWVVWDELOLW\DUHMXVWDIHZUHDVRQVZK\LWoVDJUHDW3\WKRQFRGLQJUHVRXUFH
7KHƬUVWWKLQJZHQHHGWRDGGUHVVLVWKDWWKHUHLVQRVXFKRSHUDWLQJ /LQX[ZRUNVFRQVLGHUDEO\GLƪHUHQWO\WR:LQGRZVRUPDF26,WoVIUHHIRU
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
WKHFXUUHQWSRSXODUGLVWURV8EXQWX/LQX[0LQW)HGRUDRSHQ686( Windows license can cost up to £100, and a Mac considerably more,
'HELDQ5DVSELDQfWKHOLVWJRHVRQ(DFKRQHRIWKHVHGLVWURVRƪHUV a user, be they a developer, gamer, or someone who wants to put an
WKHXVHUVRPHWKLQJDOLWWOHGLƪHUHQW:KLOHHDFKKDVWKH/LQX[NHUQHODW older computer to use, can quickly download a distro and get to work in
LWVFRUHWKH\SURYLGHGLƪHUHQWORRNLQJGHVNWRSHQYLURQPHQWVGLƪHUHQW a matter of minutes.
SUHORDGHGDSSOLFDWLRQVGLƪHUHQWZD\VLQZKLFKWRXSGDWHWKHV\VWHP
DQGJHWPRUHDSSVLQVWDOOHGDQGDVOLJKWO\GLƪHUHQWORRNDQGIHHO 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. DYDLODEOHRQWKH,QWHUQHWKDYHDFHUWDLQnVSLQoLQWKDWVRPHRƪHU
/LQX[LVDJUHDWRSHUDWLQJV\VWHPLQ
ZKLFKWRVWDUWFRGLQJ
112 www.SFOpublications.com
Why Linux?
LQFUHDVHGVHFXULW\DIDQF\ORRNLQJGHVNWRSDJDPLQJVSHFLƬFVSLQRU
something directed toward students. This extensibility makes Linux a
more desirable platform to use, as you can quickly mould the system
LQWRDGHYHORSPHQWEDVHLQFOXGLQJPDQ\GLƪHUHQWNLQGVRI,'(VIRUWKH
likes of Python, web development, C++, Java and so on; or even a base
for online anonymity, perhaps as a Minecraft server, media centre and
much more.
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,
WKHUHDUH DWWKHWLPHRIZULWLQJ RYHUVSHFLƬFSURJUDPPLQJ
applications just on Linux Mint alone, and an incredible 62,000+ overall
packages catering from Amateur Radio to WWW tools.
$/LQX[SURJUDPPLQJHQYLURQPHQWFDQEH
DVVLPSOHRUDVFRPSOH[DV\RXQHHGLWWREH
www.SFOpublications.com 113
Learning Linux
*(77,1*$5281'
7RGURSLQWRWKH7HUPLQDOFOLFNRQWKHIRXUWKLFRQIURPWKHOHIWDORQJWKHWRSRIWKH5DVSEHUU\3LGHVNWRSWKHRQHZLWKDULJKW
IDFLQJDUURZDQGDQXQGHUVFRUH7KLVLVWKHVKHOORU7HUPLQDO
67(3 First, you’re going to look at directories and the 67(3 (QWHUls 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. FRORXUFRGHLVZRUWKNQRZLQJGLUHFWRULHVDUHEOXHZKLOHPRVWƬOHV
(QWHU clear DQGSUHVVUHWXUQWRFOHDQWKHVFUHHQ1RZHQWHU pwd. DUHZKLWH$V\RXJRRQ\RXoOOVHHRWKHUFRORXUVH[HFXWDEOHƬOHV
This stands for Print Working Directory and displays /home/pi.. SURJUDPV DUHEULJKWJUHHQDUFKLYHGƬOHVDUHUHGDQGVRRQ%OXH
and white are the two you need to know to get started.
67(3 When you log in to your Raspberry Pi, you don’t 67(3 Now you’re going to move from the pi directory into
start at the base of the hard drive, known as the WKH'RFXPHQWVGLUHFWRU\(QWHUcd 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 ‘/’ FRPPDQGVWDQGVIRUFKDQJHGLUHFWRU\1RZHQWHUpwd again to
symbol. So, “‘/home/pi’” tells you that in the root is a directory called YLHZWKHGLUHFWRU\SDWK,WZLOOGLVSOD\KRPHSL'RFXPHQWV(QWHU
home, and the next “‘/’” says that inside “home” is a directory called lsWRYLHZWKHƬOHVLQVLGHWKH'RFXPHQWVGLUHFWRU\
“pi”. That’s where you start.
www.SFOpublications.com
Using the Filesystem
67(3 How do you get back up to the pi directory? By using 67(3 The “ls” and “cd” commands can also be used with
a command “cd ..”. In Linux two dots means the PRUHFRPSOH[SDWKV(QWHUls 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.
$%62/87(965(/$7,9(3$7+6
,WLVLPSRUWDQWWRNQRZWKHGLƪHUHQFHEHWZHHQWKHZRUNLQJGLUHFWRU\URRWGLUHFWRU\DQGKRPH7KHUHDUHDOVRWZRW\SHVRI
SDWK$EVROXWHDQG5HODWLYH7KHVHDUHHDVLHUWRXQGHUVWDQGWKDQWKH\VRXQG/HWoVWDNHDORRNf
67(3 By default, commands like “ls” use the working 67(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. GLUHFWRU\LQURRWVR\RXZLOOJHWDp1RVXFKƬOHRUGLUHFWRU\q
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.
67(3 The root directory is always ‘/’. Entering: ls / 67(3 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,
GLƪHUHQFHEHWZHHQpOV'RFXPHQWV3LFWXUHVqDQGpOV'RFXPHQWV while “cd ~” moves straight to your home directory, no matter
3LFWXUHVq7KHƬUVWFRPPDQGOLVWVWKHFRQWHQWVRIWKH3LFWXUHV 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.SFOpublications.com 115
Learning Linux
/22.,1*$7),/(6
2SHUDWLQJV\VWHPVDUHEXLOWRQƬOHVDQGIROGHUVRUGLUHFWRULHVLI\RXSUHIHU:KLOH\RXoUHXVHGWRYLHZLQJ\RXURZQƬOHVPRVW
RSHUDWLQJV\VWHPVNHHSRWKHUƬOHVRXWRIVLJKW,Q5DVSELDQ\RXKDYHDFFHVVWRHYHU\ƬOHLQWKHV\VWHP
67(3 :HoYHDOUHDG\ORRNHGDWpOVqZKLFKOLVWVWKHƬOHVLQ 67(3 After the permission letters come a single number.
the working directory, but you are more likely to 7KLVLVWKHQXPEHURIƬOHVLQWKHLWHP,ILWoVDƬOH
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
LVNQRZQDVWKHDUJXPHQW7KLVLVDQRSWLRQWKDWPRGLƬHVWKH HDFKGLUHFWRU\FRQWDLQVWZRKLGGHQƬOHVRQHZLWKDVLQJOHGRW
behaviour of the command. DQGRQHZLWKWZRGRWV 'LUHFWRULHVFRQWDLQLQJƬOHVRURWKHU
directories will have a higher number.
67(3 7KHpOqDUJXPHQWOLVWVƬOHVDQGGLUHFWRULHVLQORQJ 67(3 Next you’ll see the word “pi” listed twice on each
IRUPDW(DFKƬOHDQGGLUHFWRU\LVQRZRQDVLQJOH line. This refers to the user rather than the name of
OLQHDQGEHIRUHHDFKƬOHLVDORWRIWH[W)LUVW\RXoOOVHHORWVRIOHWWHUV \RXUFRPSXWHU \RXUGHIDXOWXVHUQDPHLVpSLq 7KHƬUVWLVWKHRZQHU
and dashes, like ‘drwxr-xr-x’. Don’t worry about these for now; they RIWKHƬOHDQGWKHVHFRQGLVWKHJURXS7\SLFDOO\WKHVHZLOOERWKEH
are known as ‘permissions’ and we’ll come to those later. WKHVDPHDQG\RXoOOVHHHLWKHUnSLoRUnURRWo<RXFDQHQWHUls -l /
WRYLHZWKHƬOHVDQGGLUHFWRULHVLQWKHURRWGLUHFWRU\WKDWEHORQJWR
the root account.
www.SFOpublications.com
Listing and Moving Files
67(3 7KHQH[WQXPEHUUHODWHVWRWKHVL]HRIWKHƬOHLQ 67(3 Finally, you should be aware that there are many
E\WHV,Q/LQX[HDFKWH[WƬOHLVPDGHXSRIOHWWHUV KLGGHQƬOHVLQ/LQX[7KHVHDUHOLVWHGXVLQJWKHpDq
DQGHDFKOHWWHUWDNHVXSDE\WHVRRXUQDPHVW[WƬOHKDVE\WHV DUJXPHQW+LGGHQƬOHVDQGGLUHFWRULHVEHJLQZLWKDGRW VR\RX
DQGFKDUDFWHUVLQWKHGRFXPHQW)LOHVDQGGLUHFWRULHVFDQEH VKRXOGQHYHUVWDUWDƬOHRUGLUHFWRU\ZLWKDGRWXQOHVV\RXZDQWWR
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”.
620(&20021',5(&725,(6
1RZWKDW\RXNQRZKRZWRYLHZWKHFRQWHQWVRI\RXUKDUGGULYH\RXoOOVWDUWWRQRWLFHDORWRIGLUHFWRULHVZLWKQDPHVOLNHELQVELQ
YDUDQGGHY7KHVHDUHWKHƬOHVDQGGLUHFWRULHVWKDW\RXDUHNHSWDZD\IURPRQD0DFDQGZRQoWHQFRXQWHURQD:LQGRZV3&
67(3 Enter: ls -lah /WRYLHZDOORIWKHƬOHVDQG 67(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
ZLWKpXVUqWKHXVUGLUHFWRU\LVZKHUHƬQG\RXƬQGSURJUDPWRROV
and libraries.
67(3 Bin is a directory that stores binaries. This is the 67(3 Lib is a directory that contains libraries of code
Linux way of saying programs or applications. WKDWDUHUHIHUUHGWRE\RWKHUSURJUDPV GLƪHUHQW
Sbin is for system binaries, which are the programs that make SURJUDPVVKDUHƬOHVLQ/LE p9DUqLVVKRUWIRUYDULRXVZKLFKLV
up your system. Dev contains references to your devices: hard PRVWO\ƬOHVXVHGE\WKHV\VWHPEXW\RXPD\QHHGWRZRUNZLWK
drive, keyboard, mouse and so on. Etc contains your system items here. Finally there is a directory called “tmp”, which is for
FRQƬJXUDWLRQƬOHV WHPSRUDU\ƬOHVƬOHVSODFHGKHUHDUHRQ\RXUV\VWHPIRUWKHVKRUW
term and can be deleted from the system.
www.SFOpublications.com 117
Learning Linux
&5($7,1*),/(6
2QFH\RXOHDUQWRUHFRJQLVHWKHƬOHVDQGGLUHFWRULHVWKDWPDNHXS5DVSELDQ26LWoVWLPHWRGLVFRYHUKRZWRPDNH\RXURZQ
.QRZLQJKRZWRPDNHHGLWDQGGHOHWHƬOHVDQGGLUHFWRULHVLVHVVHQWLDOLI\RXZDQWWRPDNH\RXURZQSURMHFWV
118 www.SFOpublications.com
Creating and Deleting Files
5(029,1*),/(6
:HoYHFUHDWHGVRPHƬOHVWKDWZHGRQoWZDQWVRKRZGRZHJRDERXWUHPRYLQJWKHP",WWXUQVRXWWKDWGHOHWLQJƬOHVLQ\RXU
5DVSEHUU\3LLVUHDOO\HDV\ZKLFKPD\EHDSUREOHPVREHFDUHIXO
67(3 Enter: ls –lWRYLHZWKHƬOHVLQ\RXUKRPHGLUHFWRU\ 67(3 We’re going to use a wildcard (*) to delete our next
If you’ve followed the steps before then you should WZRƬOHVEXWDJDLQWKLVLVVRPHWKLQJ\RXUHDOO\
KDYHWKUHHƬOHVpWHVWqpWHVWƬOHqDQGp7HVWƬOHq:HoUHJRLQJWRJHWULG QHHGWRGRZLWKFDUH)LUVWXVHpOVqWROLVWWKHƬOHVDQGPDNHVXUH
of these items because they were created as an example. it’s the one you want to delete. Enter: ls test*WRYLHZƬOHVWKDW
match the word “test” and any other characters. The “*” character
is called a “wildcard” and it means any characters here.
www.SFOpublications.com 119
Learning Linux
0$1$*,1*),/(6$1'',5(&725,(6
1RZWKDW\RXNQRZKRZWRFUHDWHƬOHV\RXoOOZDQWWROHDUQKRZWRPDNHGLUHFWRULHVZKLFKDUHWKHVDPHWKLQJDVIROGHUVDV
ZHOODVPRYHLWHPVDURXQG,I\RXDUHPRUHXVHGWRZRUNLQJZLWKDGHVNWRSLQWHUIDFHWKLVFDQWDNHDELWRIJHWWLQJXVHGWR
67(3 (QWHUls to quickly view all the directories currently 67(3 Like touch, you can create multiple directories
in in the home location. Directories are created DWRQFHZLWKWKHPNGLUFRPPDQG(QWHUmkdir
XVLQJWKHpPNGLUqFRPPDQG PDNHGLUHFWRU\ (QWHUmkdir testdir2 testdir3DQGHQWHUls<RXoOOQRZƬQGVHYHUDO
testdir WRFUHDWHDQHZGLUHFWRU\LQ\RXUKRPHGLUHFWRU\(QWHU GLUHFWRULHVFDOOHGWHVWGLU$OVROLNHƬOHV\RXVKRXOGNQRZWKLVPHDQV
ls again to see it. you can’t (and really shouldn’t) create directories with spaces. As
ZLWKƬOHVXVHDQXQGHUVFRUH pBq FKDUDFWHULQVWHDGRIDVSDFH
67(3 7KHpPNGLUqFRPPDQGLVGLƪHUHQWWRWRXFKLQWKDW 67(3 You can create directories inside of each other using
it doesn’t update the timestamp if you use it with a WKHGLUHFWRU\SDWK(QWHUmkdir Documents/
GLUHFWRU\WKDWDOUHDG\H[LVWV(QWHUmkdir testdir again and you’ll photos to create a new directory called “photos” inside your
JHWWKHHUURUpPNGLUFDQQRWFUHDWHGLUHFWRU\nWHVWGLU)LOHH[LVWVq documents directory. The directory has to already exist, though,
WU\WRHQWHUmkdir articles/reports and you’ll get an error
because there is no articles directory.
120 www.SFOpublications.com
Create and Remove Directories
67(3 To create a directory path you need to pass in the 67(3 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 WKHFRPPDQGVWUXFWXUHLVDOZD\VFRPPDQGRSWLRQDQGDUJXPHQW
Dno6RHQWHUmkdir -p articles/reports(QWHUls 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 W\SLFDOO\VLQJOHOHWWHUVVWDUWLQJZLWKpq DQGƬQDOO\WKHDUJXPHQW
sitting inside. RIWHQDƬOHRUGLUHFWRU\VWUXFWXUH ,WoVDOZD\VFRPPDQGRSWLRQ
then argument.
*(77,1*5,'2)',5(&725,(6
'HOHWLQJGLUHFWRULHVLVSUHWW\HDV\LQ/LQX[DORQJZLWKƬOHVDQGWKLVFDQEHDSUREOHP,WoVWRRHDV\WRGHOHWHHQWLUHGLUHFWRULHV
FRQWDLQLQJƬOHVDQGWKHVHDUHLQVWDQWO\UHPRYHGQRWVHQWWRDWUDVKGLUHFWRU\7UHDGFDUHIXOO\
67(3 Now we’ll try to get rid of the articles directory 67(3 $VZLWKPXOWLSOHƬOHV\RXFDQGHOHWHPXOWLSOH
(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*
WKHP QRƬOHVRURWKHUGLUHFWRULHV and press Y and return to each prompt. It’s a good idea to use the
-i option whenever using the rm command.
www.SFOpublications.com 121
Learning Linux
86,1*7+(029(&200$1'
,Q/LQX[UHQDPLQJDƬOHLVVLPSO\PRYLQJLWIURPRQHQDPHWRDQRWKHUDQGFRS\LQJDƬOHLVPRYLQJLWZLWKRXWGHOHWLQJWKH
RULJLQDO'RQoWSDQLFLWoVTXLWHHDV\WRPDVWHU
67(3 Before we can move anything around, we need to 67(3 (QWHUPYWHVWÀOHWHVWGLU and press return
KDYHDIHZWHVWLWHPVLQRXUKRPHGLUHFWRU\(QWHU WRPRYHWKHWHVWƬOHGRFXPHQWLQWRWKHWHVWGLU
WRXFKWHVWÀOH and mkdir testdirWRFUHDWHDWHVWƬOHDQGWHVW GLUHFWRU\(QWHUls to see that it’s no longer in the home directory,
GLUHFWRU\LQ\RXUKRPHGLUHFWRU\(QWHUls to check that they are and ls testdirWRVHHWKHWHVWƬOHQRZVLWWLQJLQWKHWHVWGLU
both present. GLUHFWRU\1RZHQWHUmkdir newparent to create a new directory.
67(3 Files and directories are moved using the mv 67(3 'LUHFWRULHVZLWKƬOHVDUHPRYHGLQWKHVDPHZD\
FRPPDQG7KLVLVGLƪHUHQWWRWKHFRPPDQGVZHoYH (QWHUmv 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
FRPPDQGOLQHLVFRPPDQGRSWLRQDUJXPHQW 7KHƬUVWDUJXPHQW GLUHFWRU\WRƬQGWKHƬOH(QWHUcd /newparent/testdir and
LVWKHVRXUFH WKHƬOHRUGLUHFWRU\WREHPRYHG DQGWKHVHFRQGLV HQWHUlsWRYLHZWKHWHVWƬOHVLWWLQJLQVLGHWKHGLUHFWRU\
the destination.
122 www.SFOpublications.com
Copying, Moving and Renaming Files
67(3 Files and directories can be moved up using the 67(3 <RXFDQDOVRPRYHƬOHVXVLQJORQJHUSDWKV(QWHU
GRXEOHGRW pq DVDQDUJXPHQW(QWHUls –la to cd ~ to return to the home directory and
YLHZ\RXUWHVWƬOHDQGWKHVLQJOHDQGGRXEOHGRWƬOHV7KHVLQJOHGRW PYQHZSDUHQWWHVWÀOHQHZSDUHQWWHVWGLUWHVWÀOH to
is the current directory and the double dot is the parent directory. PRYHWKHWHVWƬOHIURPLWVFXUUHQWORFDWLRQEDFNLQVLGHWKHWHVWGLU
(QWHUPYWHVWÀOHWRPRYHWKHWHVWƬOHXSLQWRWKHQHZSDUHQW GLUHFWRU\(QWHUls newparent/testdirWRYLHZWKHƬOHEDFNLQ
GLUHFWRU\(QWHUcd .. to move up to the parent directory. its current directory.
5(1$0,1*),/(6$1'',5(&725,(6
7KHPYFRPPDQGLVQoWXVHGMXVWWRPRYHƬOHVLWDOVRVHUYHVWKHSXUSRVHRIUHQDPLQJƬOHV HƪHFWLYHO\LWPRYHVLWIURPLWVROG
QDPHWRDQHZQDPH /HWoVVHHKRZWRXVHPYWRUHQDPHLWHPV
67(3 /HWoVVWDUWE\PDNLQJDQHZWHVWƬOHFDOOHGpQDPHVq 67(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,
WKHWHVWƬOHLVSUHVHQW:HoUHJRLQJWRWXUQWKLVLQWRDƬOHWKDW 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”. friendsWRPRYHWKHQDPHVƬOHLQVLGHWKHIULHQGVGLUHFWRU\
www.SFOpublications.com 123
Learning Linux
+(<0$1
7KHPDQSDJHVDUHRQHRIWKHEHVWIHDWXUHVRI/LQX[DQGDVDEXLOWLQWRROLWoVLQYDOXDEOHIRUERWKEHJLQQHUDQGVHQLRUOHYHO
/LQX[DGPLQLVWUDWRUV/HWoVVHHKRZLWZRUNV
67(3 Linux has a built-in manual, known as man for 67(3 0RVWFRPPDQGVDUHSUHWW\HDV\WRƬJXUHRXWKRZ
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
HQWHUman and the name of the command you want to learn more options and the letters used to activate them. Most man pages are
DERXW6WDUWE\HQWHULQJman 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.
67(3 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”
DQGWKHQWKHV\QRSVLVVKRZV\RXKRZLWZRUNV,QWKLVFDVHpOV
>237,21@>),/(@q6R\RXHQWHUls followed by options (such as
-la DQGWKHƬOHRUGLUHFWRU\WROLVW
www.SFOpublications.com
Using the Man Pages
67(3 Scroll to the bottom of the man page to discover 67(3 The man command can be used for just about every
PRUHLQIRUPDWLRQ7\SLFDOO\\RXZLOOƬQGWKH FRPPDQG\RXXVHLQ/LQX[<RXFDQHYHQHQWHU
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. pQDQRqRUpFKPRGqWDNHWLPHWRHQWHUman nano or man chmod
and read the instructions.
86,1*0$1237,216
%HFDXVHPDQGRHVQoWFKDQJHDQ\WKLQJOLNHPYRUPNGLULWLVWHPSWLQJQRWWRVHHLWDVDFRPPDQG%XWLWLVDQGOLNHDOORWKHU
FRPPDQGVLWKDVRSWLRQV7KHVHFDQEHYHU\KDQG\WROHDUQ
67(3 Entering: man man enables you to view some of 67(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).
+HUH\RXoOOƬQGFRPPDQGVOLNHpOVqpPNGLUqDQGpFGqDORQJZLWK
their description.
67(3 If you’re fast you may have noticed the start of the 67(3 Entering the man page for all the commands
WH[WƮHZXSRƪWKHSDJH7KLVLVEHFDXVHWKHpPDQ 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.SFOpublications.com 125
Learning Linux
7+(-2<2)7(;7
7REHDEOHWRHGLWRUFUHDWHDWH[WƬOH\RXQHHGDJRRGWH[WHGLWRU/LQX[KDVPDQ\EXWKHUHDUHVRPHLQDFWLRQRQWKH
5DVSEHUU\3L
67(3 7KHƬUVWWH[WHGLWRUIRUWKH5DVSEHUU\3LLVWKH 67(3 Vi is the original Unix command but in this case it
GHIDXOWGHVNWRSHQYLURQPHQWDSS/HDISDG7R launches VIM, the new Linux version of Vi. Although
XVH\RXFDQHLWKHUGRXEOHFOLFNDQH[LVWLQJWH[WƬOHRUFOLFNWKH 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.
67(3 From the Terminal there are even more options, 67(3 Nano is another favourite, and simple, text editor
although using the correct command, you can DYDLODEOHIRU/LQX[(QWHUnano 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 ZULWLQJ\RXURZQKHOSƬOHV7RH[LW1DQRSUHVV&WUO;IROORZHGE\
GD\VLVYL,QWKH7HUPLQDOHQWHUvi. <WRVDYHWKHƬOHRU1WRH[LWZLWKRXWVDYLQJ
www.SFOpublications.com
Editing Text Files
67(3 The previous command contacts the Debian 67(3 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 3LKRZHYHUE\HQWHULQJsudo 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.
www.SFOpublications.com 127
Learning Linux
:+$7,6$86(5"
$QLPSRUWDQWSDUWRIXVLQJ/LQX[LVWKHFRQFHSWRIXVHUVDQGXQGHUVWDQGLQJZKLFKXVHU\RXDUHDQGZKLFKJURXS\RXEHORQJWR
/LNHDOOPRGHUQFRPSXWHUV\RXFDQKDYHPXOWLSOHXVHUDFFRXQWVZLWKHDFKKDYLQJGLƪHUHQWOHYHOVRIDFFHVV
67(3 7KHƬUVWWKLQJ\RXQHHGWRGRLVJHWDFRQFHSWRI 67(3 To allow this, you need to use the sudo command.
ZKLFKXVHU\RXDUH(QWHUwhoami 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
QDPHGLƪHUHQWO\GXULQJVHWXS 7KHpZKRDPLqFRPPDQGPLJKWVHHP 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
RILW(QWHUsudo useradd -m lucy (or pick your name).
67(3 When you are working in Linux, from time to time a 67(3 1RZDGGDSDVVZRUGIRUWKHQHZDFFRXQW(QWHU
‘Permission denied’ error will occur, typically when sudo passwd lucyDQGHQWHUDVKRUWSDVVZRUG
\RXWU\WRFUHDWHHGLWRUH[HFXWH UXQ DƬOHRUGLUHFWRU\RXWVLGH Retype the same password and you’ll now have two accounts on
RI\RXUDUHDRISULYLOHJH,I\RXZDQWWRVHHWKLVHQWHUmkdir / \RXU5DVSEHUU\3L1RZHQWHUls -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.SFOpublications.com
Getting to Know Users
67(3 /HWoVWU\VZLWFKLQJWRRXUQHZDFFRXQW(QWHUsu 67(3 We’ll look at permissions in the next tutorial, but
lucy and enter the password you just created IRUQRZWU\WRFUHDWHDƬOHDVEHIRUH(QWHUtouch
IRUWKDWDFFRXQW1RWLFHWKDWWKHFRPPDQGOLQHQRZVD\VpOXF\# WHVWÀOHWRFUHDWHDƬOH,WZLOOVD\pWRXFKFDQQRWWRXFKnWHVWƬOHo
raspberrypi” but the working directory is “still /home/pi” (check Permission denied”. This is because your new user account doesn’t
WKLVXVLQJpSZGq (QWHUwhoamiWRFRQƬUPWKDW\RXDUHQRZWKH KDYHWKHULJKWWRFUHDWHƬOHVLQWKHKRPHSLGLUHFWRU\(QWHUsu
new user. pi to switch back to your pi account.
*(77,1*68'2
:HQRZKDYHWZRDFFRXQWVRQRXU5DVSEHUU\3LOXF\DQGSL7KHOXF\DFFRXQWFDQHGLWƬOHVLQKRPHOXF\DQGWKHSLDFFRXQWFDQ
HGLWƬOHVLQKRPHSL%XWWKHUHoVDOVRDWKLUGDFFRXQWFDOOHGpURRWqWKDWVLWVDERYHERWKOXF\DQGSL,WFDQHGLWƬOHVDQ\ZKHUH
67(3 The root account is all-powerful. It is possible, but not 67(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
\RXoOOQHHGWRJLYHLWDSDVVZRUGƬUVW XVLQJpVXGRSDVVZGURRWq 7KHQ 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ÀOHWRFUHDWHDƬOHLQWKHOXF\GLUHFWRU\ZKLOHVWLOO
using the pi account.
67(3 This step is optional. Only the pi user can use sudo. If
we want to give the lucy account sudo privileges, it
QHHGVWREHDGGHGWRWKHVXGRHUVƬOH(QWHUsudo visudo to view
WKHVXGRHUVƬOH$GGlucy ALL=(ALL) NOPASSWD: ALL to the
ODVWOLQHDQGXVH&RQWURO2WRRXWSXWWKHƬOH5HPRYHWKHpWPSq
67(3 Most people think sudo stands for “super user”,
WKDWLVDGGHGWRWKHƬOHQDPHDVDVHFXULW\PHDVXUH1RWHWKDWPRVW
but it stands for “substitute user do”. It enables
DFFRXQWVDUHQRWDGGHGWRWKHVXGRHUVƬOHDVDPDWWHURIFRXUVH
you to perform a command as another user. Enter: sudo -u
lucy touch /home/lucy/testWRFUHDWHDƬOHLQVLGHWKHOXF\
home directory. You won’t get an error because the lucy user has
permission to edit that directory.
www.SFOpublications.com 129
Learning Linux
Ownership and
Permissions
Once you’ve got the hang of users, you need to learn about ownership and
SHUPLVVLRQV'LƪHUHQWXVHUVKDYHGLƪHUHQWDUHDVRIRZQHUVKLSDQGFDQGRGLƪHUHQW
WKLQJVZLWKHDFKƬOH3HUPLVVLRQVLQ/LQX[FDQEHTXLWHFRPSOH[EXWZLWKFDUHIXO
WKRXJKWLWoVQRWWRRGLƯFXOW
2:1(5$1'35,9,/(*(
(DFKXVHUDFFRXQWLQ/LQX[LVDQRZQHURIDVHFWLRQRIWKHƬOHV\VWHPWKHLU+RPHDUHD:LWKLQWKLVDUHDWKH\GRZKDWWKH\OLNH
ZLWKLQUHDVRQ DVWKH\KDYHRZQHUSULYLOHJHV(OVHZKHUHWKRXJKWKH\XVXDOO\MXVWKDYHUHDGRQO\SULYLOHJHV
67(3 If you followed the previous tutorial you should now 67(3 7KHƬUVWOHWWHULQWKHSHUPLVVLRQVDOVRLQGLFDWHVD
have two accounts on your Raspberry Pi. One called GLUHFWRU\RUƬOH1RWLFHWKDWDOOWKHRWKHUƬOHVVWDUW
“pi” and the other with a name (Lucy in our case). An essential aspect ZLWKDnGoDQGRXUWH[WƬOHW[WƬOHVWDUWVZLWKDno7KDWoVZKDWWKHƬUVW
RI/LQX[LVWKHLGHDRIƬOHDQGGLUHFWRU\RZQHUVKLSZKRRZQVDQG letter means. It’s either a ‘d’, in which case it’s a directory, or a ‘-’, in
KDVDFFHVVWRZKDW<RXQHHGDWHVWƬOHVRHQWHUWRXFKWHVWÀOH. ZKLFKFDVHLWoVQRWLWoVDƬOH(QWHUOVOWHVWÀOHW[Wto view
WKHSHUPLVVLRQVIRUMXVWWKLVƬOH
130 www.SFOpublications.com
Ownership and Permissions
67(3 The ‘r’ means that particular permission is read and 67(3 The presence of r, w, or x means that this aspect is
it’s set to On. The nine letters here are divided into SRVVLEOHDGDVKPHDQVLWLVQoW2XUWHVWƬOHW[WKDV
WKUHHJURXSVRIWKUHHOHWWHUVUZ[7KH\VWDQGIRUUHDGZULWHDQG no x letter; so if it were a script it wouldn’t run. So why are there so
H[HFXWH UXQ 5HDGPHDQVWKHƬOHFDQEHYLHZHG XVLQJFDWRUQDQR many letters? Why not just three; read, write and execute? The three
ZPHDQVWKHƬOHFDQEHHGLWHGRUPRYHGDQG[PHDQVWKHƬOH EORFNVRIWKUHHOHWWHUVDUHIRUGLƪHUHQWVHWVRISHRSOHXVHUJURXS
typically a script or program - can be run. and other.
&+$1*,1*3(50,66,216
1RZWKDW\RXNQRZKRZJURXSVRISHUPLVVLRQVZRUNLWoVWLPHWRORRNDWKRZWRFKDQJHWKHP
67(3 $OSKDQRWDWLRQLVƬQHEXWPDQ\/LQX[DGPLQV
use octal notation instead. This is a three-
digit number that represents permissions. This is the formula:
read=4, write=2 and execute=1 and you add them up for each
group, therefore if a group is read, write and execute it’s 7, if it’s
67(3 The chmod command is one of the trickier ones
read and write it’s 6 or if it’s just execute it’s 1. A popular option
to understand. There are two ways you can adjust
is 755. Enter: FKPRGWHVWÀOHW[WWRFKDQJHWKHƬOH
SHUPLVVLRQVWKHƬUVWLVXVLQJFKPRGZLWKDQRSWLRQWRWDUJHWRQH
using octal notation.
of the three groups: owner, group, other. For these you use u, g
or o followed by = and the letters or dashes you want. So enter:
FKPRGXJR U[WHVWÀOHW[W to make all three groups read,
write and execute.
www.SFOpublications.com 131
Learning Linux
/2762)/,18;
/LQX[LVDKXJHDQGYHUVDWLOHFRPPDQGOLQHODQJXDJHDQGWKHUHDUHKXQGUHGVRIFRPPDQGV\RXFDQOHDUQDQGXVH+HUHDUHD
IHZWKDWFDQKHOS\RXJHWPRUHIURP\RXU5DVSEHUU\3L
67(3 The Raspberry Pi is a great little computer, so 67(3 (QWHUuname to view the name of the operating
OHWoVVWDUWE\JHWWLQJVRPHLQIRUPDWLRQ(QWHU 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
SURFHVVRUV,I\RXKDYHD5DVSEHUU\3L\RXZLOOVHHIRXUSURFHVVRUV 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.SFOpublications.com
Useful System and Disk Commands
67(3 (QWHUvcgencmd measure_temp to view the 67(3 One command you might be wondering about is
current operating system temperature of your KRZWRVZLWFKRƪRUUHVWDUW\RXU5DVSEHUU\3LIURP
5DVSEHUU\3L(QWHUvcgencmd get_mem arm to view the RAM WKHFRPPDQGOLQH'RQoWMXVWKLWWKHSRZHUVZLWFK(QWHUsudo
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 VWDQGVIRUpKDOWq RUHQWHUsudo shutdown –r now to restart
attached USB devices. your Raspberry Pi.
',6.&200$1'6
/HDUQWKHWZRFRPPDQGVWKDWHQDEOH\RXWRYLHZ\RXUGLVNVSDFHDQGWKHƬOHVRQLWGI GLVNIUHHVSDFH DQGGX GLVNXVDJH
:LWKWKHVHWZRFRPPDQGV\RXFDQYLHZWKHƬOHXVDJHRQ\RXU6'FDUG
67(3 Start by entering: df in the command line. It 67(3 Now enter: du<RXVKRXOGVHHORWVRIWH[WƮ\
returns a list of the volumes contained on your XSWKHVFUHHQ7KLVLVWKHGLVNXVDJHIRUWKHƬOHV
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 | lessWRYLHZWKHƬOHVDQG
their respective usage one page at a time.
67(3 Enter: df –h to get the list in human readable 67(3 You don’t typically enter: du on its own; most of the
IRUP7KHƬUVWWZROLQHVVKRXOGUHDGpURRWIVqDQG WLPH\RXZDQWWRYLHZWKHGLVNXVDJHRIDVSHFLƬF
“/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). EUHDNGRZQRIWKHƬOHVFRQWDLQHGXVHWKHpDqRSWLRQ DOO (QWHU
du -ha python_gamesWRYLHZDOOWKHƬOHVFRQWDLQHGDQGWKHLU
disk usage.
www.SFOpublications.com 133
Learning Linux
Managing Programs
and Processes
%HLQJDEOHWRHƪHFWLYHO\PDQDJHWKHDFWLYHSURJUDPVDQGSURFHVVHVRQ\RXU5DVSEHUU\
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.
352*5$06$1'352&(66(6
/LQX[KDVDWULFNXSLWVVOHHYHZKHQLWFRPHVWREHLQJDEOHWRPDQDJHSURJUDPVDQGSURFHVVHV:KHQ:LQGRZVFORVHVD
SURJUDPWKHDOORFDWHGPHPRU\RIWHQLVQoWIUHHGXSDJDLQ+RZHYHU/LQX[LVIDUPRUHVWUHDPOLQHG
67(3 As you get 67(3 If you type in “ps” on its own you don’t see much.
into Linux <RXVKRXOGVHHWZRLWHPVEDVKDQGSV%DVK
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
ZKHQWKHSURFHVVLVƬQLVKHG
it closes it and reclaims
WKH{PHPRU\
67(3 If you
want to
see processes used by
other users (including
those started by root)
HQWHUps –a. The
option stands for all
67(3 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
SURFHVVVWDWXV {FRPPDQG
you every process on
the system including the
background processes.
You may need to pipe it
through less using
pSVH_OHVVq
www.SFOpublications.com
Managing Programs and Processes
67(3 The ps 67(3 The “ps aux” command displays the processes
command LQFROXPQV7KHƬUVWLVWKH8VHUIROORZHGE\WKH
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
ZD\WRXVHSVLVWRHQWHU
SVDX[. Piping this
command through less
is the best way to go
DERXWXVLQJSV(QWHU
SVDX[_OHVV to view
your processes.
9,(:,1*$1'48,77,1*352&(66(6
1RZWKDW\RXoYHJRWDKDQGOHRQSURFHVVHV\RXQHHGWRNQRZZKDWWRGRZLWKWKHP<RXFDQYLHZSURFHVVHVUXQQLQJLQUHDO
WLPHDQGTXLWRQHVWKDW\RXQRORQJHUQHHGRUWKRVHWKDWDUHSUREOHPDWLF
67(3 While ps is a great tool for checking all the 67(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.
67(3 7RSƬOOVWKHGLVSOD\ZLWKSURFHVVHVDQGLWƬWVDV 67(3 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 sleepWRƬQGLWV3,'QXPEHU RQRXUVLWLV
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.SFOpublications.com 135
Learning Linux
,1287/,18;$//$%287
(YHU\WKLQJRQDFRPSXWHULVDERXWLQSXWDQGRXWSXW<RXLQSXWWKLQJVLQWRWKHFRPSXWHU SUHVVNH\VPRYHWKHPRXVH DQGLW
PDNHVFDOFXODWLRQVDQGRXWSXWVFRQWHQW FKDQJHVWKHGLVSOD\PDNHVDQRLVHIRUH[DPSOH
67(3 When 67(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 W[WqRXWSXWVWKHOLVWRILWHPVWRDQHZWH[WƬOHFDOOHGpJDPHVW[Wq
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).
67(3 7KHJDPHVW[WƬOHQRZFRQWDLQVWKHRXWSXWIURP
This is the regular way
the ls command. You can check it using “nano
of doing it, which is why
JDPHVW[Wq,WoVDQHGLWDEOHWH[WƬOHFRQWDLQLQJDOOWKHSHUPLVVLRQV
it’s “standard input and
XVHUDQGƬOHVL]HLQIRUPDWLRQDQGWKHQDPHVRIWKHƬOHV7KHRXWSXW
output” (often called
from the ls -l command, normally displayed on the screen, was
“stdin” and “stdout”
LQVWHDGVHQWWRWKLVƬOH3UHVV&RQWURO;WRTXLWQDQR
for short).
www.SFOpublications.com
Input, Output and Pipes
86,1*3,3(6
$VZHOODVGLUHFWLQJLQSXWDQGRXWSXWWRDQGIURPƬOHV\RXFDQVHQGWKHRXWSXWIURPRQHFRPPDQGGLUHFWO\LQWRDQRWKHU7KLV
LVNQRZQDVSLSLQJDQGXVHVWKHSLSHFKDUDFWHUp_q
67(3 As you start to get more advanced in Linux, you begin 67(3 You can pipe commands multiple times. Enter:
to create more powerful commands, and one way FDWEDQGVW[W_VRUW_JUHS7KH to get
\RXGRWKLVLVE\XVLQJWKHSLSHFKDUDFWHU p_q 7DNHVRPHWLPHWRƬQG 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. RXWSXWIURPVRUWLVSDVVHGLQWRJUHSZKLFKƬOWHUVRXWWKHEDQGV
starting with “The”. These bands form the output.
67(3 We’ve used the pipe a few times in the book (“ps 67(3 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 WRDSSHQGRXWSXWWHGGDWDWRDƬOHWKDWDOUHDG\H[LVWV(QWHUcat
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 WKHEDQGVW[WƬOHDQGSLSHVLWLQWRWKHZF ZRUGFRXQW IXQFWLRQ7KH
count) function. This then tells us how many lines, words and RXWSXWIURPZFLVDSSHQGHGWRWKHHQGRIWKHEDQGVW[WƬOH(QWHU
characters are in the document. FDWEDQGVW[W to view it.
www.SFOpublications.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.
7(50,1$/)81
$OOWKHVHFRPPDQGVDUH/LQX[EDVHGVRQRWRQO\FDQ\RXXVHWKHPRQWKH5DVSEHUU\3LEXWDOVRRQDQ\RIWKH'HELDQEDVHG
/LQX[GLVWULEXWLRQV
67(3 7KHƬUVWFRPPDQGZHoUHJRLQJWRXVHLVVO, it’s 67(3 If you’ve ever fancied having the computer read
QRWLQVWDOOHGE\GHIDXOWVRHQWHUsudo 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 5DVSELDQUHTXLUHV\RXWRLQVWDOOWKH7HUPLQDODSS)RUWXQHƬUVW
displays a Steam Locomotive travelling across the screen (hence ‘sl’). (QWHUsudo apt-get install fortuneWKHQVLPSO\HQWHU
(QWHULQJLS (note the upper case) also works. fortune, into the Terminal to see what comes up.
138 www.SFOpublications.com
Fun Things to Do in the Terminal
67(3 If you’re stuck trying to work out all the possible 67(3 If you really want to expand the whole cow thing,
IDFWRUVIRUDQ\SDUWLFXODUQXPEHUVLPSO\HQWHU for whatever reason, then pipe the fortune
factor followed by the number. For example, factor 7 doesn’t FRPPDQGWKURXJKLWZLWKfortune | cowsay; and for the
RƪHUPXFKRXWSXWZKHUHDVIDFWRUGLVSOD\VPRUH JUDSKLFDOFRZHTXLYDOHQWIRUWXQH_[FRZVD\. Plus, there’s
DOZD\VFRZWKLQN7U\Fowthink ...This book is awesome.
67(3 To further the cow element, there’s even a 67(3 Expanding the toilet command, you can actually
graphical, i.e. non-Terminal, cow available. Install generate some decent looking graphics through
LWZLWKVXGRDSWJHWLQVWDOO[FRZVD\, then when it’s LW)RUH[DPSOHWU\WKLVtoilet -f mono12 -F metal David.
LQVWDOOHGHQWHUVRPHWKLQJVLPLODUWRFRZVD\VXFKDV[FRZVD\%'0 <RXFDQHQWHUtoilet --help, for a list of the command line
Publications are ace!. arguments to expand further.
www.SFOpublications.com 139
Learning Linux
025()81<$<
6LQFHWKH7HUPLQDOVHVVLRQLVDOUHDG\RSHQDQG\RXUNH\ERDUGGLJLWVDUHQLFHO\ZDUPHGXSKHUHDUHDQRWKHUWZRSDJHVRI
7HUPLQDOQRQVHQVH
67(3 Remember the old ZX Spectrum days of computing, 67(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 RIWLPH2GGO\WKRXJKLWLVQoW(QWHUVudo apt-get install
GRWKHVDPH6LPSO\HQWHUyes followed by some text, i.e. yes onekoWKHQW\SHoneko 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.
67(3 The Matrix was one of the most visually copied 67(3 This entry is a little more serious than the previous.
ƬOPVHYHUUHOHDVHGDQGWKHUHoVHYHQDYHUVLRQRI Fork Bomb is a command that continually replicates
WKH0DWUL[FRGHDYDLODEOHIRU/LQX[,QVWDOOLWZLWKsudo apt-get itself until it has used up all the available system resources,
LQVWDOOFPDWUL[:KHQLWoVGRQHHQWHUFPDWUL[DQGIROORZWKH eventually causing your computer to crash. You don’t have to try it,
white rabbit, Neo. Unlike the real Matrix though, you can press EXWLWoVLQWHUHVWLQJQRQHWKHOHVV6LPSO\HQWHU:(){ :|:& }: and
Ctrl+C to exit. be prepared to reboot.
www.SFOpublications.com
More Fun Things to Do in the Terminal
67(3 Stringing several commands and piping them 67(3 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 DKDOILQFKƮRSSLHVFUDPPHGZLWKDOOPDQQHURIGHPRVFHQHJRRGLHV
command, together with toilet, can yield some impressive results. <RXoYHDOUHDG\LQVWDOOHGEEIURPWKHSUHYLRXVVWHSVRMXVWHQWHUbb.
(QWHUwhile true; do echo “$(date ‘+%D %T’ | toilet Follow the onscreen instructions and turn up your volume.
-f term -F border --metal)”; sleep 1; done.
67(3 Talking computers were the craze of the ‘80s. To 67(3 This entry is in two parts. First you need to get
UHOLYHWKHIXQHQWHUsudo apt-get install KROGRIWKHQHFHVVDU\SDFNDJHVsudo apt-
espeakWKHQespeak “This is a Raspberry Pi” to have get install libcurses-perl:KHQWKDWoVGRQHHQWHUcd
the computer repeat the text inside the quotes to you. Make sure Downloads/ && wget http://search.cpan.org/CPAN/
\RXUYROXPHLVWXUQHGXSDQGWU\WKHIROORZLQJOV!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.
67(3 $URDULQJ$6&,,ƬUHLVQoWWKHPRVWXVHIXOFRPPDQG
WRKDYHDW\RXUGLVSRVDOEXWLWoVIXQ,QVWDOOLWZLWK
sudo apt-get install libaa-binWKHQXVHDDÀUH. It’s not
H[DFWO\ZDUPLQJEXW\RXJHWWKHLGHD7RH[SDQGWKHDERYHHQWHU
sudo apt-get install bb caca-utilsWKHQFDFDÀUH.
www.SFOpublications.com
Learning Linux
7$.,1*&200$1'
7KHUHDUHFRXQWOHVV/LQX[WLSVVHFUHWVKDFNVDQGWULFNVRXWWKHUH6RPHDUHYHU\ROGRULJLQDWLQJIURP/LQX[oV8QL[KHULWDJH
ZKLOHRWKHUVDUHUHFHQWDGGLWLRQVWR/LQX[ORUH+HUHDUHRXUWHQIDYRXULWHWLSVDQGWULFNV
($67(5(**6 Emacs text editor, is a great piece of 7(50,1$/%52:6,1* Ever fancied being able to
software but did you know it also contains browse the Internet from
a hidden Easter Egg? With Emacs installed (VXGRDSWJHWLQVWDOO the Terminal? While not particularly useful, it is a fascinating thing to
HPDFV GURSWRD7HUPLQDOVHVVLRQDQGHQWHU EHKROG7RGRVRHQWHU
emacs -batch -l dunnet sudo apt-get install elinks
Dunnet is a text adventure written by Ron Schnell in 1982, and 7KHQ
hidden in Emacs since 1994.
elinks
Enter the website you want to visit.
0221%8**< Based on the classic 1982 arcade game, /(7,7612: 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 \RXoUHLQWHUHVWHGKRZHYHUHQWHU
JDPHDYDLODEOHLQWKH/LQX[7HUPLQDOE\HQWHULQJ
wget
sudo apt-get install moon-buggy
KWWSVJLVWJLWKXEXVHUFRQWHQWFRPVRQWHN
7KHQ UDZGHDHIEIHHIFD
snowjob.sh
moon-buggy
FKPRG[VQRZMREVK
Enjoy.
./snowjob.sh
www.SFOpublications.com
Linux Tips and Tricks
0(025<+2*6 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
PHPRU\RQ\RXU5DVSEHUU\3LVLPSOHHQWHU 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
%%6HV
This sorts the output by system memory use.
telnet battlestarbbs.dyndns.org
There are countless operational BBSes available; check out
ZZZWHOQHWEEVJXLGHFRPEEVOLVWGHWDLO for more.
6+5(''(5 :KHQ\RXGHOHWHDƬOHWKHUHoVVWLOODFKDQFHRI
someone with the right software being able to
UHWULHYHLW+RZHYHUƬOHVFDQEHVHFXUHO\DQGSHUPDQHQWO\GHOHWHG
XVLQJ6KUHG
',5(&725<75((6 If you want to create an entire
VKUHG]YX1$0(2)),/(W[W directory (or folder) tree with a
VLQJOHFRPPDQG\RXFDQXVH
5HSODFH1$0(2)),/(ZLWKWKHQDPHRIWKHƬOHWRGHOHWH
mkdir -p New-Dir/
^VXEIROGHUVXEIROGHUVXEIROGHUVXEIROGHU`
This creates a New-Dir with four sub folders within.
www.SFOpublications.com
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.
723&200$1'6
7KHVHPD\QRWEHWKHPRVWFRPPRQFRPPDQGVXVHGE\HYHU\RQHEXWWKH\ZLOOFHUWDLQO\IHDWXUHIUHTXHQWO\IRUPDQ\XVHUVRI
/LQX[DQGWKHFRPPDQGOLQH
The pwd command prints the full pathname of The rmFRPPDQGUHPRYHV GHOHWHV ƬOHVRU
the current working directory (pwd stands for GLUHFWRULHV7KHUHPRYDOSURFHVVXQOLQNVDƬOHQDPH
pwd “print working directory”). Note that the GNOME rm LQDƬOHV\VWHPIURPGDWDRQWKHVWRUDJHGHYLFH
terminal also displays this information in the title and marks that space as usable by future writes. In
bar of its window. RWKHUZRUGVUHPRYLQJƬOHVLQFUHDVHVWKHDPRXQW
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 FUHDWHGLUHFWRULHVRQDƬOHV\VWHPLIWKHVSHFLƬHG
clear terminal type and then in the terminfo database mkdir directory does not already exist. For example,
WRƬJXUHRXWKRZWRFOHDUWKHVFUHHQ7KLVLV mkdir work creates a work directory. More than
equivalent to typing Control-L when using the RQHGLUHFWRU\PD\EHVSHFLƬHGZKHQFDOOLQJPNGLU
bash shell.
www.SFOpublications.com
Command Line Quick Reference
C:\Commonly_Used_Commands
86()8/+(/3ǖ,1)2&200$1'6
7KHIROORZLQJFRPPDQGVDUHXVHIXOIRUZKHQ
\RXDUHWU\LQJWROHDUQPRUHDERXWWKHV\VWHPRU
SURJUDP\RXDUHZRUNLQJZLWKLQ/LQX[<RXPLJKW
QRWQHHGWKHPHYHU\GD\EXWZKHQ\RXGRWKH\
ZLOOEHLQYDOXDEOH
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 WUDQVIRUPDWLRQVRQDQLQSXWVWUHDPDƬOHRULQSXW
information using megabytes. from a pipeline.
The df FRPPDQGGLVSOD\VƬOHV\VWHPGLVNVSDFH
The adduser command adds a new user to the
df usage for all partitions. The command df-h adduser system. Similarly, the addgroup command adds a
is probably the most useful (the -h means
QHZJURXSWRWKH{V\VWHP
human-readable).
The top program provides a dynamic real-time The deluser command removes a user from
view of a running system. It can display WKHV\VWHP7RUHPRYHWKHXVHUoVƬOHVDQG
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.
QXPEHURIƬOHVIRUDSDUWLFXODUVHDUFKSDWWHUQDQG 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.SFOpublications.com
Learning Linux
A
adduser Add a new user dd Data Dump, convert and
G
gawk Find and Replace text
FRS\DƬOH ZLWKLQƬOH V
arch Print machine architecture
diff 'LVSOD\WKHGLƪHUHQFHV grep 6HDUFKƬOH V IRUOLQHVWKDW
awk Find and replace text
EHWZHHQWZRƬOHV match a given pattern
ZLWKLQƬOH V
dirname Convert a full path name groups Print group names a user
B
to just a path is in
du (VWLPDWHƬOHVSDFHXVDJH gzip Compress or decompress
bc An arbitrary precision QDPHGƬOH V
calculator language
E H
C
cat &RQFDWHQDWHƬOHVDQGSULQW
echo
ed
Display message on screen
A line oriented text editor
head 2XWSXWWKHƬUVWSDUW
RIƬOH V
on the standard output (edlin)
hostname Print or set system name
chdir Change working directory egrep 6HDUFKƬOH V IRUOLQHV
that match an
I
chgrp Change the group
extended expression
RZQHUVKLSRIƬOHV
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 &RS\ƬOHVDQG
H[SU Evaluate expressions
cmp &RPSDUHWZRƬOHV set attributes
F
comm &RPSDUHWZRVRUWHGƬOHV
cp
line by line
&RS\RQHRUPRUHƬOHVWR factor Print prime factors
J
join Join lines on a
another location
fdisk Partition table FRPPRQƬHOG
crontab Schedule a command to manipulator for Linux
K
run at a later time
fgrep 6HDUFKƬOH V IRUOLQHVWKDW
csplit 6SOLWDƬOHLQWRFRQWH[W PDWFKDƬ[HGVWULQJ
determined pieces kill Stop a process
ÀQG 6HDUFKIRUƬOHVWKDWPHHW
from running
cut 'LYLGHDƬOHLQWR a desired criteria
several parts
L
fmt Reformat paragraph text
D
fold :UDSWH[WWRƬWD
VSHFLƬHGZLGWK less Display output one screen
at a time
date Display or change the format Format disks or tapes
date & time ln 0DNHOLQNVEHWZHHQƬOHV
fsck Filesystem consistency
dc Desk calculator check and repair locate )LQGƬOHV
www.SFOpublications.com
A-Z of Linux Commands
logname
lpc
Print current login name
Line printer
rm
rmdir
5HPRYHƬOHV
Remove folder(s) U
umount Unmount a device
control program rpm Remote Package Manager
XQH[SDQG Convert spaces to tabs
lpr 2ƪOLQHSULQW rsync 5HPRWHƬOHFRS\
V\QFKURQLVHƬOHWUHHV uniq 8QLTXLI\ƬOHV
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 0HUJHWZRƬOHVLQWHUDFWLYHO\
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
VSHFLDOƬOHV
more Display output one screen
at a time
sleep
sort
'HOD\IRUDVSHFLƬHGWLPH
6RUWWH[WƬOHV
9
vdir Verbosely list directory
mount 0RXQWDƬOHV\VWHP split 6SOLWDƬOHLQWR FRQWHQWV COVOEo
Ƭ[HGVL]HSLHFHV
N
SSH Connects to a remote host
FRPSXWHUDVDVSHFLƬHG
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
ZULWHƬOHV
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 /RFDWHDSURJUDPƬOHLQ
sum
P
3ULQWDFKHFNVXPIRUDƬOH the user’s path
symlink Make a new name for who Print all usernames
DƬOH currently logged in
passwd Modify a user password
paste 0HUJHOLQHVRIƬOHV sync Synchronise data on disk whoami Print the current user id
with memory and name
pathchk &KHFNƬOHQDPHSRUWDELOLW\
pr
printcap
&RQYHUWWH[WƬOHV
for printing
Printer capability database
T
tac Concatenate and write
X
[DUJV Execute utility, passing
ƬOHVLQUHYHUVH
printenv Print environment variables constructed argument list(s)
tail Output the last part
printf Format and print data
Y
RIƬOHV
tar Tape Archiver
R
the system
traceroute Trace Route to Host
ram Ram disk device tr Translate, squeeze and or
rcp &RS\ƬOHVEHWZHHQ delete characters
two machines tsort Topological sort
www.SFOpublications.com
Index
&KHFNRXW3&/ V&RGH3RUWDO
)5((
&RPSOHWH3URJUDPV
2YHUOLQHVRIFRGH
9LVLWSFOSXEOLFDWLRQVFRP
H[FOXVLYHV
3OHDVHQRWH6LJQXSLVUHTXLUHGWRGRZQORDG
148 www.SFOpublications.com
Code Repository
:HoYHLQFOXGHGDXQLTXH3\WKRQFRGH
UHSRVLWRU\IRU\RXWRIUHHO\XVHLQ\RXU
RZQSURJUDPV7KHUHoVHYHU\WKLQJ\RXFDQ
WKLQNRILQKHUHWRKHOS\RXFUHDWHDVXSHUE
SLHFHRISURJUDPPLQJ
:HoYHJRWFRGHWKDWFRYHUVQXPEHU
JXHVVLQJJDPHVUDQGRPQXPEHU
JHQHUDWRUV*RRJOHVHDUFKFRGHJDPH
FRGHDQLPDWLRQFRGHJUDSKLFVFRGHWH[W
DGYHQWXUHFRGHDQGHYHQFRGHWKDWSOD\V
PXVLFVWRUHGRQ\RXUFRPSXWHU
7KLVLVDQH[FHOOHQWUHVRXUFHWKDW\RX
ZRQoWƬQGLQDQ\RWKHU3\WKRQERRN6R
XVHLWWDNHLWDSDUWDGDSWLWWR\RXURZQ
SURJUDPVDQGVHHZKDW\RXFDQFUHDWH
ZZZSFOSXEOLFDWLRQVFRP 149
Code Repository
def Read():
SDWK LQSXW ³(QWHUWKH¿OHSDWKWRUHDG´
¿OH RSHQ SDWK´U´
SULQW ¿OHUHDG 2
LQSXW µ3UHVV(QWHU¶
¿OHFORVH
def Write():
SDWK LQSXW ³(QWHUWKHSDWKRI¿OHWRZULWHRUFUHDWH´
LIRVSDWKLV¿OH SDWK
SULQW µ5HEXLOGLQJWKHH[LVWLQJ¿OH¶
else:
SULQW µ&UHDWLQJWKHQHZ¿OH¶
WH[W LQSXW ³(QWHUWH[W´
¿OH RSHQ SDWK´Z´
¿OHZULWH WH[W
def Add():
SDWK LQSXW ³(QWHUWKH¿OHSDWK´
WH[W LQSXW ³(QWHUWKHWH[WWRDGG´
¿OH RSHQ SDWK´D´
¿OHZULWH µ?Q¶WH[W
def Delete():
This part of the code imports the necessary modules. SDWK LQSXW ³(QWHUWKHSDWKRI¿OHIRUGHOHWLRQ´
1 The OS and Subprocess modules deal with the LIRVSDWKH[LVWV SDWK
SULQW µ)LOH)RXQG¶
operating system elements of the program.
RVUHPRYH SDWK
SULQW µ)LOHKDVEHHQGHOHWHG¶
Each def XXX() functions store the code for each
2 of the menu’s options. Once the code within the
else:
SULQW µ)LOH'RHVQRWH[LVW¶
function is complete, the code returns to the main
menu for another option. def Dirlist():
SDWK LQSXW ³(QWHUWKH'LUHFWRU\SDWKWRGLVSOD\´
This is part of the code that checks to see what OS VRUWOLVW VRUWHG RVOLVWGLU SDWK
3 the user is running. In Windows the CLS command i=0
clears the screen, whereas in Linux and macOS, the ZKLOH LOHQ VRUWOLVW
SULQW VRUWOLVW>L@¶?Q¶
Clear command wipes the screen. If the code tries
L
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. IS LQW LQSXW µ&KHFNH[LVWHQFHRI?Q)LOH?Q
'LUHFWRU\?Q¶
These are the options, from 1 to 12. Each executes LIIS
4 the appropriate function when the relevant number SDWK LQSXW ³(QWHUWKH¿OHSDWK´
is entered. RVSDWKLV¿OH SDWK
150 www.SFOpublications.com
Python File Manager
GHI2SHQ¿OH
SDWK LQSXW µ(QWHUWKHSDWKRISURJUDP¶
try:
RVVWDUW¿OH SDWK
except:
SULQW µ)LOHQRWIRXQG¶
UXQ ,PSRUWV
ZKLOH UXQ There are three modules to import here: Shutil, OS and
try: 7LPH7KHƬUVWWZRGHDOZLWKWKHRSHUDWLQJV\VWHPDQGƬOH
RVV\VWHP µFOHDU¶
except OSError: 3 management and manipulation; and the Time module simply
displays the current time and date.
RVV\VWHP µFOV¶
SULQW µ?Q!!!!!!!!!!3\WKRQ)LOH0DQDJHU?Q¶
SULQW µ7KHFXUUHQWWLPHDQGGDWHLV¶WLPHDVFWLPH Note how we’ve included a try and except block to check if
SULQW µ?Q&KRRVHWKHRSWLRQQXPEHU?Q¶ the user is running the code on a Linux system or Windows.
GHF LQW LQSXW µ¶¶5HDGD¿OH Windows uses CLS to clear the screen, while Linux uses clear.
:ULWHWRD¿OH The try block should work well enough but it’s a point of
$SSHQGWH[WWRD¿OH possible improvement depending on your own system.
'HOHWHD¿OH
www.SFOpublications.com 151
Code Repository
152 www.SFOpublications.com
Number Guessing Game
&RGH,PSURYHPHQWV
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
WKHSOD\HUIRUJHWWLQJDnKROHLQRQHoFRUUHFWJXHVVRQWKHLUƬUVWWU\ CR=0
/XFN
0RUHRYHUWKHQXPEHUJXHVVLQJJDPHFRGHGRHVRƪHUVRPHURRP (QGXUDQFH UDQGRPUDQGLQW
&5 UDQGRPUDQGLQW
IRULPSOHPHQWLQJLQWR\RXUFRGHLQDGLƪHUHQWPDQQHU:KDW
/XFN UDQGRPUDQGLQW
we mean by this is, the code can be used to retrieve a random 3ULQW ³<RXUFKDUDFWHU¶VVWDWVDUHDVIROORZV?Q´
number between a range, which in turn can give you the start of a 3ULQW ³(QGXUDQFH´(QGXUDQFH
FKDUDFWHUFUHDWLRQGHƬQHGIXQFWLRQZLWKLQDQDGYHQWXUHJDPH 3ULQW ³&RPEDW5DWLQJ´&5
3ULQW ³/XFN´/XFN
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.SFOpublications.com 153
Code Repository
Polygon Circles
+HUHoVDIXQDQGPDWKHPDWLFDO 32/<*21&,5&/(63<
ORRNDWPDNLQJDFLUFOHIURP 7KHUHoVORWVRIPDWKHPDWLFVXVHGKHUHDORQJZLWKVRPH
VWUDLJKWOLQHV8VLQJWKH0DWK LQWULFDWHFRRUGLQDWHPDQLSXODWLRQZLWKWKH7XUWOHPRGXOH
(QWHUWKHFRGHDQGH[HFXWHLWWRVHHKRZLWWXUQVRXW
PRGXOHLQSDUWLFXODUVLQFRVDQG
3LWKLVFRGHZLOOGUDZDVHULHV from turtle import*
IURPPDWKLPSRUWVLQFRVSL
RIVWUDLJKWOLQHVXVLQJWKH7XUWOH U
PRGXOH7KHHQGUHVXOWLVTXLWH LQF SL
W Q
UHPDUNDEOHDQGKDVSOHQW\RI IRU L LQ UDQJH
[ U VLQ W \ U FRV W
VFRSHIRUIXUWKHUH[SORUDWLRQ [ U VLQ WQ \ U FRV WQ
SHQXS JRWR [\
SHQGRZQ JRWR [\
W LQF
*UDSKLFDO(QKDQFHPHQWV
There are several ways in which you can improve this code to make For example:
LWPRUHLQWHUHVWLQJ<RXFDQLQVHUWFRORXUVSHUKDSVDGLƪHUHQW
FRORXUIRUHYHU\OLQH<RXFDQGLVSOD\DPHVVDJHLQVLGHWKHFLUFOH IRULLQUDQJH
and have the Turtle draw around it. Let your imagination run wild [ U VLQ W \ U FRV W
on this one. [ U VLQ WQ \ U FRV WQ
VSHHG µIDVWHVW¶
SHQXS JRWR [\
Turtle’s graphics can take a while to map out and draw, depending
SHQGRZQ JRWR [\
on how big and how intricate an image it is you’re designing. Whilst W LQF
WKHHƪHFWFDQEHTXLWHVWXQQLQJLWLVOLPLWHGE\WKHDPRXQWRI
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
IXQFWLRQWXUWOHVSHHG ZLOOTXLFNHQWKLQJVXS
WKH7XUWOH,WFHUWDLQO\PDNHVDGLƪHUHQFHDQGLVZRUWKFRQVLGHULQJ
if you’re drawing Turtle images for games or presentations.
Turtle.speed() comes in various values:
VORZHVW
VORZ
normal
fast
fastest
<RXFDQH[SHULPHQWZLWKWKHYDULRXVVSHHGVE\DGGLQJWKHIXQFWLRQ
in the for loop, just before the penup line.
154 www.SFOpublications.com
Polygon Circles/Random Number Generator
[ UDQGLQW QPEQPE
SULQW ³?Q7KH UDQGRP QXPEHUEHWZHHQ´QPE´DQG´QPE´LV?Q´
print(x)
0RUH,QSXW
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 8. SULQW ³?Q!!!!!!!!!!5DQGRP7XUWOH,PDJH?Q´
QPE LQW LQSXW ³(QWHUWKHVWDUWQXPEHU³
QPE LQW LQSXW ³(QWHUWKHVHFRQGQXPEHU³
Furthermore, the core of the code can be used in a text adventure QPE LQW LQSXW ³(QWHUWKHWKLUGQXPEHU³
JDPHZKHUHWKHFKDUDFWHUƬJKWVVRPHWKLQJDQGWKHLUKHDOWK 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 ’s Number
*XHVVLQJ*DPHZKHUHZHGHILQHGWKHVWDWVIRUWKHDGYHQWXUH WXUWOHIRUZDUG QPE
game’s character. WXUWOHOHIW
WXUWOHIRUZDUG QPE
<RXFDQDOVRLQWURGXFHWKH7XUWOHPRGXOHLQWRWKHFRGHDQG WXUWOHOHIW
SHUKDSVVHWVRPHGHƬQHGUXOHVIRUGUDZLQJDVKDSHREMHFWRU WXUWOHIRUZDUG QPE
WXUWOHOHIW
something based on a user inputted random value from a range
WXUWOHIRUZDUG QPE
RIQXPEHUV,WWDNHVDOLWWOHZRUNLQJRXWEXWWKHHƪHFWLVFHUWDLQO\ WXUWOHOHIW
really interesting.
Whilst it’s a little rough around the edges, you can easily make it
more suitable.
www.SFOpublications.com 155
Code Repository
Random Password
Generator
:HoUHDOZD\VEHLQJWROGWKDWRXU 51'3$66:25'3<
SDVVZRUGVDUHQoWVHFXUHHQRXJK &RS\WKHFRGHDQGUXQLWHDFKWLPH\RXoOOJHWDUDQGRPVWULQJ
ZHOOKHUHoVDVROXWLRQIRU\RXWR RIFKDUDFWHUVWKDWFDQHDVLO\EHXVHGDVDVHFXUHSDVVZRUG
ZKLFKZLOOEHLQFUHGLEO\GLƯFXOWIRUDSDVVZRUGFUDFNHUWRKDFN
LPSOHPHQWLQWR\RXURZQIXWXUH
import string
SURJUDPV7KHUDQGRPSDVVZRUG import random
JHQHUDWRUFRGHEHORZZLOOFUHDWH
GHIUDQGRPSDVVZRUG
DOHWWHUVWULQJRIZRUGV ERWK FKDUV VWULQJDVFLL B XSSHUFDVH VWULQJDVFLL B
ORZHUFDVHVWULQJGLJLWV
FDVHV DQGQXPEHUVHDFKWLPH size= 8
LWoVH[HFXWHG UHWXUQµ¶MRLQ UDQGRPFKRLFH FKDUV IRU[LQ
UDQJH VL]H
SULQW UDQGRPSDVVZRUG
6HFXUH3DVVZRUGV
There’s plenty you can do to modify this code and improve it $GGLQJDORRSWRSULQWDSDVVZRUGƬIW\WLPHVLVH[WUHPHO\HDV\IRU
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
WKHFKRVHQSDVVZRUGWRDƬOHWKHQVHFXUHO\FRPSUHVVLWXVLQJWKH import random
SUHYLRXVUDQGRPQXPEHUJHQHUDWRUDVDƬOHSDVVZRUGDQGVHQGLW
to a user for their new password.
GHIUDQGRPSDVVZRUG
FKDUV VWULQJDVFLL B XSSHUFDVHVWULQJDVFLL B
An interesting aspect to this code is the ability to introduce a loop ORZHUFDVHVWULQJGLJLWV
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 UHWXUQµ¶MRLQ UDQGRPFKRLFH FKDUV IRU[LQ
a random password for them each month. UDQJH VL]H
n=0
ZKLOHQ
SULQW UDQGRPSDVVZRUG
Q Q
7KLVZLOORXWSXWƬIW\UDQGRPSDVVZRUGVEDVHGRQWKHSUHYLRXV
random selection of characters.
156 www.SFOpublications.com
Random Password Generator/Keyboard Drawing Script
def main():
ZLGWK
speed(0) 2
SHQFRORU ³EOXH´
RQNH\ XS ³X´
RQNH\ GRZQ ³G´
RQNH\ FOHDU ³F´ An initial set of comments to display the controls, which can
RQNH\ KRPH ³K´ 1 also be outputted as a separate tkinter window if you want,
RQNH\ ODPEGD IRUZDUG ³5LJKW´
and importing the necessary modules: tkinter and turtle.
RQNH\ ODPEGD EDFN ³/HIW´
RQNH\ ODPEGD OHIW ³O´
Setting up the separate tkinter window displaying the controls
RQNH\ ODPEGD ULJKW ³U´
listen() 2 DQGFUHDWLQJDIXQFWLRQWRGHƬQHWKHZLGWKVSHHGDQGFRORXU
UHWXUQ ³'RQH´ of the line being drawn; also setting up the onkey functions for
LIB B QDPH B B ³ B B PDLQ B B ´ the controls of the pen.
msg = main()
print(msg) 3 $QHDWZD\WRƬQDOLVHWKHFRGHDQGORRSLWVR\RXFDQFRQWLQXH
mainloop() 3 drawing with the pen.
www.SFOpublications.com 157
Code Repository
import pygame
S\JDPHLQLW
7KH-R\2I7H[W
%/$&.
+HUH\RXFDQVHHWKDWZHoYHVWDUWHGE\GHƬQLQJWKHFRORXUV
:+,7(
but left the text black throughout the rest of the code; then,
%/8(
*5((1 also left the display window with a white background. The code
5(' itself is fairly easy to follow and you can improve it by using
GLƪHUHQWFRORXUVFKDQJLQJWKHIRQWIRUHDFKWH[WH[DPSOHDQG
3, its size too.
VL]H Try using some of the text examples individually in your code as
VFUHHQ S\JDPHGLVSOD\VHW B PRGH VL]H an introduction to your program perhaps. Either way you use
it, it will help make it stand out a little more than the standard
S\JDPHGLVSOD\VHW B FDSWLRQ ³7H[W([DPSOHV´
Python code you will likely come across during your time as
a programmer.
done = False
FORFN S\JDPHWLPH&ORFN
ZKLOHQRWGRQH
IRUHYHQWLQS\JDPHHYHQWJHW
LIHYHQWW\SH S\JDPH48,7
GRQH 7UXH
VFUHHQ¿OO :+,7(
S\JDPHGUDZOLQH VFUHHQ%/$&.>@
> @
S\JDPHGUDZOLQH VFUHHQ%/$&.>@
> @
158 www.SFOpublications.com
Pygame Text Examples/Google Search Script
6HDUFKLQJ)RU0RUH
Here we’ve used the Zenity command to create the dialog box, The last two for Chrome and Internet Explorer respectively.
which as we mentioned is only available to Linux machines (such as
Ubuntu, Raspberry Pi, Linux Mint and so on). If you want to execute There is a Zenity for Windows project available on GitHub at www.
LWLQ:LQGRZV\RXKDYHDFRXSOHRISRVVLELOLWLHV\RXFDQƬQGD github.com/kvaps/zenity-windows. It’s a good working version
:LQGRZVYHUVLRQRI=HQLW\DQGSDVVWKHXVHUoVTXHU\WKURXJKLWRU but you do need to install it to a folder on your system where you
you can create a Tkinter dialog box to pass the information. ZRQoWUHTXLUHDGPLQLVWUDWRUDFFHVVWREHDEOHWRUXQWKH=HQLW\
program. When you have Zenity installed, you can modify the
<RXFDQVHHWKDWWKLVSDUWLFXODUFRGHXVHVWKH&KURPLXPEURZVHU Windows version of this code in Python to read:
which comes preinstalled on the Raspberry Pi, and some versions
of Linux. To use your favourite browser in Windows, for example, import os
you will need to change the command in the last line of the code LPSRUWXUOOLESDUVH
to read Firefox, or whatever you use, together with the Start
command. So essentially, one of the following: JRRJOH RVSRSHQ µVWDUWF?7HPS?=HQLW\??ELQ?
]HQLW\HQWU\WH[W ´(QWHU\RXU*RRJOHVHDUFK³
WLWOH ´*RRJOH6HDUFK´¶ UHDG
RVV\VWHP µVWDUW¿UHIR[KWWSZZZJRRJOHFRP
JRRJOH XUOOLESDUVHTXRWH JRRJOH
VHDUFK"T V¶ JRRJOH
RVV\VWHP µVWDUW¿UHIR[KWWSZZZJRRJOHFRP
VHDUFK"T V¶ JRRJOH
RVV\VWHP µVWDUWFKURPHKWWSZZZJRRJOHFRP
VHDUFK"T V¶ JRRJOH
RVV\VWHP µVWDUWLH[SORUHKWWSZZZJRRJOHFRP
VHDUFK"T V¶ JRRJOH
www.SFOpublications.com 159
Code Repository
160 www.SFOpublications.com
Text to Binary Convertor
With regards to improvements, you could display the binary WH[W B URWDWH B GHJUHHV
conversion in a Pygame window, using the animated text options
IURPSDJH<RXFRXOGDOVRDVNWKHXVHULIWKH\ZDQWHGWRKDYH %LQDU\ µµMRLQ IRUPDW RUG [ µE¶ IRU[
another go, or even ask if they wanted the binary output to be LQFRQYHUVLRQ
VDYHGWRDƬOH
ZKLOHQRWGRQH
www.SFOpublications.com 161
Code Repository
SULQW µ¶¶<RX¿QG\RXUVHOIDWDVPDOOLQQ7KHUH¶V
OLWWOHJROGLQ\RXUSXUVHEXW\RXUVZRUGLVVKDUS
DQG \RX¶UH UHDG\ IRU DGYHQWXUH
:LWK \RX DUH WKUHH RWKHU FXVWRPHUV
$ UDJJHG ORRNLQJ PDQ DQG D SDLU RIGDQJHURXV
ORRNLQJ JXDUGV¶¶¶
def start():
SULQW ³?Q´
SULQW ³'R \RX DSSURDFKWKH´
SULQW ³?Q´
SULQW ³ 5DJJHGORRNLQJPDQ´
SULQW ³ 'DQJHURXV ORRNLQJ JXDUGV´
FPGOLVW >³´³´@
cmd=getcmd(cmdlist)
162 www.SFOpublications.com
Text Adventure Script
LIFPG ³´
ragged() def getcmd(cmdlist):
HOLI FPG ³´ FPG LQSXW QDPH´!´
guards() if cmd in cmdlist:
return cmd
def ragged(): HOLI FPG ³KHOS´
SULQW ³?Q´ SULQW ³?Q(QWHU\RXUFKRLFHVDVGHWDLOHGLQ
SULQW µ¶¶<RX ZDON XSWRWKHUDJJHGORRNLQJPDQDQG WKH JDPH´
JUHHW KLP SULQW ³RU HQWHUµTXLW¶WROHDYHWKHJDPH´
+HVPLOHVDWRRWKOHVVJULQDQGZLWKDVWUDQJH return getcmd(cmdlist)
DFFHQW VD\V HOLIFPG ³TXLW´
³%X\ PH D FXSRIZLQHDQG,¶OOWHOO\RXRI SULQW ³?Q´
JUHDW WUHDVXUH¶¶¶ WLPHVOHHS
WLPHVOHHS SULQW ³6DGO\ \RXUHWXUQWR\RXUKRPHODQGZLWKRXW
IDPH RU IRUWXQH´
def guards(): WLPHVOHHS
SULQW ³?Q´ exit()
SULQW µ¶¶<RX ZDONXSWRWKHGDQJHURXVORRNLQJJXDUGV
DQG JUHHW WKHP
7KHJXDUGVORRNXSIURPWKHLUGULQNVDQG LIB B QDPH B B ´ B B PDLQ B B ´
VQDUO DW \RX start()
³:KDW GR \RX ZDQWEDUEDULDQ"´2QHJXDUGUHDFKHV
IRU WKH KLOW RI KLV VZRUG¶¶¶
WLPHVOHHS
$GYHQWXUH7LPH
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
WKHVWRU\DORQJ\RXoOOƬQGWKDW\RXFDQUHSHDWFHUWDLQLQVWDQFHV
such as a chance meeting with an enemy or the like.
:HoYHFUHDWHGHDFKRIWKHWZRHQFRXQWHUVDVDGHƬQHGVHW
of functions, along with a list of possible choices under the
FPGOLVWOLVWDQGFPGYDULDEOHRIZKLFKLVDOVRDGHƬQHGIXQFWLRQ
([SDQGLQJRQWKLVLVTXLWHHDV\MXVWPDSRXWHDFKHQFRXQWHUDQG
FKRLFHDQGFUHDWHDGHƬQHGIXQFWLRQDURXQGLW3URYLGLQJWKHXVHU
GRHVQoWHQWHUTXLWLQWRWKHDGYHQWXUHWKH\FDQNHHSSOD\LQJ
www.SFOpublications.com 163
Code Repository
screen = Screen()
\HUWOH 7XUWOH
GHIN
VFUHHQRQVFUHHQFOLFN FOLFN B KDQGOHU
VFUHHQOLVWHQ
VFUHHQPDLQORRS
1LQMD7XUWOH0RXVH
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.SFOpublications.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
OHQJWKRIWLPHWKH\ZDQWXQWLOWKHDODUPJRHVRƪUDWKHUWKDQ
VD V\VDUJY having to include it in the command line.
OVD OHQ V\VDUJY
LI OVD
SULQW ³8VDJH>S\WKRQ@$ODUP&ORFNS\GXUDWLRQ B
LQ B PLQXWHV´
SULQW ³([DPSOH>S\WKRQ@$ODUP&ORFNS\´
SULQW ³8VH D YDOXH RI PLQXWHV IRU WHVWLQJ WKH
DODUP LPPHGLDWHO\´
SULQW ³%HHSV D IHZ WLPHVDIWHUWKHGXUDWLRQLVRYHU´
SULQW ³3UHVV &WUO& WR WHUPLQDWH WKH DODUP
FORFN HDUO\´
V\VH[LW
try:
PLQXWHV LQW VD>@
except ValueError:
SULQW ³,QYDOLGQXPHULFYDOXH V IRUPLQXWHV´VD>@
SULQW ³6KRXOG EH DQ LQWHJHU ! ´
V\VH[LW
LIPLQXWHV
SULQW ³,QYDOLGYDOXHIRUPLQXWHVVKRXOGEH! ´ Windows users, if Python 3 is the only version installed on your
V\VH[LW 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
S\WKRQ$ODUP&ORFNS\
LIPLQXWHV
XQLW B ZRUG ³PLQXWH´
Again, you could easily incorporate this into a Windows batch
else:
XQLW B ZRUG ³PLQXWHV´ ƬOHDQGHYHQVHWDVFKHGXOHWRDFWLYDWHWKHDODUPDWFHUWDLQ
times of the day.
www.SFOpublications.com 165
Code Repository
,UHPHPEHU
7KHGDUNZRRGVPDVNLQJVORSHVRIVRPEUHKLOOV
7KHJUH\FORXGV¶OHDGHQHYHUODVWLQJDUFK
7KHGXVN\VWUHDPVWKDWÀRZHGZLWKRXWDVRXQG
$QG WKH ORQH ZLQGV WKDW ZKLVSHUHG GRZQ WKH SDVVHV
9LVWDRQYLVWDPDUFKLQJKLOOVRQKLOOV
6ORSH EH\RQG VORSH HDFK GDUN ZLWK VXOOHQWUHHV
2XU JDXQW ODQG OD\ 6R ZKHQ D PDQ FOLPEHG XS
$ UXJJHG SHDN DQG JD]HG KLV VKDGHG H\H
6DZ EXW WKH HQGOHVV YLVWD ± KLOO RQ KLOO
6ORSH EH\RQG VORSH HDFK KRRGHG OLNH LWV EURWKHUV
,WZDVDJORRP\ODQGWKDWVHHPHGWRKROG
$OO ZLQGV DQG FORXGV DQG GUHDPV WKDW VKXQWKHVXQ
:LWK EDUH ERXJKV UDWWOLQJ LQ WKH ORQHVRPH ZLQGV
$QG WKH GDUN ZRRGODQGV EURRGLQJ RYHU DOO
1RW HYHQ OLJKWHQHG E\ WKH UDUH GLP VXQ
:KLFK PDGH VTXDW VKDGRZV RXW RI PHQ WKH\FDOOHGLW
&LPPHULD ODQG RI 'DUNQHVV DQG GHHS 1LJKW
,WZDVVRORQJDJRDQGIDUDZD\
, KDYH IRUJRW WKH YHU\ QDPH PHQFDOOHGPH
7KH D[H DQG ÀLQWWLSSHG VSHDU DUH OLNH D GUHDP
$QG KXQWV DQG ZDUV DUH VKDGRZV , UHFDOO
Only the stillness of that sombre land;
7KH FORXGV WKDW SLOHG IRUHYHU RQ WKH KLOOV
7KH GLPQHVV RI WKH HYHUODVWLQJ ZRRGV
&LPPHULD ODQG RI 'DUNQHVV DQG WKH 1LJKW
2KVRXORIPLQHERUQRXWRIVKDGRZHGKLOOV
7R FORXGV DQG ZLQGV DQG JKRVWV WKDW VKXQ WKH VXQ
+RZ PDQ\ GHDWKV VKDOO VHUYH WR EUHDN DW ODVW
7KLV KHULWDJH ZKLFK ZUDSV PH LQ WKH JUH\
$SSDUHO RI JKRVWV" , VHDUFK P\ KHDUW DQG ¿QG
&LPPHULD ODQG RI 'DUNQHVV DQG WKH 1LJKW
µ¶¶VSOLW µ?Q¶
166 www.SFOpublications.com
Vertically Scrolling Text
class Credits:
GHIB B LQLW B B VHOIVFUHHQ B UHFWOVW $/RQJ7LPH$JRf
VHOIVUHFW VFUHHQ B UHFW The obvious main point of enhancement is the actual text
VHOIOVW OVW LWVHOI5HSODFHLWZLWKDOLVWRIFUHGLWVRUDQHTXDOO\HSLFRSHQLQJ
VHOIVL]H
storyline to your Python game, and it will certainly hit the
VHOIFRORU
VHOIEXII B FHQWHU\ VHOIVUHFWKHLJKW mark with whoever plays it. Don’t forget to change the screen
VHOIEXII B OLQHV resolution if needed; we’re currently running it at 800 x 600.
VHOIWLPHU
VHOIGHOD\
VHOIPDNH B VXUIDFHV
def update(self):
LISJWLPHJHW B WLFNV VHOIWLPHU!VHOIGHOD\
VHOIWLPHU SJWLPHJHW B WLFNV
IRU WH[W UHFW LQ VHOIWH[W
UHFW\
GHIUHQGHU VHOIVXUI
IRUWH[WUHFWLQVHOIWH[W
VXUIEOLW WH[WUHFW
ZKLOHUXQQLQJ
IRUHYHQWLQSJHYHQWJHW
LIHYHQWW\SH 48,7
running = False
VFUHHQ¿OO
FUHGXSGDWH
FUHGUHQGHU VFUHHQ
SJGLVSOD\XSGDWH
FORFNWLFN
www.SFOpublications.com 167
Code Repository
FORFNDIWHU WLFN
URRW WN7N
FORFN WN/DEHO URRWIRQW µDULDO¶µEROG¶
EJ ¶JUHHQ¶
FORFNSDFN ¿OO ¶ERWK¶H[SDQG
tick()
URRWPDLQORRS
168 www.SFOpublications.com
Python Digital Clock
7LFN7RFN
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 URRWWLWOH µ6WRS:DWFK¶
TXLFNJODQFHWRZKHUHZHoYHSODFHGLWRQWKHVFUHHQ URRWUHVL]DEOH 7UXH)DOVH
URRWJULG B FROXPQFRQ¿JXUH ZHLJKW
7KH7NLQWHUER[FDQEHPRYHGDURXQGZLWKRXWDƪHFWLQJWKHWLPH SDGGLQJ GLFW SDG[ SDG\
ZLGJHW 6WRS:DWFK URRW SDGGLQJ
maximised or closed by the user at will. We haven’t given the
ZLGJHWJULG VWLFN\ WNLQWHU16(: SDGGLQJ
Tkinter clock window a title, so you can add to that easily enough
URRWPDLQORRS
by snipping the code from other examples in this book.
GHIB B LQLW B B VHOIPDVWHU 1RQHFQI ^` NZ
Another area of improvement is to include this code when SDGGLQJ GLFW SDG[ NZSRS µSDG[¶ SDG\ NZ
Windows or Linux starts, so it automatically pops up on the SRS µSDG\¶
desktop. See also, if you’re able to improve its functionality by VXSHU B B LQLW B B PDVWHUFQI NZ
LQFOXGLQJGLƪHUHQWWLPH]RQHV5RPH3DULV/RQGRQ1HZ<RUN VHOIJULG B FROXPQFRQ¿JXUH ZHLJKW
Moscow and so on. VHOIJULG B URZFRQ¿JXUH ZHLJKW
VHOI B B WRWDO
VHOI B B ODEHO WNLQWHU/DEHO VHOI
WH[W ¶7RWDO7LPH¶
VHOI B B WLPH WNLQWHU6WULQJ9DU VHOI
µ¶
VHOI B B GLVSOD\ WNLQWHU/DEHO VHOI
WH[WYDULDEOH VHOI B B WLPH
VHOI B B EXWWRQ WNLQWHU%XWWRQ VHOI
WH[W ¶6WDUW¶FRPPDQG VHOI B B FOLFN
VHOI B B ODEHOJULG URZ FROXPQ
VWLFN\ WNLQWHU( SDGGLQJ
VHOI B B GLVSOD\JULG URZ FROXPQ
VWLFN\ WNLQWHU(: SDGGLQJ
VHOI B B EXWWRQJULG URZ FROXPQ
FROXPQVSDQ VWLFN\ WNLQWHU16(: SDGGLQJ
www.SFOpublications.com 169
Code Repository
Python Scrolling
Ticker Script
<RXPD\EHVXUSULVHGWRKHDU 7,&.(53<
WKDWRQHRIWKHVQLSSHWVRIFRGH :HoUHXVLQJ7NLQWHUKHUHDORQJZLWKWKH7LPHPRGXOHWR
GHWHUPLQHWKHVSHHGWKHWH[WLVGLVSOD\HGDFURVVWKHZLQGRZ
ZHoUHRIWHQDVNHGIRULVVRPH
IRUPRIVFUROOLQJWLFNHU:KLOVW
ZHoYHFRYHUHGYDULRXVIRUPVRI import time
VFUROOLQJWH[WSUHYLRXVO\WKHWLFNHU import tkinter as tk
LVVRPHWKLQJWKDWVHHPVWRNHHS URRW WN7N
FURSSLQJXS6RKHUHLWLV FDQYDV WN&DQYDV URRWURRWWLWOH ³7LFNHU&RGH´
KHLJKW ZLGWK EJ ´\HOORZ´
FDQYDVSDFN
IRQW µFRXULHU¶µEROG¶
7LFNHU7LPH WH[W B ZLGWK
WKHSL[HOYDOXHGHSHQGVRQG[IRQWDQGOHQJWKRIWH[W
pixels = 9000
for p in range(pixels):
PRYHWH[WREMHFWE\LQFUHPHQWVG[G\
G[ ! ULJKW WR OHIW
FDQYDVPRYH WH[W G[ G\
The ticker example can be used for system warnings,
FDQYDVXSGDWH
perhaps something that will display across your work or VKRUWHU GHOD\!IDVWHUPRYHPHQW
home network detailing the shutting down of a server WLPHVOHHS
over the weekend for maintenance; or even just to SULQW N WHVWKHOSVZLWKSL[HOYDOXH
inform everyone as to what’s happening. We’re sure
you will come up with some good uses for it. URRWPDLQORRS
170 www.SFOpublications.com
Python Scrolling Ticker Script/Simple Python Calculator
SULQW ³6LPSOH3\WKRQ&DOFXODWRU?Q´
GHIDGG [\
UHWXUQ[\
GHIVXEWUDFW [\
UHWXUQ [ \
GHIPXOWLSO\ [\
return x * y
GHIGLYLGH [\
UHWXUQ[\
SULQW ³6HOHFWRSHUDWLRQ?Q´
SULQW ³$GG´
SULQW ³6XEWUDFW´
SULQW ³0XOWLSO\´
SULQW ³'LYLGH´
LIFKRLFH µ¶
SULQW QXP´´QXP´ ´DGG QXPQXP
,PSURYHG&DOFXODWLRQV
HOLIFKRLFH µ¶ The obvious contender for improvement here is using the
SULQW QXP´´QXP´ ´VXEWUDFW QXPQXP &UHDWH<RXU2ZQ0RGXOHVURXWHDQGH[WUDFWLQJWKHIXQFWLRQ
GHƬQLWLRQVDVDPRGXOH<RXFDQWKHQFDOOWKHPRGXOHDQGIRFXV
HOLIFKRLFH µ¶
on the body of the code.
SULQW QXP´ ´QXP´ ´PXOWLSO\ QXPQXP
HOLIFKRLFH µ¶ The other area of improvement is code itself. Where there’s
SULQW QXP´´QXP´ ´GLYLGH QXPQXP 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
SULQW ³,QYDOLGLQSXW´ to the main menu. Perhaps, improvement to the Invalid Input
section is worth looking into as well.
www.SFOpublications.com 171
Code Repository
llC = 65
O&
O'E
O'
O(E
O(
O)
O*E
O*
O$E
O$
O%E
O%
&
'E
'
(E
(
) 2
*E
*
$E
A = 440
Bb = 466
B = 494
K&
hDb = 554
hD = 587
K(E
hE = 659
hF = 698
hGb = 740
hG = 784
K$E
hA = 880
K%E
hB = 988
WLPHVOHHS
172 www.SFOpublications.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
LVVHWWLQJWKHGXUDWLRQZKLOHSHTXDOVZKLFK\RXFDQXVHIRU
the time.sleep function.
7KHVHYDULDEOHVVHWWKHIUHTXHQFLHVZLWKWKHFRUUHVSRQGLQJ
2 numbers, which can be used in the next section of the code.
:LQVRXQGEHHSUHTXLUHVDIUHTXHQF\DQGGXUDWLRQZLWKLQWKH
3 EUDFNHWV7KHIUHTXHQFLHVFRPHIURPWKHODUJHVHWRIYDULDEOHV
called in the second section of the code and the duration is
through the t variable set at the start of the code. There’s a
half-second, using the variable p, pause between blocks of
winsound.beep statements.
www.SFOpublications.com 173
Code Repository
| |
O |
|
|
|
¶¶¶µ¶¶
| |
O |
| |
|
|
¶¶¶µ¶¶
| |
O |
__
|
|
¶¶¶µ¶¶
| |
O |
_?_
|
|
¶¶¶µ¶¶
| |
O |
_?_
_
174 www.SFOpublications.com
Hangman Game Script
www.SFOpublications.com 175
Index
176 www.SFOpublications.com
Coding Projects & Tips
:HoUHJRLQJWRƬQLVKRƪE\ORRNLQJDW
VRPHLQWHUHVWLQJFRGLQJHOHPHQWVWKDW
\RXFDQLQFRUSRUDWHLQWR\RXURZQ
XQLTXHSURMHFWVDQGFRGH,QWKLVVHFWLRQ
\RXoOOƬQGFRGHIRUFUHDWLQJDORDGLQJ
VFUHHQIRU\RXUFRQWHQWWH[WDQLPDWLRQV
XVLQJ$6&,,DUWFOHYHUZD\VLQZKLFK\RX
FDQLQFOXGHDQLPDWHGVHFWLRQVDWWKH
FRPPDQGSURPSWDQGHYHQFRGHWKDW
FDQWUDFNWKH,QWHUQDWLRQDO6SDFH6WDWLRQ
LQUHDOWLPHZKLOHGLVSOD\LQJERWKWKH
DVWURQDXWVRQERDUGDQGLWVFXUUHQW
ODWLWXGHDQGORQJLWXGH
7KHUHDUHDOVRSDJHVRIFRPPRQDQG
ODQJXDJHVSHFLƬFPLVWDNHVWRKHOS\RX
DYRLGDQGFUHDWHHUURUIUHHDQG
HƪHFWLYHFRGHLQWKHIXWXUH
www.SFOpublications.com 177
Coding Projects & Tips
/2$'qq 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.
6&5((1
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
IROGHULQVLGHDQRUPDOWH[WƬOH
6DYHWKHƬOHFDOOLWVFUHHQVW[WIRUQRZ
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:
$'9(1785(7,0(
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
GHƬQLWHO\DGGDOLWWOHVRPHWKLQJHOVHH[WUD
178 www.SFOpublications.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.
5HPHPEHUWRKDYHWKH$6&,,WH[WƬOHLQWKHVDPHIROGHUDVWKH3\WKRQ
def loading _ bar(seconds): code, or, at the VFUHHQV RSHQ pVFUHHQVW[WqnUo part of the code, point
for loading in range(0,seconds+1): WRZKHUHWKHWH[WƬOHLVORFDWHG
www.SFOpublications.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
HƪHFWVIURPWKHFRPPDQGOLQH
7+(),1$/&2817'2:1
and so on to 10. It’ll take some time, but it’s worth it in the end. Of course,
\RXFDQDOZD\VWDNHDGLƪHUHQWDSSURDFKDQGGHVLJQWKHQXPEHUV\RXUVHOI
The next step of the process is to initialise the code settings and start
the countdown:
#Initialise settings
start = 10
message = “> BLAST OFF!! <”
180 www.SFOpublications.com
Text Animations
To extend the code, or make it easier to use, you can always %/$672))
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
DQLPDWHGURFNHWWKDWoOOODXQFKDIWHUWKH%ODVW2ƪPHVVDJHKDV
DQHZ3\WKRQƬOHFDOOHG&RXQWGRZQS\DORQJZLWKWKH26DQG
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: SURGXFHVWKHHƪHFWRIDQ$6&,,OLNHURFNHWWDNLQJRƪDQG
FRXQW¿YH 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: DWWKHHQGRIWKH%ODVW2ƪPHVVDJHDGGWKHIROORZLQJOLQHV
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: KWWSVSFOSXEOLFDWLRQVFRPH[FOXVLYHV
52//,1*',(
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()
www.SFOpublications.com 181
Coding Projects & Tips
72%2/'/<*2f
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
:KLOHZHoUHQRWDEOHWRƬOO\RXLQRQDOOWKHGHWDLOVUHJDUGLQJWKH
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
VWDWLRQoVFXUUHQWODWLWXGHDQGORQJLWXGHHYHU\ƬYHVHFRQGVZKLOHDOVR
DQGORQJLWXGHRIWKH,66DVLWRUELWV(DUWKDQGDƬQDOODUJHZLQGRZ
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.
7+(*5$3+,&6
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.SFOpublications.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,
DQGWLPH\RXDOUHDG\NQRZ7KHZHEEURZVHUPRGXOHZLOORSHQWH[WƬOHV
LQWKHGHIDXOWWH[WƬOHDSSOLFDWLRQsGHVSLWHZKDWLWVQDPHPD\VXJJHVW
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: SLSLQVWDOOJHRFRGHU. Geocoder can retrieve a users’ location based
call them map and iss respectively, and click GIF as the image format. RQWKHLU,3DGGUHVVDVHDFK,63ZLOOKDYHDJHRVSHFLƬF,3
Remember to also resize the ISS image before saving it as a GIF.
#Retrieve the names of all the astronauts currently on
ERDUGWKH,66DQGRZQODWORQJZULWHWRD¿OHDQGGLVSOD\
7+(&2'( 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: KWWSDSLRSHQQRWLI\RUJDVWURVMVRQ, and, KWWSDSL a.write(“\nYour current Lat/Long is: “ + str(g.latlng)) #
RSHQQRWLI\RUJLVVQRZMVRQ. One of which contains the data regarding SULQWV\RXUFXUUHQWODWORQJLQWKHWH[W¿OH
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.
,WWKHQFUHDWHVDQHZWH[WƬOHFDOOHGLVVW[WZKHUHLWoOOZULWHn7KHUHDUH
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
WKDWLQIRUPDWLRQWRWKHHQGRIWKHWH[WƬOHWKDWFRQWDLQVWKHQDPHVRI
the astronauts. The last line, webbrowser.open(“iss.txt”) will use the
ZHEEURVHUPRGXOHWRRSHQDQGGLVSOD\WKHQHZO\ZULWWHQWH[WƬOHLQWKH
V\VWHPoVGHIDXOWWH[WƬOHUHDGLQJDSS
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.SFOpublications.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” ERDUGWKH,66DQGRZQODWORQJZULWHWRD¿OHDQGGLVSOD\
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
ODW ÀRDW ODW for p in people:
ORQ ÀRDW ORQ 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) \RXUFXUUHQWODWORQJLQWKHWH[W¿OH
a.close()
webbrowser.open(“iss.txt”)
1RZIRUWKHƬQDOSDUWRIWKHFRGH+HUHZHFROOHFWWKHORFDWLRQGDWDIURP
#Setup world map in Turtle
the ISS status API, pulling out the latitude and longitude elements of the screen = turtle.Screen()
-621ƬOH7KHFRGHWKHQSULQWVWKHODWLWXGHDQGORQJLWXGHGDWDWRWKH screen.setup(1280, 720)
FRQVROH7HUPLQDOWUDQVIHUULQJWKHGDWDIURPDƮRDWWRDVWULQJLQRUGHU 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
YDULDEOHVODWDQGORQWRXSGDWHWKH,66LFRQRQWKHPDSHYHU\ƬYHVHFRQGV screen.bgpic(“map.gif”)
184 www.SFOpublications.com
Tracking the ISS with Python
www.SFOpublications.com 185
Coding Projects & Tips
$6&,,$1,0$7,21
/HWoVDVVXPH\RXZDQWHGWRFUHDWHDQDQLPDWHG$6&,,+DSS\%LUWKGD\3\WKRQVFULSWZLWKWKHZRUGV+DSS\DQG%LUWKGD\
DOWHUQDWLQJLQDSSHDUDQFH+HUHoVKRZLWoVGRQH
67(3 First we need to create some ASCII-like text, head 67(3 6DYHWKHWH[WƬOHDVW[W (you can call it what you
over to KWWSSDWRUMNFRPVRIWZDUHWDDJ. This is OLNHEXWQRZIRUHDVHRIXVHW[WZLOOVXƯFH 6DYH
an online Text to ASCII generator, created by Patrick Gillespie. Start WKHƬOHLQWKHQHZO\FUHDWHG7HVWIROGHU:KHQLWoVVDYHGGRH[DFWO\
by entering +DSS\ 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 %LJ. VDYHWKHƬOHDVW[W.
67(3 Now create a folder in your Python code directory 67(3 Open up Python and create a 1HZ)LOH. 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 6HOHFW &RS\ 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.SFOpublications.com
Using Text Files for Animation
67(3 Next we need to create a list of the names of the 67(3 Here’s the code in full:
WH[WƬOHVZHZDQWWRRSHQDQGWKHQZHQHHGWR
LPSRUWRVWLPH
open them for display in the Terminal.
RVV\VWHP ¶FOV·LIRVQDPH ¶QW·HOVH¶FOHDU·
ÀOHQDPHV >´W[Wµ´W[Wµ@
IUDPHV >@ ÀOHQDPHV >´W[Wµ´W[Wµ@
IUDPHV >@
IRUQDPHLQÀOHQDPHV
ZLWKRSHQ QDPH´UµHQFRGLQJ µXWIµ DVI IRUQDPHLQÀOHQDPHV
IUDPHVDSSHQG IUHDGOLQHV ZLWKRSHQ QDPH´UµHQFRGLQJ µXWIµ DVI
IUDPHVDSSHQG IUHDGOLQHV
IRULLQUDQJH
IRUIUDPHLQIUDPHV
SULQW ´µMRLQ IUDPH
WLPHVOHHS
RVV\VWHP ¶FOV·LIRVQDPH ¶QW·HOVH
¶FOHDU·
67(3 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
67(3 We’ve used the UTF8 standard when opening the WKH&/6FRPPDQGn(/6(oLI\RXoUHXVLQJ/LQX[RUD0DFWKH&OHDU
WH[WƬOHVDV$6&,,DUWDVWH[WZLWKLQDWH[WƬOH command will work correctly. If you want, you could use a Try/
RIWHQUHTXLUHV\RXWRVDYHWKHƬOHDV87)FRPSOLDQWsGXHWRWKH Except statement instead.
FKDUDFWHUVXVHG1RZZHFDQDGGDORRSWRGLVSOD\WKHƬOHVDVW[W
then 2.txt, creating the illusion of animation while clearing the
VFUHHQDIWHUHDFKƬOHLVGLVSOD\HG
67(3 Save the Python code in the same folder as the text 67(3 You can spice things up a little by adding system/
ƬOHVDQGGURSLQWRD7HUPLQDORU&RPPDQG3URPSW 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.SFOpublications.com 187
Coding Projects & Tips
Passing Variables
to Python
7+(:,1'2:6:$<
7KHWZRV\VWHPVXVHPRGHUDWHO\GLƪHUHQWZD\VWRDFFRPSOLVKWKHVDPHWDVN:LQGRZVLVVOLJKWO\HDVLHU E\DVLQJOHFRPPDQG
DQGVRZHoOOVWDUWWKHUH
67(3 Let’s begin by creating a sample folder within your 67(3 Now open Python, and create a New File. Enter the
Python directory; call it EDWS\, for example. Within following code:
WKHEDWS\IROGHUFUHDWHDQHZWH[WƬOHDQGHQWHUWKHIROORZLQJ
LPSRUWRV
#HFKRRII
Q RVHQYLURQ>¶QDPH·@
VHWSQDPH :KDWLV\RXUQDPH"
SULQW ´<RXUQDPHLV´Q
HFKR/HW·VWU\DQGSDVVWKLVWRD3\WKRQVFULSW
S\WKRQEDWS\S\
HFKR,WZRUNHG
67(3 We won’t go into the intricacies of Windows batch 67(3 Here we’re using the OS module that will utilise the
ƬOHVKHUH6XƯFHWRVD\WKLVFRGHZLOODVNIRUDXVHUoV system variables. When we create a variable in a
name, store the name as a variable called name, display a message, EDWFKƬOH RU%DVKVFULSW ZHoUHVWRULQJWKHFRQWHQWVRIWKHYDULDEOH
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
WKHƬOHDVDEDWFKƬOHFOLFN)LOH!6DYH$V, call it EDWS\EDW and set content of the command RVHQYLURQ. Os.environ is calling the
6DYH$V7\SH as $OO)LOHV. V\VWHPYDULDEOHnQDPHoZKLFKZHFUHDWHGLQWKHEDWFKƬOH6DYHWKH
code as EDWS\S\.
188 www.SFOpublications.com
Passing Variables to Python
7+(/,18;:$<
/LQX[oVYHUVLRQRISDVVLQJYDULDEOHVWR3\WKRQLVVOLJKWO\GLƪHUHQWMXVWEHFDXVHLWoV/LQX[,WoVHDV\WKRXJKDQGKHUHoVKRZ
LWoVGRQH
67(3 Start by opening your favourite Linux text editor, 67(3 1RZFUHDWHDQHZ3\WKRQƬOHDQGHQWHUWKHIROORZLQJ
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
67(3 Drop into a Terminal session and make a new 67(3 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 EDWS\VK, and from the Terminal enable the script as VDPHDVLQ:LQGRZV7KHPDMRUGLƪHUHQFHVDUHPDNLQJWKH%DVK
executable with: FKPRG[EDWS\VK. script executable, and adding the H[SRUWƬUVWQDPH command to
WKH%DVKƬOH,Q/LQX[\RXQHHGWRH[SRUWV\VWHPYDULDEOHVEHIRUH
they can be accessed by the subsystem, in this case the Python code.
www.SFOpublications.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
WKHEHJLQQHUWRƬQGWKHLUSURJUDPPLQJIHHW+RZHYHUDVZLWKDQ\RWKHUSURJUDPPLQJ
language, it can be easy to make common mistakes that’ll stop your code from running.
'()%(*,11(5Ǔ0,67$.(6 ǔ
+HUHDUHWHQFRPPRQ3\WKRQSURJUDPPLQJPLVWDNHVPRVWEHJLQQHUVƬQGWKHPVHOYHVPDNLQJ%HLQJDEOHWRLGHQWLI\WKHVH
PLVWDNHVZLOOVDYH\RXKHDGDFKHVLQWKHIXWXUH
9(56,216 ,1'(1767$%6$1'63$&(6
To add to the confusion that most beginners already face when Python uses precise indentations when displaying its code. The
coming into programming, Python has two live versions of its indents mean that the code in that section is a part of the previous
language available to download and use. There is Python version statement, and not something linked with another part of the code.
2.7.x and Python 3.6.x. The 3.6.x version is the most recent, and Use four spaces to create an indent, not the Tab key.
the one we’d recommend starting. But, version 2.7.x code doesn’t
always work with 3.6.x code and vice versa.
7+(,17(51(7 &200(17,1*
Every programmer has and does at some point go on the Internet Again we mention commenting. It’s a hugely important factor in
and copy some code to insert into their own routines. There’s programming, even if you’re the only one who is ever going to view
nothing wrong with using others’ code, but you need to know how the code, you need to add comments as to what’s going on. Is this
the code works and what it does before you go blindly running it on function where you lose a life? Write a comment and help you, or
your own computer. anyone else, see what’s going on.
190 www.SFOpublications.com
Python Beginner’s Mistakes
&2817,1*/2236 &2/216
Remember that in Python a loop doesn’t count the last number you It’s common for beginners to forget to add a colon to the end of a
specify in a range. So if you wanted the loop to count from 1 to 10, structural statement, such as:
then you will need to use:
FODVV+DQJPDQ
Q OLVW UDQJH GHIJXHVV VHOIOHWWHU
Which will return 1 to 10. And so on. The colon is what separates the code, and creates the
indents to which the following code belongs to.
&$6(6(16,7,9(
Python is a case sensitive programming language, so you will need
to check any variables you assign. For example, /LYHV is a
GLƪHUHQWYDULDEOHWROLYHV FDOOLQJWKHZURQJYDULDEOHLQ\RXUFRGH
can have unexpected results.
23(5$7256
Using the wrong operator is also a common mistake to make. When
you’re performing a comparison between two values, for example,
\RXQHHGWRXVHWKHHTXDOLW\RSHUDWRU DGRXEOHHTXDOV 8VLQJ
DVLQJOHHTXDO LVDQDVVLJQPHQWRSHUDWRUWKDWSODFHVDYDOXHWRD
YDULDEOH VXFKDVOLYHV
%5$&.(76
Everyone forgets to include that extra bracket they should have
added to the end of the statement. Python relies on the routine 23(5$7,1*6<67(06
having an equal amount of closed brackets to open brackets, so any
:ULWLQJFRGHIRUPXOWLSOHSODWIRUPVLVGLƯFXOWHVSHFLDOO\ZKHQ\RX
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.SFOpublications.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
$QLPPXWDEOHƮRDWLQJSRLQWQXPEHUXVHGLQ3\WKRQ
Block
Used to describe a section or sections of code that are Function
grouped together. 8VHGLQ3\WKRQWRGHƬQHDVHTXHQFHRIVWDWHPHQWVWKDWFDQEH
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
FDQEHVLQJOHOLQHRUPXOWLOLQHDQGDUHGHƬQHGE\DRUnoo
program in question.
Debian GUI
A Linux-based distro or distribution that forms the Debian Project.
Graphical User Interface. The interface which most modern
7KLVHQYLURQPHQWRƪHUVWKHXVHUDIULHQGO\DQGVWDEOH*8,WR
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
8VHGWRGHƬQHDIXQFWLRQRUPHWKRGLQ3\WKRQ
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
FRUHEXWRƪHUVVRPHWKLQJGLƪHUHQWLQLWVSUHVHQWDWLRQWRWKHHQGXVHU 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
8VHGDVDPHDQVRIEUHDNLQJIURPWKHQRUPDOƮRZRIDFRGHEORFNLQ 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.SFOpublications.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, $IXQFWLRQWKDWXVHGWRUHWXUQDOLVWRILQWHJHUVGHƬQHGE\WKH
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.
RIDQ\W\SHDQGFDQUHDGLO\EHPRGLƬHG
Strings
Local Variable 6WULQJVFDQVWRUHFKDUDFWHUVWKDWFDQEHPRGLƬHG7KHFRQWHQWVRI
$YDULDEOHWKDWoVGHƬQHGLQVLGHDIXQFWLRQDQGLVRQO\XVHDEOHLQVLGH 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
FDQH[HFXWHFRGHDQGQDYLJDWHWKHƬOHV\VWHP
Module
$3\WKRQƬOHWKDWFRQWDLQVYDULRXVIXQFWLRQVWKDWFDQEHXVHGZLWKLQ Tkinter
DQRWKHUSURJUDPWRIXUWKHUH[WHQGWKHHƪHFWLYHQHVVRIWKHFRGH A Python module designed to interact with the graphical
HQYLURQPHQWVSHFLƬFDOO\WKHWN*8, 7RRO.LW*UDSKLFDO8VHU
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 $PXOWLWDVNLQJPXOWLXVHURSHUDWLQJV\VWHPGHVLJQHGLQWKHnVDW
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
JUDSKLFVDQGVRXQGOLEUDULHVDQGZDVƬUVWGHYHORSHGLQ When you enter: LPSRUWWKLV into the IDLE, the Zen of Python
October 2000. is displayed.
www.SFOpublications.com 193
ad The Complete
Re Manual Series
Available on
NOTE: This is a limited reader offer running from 1st J˨˟y 2023 to 1st ʷ˘˖ember 2023.
Terms and conditions apply and can be found at www.pclpublications.com
Want to master your Coding?
Then don’t miss our NEW Programming
magazine on digital platforms NOW!