0% found this document useful (0 votes)
987 views

The Complete Python Coding Manual - 3rd Edition, 2023

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
987 views

The Complete Python Coding Manual - 3rd Edition, 2023

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 196

MASTER PYTHON PROGRAMMING


The Complete

Coding Manual
The essential manual for improving
your Python programming skills

OVER

820GUIDES
&TIPS

www.pclpublications.com 100% INDEPENDENT


ad The Complete
Re Manual Series
Available on

For a full list of titles available please visit:


www.pclpublications.com
The Complete

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.

Whether you’re looking to learn Python for future career prospects, or


just have some fun and discover something new, our step-by-step
tutorials and guides will give you that much-needed foothold to help
you on your way.

So let’s dive in and start coding with Python.

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

Welcome to Python 70 Dictionaries


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

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

Where to start learning how to code?


5HPDUNDEO\WKLVLVWKHPRVWGLƯFXOW
step. There are plenty of programming
ODQJXDJHVRXWWKHUHDQGDVHHPLQJO\
XQOLPLWHGQXPEHURIWRROVWRKHOS\RX
DFKLHYHZKDW\RXZDQWEXWZKHUHGR
\RXEHJLQ"
,QWKLVVHFWLRQZHORRNDWZKDW\RXZLOO
QHHGWRWDNHWKRVHƬUVWWHQWDWLYHVWHSV
LQWRWKHZRUOGRIFRGLQJ<RXZRQoW
VXGGHQO\EHFRPHDSURJUDPPHULQ
WZHQW\IRXUKRXUVOHDUQLQJKRZWRFRGH
SURSHUO\WDNHVWLPHDQGSDWLHQFH%XW
ZLWKDOLWWOHKHOS\RXFDQPDVWHUWKH
EDVLFVDQGVWDUW\RXUFRGLQJMRXUQH\

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

MORE THAN CODE


For those of you old enough to remember the ‘80s, the golden era of home
FRPSXWLQJWKHZRUOGRIFRPSXWLQJZDVDYHU\GLƪHUHQWVFHQHWRKRZLWLV
today. 8-bit computers that you could purchase as a whole, as opposed to
EHLQJLQNLWIRUPDQG\RXKDYLQJWRVROGHUWKHSDUWVWRJHWKHUZHUHWKHVWXƪ
of dreams; and getting your hands on one was sheer bliss contained within
a large plastic box. However, it wasn’t so much the new technology that
FRPSXWHUVWKHQRƪHUHGPRUHRYHULWZDVWKHIDFWWKDWIRUWKHƬUVWWLPH
ever, you could control what was being viewed on the ‘television’.

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


Times have changed since programming in the ‘80s, time, many users decided they wanted to create their own content, their
EXWWKHFRUHYDOXHVVWLOOUHPDLQ own games; or simply something that could help them with their homework
RUKRPHƬQDQFHV7KHVLPSOLFLW\RIWKHELWKRPHFRPSXWHUPHDQWWKDW

“It’s up to you
creating something from a few lines of BASIC code was achievable and so
WKHƬUVWJHQHUDWLRQRIKRPHEUHGSURJUDPPHUZDVERUQ

how far to take


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

your coding
game. This of course led to the programmer becoming more than simply
someone who could fashion a sprite on the screen and make it move at the
press of a key.

adventure!” Naturally, time has moved on and with it the technology that we use.
However, the fundamentals of programming remain the same; but what
exactly does it take to be a programmer?

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


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

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


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

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

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


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

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


learning the actual code itself. However, with time, patience and the
determination to learn, anyone can become a programmer. Whether
Being able to follow a logical pattern and you want to be part of a triple-A video game team or simply create an
VHHDQHQGUHVXOWLVRQHRIWKHPRVWYDOXHG automated routine to make your computing life easier, it’s up to you how
skills of a programmer. far to take your coding adventure!

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

A Brief History of Coding


It’s easy to think that programming a machine to automate a process or calculate a value
LVDPRGHUQFRQFHSWWKDWoVRQO\UHDOO\KDSSHQHGLQWKHODVWƬIW\\HDUVRUVR+RZHYHU
that assumption is quite wrong, coding has actually been around for quite some time.

01000011 01101111 01100100 01100101


(VVHQWLDOO\DOOIRUPVRIFRGLQJDUHPDGHXSRIRQHVDQG]HURVRQRURƪVWDWHV7KLVZRUNV
IRUDPRGHUQFRPSXWHUDQGHYHQWKHROGHVWNQRZQFRPSXWDWLRQDOGHYLFH

~87 BC a$' 1800 Ǖ Ǖ

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

Ada Lovelace translated


the memoirs of the Italian
mathematician, Francis
Maneclang, regarding
Charles Babbage’s
Analytical Engine. She
made copious notes within
her writing, detailing a
7KH%DQŅ0ŅVÜEURWKHUVWKUHH3HUVLDQ method of calculating
scholars who worked in the House of Bernoulli Numbers
Wisdom in Baghdad, published the using the engine. This is
Book of Ingenious Devices in around UHFRJQLVHGDVWKHƬUVW
850 AD. Among the inventions listed computer program. Not
was a mechanical musical instrument: bad, considering there
a hydro-powered organ that played were no computers
interchangeable cylinders automatically. available at the time.

10 www.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.

Ǖ  Ǖ Ǖ 1990s-Present Day

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

The Internet age brought a wealth of new


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

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.

JAVASCRIPT JavaScript (often shortened to JS) is a lightweight,


LQWHUSUHWHGREMHFWRULHQWHGODQJXDJHZLWKƬUVWFODVV
functions. JavaScript runs on the client side of the web, that can be used to design
or program how the web pages behave on the occurrence of an event. JavaScript is
an easy to learn and also powerful scripting language, widely used for controlling
web page behaviour.

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

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


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

PYTHON Python is a widely used high level programming language used


for general purpose programming, created by Guido van
5RVVXPDQGƬUVWUHOHDVHGLQ$QLQWHUSUHWHGODQJXDJH3\WKRQKDVDGHVLJQ
philosophy that emphasises code readability and a syntax that allows programmers
to express concepts in fewer lines of code. This can make it easier for new
programmers to learn.

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


language. It has imperative, object-oriented and generic programming
features. It was designed with a bias toward system programming and embedded,
UHVRXUFHFRQVWUDLQHGDQGODUJHV\VWHPVZLWKSHUIRUPDQFHHƯFLHQF\DQGƮH[LELOLW\
of use as its design highlights.

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


Matsumoto, blended parts of his favourite languages (Perl,
6PDOOWDON(LƪHO$GDDQG/LVS WRIRUPDQHZODQJXDJH)URPLWVUHOHDVHLQ
5XE\KDVGUDZQGHYRWHGFRGHUVZRUOGZLGH5XE\LVVHHQDVDƮH[LEOHODQJXDJH
HVVHQWLDOSDUWVRI5XE\FDQEHUHPRYHGRUUHGHƬQHGDWZLOO([LVWLQJSDUWVFDQEH
added to.

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


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

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


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

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

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


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

The trick is to slow down and, to begin with, not look too deeply
into coding. Like all good projects, you need a solid foundation
on which to build your skill and to have all the necessary tools
available to hand to enable you to complete the basic steps. This
is where creating a coding platform comes in, as it will be your
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

OPERATING SYSTEMS VIRTUAL MACHINES


Windows 10 is the most A virtual machine is a piece of software that allows you to install a
used operating system in IXOO\ZRUNLQJRSHUDWLQJV\VWHPZLWKLQWKHFRQƬQHVRIWKHVRIWZDUH
the world, so it’s natural LWVHOI7KHLQVWDOOHG26ZLOODOORFDWHXVHUGHƬQHGUHVRXUFHVIURPWKH
WKDWWKHYDVWPDMRULW\RI host computer, providing memory, hard drive space etc, as well as
coding tools are written for Microsoft’s leading operating sharing the host computer’s Internet connection.
system. However, don’t discount macOS and especially Linux.
The advantage of a virtual
PDF26XVHUVHQMR\DQHTXDOQXPEHURIFRGLQJWRROVWRWKHLU machine is that you can work
:LQGRZVFRXQWHUSDUWV,QIDFW\RXZLOOSUREDEO\ƬQGWKDWD with Linux, for example, without
lot of professional coders use a Mac over a PC, simply because LWDƪHFWLQJ\RXUFXUUHQWO\
of the fact that the Mac operating system is built on top of installed host OS. This means
Unix (the command-line OS that powers much of the world’s that you can have Windows 10
ƬOHV\VWHPVDQGVHUYHUV 7KLV8QL[OD\HUOHWV\RXWHVWSURJUDPV running, launch your virtual machine client, boot into Linux and use
in almost any language without using a specialised IDE. all the functionality of Linux while still being able to use Windows.

Linux, however, is by far one of the most popular and This, of course, makes it a fantastic coding platform, as you can
important, coding operating systems available. Not only 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”)

Using Virtual Machines


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

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 itself, is an app that will allow you to install a


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

The Hypervisor will take resources from the host system - your
physical computer, to create the virtual computer. This means that
part of your physical computer’s: memory, CPU, hard drive space
and other shared resources, will be set aside for use in the virtual <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.

This resource overhead


VIRTUAL OS
can be crippling for the )URPZLWKLQDK\SHUYLVRU\RXoUHDEOHWRUXQDQXPEHURIGLƪHUHQW
physical machine if you operating systems. The type of OS depends greatly on the
don’t already have enough hypervisor you’re running, as some are better at emulating a
memory, or hard drive particular system over others. For example, VirtualBox, a free and
space available, or your easy to use hypervisor from Oracle, is great at running Windows
computer has a particularly and Linux virtual machines, but isn’t so good at Android or macOS.
slow processor. While it’s QEMU is good for emulating ARM processors, therefore ideal for
entirely possible to run $QGURLGDQGVXFKEXWLWFDQEHGLƯFXOWWRPDVWHU
virtual machines on as little
as 2GB of memory, it’s not There are plenty of hypervisors available to try for free, with an
advisable. Ideally, you will HTXDODPRXQWFRPPHUFLDOO\DYDLODEOHWKDWDUHVLJQLƬFDQWO\PRUH
need a minimum of 8GB SRZHUIXODQGRƪHUEHWWHUIHDWXUHV+RZHYHUIRUPRVWXVHUVERWK
of memory (you can get EHJLQQHUDQGSURIHVVLRQDO9LUWXDO%R[GRHVDJRRGHQRXJKMRE
away with 4GB, but again,
your physical computer Within a hypervisor, you’re able to set up and install any of the
ZLOOEHJLQWRVXƪHUZLWK newer distributions of Linux, or if you feel the need, you’re also able
the loss of memory to the to install some of the more antiquated versions. You can install early
virtual machine), at least 25 versions of Windows, even as far back as Windows 3 complete with
to 50GB of free space on '26sDOWKRXJK\RXPD\ƬQGVRPHIXQFWLRQDOLW\RIWKH90ORVW
your hard drive and a quad- due to the older drivers (such as access to the network).
core processor (again, you
can have a dual-core CPU, With this in mind then, you’re able to have an installation of Linux
but that can cause a bottleneck on your physical computer). Mint, or the latest version of Ubuntu, running in an app on your
Windows 10 PC. This is the beauty of using a virtual machine.
7KHOLPLWWRKRZPDQ\GLƪHUHQWYLUWXDOPDFKLQHV\RXKRVWRQ\RXU Conversely, if your physical computer has Linux as its installed
physical computer is restricted, therefore, by the amount of physical operating system, then with a hypervisor you’re able to create a
system resources you can allocate to each, while still leaving enough Windows 10 virtual machine – although you will need to have a
for your physical computer to operate on. licence code available to register and activate Windows 10.

16 www.SFOpublications.com
Using Virtual Machines

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


is having two, or more, physical operating systems installed on
ADVANTAGES FOR CODERS
the same, or multiple, hard drives on a single computer. As the )RUWKHFRGHUKDYLQJDYLUWXDOPDFKLQHVHWXSRƪHUVPDQ\
computer powers up, you’re given the option to choose which OS advantages, the most popular being cross-platform code. Meaning if
you want to boot into. While this sounds like a more ideal scenario you write code within Windows 10, then with an installation of a
it isn’t always as straight forward as it sounds, as all the operating /LQX[GLVWURLQDK\SHUYLVRU\RXoUHDEOHWRTXLFNO\DQGHƪRUWOHVVO\
systems that are booted into will have full access to the computer’s power up the virtual machine and test your code in a completely
entire system resources. GLƪHUHQWRSHUDWLQJV\VWHP)URPWKLV\RXoUHDEOHWRLURQRXWDQ\
EXJVWZHDNWKHFRGHVRLWZRUNVEHWWHURQDGLƪHUHQWSODWIRUPDQG
The problems with dual-booting come when one of the operating expand the reach of your code to non-Windows users.
systems is updated. Most updates cover security patching, or bug
Ƭ[LQJKRZHYHUVRPHXSGDWHVFDQDOWHUWKHFRUHWKHNHUQHORI 7KHDGYDQWDJHRIEHLQJDEOHWRFRQƬJXUHDGHYHORSPHQW
the OS. When these changes are applied, the update may alter the HQYLURQPHQWLQVSHFLƬFZD\VIRUVSHFLƬFSURMHFWVLVTXLWH
way in which the OS starts up, meaning the initial boot choice you invaluable. Using a virtual machine setup greatly reduces the
made could be overwritten, leaving you without the ability to access uncertainties that are inherent to having multiple versions of
the other operating systems installed on the computer. To rectify programming languages, libraries, IDEs and modules installed, to
this, you’ll need to access the Master Boot Record and alter the VXSSRUWWKHPDQ\GLƪHUHQWSURMHFWV\RXPD\EHFRPHLQYROYHGLQDV
FRQƬJXUDWLRQWRUHDOORZERRWLQJLQWRWKHRWKHUV\VWHPV7KHUHoV DFRGHU(OHPHQWVRIFRGHWKDWnWDONoGLUHFWO\WRVSHFLƬFVRIDQ
DOVRWKHGDQJHURISRVVLEO\RYHUZULWLQJWKHƬUVWLQVWDOOHG26RU operating system can easily be overcome, without the need to
overwriting data and more often than not, most operating systems clutter up your main, host system with cross-platform libraries,
don’t play well when running side-by-side. Indeed, while good, dual- ZKLFKLQWXUQPD\KDYHDQDƪHFWRQRWKHUOLEUDULHVZLWKLQWKH,'(
booting has more than its fair share of problems. In contrast, using a
virtual machine environment, while still problematic at times, takes Another element to consider is stability. If you’re writing code that
out some of the more nasty and disastrous aspects of using multiple could potentially cause some instability to the core OS during its
operating systems on a single computer. development phase, then executing and testing that code on a
virtual machine makes more sense than testing it on your main
computer; where having to repeatedly reboot, or reset something
(YHQROGRSHUDWLQJV\VWHPVFDQEHUXQLQVLGHD
due to the code’s
YLUWXDOPDFKLQH
instabilities, can
become
LQHƯFLHQWDQG
MXVWSODLQ
annoying.

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

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


our Linux titles, KWWSVSFOSXEOLFDWLRQVFRP to learn how to
install Linux in a virtual environment and how best to utilise the
operating system.

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.

TIME AND PATIENCE


Despite what other books may lead you to believe, you won’t become a programmer
in 24-hours. Learning to code in Python takes time, and patience. You may become
VWXFNDWWLPHVDQGRWKHUWLPHVWKHFRGHZLOOƮRZOLNHZDWHU8QGHUVWDQG\RXoUHOHDUQLQJ
something entirely new, and you will get there.

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

Python is a fantastic programming


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

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

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

BASIC was once the starter language that early


8-bit home computer users learned.

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

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


and makes for an ideal beginner’s programming language.

www.SFOpublications.com 23
Welcome to Python

What can You


Do with Python?
3\WKRQLVDQRSHQVRXUFHREMHFWRULHQWHGSURJUDPPLQJODQJXDJHWKDWoVVLPSOHWR
XQGHUVWDQGDQGZULWHZLWK\HWDOVRSRZHUIXODQGH[WUHPHO\PDOOHDEOH,WoVWKHVH
FKDUDFWHULVWLFVWKDWKHOSPDNHLWVXFKDQLPSRUWDQWODQJXDJHWROHDUQ

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.

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


WEB DEVELOPMENT Playing Games) available utilise Python as a companion language for
the server-side elements. These include: code to search for potential
cheating, load balancing across the game’s servers, player skill
:HEGHYHORSPHQWKDVPRYHGRQFRQVLGHUDEO\VLQFHWKHHDUO\
matchmaking and to check whether the player’s client-side game
GD\VRI+70/VFULSWLQJLQDOLPLWHGWH[WHGLWRU7KHPDQ\
matches the server’s versions. There’s also a Python module that
IUDPHZRUNVDQGZHEPDQDJHPHQWVHUYLFHVDYDLODEOHQRZ
can be included in a Minecraft server, enabling the server admin to
PHDQVWKDWEXLOGLQJDSDJHKDVEHFRPHLQFUHDVLQJO\FRPSOH[
add blocks, send messages and automate a lot of the background
complexities of the game.
:LWK3\WKRQWKHZHEGHYHORSHUKDVWKHDELOLW\WRFUHDWH
G\QDPLFDQGKLJKO\VHFXUHZHEDSSVHQDEOLQJLQWHUDFWLRQZLWK
RWKHUZHEVHUYLFHVDQGDSSVVXFKDV,QVWDJUDPDQG3LQWHUHVW
3\WKRQDOVRDOORZVWKHFROOHFWLRQRIGDWDIURPRWKHUZHEVLWHV
DQGHYHQDSSVEXLOWZLWKLQRWKHUZHEVLWHV
PYTHON EVERYWHERE
As you can see, Python is quite a versatile
programming language. By learning Python,
you are creating a well-rounded skillset that’s
able to take you into the next generation of
computing, either professionally or simply as
a hobbyist.

Whatever route you decide to take on your


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

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

Alexa, Amazon’s Virtual Data analysis and


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

in PYTHON AND
LINUX SKILLS
N UMBERS

As of the end of 20,


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

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


RECOMMENDED FACEBOOK POSTS THAT OVER 75% OF
CONTENT FROM NETFLIX ARE FILTERED NASA’S WORKFLOW
IS GENERATED FROM 7+528*+3<7+21Ǖ AUTOMATION
0$&+,1(/($51,1*ǟ CODED MACHINE 6<67(0621Ǖ%2$5'
CODED BY PYTHON. LEARNING. THE I.S.S. USE PYTHON.

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.

Python developers enjoy an average salary of

£60,000

95% OF ALL BEGINNER 75% OF ALL PYTHON 79% OF ALL 49% OF WINDOWS
CODERS START WITH DEVELOPERS USE PROGRAMMERS 10 DEVELOPERS
AND STILL USE, PYTHON 3, WHEREAS USE PYTHON USE PYTHON 3
PYTHON AS THEIR 25% STILL USE THE REGULARLY, 21% USE AS THEIR MAIN
PRIMARY OR OUTDATED PYTHON 2 IT AS A SECONDARY PROGRAMMING
SECONDARY LANGUAGE. VERSION. LANGUAGE. LANGUAGE.

www.SFOpublications.com 27
Welcome to Python

How to Set Up
Python in Windows
:LQGRZVXVHUVFDQHDVLO\LQVWDOOWKHODWHVWYHUVLRQRI3\WKRQYLDWKHPDLQ3\WKRQ
'RZQORDGVSDJH:KLOVWPRVWVHDVRQHG3\WKRQGHYHORSHUVPD\VKXQ:LQGRZVDVWKH
SODWIRUPRIFKRLFHIRUEXLOGLQJWKHLUFRGHLWoVVWLOODQLGHDOVWDUWLQJSRLQWIRUEHJLQQHUV

INSTALLING PYTHON 3.X


Microsoft Windows doesn’t come with Python preinstalled as standard, so you’re going to have to install it yourself manually.
Thankfully, it’s an easy process to follow.

STEP 1 Start by opening your web browser to www.python. STEP 3 Choosing the Customise option allows you to
org/downloads/. Look for the button detailing the specify certain parameters, and whilst you may
download link for Python 3.x. Python is regularly updated, changing stay with the defaults, it’s a good habit to adopt as sometimes (not
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.

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


much the same way as the Shell you opened in
Windows 10 users can now Step 8; note the three left-facing arrows (>>>). Whilst it’s a perfectly
ƬQGWKHLQVWDOOHG3\WKRQ ƬQHHQYLURQPHQWLWoVQRWWRRXVHUIULHQGO\VROHDYHWKHFRPPDQG
3.x within the Start button line for now. Enter: exit() to leave and close the Command
Recently Added section. Prompt window.
7KHƬUVWOLQN3\WKRQ
(32-bit) will launch the
command line version of
Python when clicked (more
on that in a moment). To
open the IDLE, type IDLE
into Windows start.

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

Next, enter: python --version into the Terminal


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

However, if you want the latest, cutting edge


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

30 www.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

In the Terminal, go to the Downloads folder


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

Within the Python folder, enter:


STEP 8
FRQÀJXUH
sudo make altinstall
This could take a while, depending on the speed of your computer.
2QFHƬQLVKHGHQWHUpython3.7 --version to check the latest
installed version. You now have Python 3.7 installed, alongside older
Python 3.x.x and Python 2.

PYTHON ON macOS
Installation of Python on macOS can be done in much the
same way as the Windows installation. Simply go to the Python
webpage, hover your mouse pointer over the Downloads
link and select Mac OS X from the options. You will then be
guided to the Python releases for Mac versions, along with the
necessary installers for macOS 64-bit for OS X 10.9 and later.

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

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


RƪHUDIHZXSGDWHV$OWKRXJKRQWKHZKROHLWoVYHU\VLPLODULQ
appearance and operation to the previous version of Raspbian. The
XSGDWHVDUHPDLQO\LQOLQHZLWKWKH.oVGLVSOD\DQGSOD\EDFNJLYLQJWKH
Pi 4 a new set of graphical drivers and performance enhancements.

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

PYTHON PROGRAMMING RECIPES


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

PROGRAM COMMANDS
You might not understand some of the Python commands, like bowl.append and cake.cook(bowl).
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

+,*+Ǖ/(9(//$1*8$*(6 ZEN OF PYTHON


Computer languages that are easy to read are known as “high-level”. Python lets you access all the power of a computer in a language
7KLVLVEHFDXVHWKH\Ʈ\KLJKDERYHWKHKDUGZDUH DOVRUHIHUUHGWRDV that humans can understand. Behind all this is an ethos called “The
pWKHPHWDOq /DQJXDJHVWKDWpƮ\FORVHWRWKHPHWDOqOLNH$VVHPEO\ Zen of Python.” This is a collection of 20 software principles that
are known as “low-level”. Low-level languages commands read a bit LQƮXHQFHVWKHGHVLJQRIWKHODQJXDJH3ULQFLSOHVLQFOXGHp%HDXWLIXO
like this: PVJGE[DOHQHTXPVJ. is better than ugly” and “Simple is better than complex.” Type
import this into Python and it will display all the principles.

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

WORLD OF PYTHON Python 3.7 is the newest release PYTHON 3.X ,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

PYTHON 2.X 6RZK\WZR":HOO3\WKRQZDVRULJLQDOO\ 3.X WINS 3\WKRQoVJURZLQJSRSXODULW\KDVPHDQWWKDW


ODXQFKHGLQDQGKDVVLQFHWKHQ LWoVQRZSUXGHQWWRVWDUWOHDUQLQJWRGHYHORS
DGRSWHGTXLWHDODUJHFROOHFWLRQRIPRGXOHVVFULSWVXVHUVWXWRULDOV ZLWKWKHQHZIHDWXUHVDQGEHJLQWRSKDVHRXWWKHSUHYLRXVYHUVLRQ
DQGVRRQ2YHUWKH\HDUV3\WKRQKDVIDVWEHFRPHRQHRIWKHƬUVW 0DQ\GHYHORSPHQWFRPSDQLHVVXFKDV6SDFH;DQG1$6$XVH
JRWRSURJUDPPLQJODQJXDJHVIRUEHJLQQHUVDQGH[SHUWVWRFRGH 3\WKRQIRUVQLSSHWVRILPSRUWDQWFRGH
LQZKLFKPDNHVLWDQH[WUHPHO\YDOXDEOHUHVRXUFH

www.bdmpublications.com 35
Index

36 www.SFOpublications.com
First Steps into Python

Now that you have the latest version of


Python installed, you can begin to get
SURJUDPPLQJ7KHVHDUH\RXUƬUVWVWHSVLQ
the wider world of Python and we’re here
WRKHOS\RXZULWH\RXUƬUVWSLHFHRIFRGH
save it, and run it in the Python IDLE Shell.
We cover variables, numbers and
expressions, user input, conditions and
loops, and the types of errors you will
undoubtedly come across in your time
with Python. Let’s start and see how to
get coding.

38 Starting Python for the First Time


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

www.SFOpublications.com 37
First Steps into Python

Starting Python for


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

STARTING PYTHON
As when learning anything new, you need to start slow. You can pick up the pace as your experience grows, but for now, let’s
just get something appearing on the screen. Don’t worry, you’ll soon be coding like a pro!

STEP 1 Click on the Windows Start button, and start typing STEP 3 For example, in the Shell enter: 2+2
‘idle’. The result will be the currently installed After pressing Enter, the next line will display the
version of Python, IDLE (Python 3.7 32-bit), for example. You can answer: 4. Basically, Python has taken the ‘code’ and produced the
Pin it to the Start for convenience, otherwise simply click the icon to relevant output.
launch the Python Shell.

STEP 2 The Shell is where you can enter code and see the STEP 4 The Python Shell acts very much like a calculator,
responses and output of code you’ve programmed since code is basically a series of mathematical
into Python. This is a kind of sandbox, if you will, where you’re able 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

Your First Code


(VVHQWLDOO\\RXoYHDOUHDG\ZULWWHQ\RXUƬUVWSLHFHRIFRGHZLWKWKHSULQW p+HOOR
HYHU\RQHq IXQFWLRQIURPWKHSUHYLRXVWXWRULDO+RZHYHUOHWoVH[SDQGWKDWDQGORRNDW
entering your code and playing around with some other Python examples.

PLAYING WITH PYTHON


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

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

STEP 7 <RXFDQSOD\DURXQGZLWKGLƪHUHQWNLQGVRIYDULDEOHV STEP 10 In Python 3 we can separate the two variables


together with the Print function. For example, we with a space by using a comma:
could assign variables for someone’s name:
print(name, surname)
name=”David”
Alternatively, you can add the space yourself:
print(name)
print(name+” “+surname)
As you can see, the use of the comma is much neater.
&RQJUDWXODWLRQV\RXoYHMXVWWDNHQ\RXUƬUVWVWHSVLQWRWKHZLGH
world of Python,

www.SFOpublications.com 41
First Steps into Python

Saving and Executing


Your Code
:KLOHZRUNLQJLQWKH,'/(6KHOOLVSHUIHFWO\ƬQHIRUVQLSSHWVRIFRGHLWoVQRWGHVLJQHG
for entering longer program listings. In this section, we’ll introduce you to the IDLE
Editor, where most of our code will be entered from now on.

EDITING CODE
You will eventually reach a point where you have to move on from inputting single lines of code into the Shell. Instead, the
IDLE Editor will allow you to save and execute your Python code.

STEP 1 First, open the Python IDLE Shell. When it’s up, click STEP 3 As you can see the same colour coding is in place in
on File > New File, this will open a new window with the IDLE Editor as it is in the Shell, enabling you to
Untitled as its name. This is the Python IDLE Editor, and within it, you better understand what’s going on with your code. To execute the
can enter the code you need to create your future programs. 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.

STEP 7 ,I\RXRSHQWKHƬOHORFDWLRQRIWKHVDYHG3\WKRQ STEP 10 1RZFUHDWHDQHZƬOH&ORVHWKH(GLWRUDQGRSHQ


code, you’ll notice that it ends in a .py extension. a new instance (File > New File from the Shell).
7KLVLVWKHGHIDXOW3\WKRQƬOHQDPHDQ\FRGH\RXFUHDWHZLOOEH Enter the following, and save it as hello.py:
whatever.py, and any code downloaded from the many Internet
a=”Python”
Python resource sites will be .py. Just ensure that the code is written
b=”is”
for Python 3.
c=”cool!”
print(a, b, c)
We will use this code in the next tutorial.

www.SFOpublications.com 43
First Steps into Python

Executing Code from


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

COMMAND THE CODE


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

STEP 1 :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)

DIFFERENT VERSIONS OF PYTHON


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

www.SFOpublications.com 45
First Steps into Python

Numbers and Expressions


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

IT’S ALL MATHS, MAN


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

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

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


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

46 www.SFOpublications.com
Numbers and Expressions

STEP 5 You can also use STEP 8 This will be


an operation to displayed as
see the remainder left over from ‘0b11’, converting the integer
division. For example: LQWRELQDU\DQGDGGLQJWKHSUHƬ[
0b to the front. If you want to
10/3
UHPRYHWKHESUHƬ[WKHQ\RX
will display 3.333333333, which can use:
is, of course, 3.3-recurring. If you
format(3, ‘b’)
now enter:
The Format command converts
10%3
a value, the number 3, to a
This will display 1, which is the formatted representation
remainder left over from dividing as controlled by the format
10 by 3. VSHFLƬFDWLRQWKHnEoSDUW

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


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

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

Working with Variables


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

VARIOUS VARIABLES
We’ll be working with the Python 3 IDLE Shell in this tutorial. If you haven’t already, open Python 3 or close down the previous
IDLE Shell to clear up any old code.

STEP 1 In some programming languages, you’re required STEP 3 As we’ve seen previously, variables can be
to use a dollar sign to denote a string, which is a concatenated using the plus symbol between the
variable made up of multiple characters, such as a name of a person. variable names. In our example, we can use: print (name + “:
In Python this isn’t necessary, so, for example, in the Shell enter: “ + title). The middle part, between the quotations, allows
name=”David Hayward” (use your own name, unless you’re also us to add a colon and a space. As variables are connected without
called David Hayward). spaces, we need to add them manually.

STEP 2 You can check the type of variable in use by issuing STEP 4 We can also
the type () command, placing the name of the combine variables
variable inside the brackets. In our example, this would be: within another variable. For
type (name). Add a new string variable: title=”Descended example, to combine both name
from Celts”. and title variables into a new
variable, we use:
character=name + “: “ +
title
Then output the content of the
new variable as:
print (character)
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.

STEP 7 Another example of TypeCasting is when you ask STEP 10 :KHQFRPELQLQJLQWHJHUVDQGƮRDWV3\WKRQ


for input from the user, such as a number. for XVXDOO\FRQYHUWVWKHLQWHJHUWRDƮRDWEXWVKRXOG
example, enter: the reverse ever be applied, it’s worth remembering that Python
GRHVQoWUHWXUQWKHH[DFWYDOXH:KHQFRQYHUWLQJDƮRDWWRDQ
age= input (“How old are you? “)
integer, Python will always round down to the nearest integer,
All data stored from the Input command is stored as a string variable. called truncating; in our case instead of 19.99, it becomes 19.

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

Conditions and Loops


Conditions and loops are what make a program interesting, they can be simple or rather
FRPSOH[+RZ\RXXVHWKHPGHSHQGVJUHDWO\RQZKDWWKHSURJUDPLVWU\LQJWRDFKLHYH
they could be the number of lives left in a game, or just displaying a countdown.

TRUE CONDITIONS
Keeping conditions simple, to begin with, makes learning to program a more enjoyable experience. Let’s start then by
checking if something is TRUE, then doing something else if it isn’t.

STEP 1 Let’s create a new Python program that will ask the STEP 3 Now we’ll use an if statement to check if the word_
user to input a word, then check it to see if it’s a length variable is equal to four, and print a friendly
four-letter word or not. Start with File > New File, and begin with conformation if it applies to the rule:
the input variable:
word=input(“Please enter a four-letter word: “)
word=input(“Please enter a four-letter word: “) word_length=len(word)
if word_length == 4:
SULQW ZRUG´LVDIRXUOHWWHUZRUG:HOOGRQHµ
The double equal sign (==) check if something is equal to
something else.

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

56 www.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 1 &RGHLVQoWDVƮXLGDVWKHZULWWHQZRUGQRPDWWHU STEP 3 Thankfully Python is helpful when it comes to


how good the programming language is. Python is displaying error messages. When you receive an
certainly easier than most languages, but even it is prone to some HUURULQUHGLQNIURPWKH,'/(6KHOOLWZLOOGHƬQHWKHHUURULWVHOI
annoying bugs. The most common are typos by the user, and while along with the line number where the error has occurred. While in
HDV\WRƬQGLQVLPSOHGR]HQOLQHFRGHLPDJLQHKDYLQJWRGHEXJ the IDLE Editor this is a little daunting for lots of code, text editors
multi-thousand line code. help by including line numbering.

STEP 2 As we’ve mentioned, the most common of errors is STEP 4 Syntax errors are probably the second most
the typo, often at the command level, mistyping the common errors you’ll come across as a programmer.
print command for example. However, they also occur when you’ve Even if the spelling is correct, the actual command itself is wrong. In
got numerous variables, all of which have lengthy names. The best Python 3 this often occurs when Python 2 syntaxes are applied. The
advice is to simply go through the code and check your spelling. most annoying of these is the print function. In Python 3, we use
print(“words”), whereas Python2 uses print “words”.

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


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

STEP 3 Now we can insert the Pi calculation algorithm numberofdigits = int(input(“please enter the
part of the code. This is a version of the number of decimal place to calculate Pi to: “))
Chudnovsky Algorithm: getcontext().prec = numberofdigits
def calc(n):
t = Decimal(0)
pi = Decimal(0)
deno = Decimal(0)
k = 0
for k in range(n):
t = (Decimal(-1)**k)*(math.
factorial(Decimal(6)*k))*(13591409+545140134*k)
deno = math.factorial(3*k)*(math.
factorial(k)**Decimal(3))*(640320**(3*k))
pi += Decimal(t)/Decimal(deno)
pi = pi * Decimal(12)/
Decimal(640320**Decimal(1.5))
pi = 1/pi
return str(pi)

62 www.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

STEP 10 7RƬQLVKRXUFRGHZHQHHGWRLQLWLDOLVHWKH t = Decimal(0)


colorama module, and then start the time function pi = Decimal(0)
DWWKHSRLQWZKHUHWKHFDOFXODWLRQVWDUWVDQGZKHQLWƬQLVKHV7KH deno = Decimal(0)
end result displays, in coloured ink, how long the process took (in k = 0
the Terminal or command line): for k in range(n):
t = (Decimal(-1)**k)*(math.
from decimal import Decimal, getcontext
factorial(Decimal(6)*k))*(13591409+545140134*k)
import math
deno = math.factorial(3*k)*(math.
import time
factorial(k)**Decimal(3))*(640320**(3*k))
import colorama
pi += Decimal(t)/Decimal(deno)
from colorama import Fore
pi = pi * Decimal(12)/
colorama.init()
Decimal(640320**Decimal(1.5))
numberofdigits = int(input(“please enter the number pi = 1/pi
of decimal places to calculate Pi to: “)) return str(pi)
getcontext().prec = numberofdigits
print(calc(1))
start_time = time.time() SULQW )RUH5('´?Q7LPHWDNHQµWLPHWLPH 
def calc(n): start_time)

www.SFOpublications.com 63
Index

64 www.SFOpublications.com
Manipulating Data

Data is everything. It’s more valuable


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

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

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

WORKING WITH LISTS


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

STEP 1 A list is a sequence of data values called items. You STEP 3 You can also access, or index, the last item in a list by
create the name of your list followed by an equal using the minus sign before the item number [-1], or
sign, then square brackets and the items separated by commas; the second to last item with [-2], and so on. Trying to reference an
note that strings use quotes: item that isn’t in the list, such as [10] will return an error:
numbers = [1, 4, 7, 21, 98, 156] numbers[-1]
mythical_creatures – [“Unicorn”, “Balrog”, mythical_creatures[-4]
“Vampire”, “Dragon”, “Minotaur”]

STEP 2 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

STEP 7 5HPRYDORILWHPVFDQEHGRQHLQWZRZD\V7KHƬUVW STEP 10 Based on that, we can create a program to store


is by the item number: someone’s name and age as a list:
del numbers[7] name=input(“What’s your name? “)
lname=list(name)
The second, by item name:
age=int(input(“How old are you: “))
mythical_creatures.remove(“Nessie”) lage=[age]
user = lname + lage
The combined name and age list is called user, which can be called
by entering user into the Shell. Experiment and see what you can do.

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

THE IMMUTABLE TUPLE


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

STEP 1 A tuple is created the same way as a list, but in this STEP 3 You can create grouped tuples into lists that contain
instance you use curved brackets instead of square multiple sets of data. For instance, here we have a
brackets. For example: tuple called NPC (Non-Playable Characters) containing the character
name, and their combat rating, for an adventure game:
months=(“January”, “February”, “March”, “April”,
“May”, “June”) NPC=[(“Conan”, 100), (“Belit”, 80), (“Valeria”,
months 95)]

STEP 2 As with lists, the items within a named tuple can be STEP 4 Each of these data items can be accessed as a whole
indexed according to their position in the data range: by entering NPC into the Shell, or they can be
indexed according to their position NPC[0]. You can also index the
months[0]
individual tuples within the NPC list:
months[5]
NPC[0][1]
And so on. However, any attempt at deleting, or adding, to the tuple
will result in an error in the Shell. Will display 100.

68 www.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.

STEP 7 Tuples though, utilise a feature called unpacking, STEP 10 :HFDQXVHWKHPD[DQGPLQIXQFWLRQVWRƬQGWKH


where the data items stored within a tuple are highest and lowest values of a tuple composed of
assigned variables. First, create the tuple with two items (name and numbers. For example:
combat rating):
numbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99)
NPC=(“Conan”, 100)
7KHQXPEHUVFDQEHLQWHJHUVDQGƮRDWV7RRXWSXWWKHKLJKHVWDQG
lowest, use:
print(max(numbers))
print(min(numbers))

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

Date and Time


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

TIME LORDS
The Time module contains functions that help you retrieve the current system time, read the date from strings, format the
time and date, and much more.

STEP 1 First you need to import the Time module. It’s one STEP 3 You can see the structure of how time is presented
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.

OPEN, READ AND WRITE


,Q3\WKRQ\RXFUHDWHDƬOHREMHFWVLPLODUWRFUHDWLQJDYDULDEOHRQO\\RXSDVVLQWKHƬOHXVLQJWKHopen() function. Files are
usually categorised as text or binary.

STEP 1 Start by entering some text into your system’s STEP 3 If you now enter poem into the Shell, you will get
text editor. The text editor is preferable to a word 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

WRITE AND CLOSE


7KHZULWH IXQFWLRQLVVOLJKWO\PRUHFRPSOH[WKDQUHDG $ORQJZLWKWKHƬOHQDPH\RXPXVWDOVRLQFOXGHDQDFFHVVPRGHWKDW
GHWHUPLQHVZKHWKHUWKHƬOHLQTXHVWLRQLVLQUHDGRUZULWHPRGH

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.

STEP 2 :HFDQQRZZULWHWRWKHWH[WƬOHXVLQJWKHZULWH  STEP 4 ,I\RXQRZRSHQWKHWH[WƬOHZLWKDWH[WHGLWRU\RXoOO


function. This works opposite to read(), writing lines see that the line you created has been written to the
instead of reading them. Try this: ƬOH7KLVJLYHVXVWKHIRXQGDWLRQIRUVRPHLQWHUHVWLQJSRVVLELOLWLHV
SHUKDSVWKHFUHDWLRQRI\RXURZQORJƬOHRUHYHQWKHEHJLQQLQJRI
t.write(“You awake in a small, square room. A
an adventure game.
single table stands to one side, there is a locked
door in front of you.”)
Note, the 109, it’s the number of characters you’ve entered.

80 www.SFOpublications.com
Writing to Files

STEP 5 7RH[SDQGWKLVFRGHZHFDQUHRSHQWKHƬOHXVLQJ STEP 8 :HFDQSDVVYDULDEOHVWRDƬOHWKDWZHoYHFUHDWHG


‘a’, for access or append mode. This will add any text in Python. Perhaps we want the value of Pi to be
DWWKHHQGRIWKHRULJLQDOOLQHLQVWHDGRIZLSLQJWKHƬOHDQGFUHDWLQJ ZULWWHQWRDƬOH:HFDQFDOO3LIURPWKH0DWKPRGXOHFUHDWHDQHZ
a new one. For example: ƬOHDQGSDVVWKHRXWSXWRI3LLQWRWKHQHZƬOH
t=open(“/home/pi/Documents/text.txt”,”a”) import math
t.write(“\n”) print(“Value of Pi is: “,math.pi)
t.write(“ You stand and survey your surroundings. SULQW ´?Q:ULWLQJWRDÀOHQRZ«µ 
On top of the table is some meat, and a cup of
water.\n”)

STEP 6 We can keep extending the text line by line, STEP 9 Now let’s create a variable called pi, and assign it the
ending each with a new line (\n). When you’re value of Pi:
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.

STEP 7 7KHUHDUHYDULRXVW\SHVRIƬOHDFFHVVWRFRQVLGHU STEP 10 7RƬQLVKZHFDQXVHVWULQJIRUPDWWLQJWRFDOOWKH


using the open() function. Each depends on how the YDULDEOHDQGZULWHLWWRWKHƬOHWKHQFRPPLWWKH
ƬOHLVDFFHVVHGDQGHYHQWKHSRVLWLRQRIWKHFXUVRU)RUH[DPSOHU FKDQJHVDQGFORVHWKHƬOH
RSHQVDƬOHLQUHDGDQGZULWHDQGSODFHVWKHFXUVRUDWWKHVWDUWRI
t.write(“Value of Pi is: {}”.format(pi))
WKHƬOH
t.close()
As you can see from the results, you’re able to pass any variable to
DƬOH

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 9 You can also use a ƬQDOO\ block, which works in a


similar fashion, but you cannot use else with it. Hint:
<RXoOOQHHGWRGHOHWHWKHWH[WƬOHW[WƬOHIURP\RXUIROGHU
try:
W[W RSHQ&??8VHUV??GDYLG??'RFXPHQWV??WH[WÀOH
txt”, “r”)
try:
txt.write(“This is a test. Normal service will
shortly resume!”)
ÀQDOO\
STEP 6 You can use exceptions to handle a variety of useful
SULQW ´&RQWHQWZULWWHQWRÀOHVXFFHVVIXOO\
tasks. Using an example from our previous tutorials,
Have a nice day.”)
OHWoVDVVXPH\RXZDQWWRRSHQDƬOHDQGZULWHWRLW
txt.close()
try: except IOError:
W[W RSHQ ´&??8VHUV??GDYLG??'RFXPHQWV??WH[WÀOH SULQW ´(UURUXQDEOHWRZULWHWKHÀOH&KHFN
txt”, “r”) permissions”)
txt.write(“This is a test. Normal service will
shortly resume!”)
STEP 10 As before an error will occur as we’ve used the “r”
except IOError:
read-only permission. If we change it to a “w”, then
SULQW ´(UURUXQDEOHWRZULWHWKHÀOH&KHFN
the code will execute without the error being displayed in the IDLE
permissions”)
Shell. Needless to say, it can be a tricky getting the exception code
else:
ULJKWWKHƬUVWWLPH3UDFWLVHWKRXJKDQG\RXZLOOJHWWKHKDQJRILW
SULQW ´&RQWHQWZULWWHQWRÀOHVXFFHVVIXOO\
Have a nice day.”)
txt.close()

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 = “”

STEP 4 The newUser function is next:


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

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

STEP 6 Now to create the oldUser function:

def oldUser():
login = input(“Enter login name: “)
passw = input(“Enter password: “)
# check if user exists and login matches
password
if login in users and users[login] == passw:
print (“\nLogin successful!\n”)
print (“User:”, login, “accessed the system
on:”, time.asctime())
else:
print (“\nUser doesn’t exist or wrong
password!\n”)
STEP 9 Although a seemingly minor two lines, the while
loop is what keeps the program running. At the end
of every function, it’s checked against the current value of status. If
that global value isn’t ‘q’ then the program continues. If it’s equal to
‘q’ then the program can quit.

STEP 10 You can now create users, and then login with
their names and passwords, with the logins.txt
Ƭ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?

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


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

www.SFOpublications.com 87
Index

88 www.SFOpublications.com
Working with Modules

Modules are where you can take Python


programming to new heights; they are
the key ingredients to better code. You
can create your own modules, or you can
use some of those already available, to
help convert a mundane piece of code
into something spectacular.
Want to see how to make better use of
these modules to add a little something
extra to your code? Then read on and
learn how they can be used to forge
fantastic programs.

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

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

WORKING WITH DATES


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

STEP 1 Launch Python 3 and enter: import calendar to STEP 3 There are numerous functions, within the Calendar
call up the module and its inherent functions. Once module, that may be of interest to you when
it’s loaded into memory, start by entering: forming your own code. For example, you can display the number of
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.

INTO THE SYSTEM


2QHRIWKHSULPDU\IHDWXUHVRIWKH26PRGXOHLVWKHDELOLW\WROLVWPRYHFUHDWHGHOHWHDQGRWKHUZLVHLQWHUDFWZLWKƬOHV
stored on the system; making it the perfect module for backup code.

STEP 1 We can start the OS module with some simple STEP 3 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µ·

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


by entering:
import os
RVUHQDPH ´&??%'0??1(:µ´&??%'0??2/'µ
Or delete them…
STEP 6 To show that the OS module works roughly the
same across all platforms, we need to specify the import os
name of the app according to the OS on which you’re working. For RVUPGLU ´&??%'0??2/'µ
example, on a Raspberry Pi you would enter:
import os
RVV\VWHP ¶FKURPLXPEURZVHU´KWWS
EGPSXEOLFDWLRQVFRPµ·

STEP 10 Another module that goes together with OS is


shutil. We can use the Shutil module, together
with OS and time, to create a time-stamped backup directory, and
FRS\ƬOHVLQWRLW
import os, shutil, time
t=str(time.strftime(“%Y-%m-%d %H-%M”))
URRWBVUFBGLU U·&??%'0??'RFXPHQWV??·3DWKWR
the source directory
URRWBGVWBGLU ¶&??%DFNXS??·W3DWKWRWKH
EDFNXSGLUHFWRU\
STEP 7 Note, in the previous step’s example the use of
single and double-quotes. The single quotes encase IRUVUFBGLUGLUVÀOHVLQRVZDON URRWBVUFBGLU 
the entire command, and launching Chromium, whereas the double dst_dir = src_dir.replace(root_src_dir, root_
TXRWHVRSHQWKHVSHFLƬHGSDJH<RXFDQHYHQXVHYDULDEOHVWR dst_dir, 1)
open webpages: LIQRWRVSDWKH[LVWV GVWBGLU 
RVPDNHGLUV GVWBGLU
import os
IRUÀOHBLQÀOHV
D ¶VWDUWFKURPH´KWWSZZZJRRJOHFRXNµ·
VUFBÀOH RVSDWKMRLQ VUFBGLUÀOHB
os.system(a)
GVWBÀOH RVSDWKMRLQ GVWBGLUÀOHB
LIRVSDWKH[LVWV GVWBÀOH 
RVUHPRYH GVWBÀOH
VKXWLOFRS\ VUFBÀOHGVWBGLU
SULQW ´!!!!!!!!!!%DFNXSFRPSOHWHµ 

www.SFOpublications.com 93
Working with Modules

Using the Math Module


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

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

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

STEP 2 In our example


the number
three was returned. However,
enter the print function a few
more times and it will display
GLƪHUHQWLQWHJHUYDOXHVIURPWKH
set of numbers given, zero to STEP 5 We can extend the previous example somewhat by
ƬYH7KHRYHUDOOHƪHFWDOWKRXJK having random.choice() select from a list of mixed
pseudo-random, is adequate variables. For instance:
for the average programmer to
import random
utilise in their code.
OVW >´'DYLGµ´$YHQJHUVµ´3Lµ7UXH
´3\WKRQµ@
rnd=random.choice(lst)
STEP 3 )RUDELJJHUVHWRIQXPEHUVLQFOXGLQJƮRDWLQJ
print(rnd)
point values, we can extend the range by using the
multiplication sign:
import random
print(random.random() *100)
:LOOGLVSOD\DƮRDWLQJSRLQWQXPEHUEHWZHHQDQGWRWKHWXQH
RIDURXQGƬIWHHQGHFLPDOSRLQWV

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

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


it a title:
gamewindow=pygame.display.set_mode((800,600))
S\JDPHGLVSOD\VHWBFDSWLRQ ´$GYHQWXUH*DPHµ
<RXZLOOQRWLFHWKDWDIWHUWKHƬUVWOLQHLVHQWHUHG\RXoOOQHHGWRFOLFN
EDFNLQWRWKH,'/(6KHOOWRFRQWLQXHHQWHULQJFRGH,QDGGLWLRQ\RX
can change the title of the window to anything you like.

100 www.SFOpublications.com
Pygame Module

STEP 4 If the Pygame window still won’t


close, don’t worry, it’s just a
GLVFUHSDQF\EHWZHHQWKH,'/( ZKLFKLVZULWWHQ
with Tkinter) and the Pygame module. If you
run your code via the command line, it will close
SHUIHFWO\ƬQH

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

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


some previous tutorial code. The new elements are FORFNWLFN 
in the Subprocess module, of which one function allows us to launch a continue
second Python script from within another, and we’re going to create a EUHDN
New File called pygametxt.py:
pygame.quit()
import pygame
import time
import subprocess
pygame.init()
screen = pygame.display.set_mode((800, 250))
FORFN S\JDPHWLPH&ORFN
IRQW S\JDPHIRQW)RQW 1RQH
pygame.time.set_timer(pygame.USEREVENT, 200)
GHIWH[WBJHQHUDWRU WH[W 
tmp = ‘’
IRUOHWWHULQWH[W
WPS OHWWHU
LIOHWWHU ¶¶
yield tmp
FODVV'\QDPLF7H[W REMHFW 
def __init__(self, font, text, pos,
DXWRUHVHW )DOVH 
VHOIGRQH )DOVH
self.font = font
self.text = text
self._gen = text_generator(self.text)
self.pos = pos
self.autoreset = autoreset
self.update()
GHIUHVHW VHOI 
self._gen = text_generator(self.text)
VHOIGRQH )DOVH
self.update()
GHIXSGDWH VHOI 
LIQRWVHOIGRQH
WU\VHOIUHQGHUHG VHOIIRQW STEP 10 When we run this code, it will display a long,
render(next(self._gen), True, (0, 128, 0)) narrow Pygame window with the intro text
H[FHSW6WRS,WHUDWLRQ scrolling to the right. After a pause of ten seconds, it then launches
self.done = True the main game Python script, where we can move the warrior sprite
time.sleep(10) DURXQG2YHUDOOWKHHƪHFWLVTXLWHJRRGEXWWKHUHoVDOZD\VURRP
VXESURFHVV3RSHQ ´S\WKRQ&??8VHUV??GDYLG?? for improvement.
'RFXPHQWV??3\WKRQ??S\JDPHS\µVKHOO 7UXH
GHIGUDZ VHOIVFUHHQ 
screen.blit(self.rendered, self.pos)
text=(“A long time ago, a barbarian strode from the
frozen north. Sword in hand...”)
message = DynamicText(font, text, (65, 120),
autoreset=True)
ZKLOH7UXH
IRUHYHQWLQS\JDPHHYHQWJHW 
LIHYHQWW\SH S\JDPH48,7EUHDN
LIHYHQWW\SH S\JDPH86(5(9(17PHVVDJH
update()
HOVH
VFUHHQÀOO S\JDPHFRORU&RORU ¶EODFN·
message.draw(screen)

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

LIGHTS, CAMERA, ACTION


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

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

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


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

STEP 4 The FDQYDVPRYH EDOODE line is what moves


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

104 www.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

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


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

www.SFOpublications.com 105
Working with Modules

Create Your Own Modules


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

BUILDING MODULES
0RGXOHVDUH3\WKRQƬOHVFRQWDLQLQJFRGHWKDW\RXVDYHXVLQJDS\H[WHQVLRQ7KHVHDUHWKHQLPSRUWHGLQWR3\WKRQXVLQJWKH
now familiar import command.

STEP 1 Let’s start by creating a set of basic Mathematics STEP 3 1RZZHoUHJRLQJWRWDNHWKHIXQFWLRQGHƬQLWLRQV


functions. Multiply a number by two or three, and RXWRIWKHSURJUDPDQGLQWRDVHSDUDWHƬOH
square or raise a number to an exponent (power). Create a New File +LJKOLJKWWKHIXQFWLRQGHƬQLWLRQVDQGFKRRVHEdit > Cut. Choose
LQWKH,'/(DQGHQWHU File > New File and use Edit > Paste in the new window. We now
KDYHWZRVHSDUDWHƬOHVRQHZLWKWKHIXQFWLRQGHƬQLWLRQVDQGWKH
GHIWLPHVWZR [ 
other with the function calls.
return x * 2
GHIWLPHVWKUHH [ 
return x * 3
GHIVTXDUH [ 
return x * x
GHISRZHU [\ 
return x ** y

STEP 2 Under the above code, enter functions to call STEP 4 If you now try and execute the basic_math.py code
the code: again, the error ‘NameError: name ‘timestwo’ is
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 7 We can now make the program a little more


advanced, by utilising the newly created module to
its full. Let’s include some user interaction. Start by creating a basic
menu from which the user can choose:
print(“Select operation.\n”)
print(“1.Times by two”)
print(“2.Times by Three”)
print(“3.Square”)
SULQW ´3RZHURIµ
FKRLFH LQSXW ´?Q(QWHUFKRLFH  µ

STEP 8 Now we can add the user input to get the number
the code will work on:
QXP LQW LQSXW ´?Q(QWHUQXPEHU´
This will save the user-entered number as the variable num1.
STEP 10 Note that for the last available options, the Power
of choice, we’ve added a second variable: num2.
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

110 What is Linux?


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

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

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


XQLTXHVLWXDWLRQV:KLOHLWPD\ORRNUDGLFDOO\GLƪHUHQWIURPRQH
7X[WKH environment to the next, the actual Linux kernel can be found
Linux in modern smart TVs, in-car entertainment systems and GPS,
PDVFRW supercomputers, IoT devices, and the Raspberry Pi. NASA uses it,
/LQXVOLNHV both in the command centre and on board the ISS. Linux servers
SHQJXLQV  power the backbone of the Internet, along with most of the
websites you visit daily. Android utilises components of the Linux
kernel, as do set-top boxes, games consoles, and even some fridges,
freezers, ovens, and washing machines.

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


powerful, fast, can easily be customised, and requires very little
maintenance. However, it’s more than just a set of on-paper
performance stats. Linux means freedom from the walled-garden
approach of other operating systems. It’s a lively community of like-
5DVSELDQRQWKH5DVSEHUU\3LLVWKH minded individuals who want more from their computers, without
/LQX[GLVWULEXWLRQRIFKRLFH the shackles of price or conformity. Linux means choice.

$'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.

Another remarkable advantage for those looking to learning how


to code, is that Linux comes with most of the popular coding
environments built-in. Both Python and C++ are pre-installed in a high
percentage of Linux distros, which means you can start to program
DOPRVWDVVRRQDV\RXLQVWDOOWKHV\VWHPDQGERRWLWXSIRUWKHƬUVWWLPH

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


(DFKGLVWURRƪHUVVRPHWKLQJXQLTXHWRWKH
Windows or macOS. By system resources, we mean memory, hard drive
XVHUEXWDOOKDYH/LQX[DWWKHFRUH
space, and CPU load, as the Linux code has been streamlined and is free
from third-party ‘bloatware’, which hogs other systems resources. Of
FRXUVHDPRUHHƯFLHQWV\VWHPPHDQVPRUHUHVRXUFHVDUHDYDLODEOH run the latest versions of Windows or macOS. So rather than throwing
for the coding and testing environment, and the programs you will away an old computer, it can be reused with a Linux distro.
eventually create. Less use of resources also means you can use Linux
on older hardware that would normally struggle, or even refuse, to It’s not all about C++, Python, or any of the other more popular
programming languages, however. Using the command line of Linux,
also called the Terminal, you’re able to create Shell scripts, which are
programs designed to run from the command line and are made up of
VFULSWLQJODQJXDJHV7KH\DUHXVHGPDLQO\WRDXWRPDWHWDVNVRURƪHU
the user some form of input and output for a certain operation.

Finally, although there are many more advantages we could list, there
are thousands and thousands of free programs and apps available
that cover virtually every aspect of computing. Known as packages,
WKHUHDUH DWWKHWLPHRIZULWLQJ RYHUVSHFLƬFSURJUDPPLQJ
applications just on Linux Mint alone, and an incredible 62,000+ overall
packages catering from Amateur Radio to WWW tools.

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


program. It’s perfectly suited for developers and it’s continually
improving and evolving. If you’re serious about getting into coding, or
7KHUHDUHWKRXVDQGVRIIUHHSDFNDJHV
you just want to explore something new, give Linux a try and see how it
DYDLODEOHIRUSURJUDPPHUVXQGHU/LQX[
works for you.

$/LQX[SURJUDPPLQJHQYLURQPHQWFDQEH
DVVLPSOHRUDVFRPSOH[DV\RXQHHGLWWREH

www.SFOpublications.com 113
Learning Linux

Using the Filesystem


7RPDVWHU/LQX[LWoVLPSRUWDQWWRXQGHUVWDQGKRZWKHƬOHV\VWHPZRUNV:KDWoVPRUH
it’s also important to become familiar with the Terminal, or shell. This command line
HQYLURQPHQWPD\DSSHDUGDXQWLQJDWƬUVWEXWZLWKSUDFWLVHLWVRRQEHFRPHVHDV\WRXVH

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

Listing and Moving Files


$GPLWWHGO\XVLQJWKHGHVNWRS*8,WROLVWDQGPRYHƬOHVLVPXFKHDVLHUWKDQXVLQJWKH
Terminal and keyboard. However, it’s an important skill that you will appreciate as you
advance with the Raspberry Pi and 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

Creating and Deleting Files


%HLQJDEOHWRFUHDWHDQGGHOHWHDƬOHLVDQHYHU\GD\FRPSXWLQJVNLOO+RZHYHUZKHQ
XVLQJWKH/LQX[7HUPLQDOWKHUHoVDQHOHPHQWRIFDUHUHTXLUHGFKLHƮ\EHFDXVHDQ\
GHOHWHGƬOHVDUHQoWSODFHGLQWKHV\VWHPUHF\FOHELQ

&5($7,1*),/(6
2QFH\RXOHDUQWRUHFRJQLVHWKHƬOHVDQGGLUHFWRULHVWKDWPDNHXS5DVSELDQ26LWoVWLPHWRGLVFRYHUKRZWRPDNH\RXURZQ
.QRZLQJKRZWRPDNHHGLWDQGGHOHWHƬOHVDQGGLUHFWRULHVLVHVVHQWLDOLI\RXZDQWWRPDNH\RXURZQSURMHFWV

67(3 :HoUHJRLQJWRFUHDWHDƬOHXVLQJDFRPPDQGFDOOHG 67(3 ,I\RXWU\WRWRXFKDƬOHWKDWGRHVQoWH[LVW\RX


Touch. Touch is an interesting command that reaches FUHDWHDEODQNƬOHZLWKWKDWQDPH7U\LWQRZ7\SH
RXWWRDƬOHRUGLUHFWRU\DQGXSGDWHVLW WKLVFKDQJHVWKHV\VWHPWLPH WRXFKWHVWÀOH and ls –lWRYLHZWKHƬOHV<RXoOOQRZKDYHD
DVLI\RXoGMXVWRSHQHGWKHƬOH <RXFDQVHH7RXFKLQDFFHVVXVLQJpOV QHZƬOHLQ\RXUKRPHGLUHFWRU\FDOOHGpWHVWƬOHq1RWLFHWKDWWKHVL]H
–l” and checking the time next to a directory (such as Scratch). RIWKHƬOHLVEHFDXVHLWKDVQRWKLQJLQLW

67(3 1RZHQWHUtouch Scratch and ls –l again and 67(3 $TXLFNZRUGDERXWƬOHQDPHVUHPHPEHUWKDW


notice that the time has changed. It now matches /LQX[LVFDVHVHQVLWLYHVRLI\RXQRZHQWHUtouch
the current time. You might be wondering what this has to do with 7HVWÀOH ZLWKDFDSLWDO7 LWGRHVQoWXSGDWHnWHVWƬOHoLQVWHDGLW
FUHDWLQJƬOHVRUGLUHFWRULHV7RXFKKDVDVHFRQGPRUHSRSXODUXVH FUHDWHVDVHFRQGƬOHFDOOHGn7HVWƬOHo(QWHUls –lWRVHHERWKƬOHV
ZKLFKLVWRFUHDWHƬOHV This is confusing, so most people stick with using lowercase letters
at all times.

118 www.SFOpublications.com
Creating and Deleting Files

67(3 Another important thing to know is never to use a 67(3 +HUHDUHVRPHRWKHUƬOHVQDPHVWRDYRLG


VSDFHLQ\RXUƬOHQDPHV,I\RXWU\WRHQWHUtouch  ^`?! "oq#C_ 7KHIXOOVWRS  LVXVHGWR
WHVWÀOH, you create a document called “test” and another called FUHDWHDQH[WHQVLRQWRDƬOHXVXDOO\XVHGWRLQGLFDWHDƬOHW\SH
pƬOHq7HFKQLFDOO\WKHUHDUHZD\VWRFUHDWHƬOHVFRQWDLQLQJDVSDFH VXFKDVWH[WƬOHW[WRUFRPSUHVVHGƬOH]LSDQGVWDUWLQJDƬOHZLWK
but you should always use an underscore character (“_”) instead of a a full stop makes it invisible. Don’t use full stop in place of a space
VSDFHVXFKDVpWRXFKWHVWBƬOHq though; stick to underscores.

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.

67(3 7RJHWULGRIƬOHV\RXXVHWKHpUPqFRPPDQG 67(3 :HVHHWKDWpOVWHVW qPDWFKHVWZRƬOHVpWHVWqDQG


Enter: UP7HVWÀOHWRGHOHWHWKHƬOHFDOOHG pWHVWƬOHqEXWQRWWKHƬOHFDOOHGpƬOHq7KDWoVEHFDXVH
p7HVWƬOHq ZLWKWKHXSSHUFDVHpWq (QWHUls –lDQG\RXoOOƬQGLWoV it didn’t match the “test” part of “test*”. Check carefully over groups
gone. Where is it? It’s not in the Trash or Recycle Bin, like on a Mac RIƬOHV\RXZDQWWRUHPRYH UHPHPEHU\RXFDQoWUHFRYHUWKHP DQG
or Windows PC. It’s deleted completely and cannot be recovered. replace the “ls” with “rm”. Enter: rm test*WRUHPRYHERWKƬOHV
%HDUWKLVLQPLQGDQGDOZD\VWKLQNEHIRUHGHOHWLQJƬOHV Finally enter: UPÀOHWRJHWULGRIWKHFRQIXVLQJƬOH

www.SFOpublications.com 119
Learning Linux

Create and Remove


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

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 We’re going to remove one of the directories we 67(3 7RGHOHWHDGLUHFWRU\FRQWDLQLQJƬOHVRURWKHU


created earlier using the “rmdir” command. Enter: directories, you return to the “rm” command used
lsWRYLHZWKHƬOHVDQGGLUHFWRULHVLQWKHFXUUHQWGLUHFWRU\:HoOO WRUHPRYHƬOHVRQO\QRZZHQHHGWRXVHWKHp5qRSWLRQ ZKLFK
start by getting rid of one of the test directories. Enter: rmdir VWDQGVIRUpUHFXUVLYHq 8VLQJpUPs5qUHPRYHVDOOWKHƬOHVDQG
testdir3 and lsDJDLQWRFRQƬUPWKHGLUHFWRU\KDVEHHQUHPRYHG directories to whatever you point it at. Enter: rm -R articles to
remove the articles directory.

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

Copying, Moving and


Renaming Files
Taking command of the Terminal is essential when learning how your Raspberry
3LoVRSHUDWLQJV\VWHPZRUNV7KHFRS\LQJPRYLQJDQGUHQDPLQJRIƬOHVLVHTXDOO\
important, as you’ll be doing a lot of this throughout your Pi projects.

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\

67(3 Enter: PYWHVWÀOHQDPHV and ls. Now we can 67(3 ,WLVHDV\WRRYHUZULWHƬOHVXVLQJWKHPY


VHHWKHQHZpQDPHVqƬOHLQRXUGLUHFWRU\7KHPY FRPPDQGVRLI\RXKDYHƬOHVZLWKWKHVDPH
command can also be used to rename directories. We should still name use the “-n” option, which stands for “no overwrite”.
have our newparent directory in our home directory. Enter: mv Enter: WRXFKWHVWÀOHWRFUHDWHDQHZƬOHDQGmv -n
newparent people to rename the newparent directory. Enter: WHVWÀOHSHRSOHIULHQGV. There’s no error report though,
ls to view it. enter: lsDQG\RXoOOƬQGWHVWƬOHVWLOOWKHUH

www.SFOpublications.com 123
Learning Linux

Using the Man Pages


Linux comes with man (manual) pages that explain each command and show you all the
options you can use. Once you get the hang of reading the man pages, you’ll be able to
ƬQGDQGGRMXVWDERXWDQ\WKLQJLQ/LQX[

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

67(3 Press the H key while looking at a man page to view


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

 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

Editing Text Files


$WH[WƬOHLQ/LQX[FDQEHDQ\WKLQJIURPDVLPSOHVHWRILQVWUXFWLRQVRQKRZWRXVHDQ
DSSWRVRPHFRPSOH[3\WKRQ&RURWKHUSURJUDPPLQJODQJXDJHFRGH7H[WƬOHVFDQ
EHXVHGIRUVFULSWLQJDXWRPDWHGH[HFXWDEOHƬOHVDVZHOODVFRQƬJXUDWLRQƬOHVWRR

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 Emacs, or GNU Emacs, is an extensible and 67(3 (PDFVFDQRƪHUDQXQFRPSOLFDWHGYLHZRI\RXUWH[W


customisable, self-documenting, real-time display ƬOHRURQHZLWKDSOHWKRUDRILQIRUPDWLRQUHJDUGLQJ
editor. It’s a fantastic text editor and one that’s worth getting used WKHVWUXFWXUHRIWKHƬOHLQTXHVWLRQLWoVXSWR\RXWRZRUNRXW\RXU
to as soon as you can. Sadly, it’s not installed on the Pi by default, own preference. There’s also a hidden text adventure in Emacs,
VR\RXoOOQHHGWRLQVWDOOLW,QWKH7HUPLQDOHQWHUsudo apt-get ZKLFKZHFRYHUODWHULQWKLVERRNZK\QRWVHHLI\RXFDQƬQGLW
install emacs without our help.

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.

67(3 2QFHWKHLQVWDOODWLRQLVFRPSOHWHHQWHUemacs 67(3 Finally, Jed is an Emacs-like, cross-platform text


into the Terminal. The Emacs splash screen opens editor that’s lightweight and comes with a wealth
LQDQHZZLQGRZRƪHULQJDWXWRULDO ZKLFKZHUHFRPPHQG\RXUXQ RIIHDWXUHV7RLQVWDOOLWHQWHUsudo apt-get install jed.
through) and a guided tour amongst other information. $FFHSWWKHLQVWDOODWLRQDQGZKHQLWoVFRPSOHWHXVHjed to launch.

www.SFOpublications.com 127
Learning Linux

Getting to Know Users


You might think you’re the only person using your Raspberry Pi but there are several
GLƪHUHQWXVHUVDQGHYHQJURXSVRIXVHUV<RXUPDLQDFFRXQWLVQRUPDOO\FDOOHG3LDQG
there is an account above it called root, which is more powerful. You can also create
users and groups.

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

67(3 1RZHQWHUls –l and let’s have a good look at the


GHIDXOWSHUPLVVLRQVƬOH2XUWHVWƬOHW[WƬOHVVWDUWV
ZLWKWKHWH[WpUZUUtp6WDUWZLWKWKHƬUVWOHWWHUZKLFKLVDGDVKno
All the other items in our home directory are directories. You can tell
EHFDXVHWKH\DUHEOXHDQGRXUWHVWƬOHW[WƬOHLVZKLWH

67(3 The next nine letters of the permissions are known


as “alpha notation” because they let you know the
permissions using letters. Each permission is either on, in which case
\RXVHHDOHWWHURULWLVRƪLQZKLFKFDVH\RXVHHDGDVK7KHOHWWHU
GRHVQoWFKDQJHIRUHDFKSODFH6RWKHƬUVWSHUPLVVLRQWKHVHFRQG
letter after the directory one - is either an ‘r’ or a ‘-’. It’s never any
other letter.

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 7KHƬUVWEORFNRIWKUHHLVWKHPRVWLPSRUWDQW 67(3 Turning everything on is probably overkill, so you


7KLVLVWKHXVHUZKRRZQVWKHƬOH W\SLFDOO\SL WKH need to target each group. Do this by putting
second is for other people in the same group as the user, and the commas between each mode option. Enter: chmod u=rwx,g=rw,o=r
third is for other people on the system. Permissions are changed WHVWƬOHW[WWRJLYHXVHUVUHDGZULWHDQGH[HFXWHSULYLOHJHVXVHUUHDG
XVLQJWKHFKPRG FKDQJHƬOHPRGHELW FRPPDQG(QWHUman and write and other just read. Enter: ls –l to see your handiwork.
chmod to look at the manual.

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

Useful System and


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

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

67(3 67(3 (QWHUuname –a to view some more detailed


information. Here you’ll see the kernel name,
Remember that cat KRVWQDPHDQGNHUQHOYHUVLRQ YRQRXUV ,I\RXKDYHD
is used to list the Raspberry Pi 2 you’ll see SMP (symmetric multiprocessing),
FRQWHQWVRIDWH[WƬOH followed by the system date, CPU architecture and operating
which is what cpuinfo system (GNU/Linux).
is. There are other text
ƬOHVZLWKV\VWHPLQIR
available. Try “cat /
proc/meminfo” to get
information about
your memory, “cat /
proc/partitions” for
information about your
SD card, and “cat /proc/
version” shows which
version of Raspberry Pi
you are using.

132 www.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

Input, Output and Pipes


Most operating systems allow you to direct the output of something on the screen
WRIRUH[DPSOHDƬOH/LQX[ZLWKLWVDQFHVWUDOKLVWRU\RI8QL[OLNHFRPPDQGEDVHG
DUJXPHQWVJRHVDVWHSIXUWKHUDQGRƪHUVPXFKPRUHFRQWURO

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

67(3 As far as the computer is concerned, input and


output can be to and from a whole range of
GLƪHUHQWVRXUFHVWKDW\RXPLJKWQHYHUHYHQWKLQNDERXW$SURJUDP
FDQJHWLQSXWIURPRWKHUSURJUDPVIURPƬOHVVWRUHGRQWKHKDUG
drive and a whole host of other areas. It outputs back to the display
OLQHEXWDOVRWRƬOHVRWKHUSURJUDPVDQGHYHQRWKHUFRPPDQGV

 www.SFOpublications.com
Input, Output and Pipes

67(3 6R!HQDEOHV\RXWRRXWSXWWRƬOHVEXW\RXFDQDOVR 67(3 :HoUHJRLQJWRXVHWKLVWH[WƬOHDVLQSXWWRWKH


JHWLQSXWIURPDƬOH0DNHDQHZGLUHFWRU\FDOOHG VRUWFRPPDQG(QWHUVRUWEDQGVW[W and
PXVLF pPNGLUPXVLFq DQGVZLWFKWRLW pFGPXVLFq (QWHUnano WKHFRQWHQWIURPWKHWH[WƬOHLVXVHGDVLQSXWWRVRUW%HFDXVHWKH
EDQGVW[WWRFUHDWHDQHZWH[WƬOH(QWHUVRPHEDQGQDPHVDQG RXWSXWLVQoWVSHFLƬHGLWXVHVWKHVWDQGDUGRXWSXW WKHVFUHHQ EXW
SUHVV&RQWURO2WRRXWSXWWKHƬOH3UHVV&RQWURO;WRTXLWQDQR \RXXVHLQSXWDQGRXWSXWWRJHWKHU(QWHUVRUWEDQGVW[W!
EDQGVBVRUWHGW[WWRFUHDWHDQHZƬOHZLWKWKHEDQGQDPHVLQ
order to switch back to your pi account.

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.

67(3 )DQVRI6WDU:DUVHYHQJHWDƬ[ZKHQLWFRPHV 67(3 The rev command is certainly interesting, and at


to the Terminal. By linking to a remote server via ƬUVWZKDWVHHPVDTXLWHXVHOHVVDGGLWLRQWRWKH
the telnet command, you can watch Episode IV: A New Hope being OS can, however, be used to create some seemingly unbreakable
SOD\HGRXWDOEHLWLQ$6&,,7RYLHZWKLVVSHFWDFOHHQWHUsudo SDVVZRUGV(QWHUrev and then type some text. Then press Enter
apt-get install telnetIROORZHGE\telnet towel. and everything you typed in is reversed. Press Ctrl+C to exit.
blinkenlights.nl

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 7KHUHoVDƬQHOLQHEHWZHHQWKHUDWKHUFRRODQG 67(3 Admittedly, the command ‘toilet’ doesn’t inspire


the really quite weird. Having an ASCII cow repeat PXFKFRQƬGHQFH+RZHYHULWoVQRWDVEDGDVLW
text to you could potentially fall into the latter. Start by installing ƬUVWVRXQGV6WDUWE\LQVWDOOLQJLWZLWKsudo apt-get install
cowsaysudo apt-get install cowsayWKHQHQWHUcowsay toiletWKHQZKHQLWoVLQVWDOOHGW\SHVRPHWKLQJDORQJWKHOLQHVRI
Raspberry Pi is Ace!. In fact, you can even output the ls toilet David; or perhaps list the contents of the current folder
FRPPDQGWKURXJKWKHFRZE\HQWHULQJls | cowsay. WKURXJKLWZLWKls | toilet.

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

More Fun Things to Do in


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

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.

67(3 With that little lot completed, onto the next


SDUW(QWHUcd .. && wget http://www.
robobunny.com/projects/asciiquarium/asciiquarium.
WDUJ] WDU[IDVFLLTXDULXPWDUJ] FG
DVFLLTXDULXPB FKPRG[DVFLLTXDULXP. Providing
DOOZHQWZHOOHQWHU./asciiquarium and enjoy your very own
ASCII-based aquarium.

www.SFOpublications.com 
Learning Linux

Linux Tips and Tricks


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

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.

$6&,,$57 ASCII art can be quite striking when applied to


VRPHLPDJHV+RZHYHULWoVRIWHQGLƯFXOWWR )25*277(1&200$1'6 It’s not easy trying
get just right. You can create some great ASCII art from the images to remember all the
\RXDOUHDG\KDYHRQWKH5DVSEHUU\3LE\XVLQJLPJW[W available Linux commands. Thankfully, you can use apropos to help.
6LPSO\XVHLWZLWKDGHVFULSWLRQRIWKHFRPPDQG
LPJW[W1$0(2),0$*(),/(SQJ
DSURSRV´FRS\ÀOHVµ
5HSODFH1$0(2),0$*(),/(ZLWKWKHDFWXDOQDPHRIWKHLPDJHƬOH
DSURSRV´UHQDPHÀOHVµ
on your system.

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 cd command is one of the commands you The mvFRPPDQGPRYHVDƬOHWRDGLƪHUHQW


will use the most at the command line in Linux. It ORFDWLRQRUUHQDPHVDƬOH)RUH[DPSOHPYÀOH
cd allows you to change your working directory. You mv subUHQDPHVWKHRULJLQDOƬOHWRsub. mv sub
use it to move around within the hierarchy of your ~/DesktopPRYHVWKHƬOHnVXEoWR\RXUGHVNWRS
ƬOHV\VWHP<RXFDQDOVRXVHFKGLU directory but does not rename it. You must specify
DQHZƬOHQDPHWRUHQDPHDƬOH

The lsFRPPDQGVKRZV\RXWKHƬOHVLQ\RXU The chown command changes the user and/


current directory. Used with certain options, it lets RUJURXSRZQHUVKLSRIHDFKJLYHQƬOH,IRQO\DQ
ls \RXVHHƬOHVL]HVZKHQƬOHVZKHUHFUHDWHGDQGƬOH chown owner (a user name or numeric user ID) is given,
permissions. For example, ls ~VKRZV\RXWKHƬOHV WKDWXVHULVPDGHWKHRZQHURIHDFKJLYHQƬOHDQG
WKDWDUHLQ\RXUKRPH{GLUHFWRU\ WKHƬOHVoJURXSLVQRWFKDQJHG

The cpFRPPDQGLVXVHGWRPDNHFRSLHVRIƬOHV The chmod command changes the permissions on


and directories. For example, FSÀOHVXE makes WKHƬOHVOLVWHG3HUPLVVLRQVDUHEDVHGRQDIDLUO\
cp DQH[DFWFRS\RIWKHƬOHZKRVHQDPH\RXHQWHUHG cmod simple model. You can set permissions for user,
DQGQDPHVWKHFRS\VXEEXWWKHƬUVWƬOHZLOOVWLOO group and world and you can set whether each can
H[LVWZLWKLWVRULJLQDO{QDPH UHDGZULWHDQGRUH[HFXWHWKHƬOH

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 ps command allows you to view all the


The man man command brings up the manual
processes running on the machine. Every
ps operating system’s version of ps is slightly man man entry for the man command, which is a great place
to start when using it.
GLƪHUHQWEXWDOOGRWKHVDPHWKLQJ

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-Z of Linux Commands


There are literally thousands of Linux commands, so while this is not a complete A-Z, it
GRHVFRQWDLQPDQ\RIWKHFRPPDQGV\RXZLOOPRVWOLNHO\QHHG<RXZLOOSUREDEO\ƬQG
that you end up using a smaller set of commands over and over again but having an
overall knowledge is still very useful.

A
adduser Add a new user dd Data Dump, convert and
G
gawk Find and Replace text
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

Q tee Redirect output to


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

quotacheck  6FDQDƬOHV\VWHPIRU time Measure Program


disk usage Resource Use

quotactl Set disk quotas touch &KDQJHƬOHWLPHVWDPSV


top List processes running on

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

150 Python File Manager


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

ZZZSFOSXEOLFDWLRQVFRP 149
Code Repository

Python File Manager


7KLVƬOHPDQDJHUSURJUDPGLVSOD\V ),/(0$13<
DOLVWRIRSWLRQVWKDWDOORZ\RXWR &RS\WKHFRGHEHORZLQWRD1HZ!)LOHDQGVDYHLWDV)LOH0DQS\
UHDGDƬOHZULWHWRDƬOHDSSHQGWR 2QFHH[HFXWHGLWZLOOGLVSOD\WKHSURJUDPWLWOHDORQJZLWKWKH
FXUUHQWWLPHDQGGDWHDQGWKHDYDLODEOHRSWLRQV
DƬOHGHOHWHDƬOHOLVWWKHFRQWHQWV
RIDGLUHFWRU\DQGPXFKPRUH,WoV
UHPDUNDEO\HDV\WRHGLWDQGLQVHUW import shutil
import os
LQWR\RXURZQFRGHRUDGGWR import time 1
import subprocess

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

LIRVSDWKLV¿OH SDWK 7UXH /LVW¿OHVLQDGLUHFWRU\


SULQW µ)LOH)RXQG¶ &KHFN¿OHH[LVWHQFH
else: 0RYHD¿OH
 SULQW µ)LOHQRWIRXQG¶ &RS\D¿OH
LIIS  &UHDWHDGLUHFWRU\
SDWK LQSXW ³(QWHUWKHGLUHFWRU\SDWK´ 'HOHWHDGLUHFWRU\
RVSDWKLVGLU SDWK 2SHQDSURJUDP
LIRVSDWKLVGLU SDWK )DOVH ([LW
 SULQW µ'LUHFWRU\)RXQG¶
else: µ¶¶
SULQW µ'LUHFWRU\1RW)RXQG¶ LIGHF 
Read()
GHI0RYH  LIGHF 
SDWK LQSXW µ(QWHUWKHVRXUFHSDWKRI¿OHWRPRYH¶ Write()
PU LQW LQSXW µ5HQDPH?Q0RYH?Q¶ LIGHF 
LIPU  Add()
SDWK LQSXW µ(QWHUWKHGHVWLQDWLRQSDWKDQG¿OHQDPH¶ if dec==4:
VKXWLOPRYH SDWKSDWK Delete()
SULQW µ)LOHUHQDPHG¶ if dec==5:
LIPU  Dirlist()
SDWK LQSXW µ(QWHUWKHSDWKWRPRYH¶ if dec==6:
VKXWLOPRYH SDWKSDWK Check()
SULQW µ)LOHPRYHG¶ if dec==7: 4
 0RYH
def Copy(): if dec==8:
SDWK LQSXW µ(QWHUWKHSDWKRIWKH¿OHWRFRS\RUUHQDPH¶ Copy()
SDWK LQSXW µ(QWHUWKHSDWKWRFRS\WR¶ if dec==9:
VKXWLOFRS\ SDWKSDWK Makedir()
SULQW µ)LOHFRSLHG¶ LIGHF 
 5HPRYHGLU
def Makedir(): LIGHF 
SDWK LQSXW ³(QWHUWKHGLUHFWRU\QDPHZLWKSDWKWRPDNH  2SHQ¿OH
?QHJ&??+HOOR??1HZGLU?Q:KHUH1HZGLULVQHZ LIGHF 
GLUHFWRU\´ exit()
RVPDNHGLUV SDWK  UXQ LQW LQSXW ³5HWXUQWRPHQX?Q([LW?Q´
SULQW µ'LUHFWRU\&UHDWHG¶ LIUXQ 
exit()
GHI5HPRYHGLU 
SDWK LQSXW µ(QWHUWKHSDWKRI'LUHFWRU\¶
WUHHGLU LQW LQSXW µ'HOHWHG'LUHFWRU\?Q'HOHWH
'LUHFWRU\7UHH?Q([LW?Q¶
LIWUHHGLU 
 RVUPGLU SDWK
LIWUHHGLU 
VKXWLOUPWUHH SDWK
 SULQW µ'LUHFWRU\'HOHWHG¶
LIWUHHGLU 
exit()

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

Number Guessing Game


7KLVLVDVLPSOHOLWWOHSLHFHRI 180%(5*8(663<
FRGHEXWLWPDNHVJRRGXVHRIWKH &RS\WKHFRGHDQGVHHLI\RXFDQEHDWWKHFRPSXWHUZLWKLQ
5DQGRPPRGXOHSULQWDQGLQSXW ƬYHJXHVVHV,WoVDQLQWHUHVWLQJELWRIFRGHWKDWFDQEHTXLWH
KDQG\ZKHQ\RXULPSOHPHQWLQJDFRPELQDWLRQRIWKH5DQGRP
DQGDZKLOHORRS7KHQXPEHURI PRGXOHDORQJVLGHDZKLOHORRS
JXHVVHVFDQEHLQFUHDVHGIURP
DQGWKHUDQGRPQXPEHUUDQJHFDQ import random 1
HDVLO\EHDOWHUHGWRR guessesUsed = 0
1DPH LQSXW µ+HOOR:KDWLV\RXUQDPH"µ
QXPEHU UDQGRPUDQGLQW 
SULQW µ*UHHWLQJVµ1DPHµ,?¶PWKLQNLQJRID
QXPEHU EHWZHHQ DQG¶
ZKLOH JXHVVHV8VHG
JXHVV LQW LQSXW µ*XHVVWKHQXPEHUZLWKLQJXHVVHV¶
JXHVVHV8VHG JXHVVHV8VHG
LIJXHVVQXPEHU
SULQW µ7RRORZWU\DJDLQ¶
LIJXHVV!QXPEHU 2
SULQW µ7RRKLJKWU\DJDLQ¶
if guess == number:
break
if guess == number:
guessesUsed = str(guessesUsed)
SULQW µ:HOO GRQH µ  1DPH  µ<RXJXHVVHG
FRUUHFWO\ LQ µ  JXHVVHV8VHG  µ JXHVVHV¶
3
LIJXHVV QXPEHU
number = str(number)
SULQW µ6RUU\ RXW RI JXHVVHV7KHQXPEHU,ZDV
WKLQNLQJ RI LV µ  QXPEHU

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


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

152 www.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

Random Number Generator


8VHULQSXWDQGWKHDELOLW\WR 51'180*(13<
PDQLSXODWHWKDWLQSXWDUHLPSRUWDQW ,WPLJKWEHVLPSOHEXWWKLVOLWWOHSLHFHRIFRGHZLOODVNWKHXVHU
IRUWZRVHWVRIQXPEHUVDVWDUWDQGDƬQLVK7KHFRGHZLOOWKHQ
HOHPHQWVZLWKDQ\SURJUDPPLQJ SOXFNRXWDUDQGRPQXPEHUEHWZHHQWKHWZRVHWVDQGGLVSOD\LW
ODQJXDJH,WoVZKDWVHSDUDWHVDJRRG
from random import *
SURJUDPIURPDJUHDWSURJUDPRQH
WKDWDOORZVWKHXVHUWRLQWHUDFWDQG SULQW ³?Q!!!!!!!!!!5DQGRP1XPEHU*HQHUDWRU?Q´
QPE LQW LQSXW ³(QWHUWKHVWDUWQXPEHU³
VHHWKHUHVXOWVRIWKDWLQWHUDFWLRQ QPE LQW LQSXW ³(QWHUWKHODVW QXPEHU³

[ 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

Keyboard Drawing Script


7KH7XUWOHPRGXOHLVDQH[FHOOHQWUHVRXUFH
IRUWKH3\WKRQSURJUDPPHU+RZHYHU
ZKDWPDNHVLWPRUHLQWHUHVWLQJLVLWV
DELOLW\WRHQDEOHWKHXVHUWRFRQWUROWKH
WXUWOHRQWKHVFUHHQ7KLVSLHFHRIFRGH
GRHVH[DFWO\WKDWDOORZLQJWKHXVHUWR
XQOHDVKWKHLULQQHUDUWLVW
.(<%'5$:3<
7KHUHDUHWZRPRGXOHVLQWKLVVFULSW7XUWOHDQG7NLQWHU7KH
7XUWOHPRGXOHLVWKHPDLQGLVSOD\ZKHUHWKHXVHUFRQWUROVWKH
GUDZLQJZKHUHDV7NLQWHUVLPSO\GLVSOD\VWKHXVHUFRQWUROV
³´´
$OOPRYHPHQWVDQGWXUQVDUHE\LQFUHPHQWVRI
5LJKW DUURZ NH\ PRYH IRUZDUG
/HIW DUURZ NH\ PRYH EDFNZDUG
r = turn right
l = turn left
1
u = pen up
G SHQ GRZQ
h = go home
c = clear
³´´ $UWZRUN
from tkinter import * Just as with all code, there’s always room for improvement
from turtle import * somewhere. Here you could change the colours or ask the user
which colour they want to start with and then include a key in
URRW 7N the controls to change the pen colour whilst drawing. There’s
7 7H[W URRWURRWWLWOH ³&RQWUROV´ KHLJKW ZLGWK  also room to increase or decrease the speed of the pen, again
7SDFN WKDWFRXOGEHDXVHUGHƬQHGVSHHG<RXFDQDOVRH[SDQGWKH
7LQVHUW (1'³5LJKWDUURZNH\ PRYHIRUZDUG? controls thoroughly to include a lot more detail and options.
Q/HIW DUURZ NH\ PRYH EDFNZDUG?QU WXUQ ULJKW?QO
WXUQ OHIW?QX SHQ XS?QG SHQ GRZQ?QK JR KRPH?
QF FOHDU´

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

Pygame Text Examples


WH[W IRQWUHQGHU ³8SVLGHGRZQWH[W´7UXH%/$&.
7KHUHoVDORW\RXFDQGRXVLQJWKH WH[W S\JDPHWUDQVIRUPURWDWH WH[W
3\JDPHPRGXOHWKDWoVQRWUHODWHG VFUHHQEOLW WH[W>@

WRGLVSOD\LQJJUDSKLFV7KHPRGXOH WH[W IRQWUHQGHU ³)OLSSHGWH[W´7UXH%/$&.


WH[W S\JDPHWUDQVIRUPÀLS WH[W)DOVH7UXH
FRQWDLQVPDQ\IXQFWLRQVZKLFKFDQ VFUHHQEOLW WH[W>@
PDQLSXODWHWH[WVXFKDVƮLSSLQJLW
WH[W IRQWUHQGHU ³5RWDWLQJWH[W´7UXH%/$&.
GLVSOD\LQJLWVLGHZD\VXSVLGHGRZQ WH[W S\JDPHWUDQVIRUPURWDWH WH[W WH[W B
URWDWH B GHJUHHV
DQGHYHQURWDWLQJLWZLWKDQLPDWLRQV WH[W B URWDWH B GHJUHHV 
VFUHHQEOLW WH[W > @
7;75273<
S\JDPHGLVSOD\ÀLS
Here we’ve introduced several examples of
displaying text within the Pygame module. Each is FORFNWLFN 
easily recognised within the code, so you can pull it
out and use it in your code. S\JDPHTXLW

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

WH[W B URWDWH B GHJUHHV 

ZKLOHQRWGRQH

IRUHYHQWLQS\JDPHHYHQWJHW 
LIHYHQWW\SH S\JDPH48,7
GRQH 7UXH

VFUHHQ¿OO :+,7(

S\JDPHGUDZOLQH VFUHHQ%/$&.>@
> @
S\JDPHGUDZOLQH VFUHHQ%/$&.>@
> @

IRQW S\JDPHIRQW6\V)RQW µ&DOLEUL¶


7UXH )DOVH
WH[W IRQWUHQGHU ³6LGHZD\VWH[W´7UXH%/$&.
WH[W S\JDPHWUDQVIRUPURWDWH WH[W 
VFUHHQEOLW WH[W > @

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

Google Search Script


8VLQJWKH26DQG8UOOLEPRGXOHVWKLV *22*/(6($5&+3<
VPDOOVQLSSHWRIFRGHZLOOGLVSOD\D <RXZLOOQHHGWRSLSLQVWDOOWKH8UOOLEPRGXOHXQOHVVLWoV
ZLQGRZIRUWKHXVHUoVLQSXWWKHQSDVV DOUHDG\LQVWDOOHG,WDOVRXVHV=HQLW\ZKLFKLVD/LQX[EDVHG
*120( WRROIRUFUHDWLQJGLDORJER[HV
WKHLQSXWWRD*RRJOHVHDUFKLQWKHLU
EURZVHU,WoVUHDOO\TXLWHDKDQG\VFULSW import os
LPSRUW XUOOLESDUVH
DQGRQHWKDWoVHDVLO\LQWURGXFHGLQWR JRRJOH RVSRSHQ µ]HQLW\HQWU\WH[W ´(QWHU\RXU
\RXURZQFRGH *RRJOHVHDUFK³WLWOH ´*RRJOH6HDUFK´¶ UHDG
JRRJOH XUOOLESDUVHTXRWH JRRJOH
RVV\VWHP µFKURPLXPEURZVHUKWWSZZZJRRJOHFRP
VHDUFK"T V¶  JRRJOH

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

Text to Binary Convertor


:KLOHLWPD\QRWVHHPWRRH[FLWLQJ 7;7%,13<
WKLVWH[WWRELQDU\FRQYHUWRULV 1DWXUDOO\ZHoUHXVLQJWKHIRUPDWIXQFWLRQWRFRQYHUWWKH
DFWXDOO\TXLWHJRRGIXQ,WDOVR XVHUoVHQWHUHGWH[WVWULQJLQWRLWVELQDU\HTXLYDOHQW,I\RX
ZDQWWRFKHFNLWVDFFXUDF\\RXFDQSOXJWKHELQDU\LQWRDQ
RQO\XVHVWZROLQHVRIFRGHVRLWoV RQOLQHFRQYHUWRU
H[WUHPHO\HDV\WRLQVHUWLQWR\RXU
WH[W LQSXW ³(QWHUWH[WWRFRQYHUWWR%LQDU\³
RZQVFULSW
SULQW µµMRLQ IRUPDW RUG [ µE¶ IRU[LQWH[W

160 www.SFOpublications.com
Text to Binary Convertor

1000010 1101001 1101110 1100001 1110010


1111001
7KHWH[WWRELQDU\FRQYHUWRUGRHVRƪHUVRPHURRPIRU
S\JDPHGLVSOD\VHW B FDSWLRQ ³%LQDU\&RQYHUVLRQ´
improvement and enhancement. There are many uses: it could be
utilised in a password or secret word script, as part of an adventure done = False
game or just a novel way to display someone’s name. FORFN S\JDPHWLPH&ORFN

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

With regards to rendering the outputted binary conversion to a IRUHYHQWLQS\JDPHHYHQWJHW 


Pygame window, complete with rotating text, you can use: LIHYHQWW\SH S\JDPH48,7
GRQH 7UXH
import pygame
S\JDPHLQLW VFUHHQ¿OO :+,7(
IRQW S\JDPHIRQW6\V)RQW µ&DOLEUL¶7UXH)DOVH
%/$&.  
:+,7(   WH[W IRQWUHQGHU %LQDU\7UXH%/$&.
%/8(   WH[W S\JDPHWUDQVIRUPURWDWH WH[WWH[W B
*5((1   URWDWH B GHJUHHV
5('   WH[W B URWDWH B GHJUHHV 
VFUHHQEOLW WH[W>@
SULQW ³!!!!!!!!!!7H[WWR%LQDU\&RQYHUWRU?Q´ S\JDPHGLVSOD\ÀLS

FRQYHUVLRQ LQSXW ³(QWHUWH[WWRFRQYHUWWR%LQDU\³ FORFNWLFN 

VL]H   S\JDPHTXLW


VFUHHQ S\JDPHGLVSOD\VHW B PRGH VL]H
SULQW µµMRLQ IRUPDW RUG [ µE¶ IRU[LQFRQYHUVLRQ

www.SFOpublications.com 161
Code Repository

Text Adventure Script


7H[WDGYHQWXUHVDUHDQH[FHOOHQW $'9(1785(3<
ZD\WREXLOG\RXU3\WKRQFRGLQJ 7KH$GYHQWXUHJDPHXVHVMXVWWKH7LPHPRGXOHWREHJLQ
VNLOOVDQGKDYHVRPHIXQDWWKH ZLWKFUHDWLQJSDXVHVEHWZHHQSULQWIXQFWLRQV7KHUHoVDKHOS
V\VWHPLQSODFHWRH[SDQGXSRQDVZHOODVWKHVWRU\LWVHOI
VDPHWLPH7KLVH[DPSOHWKDWZH
FUHDWHGZLOOVWDUW\RXRQWKHSDWK
WRPDNLQJDFODVVLFWH[WDGYHQWXUH import time

ZKHUHLWZLOOHQGLVXSWR\RX SULQW ³?Q´ 


SULQW ³!!!!!!!!!!$ZHVRPH$GYHQWXUH?Q´
SULQW ³?Q´ 
WLPHVOHHS 
SULQW ³?Q$ORQJWLPHDJRDZDUULRUVWURGHIRUWKIURP
WKHIUR]HQQRUWK´
WLPHVOHHS 
SULQW ³'RHV WKLVZDUULRUKDYHDQDPH"´
QDPH LQSXW ³! ³
SULQW QDPH ³WKHEDUEDULDQVZRUGLQKDQGDQGORRNLQJ
IRU DGYHQWXUH´
WLPHVOHHS 
SULQW ³+RZHYHUHYLOLVOXUNLQJQHDUE\´
WLPHVOHHS 
SULQW ³$ SDLURIEXOERXVH\HVUHJDUGVWKHKHUR´
WLPHVOHHS 
SULQW ³:LOO´ QDPH³SUHYDLODQGZLQJUHDWIRUWXQH´
WLPHVOHHS 
SULQW ³2U GLHE\WKHKDQGVRIJUHDWHYLO"´
WLPHVOHHS 
SULQW ³?Q´ 
SULQW ³2QO\ WLPHZLOOWHOO´
WLPHVOHHS 
SULQW µ¶
WLPHVOHHS 
SULQW µ¶
WLPHVOHHS 
SULQW µ¶
WLPHVOHHS 
SULQW µ¶
WLPHVOHHS 
SULQW ³?Q´ 

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

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


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

Finally, how about introducing the Random module. This will


enable you to include an element of chance in the game. For
example, in combat, when you strike an enemy you will do a
UDQGRPDPRXQWRIGDPDJHDVZLOOWKH\<RXFRXOGHYHQZRUNRXW
the maths behind improving the chance of a better hit based on
your or your opponent’s combat skills, current health, strength and
HQGXUDQFH<RXFRXOGFUHDWHDJDPHRIGLFHLQWKHLQQWRVHHLI\RX
win or lose gold (again, improve the chances of winning by working
RXW\RXUOXFNIDFWRULQWRWKHHTXDWLRQ 

Needless to say, your text adventure can grow exponentially


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

www.SFOpublications.com 163
Code Repository

Mouse Controlled Turtle


:HoYHDOUHDG\VHHQWKH7XUWOH 0286(7857/(3<
PRGXOHEHLQJFRQWUROOHGE\WKH 7KHƬUVWSLHFHRIFRGHSUHVHQWVWKHVWDQGDUG7XUWOHZLQGRZ
XVHUYLDWKHNH\ERDUGEXWQRZZH 3UHVV6SDFHDQGWKHQFOLFNDQ\ZKHUHRQWKHVFUHHQIRUWKH
7XUWOHWRGUDZWRWKHPRXVHSRLQWHU7KHVHFRQGDOORZV\RXWR
WKRXJKWZHoGVHHKRZWKHXVHU FOLFNWKH7XUWOHDQGGUDJLWDURXQGWKHVFUHHQEXWEHZDUQHG
FDQXVHWKHLUPRXVHDVDGUDZLQJ LWFDQFUDVK3\WKRQ
WRROZLWKLQ3\WKRQ:HKDYHWZR 1st Code Example:
SRVVLEOHFRGHH[DPSOHVKHUHSLFN
ZKLFKZRUNVEHVWIRU\RX IURPWXUWOHLPSRUW6FUHHQ7XUWOH

screen = Screen()
\HUWOH 7XUWOH

GHIN 
VFUHHQRQVFUHHQFOLFN FOLFN B KDQGOHU

GHIFOLFN B KDQGOHU [\ 


VFUHHQRQVFUHHQFOLFN 1RQH GLVDEOHHYHQWLQVLGH
HYHQW KDQGOHU
\HUWOHVHWKHDGLQJ \HUWOHWRZDUGV [\
\HUWOHJRWR [ \
VFUHHQRQVFUHHQFOLFN FOLFN B KDQGOHU UHHQDEOH
HYHQW RQ HYHQW KDQGOHU H[LW

VFUHHQRQNH\ N³³ VSDFHWXUQVRQPRXVHGUDZLQJ

VFUHHQOLVWHQ

VFUHHQPDLQORRS

2nd Code Example:

from turtle import *


VKDSH ³FLUFOH´
SHQFRORU ³EOXH´
ZLGWK 
ondrag(goto)
listen()

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

Python Alarm Clock


(YHUWDNHQDTXLFNEUHDNIURPZRUNLQJ try:
DWWKHFRPSXWHUWKHQVXGGHQO\UHDOLVHG LIPLQXWHV!
SULQW ³6OHHSLQJIRU³VWU PLQXWHV  XQLW B ZRUG
PDQ\PLQXWHVODWHUWKDW\RXoYHVSHQW sleep(seconds)
SULQW ³:DNHXS´
DOOWKDWWLPHRQ)DFHERRN",QWURGXFLQJ for i in range(5):
WKH3\WKRQDODUPFORFNFRGHZKHUH\RX SULQW FKU  
VOHHS 
FDQGURSLQWRWKHFRPPDQGSURPSWDQG H[FHSW.H\ERDUG,QWHUUXSW
SULQW ³,QWHUUXSWHGE\XVHU´
WHOOWKHFRGHKRZPDQ\PLQXWHVXQWLO V\VH[LW 
WKHDODUPJRHVRƪ
:DNH\:DNH\
$/$50&/2&.3< There’s some good use of try and except blocks here, alongside
VRPHRWKHUXVHIXOORRSVWKDWFDQKHOS\RXJHWDƬUPHU
7KLVFRGHLVGHVLJQHGIRUXVHLQWKHFRPPDQGSURPSWEHWKDW
understanding of how they work in Python. The code itself
:LQGRZV/LQX[RUPDF267KHUHDUHVRPHLQVWUXFWLRQVRQKRZ
can be used in a variety of ways: in a game where something
WRXVHLWLQWKHPDLQSULQWVHFWLRQEXWHVVHQWLDOO\LWoVS\WKRQ
happens after a set amount of time or simply as a handy
$ODUP&ORFNS\ WRJRRƪLQWHQPLQXWHV 
desktop alarm clock for your tea break.

import sys Linux users, try making the alarm clock code into an alias, so
import string you can run a simple command to execute it. Then, why not
from time import sleep integrate a user input at the beginning to ask the user for the
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

Vertically Scrolling Text


:KDWoVQRWWROLNHDERXWYHUWLFDOO\ (3,&6&52//3<
VFUROOLQJWH[W",WVXVHVDUHPDQ\ :HoYHXVHGWKHSRHP&LPPHULDE\5REHUW(+RZDUGIRUWKH
WKHEHJLQQLQJRIDJDPHRU FRGHoVVFUROOLQJWH[WDORQJZLWKDGUDPDWLFEODFNEDFNJURXQG
DQGUHGWH[W:HWKLQN\RXoOODJUHHLWoVTXLWHHSLF
LQWURGXFWLRQWRVRPHWKLQJHSLF
OLNHWKHEHJLQQLQJRIHYHU\6WDU
:DUVPRYLHDOLVWRIFUHGLWVDWWKH
import pygame as pg
HQGRIVRPHWKLQJVXFKDVD3\WKRQ IURPS\JDPHORFDOVLPSRUW
SUHVHQWDWLRQ7KHOLVWJRHVRQ SJLQLW

WH[W B OLVW µ¶¶

,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

GHIPDNH B WH[W VHOIPHVVDJH 


IRQW SJIRQW6\V)RQW µ$ULDO¶VHOIVL]H
WH[W IRQWUHQGHU PHVVDJH7UXHVHOIFRORU
UHFW WH[WJHW B UHFW FHQWHU VHOIVUHFW
FHQWHU[ VHOIVUHFWFHQWHU\  VHOIEXII B FHQWHU\ )
UHWXUQ WH[WUHFW

GHIPDNH B VXUIDFHV VHOI 


VHOIWH[W >@
IRU L OLQH LQHQXPHUDWH VHOIOVW 
O VHOIPDNH B WH[W OLQH
O>@\  L VHOIEXII B OLQHV
VHOIWH[WDSSHQG O

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

VFUHHQ SJGLVSOD\VHW B PRGH 


VFUHHQ B UHFW VFUHHQJHW B UHFW
FORFN SJWLPH&ORFN
UXQQLQJ 7UXH
FUHG &UHGLWV VFUHHQ B UHFWWH[W B OLVW

ZKLOHUXQQLQJ
IRUHYHQWLQSJHYHQWJHW 
LIHYHQWW\SH 48,7
running = False
VFUHHQ¿OO 
FUHGXSGDWH
FUHGUHQGHU VFUHHQ
SJGLVSOD\XSGDWH
FORFNWLFN 

www.SFOpublications.com 167
Code Repository

Python Digital Clock


7KHUHLVDOUHDG\DFORFNGLVSOD\HG ',*&/2&.3<
RQWKHGHVNWRSRIPRVWRSHUDWLQJ 7KLVLVDVXUSULVLQJO\KDQG\OLWWOHVFULSWDQGRQHWKDWZHoYH
V\VWHPVEXWLWoVDOZD\VKDQG\WR XVHGLQWKHSDVWLQVWHDGRIUHO\LQJRQDZDWFKRUHYHQWKH
FORFNLQWKHV\VWHPWUD\RIWKHRSHUDWLQJV\VWHP
KDYHRQHRQWRSRIWKHFXUUHQWO\
import time
RSHQZLQGRZ7RWKDWHQGZK\QRW import tkinter as tk
FUHDWHD3\WKRQGLJLWDOFORFNWKDW
GHIWLFN WLPH ¶¶ 
FDQEHDFRPSDQLRQGHVNWRSZLGJHW JHWWKHFXUUHQWWLPHIURPWKH3&
WLPH WLPHVWUIWLPH µ+06¶
IRU\RX LIWLPH WLPH
WLPH WLPH
FORFNFRQ¿J WH[W WLPH

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

GHIB B FOLFN VHOI 


LIVHOI B B EXWWRQ>µWH[W¶@ µ6WDUW¶
VHOI B B EXWWRQ>µWH[W¶@ µ6WRS¶
VHOI B B VWDUW WLPHFORFN
VHOI B B FRXQWHU VHOIDIWHU B LGOH VHOI B B XSGDWH
else:
VHOI B B EXWWRQ>µWH[W¶@ µ6WDUW¶
VHOIDIWHU B FDQFHO VHOI B B FRXQWHU

GHIB B XSGDWH VHOI 


QRZ WLPHFORFN
Another example, expanding on the original code, could be a GLII QRZVHOI B B VWDUW
digital stopwatch. For that you could use the following: VHOI B B VWDUW QRZ
VHOI B B WRWDO GLII
import tkinter VHOI B B WLPHVHW µ^I`¶IRUPDW VHOI B B WRWDO
import time VHOI B B FRXQWHU VHOIDIWHU B LGOH VHOI B B XSGDWH

FODVV6WRS:DWFK WNLQWHU)UDPH  LIB B QDPH B B µ B B PDLQ B B ¶


6WRS:DWFKPDLQ
@classmethod
def main(cls):
WNLQWHU1R'HIDXOW5RRW
URRW WNLQWHU7N

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 

The obvious improvements to the Ticker code lie in 7H[WEORFNVLQVHUWKHUH


the speed of the text and what the text will display.
Otherwise you can change the background colour of V ³7KLVLVDVFUROOLQJWLFNHUH[DPSOH$V\RX
the ticker window, the font and the font colour, along FDQ VHH LW¶V TXLWH ORQJ EXW FDQ EH D ORW ORQJHU LI
with the geometry of the Tkinter window if you want to. QHFHVVDU\ ³
V ³:H FDQ HYHQH[WHQGWKHOHQJWKRIWKHWLFNHU
<HWDQRWKHULQWHUHVWLQJHOHPHQWWKDWFRXOGEH PHVVDJH E\ LQFOXGLQJ PRUH YDULDEOHV ³
V ³7KH YDULDEOHV DUH ZLWKLQ WKH VYDOXHVLQ
introduced is one of the many text to Speech modules
WKH FRGH ³
DYDLODEOHIRU3\WKRQ<RXFRXOGSLSLQVWDOORQHLPSRUWLW V ³'RQ¶W IRUJHWWRFRQFDWHQDWHWKHPDOOEHIRUHWKH
then as the ticker displays the text, the text to speech )RU ORRS DQG UHQDPH WKH µVSDFHU¶ VYDULDEOH WRR´
function will read out the variable at the same time, since
the entire text is stored in the variable labelled ‘s’. SDGIURQWDQGHQGRIWH[WZLWKVSDFHV
V µ µ WH[W B ZLGWK
 FRQFDWHQDWH LW DOO
V V  V  V  VVV
[ 
\ 
WH[W FDQYDVFUHDWH B WH[W [\DQFKRU ¶QZ¶WH[W V
font=font)
G[ 
G\ XVHKRUL]RQWDOPRYHPHQWRQO\

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

Simple Python Calculator


6RPHWLPHVWKHVLPSOHVWFRGHFDQEH
WKHPRVWHƪHFWLYH7DNHIRUH[DPSOH
WKLV6LPSOH3\WKRQ&DOFXODWRUVFULSW
,WoVEDVHGRQWKH&UHDWH<RXU2ZQ
0RGXOHVVHFWLRQVHHQHDUOLHUEXW
GRHVQoWXWLOLVHDQ\H[WHUQDOPRGXOHV
&$/&8/$7253<
:HFUHDWHGVRPHIXQFWLRQGHƬQLWLRQVWREHJLQZLWKWKHQOHDG
RQWRWKHXVHUPHQXDQGLQSXWV,WoVDQHDV\SLHFHRIFRGHWR
IROORZDQGDVVXFKFDQDOVREHH[SDQGHGZHOOWRR

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´

FKRLFH LQSXW ³?Q(QWHUFKRLFH  ´

QXP LQW LQSXW ³?Q(QWHU¿UVWQXPEHU³


QXP LQW LQSXW ³(QWHU VHFRQG QXPEHU ³

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

Playing Music with the


Winsound Module
2IFRXUVHLQVWHDGRISOD\LQJDQ 086,&3<
H[LVWLQJ03\RXFDQDOZD\V 7KHFRGHXWLOLVHVERWKWKH7LPHDQG:LQVRXQGPRGXOHV
PDNH\RXURZQPXVLF7KHFRGH GHƬQLQJWKHWRQHDQGSLWFKDQGLQVHUWLQJVPDOOSDXVHVRI
RIDVHFRQG
EHORZZLOOSOD\RXW3DFKHOEHOoV
&DQRQLQ'QROHVV LPSRUWZLQVRXQG
import time
1
W 
S 

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

for i in range (5): 6ZHHW0XVLF


Obviously the Winsound module is a Windows-only set of
ZLQVRXQG%HHS O& W functions for Python. Open your IDLE in Windows and copy the
ZLQVRXQG%HHS K&W
code in. Press F5 to save and execute, then press the Enter key,
ZLQVRXQG%HHS K( W
as instructed in the code, to start the music.
ZLQVRXQG%HHS K* W
WLPHVOHHS S
1DWXUDOO\\RXFDQVZDSRXWWKHZLQVRXQG%HHSIUHTXHQF\DQG
ZLQVRXQG%HHS O* W durations to suit your own particular music; or you can leave it as
ZLQVRXQG%HHS * W is and enjoy. Perhaps play around with the various methods to
ZLQVRXQG%HHS % W make other music.
ZLQVRXQG%HHS K' W
WLPHVOHHS S  For example, players of the Nintendo classic game, The Legend
of Zelda: Ocarina of Time, can enjoy the game’s titular musical
ZLQVRXQG%HHS O$ W
intro by entering:
ZLQVRXQG%HHS $ W
ZLQVRXQG%HHS K& W
LPSRUWZLQVRXQG
ZLQVRXQG%HHS K( W
EHHS ZLQVRXQG%HHS
WLPHVOHHS S
c = [
ZLQVRXQG%HHS O( W
 
ZLQVRXQG%HHS (W
 
ZLQVRXQG%HHS * W
 
ZLQVRXQG%HHS % W
 
WLPHVOHHS S 
3  
 
ZLQVRXQG%HHS O) W
 
ZLQVRXQG%HHS ) W
 
ZLQVRXQG%HHS $ W
 
ZLQVRXQG%HHS K& W
 
WLPHVOHHS S 
 
 
ZLQVRXQG%HHS OO& W
 
ZLQVRXQG%HHS &W
 
ZLQVRXQG%HHS ( W
 
ZLQVRXQG%HHS * W
 
WLPHVOHHS S

]
ZLQVRXQG%HHS O) W
ZLQVRXQG%HHS ) W
V FF
ZLQVRXQG%HHS $ W
ZLQVRXQG%HHS K& W
IRUIGLQV
WLPHVOHHS S 
EHHS IG
ZLQVRXQG%HHS O* W
ZLQVRXQG%HHS * W
ZLQVRXQG%HHS % W
ZLQVRXQG%HHS K' W
WLPHVOHHS S

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

Hangman Game Script


+DQJPDQLVDJUHDWJDPHWR +$1*0$13<
SURJUDPLQWR3\WKRQ,WFDQEH :HoYHPDGHD+DQJPDQJDPHERDUG WKHJDOORZV RXWRI
H[WUHPHO\FRPSOH[GLVSOD\LQJ FKDUDFWHUVWKDWFDQEHGLVSOD\HGLQWKH,'/(6KHOODORQJZLWK
DKXJHEDQNRIZRUGVWRUDQGRPO\FKRRVHIURP
JUDSKLFVWKHQXPEHURIJXHVVHVOHIW
LQWKHVHFUHWZRUGDKXJHEDQNRI
DYDLODEOHZRUGVSLFNHGDWUDQGRP import random

DQGFRXQWOHVVRWKHUHOHPHQWV,WFDQ ERDUG >µ¶¶


DOVREHTXLWHVLPSOH+HUHZHKDYHD !!!!!!!!!!+DQJPDQ
PL[EHWZHHQWKHWZR

| |
|
|
|
|
¶¶¶µ¶¶


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


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


| |
O |
__
|
|
¶¶¶µ¶¶


| |
O |
_?_
|
|
¶¶¶µ¶¶


| |
O |
_?_
_

174 www.SFOpublications.com
Hangman Game Script

| luggage responsible ambassador circumstance


¶¶¶µ¶¶ FRQJUDWXODWH IUHTXHQW¶VSOLW
UHWXUQ EDQN>UDQGRPUDQGLQW OHQ EDQN @

| | def main():
O | JDPH +DQJPDQ UDQG B ZRUG
_?_ ZKLOH QRW JDPHKDQJPDQ B RYHU 
?_ JDPHSULQW B JDPH B VWDWXV
| XVHU B LQSXW LQSXW µ?Q(QWHUDOHWWHUµ
¶¶¶@ JDPHJXHVV XVHU B LQSXW

JDPHSULQW B JDPH B VWDWXV 


FODVV+DQJPDQ LI JDPHKDQJPDQ B ZRQ 
GHIB B LQLW B B VHOIZRUG   SULQW µ?Q&RQJUDWXODWLRQV<RXKDYHZRQ¶
VHOIZRUG ZRUG else:
VHOIPLVVHG B OHWWHUV >@ SULQW µ?Q6RUU\\RXKDYHORVW¶
VHOIJXHVVHG B OHWWHUV >@ SULQW µ7KH ZRUG ZDV µ  JDPHZRUG

GHIJXHVV VHOIOHWWHU  SULQW µ?Q*RRGE\H?Q¶


LIOHWWHULQVHOIZRUGDQGOHWWHUQRWLQVHOI
JXHVVHG B OHWWHUV LIB B QDPH B B ³ B B PDLQ B B ´
 VHOIJXHVVHG B OHWWHUVDSSHQG OHWWHU main()
HOLI OHWWHU QRW LQ VHOIZRUG DQG OHWWHUQRWLQ
VHOIPLVVHG B OHWWHUV
 VHOIPLVVHG B OHWWHUVDSSHQG OHWWHU
else:
return False
48,7
UHWXUQ 7UXH Since this is the last example in our Python code repository, we
thought we’d go out with a bang and feature the hangman
GHIKDQJPDQ B RYHU VHOI  gallows being drawn with each incorrect guess of the word.
UHWXUQVHOIKDQJPDQ B ZRQ RU OHQ VHOIPLVVHG B Don’t worry if it looks misaligned in the text here, this is merely
letters) == 6)
GXHWRWKHGLƪHUHQFHVEHWZHHQXVLQJWKH3\WKRQ,'/(HGLWRU
GHIKDQJPDQ B ZRQ VHOI  and pasting the code into a word processor (which formats
LIµ B ¶QRWLQVHOIKLGH B ZRUG  WKLQJVGLƪHUHQWO\ 
 UHWXUQ7UXH
return False There’s plenty you can do to improve, enhance and expand on
ZKDWZHoYHSUHVHQWHGKHUH<RXFDQLQFOXGHDURXWLQHWKDW
GHIKLGH B ZRUG VHOI  UHWXUQVDQHUURULIWKHXVHUHQWHUVDQXPEHURUFKDUDFWHU<RX
UWQ µ¶ can include extra points for someone who guesses the entire
IRU OHWWHULQVHOIZRUG word in one go rather than one letter at a time and you could
LIOHWWHUQRWLQVHOIJXHVVHG B OHWWHUV
perhaps add Chopin’s Funeral March should you lose the game;
UWQ µ B ¶
or something celebratory if you win.
else:
 UWQ OHWWHU
return rtn

GHISULQW B JDPH B VWDWXV VHOI 


SULQW ERDUG>OHQ VHOIPLVVHG B OHWWHUV @
SULQW µ:RUG µ  VHOIKLGH B ZRUG
SULQW µ/HWWHUV 0LVVHG µ 
IRU OHWWHU LQ VHOIPLVVHG B OHWWHUV
 SULQW OHWWHU 
print ()
SULQW µ/HWWHUV*XHVVHGµ
IRU OHWWHU LQ VHOIJXHVVHG B OHWWHUV
 SULQW OHWWHU Consider replacing the bank of words too. They’re found under
print () the bank list, and could easily be swapped out for something
PRUHGLƯFXOW,I\RXGRZQORDGZZZJLWKXEFRPGZ\OHQJOLVK
GHIUDQG B ZRUG  ZRUGV\RXFDQƬQGDWH[WGRFXPHQWZLWKRYHUZRUGV
EDQN µDELOLW\DERXWDERYHDEVROXWHDFFHVVLEOH Perhaps you could swap the words in the bank to instead read
accommodation accounting beautiful bookstore WKHFRQWHQWVRIWKHWH[WƬOH
FDOFXODWRU FOHYHU HQJDJHG HQJLQHHU HQRXJK
handsome refrigerator opposite socks interested GHIUDQG B ZRUG 
VWUDZEHUU\ EDFNJDPPRQ DQQLYHUVDU\ FRQIXVHG ZLWKRSHQ ³KRPHSL'RZQORDGVZRUGVW[W´³UW´ DVI
dangerous entertainment exhausted impossible  EDQN IUHDGOLQHV
RYHUZHLJKW WHPSHUDWXUH YDFDWLRQ VFLVVRUV UHWXUQEDQN>UDQGRPUDQGLQW OHQ EDQN @
DFFRPPRGDWLRQ DSSRLQWPHQW GHFUHDVH GHYHORSPHQW
HDUWKTXDNH HQYLURQPHQW EUDQG HQYLURQPHQW QHFHVVDU\

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

178 Creating a Loading Screen


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

www.SFOpublications.com 177
Coding Projects & Tips

Creating a Loading Screen


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

/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

percent = (loading * 100) // seconds


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

#Main Code Start


os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
loading _ screen(.5) The code works in much the same way as the previous except, instead
RIUHDGLQJIURPDWH[WƬOHLWoVUXQQLQJWKURXJKDIRUORRSWKDWSULQWV
print (“\nYour code begins here...”)
Loading… followed by an animation of sorts, along with a percentage
counter; clearing the screen every second and displaying the new results.
The code is quite simple: import the OS and Time modules and then create ,WoVVLPSOH\HVEXWTXLWHHƪHFWLYHLQLWVGHVLJQ
a Python function called loading_screen with a (seconds) option. Within
WKHIXQFWLRQRSHQWKHWH[WƬOHZLWKWKH$6&,,DUWDVUHDGRQO\DQGFUHDWH
D)RUORRSWKDWoOOUHDGWKHWH[WƬOHRQHOLQHDWDWLPH1H[WSULQWWKHOLQHV
&20%,1,1*7+(7:2
– incidentally, the OLQHVHQG oo element will strip the newline from the How about combining the two elements we’ve looked at? Let’s begin with
text document, without it you’ll end up with a double-line spaced display. a Loading… progress bar, followed by the loading screen. After that, you
,QFOXGHWKHWLPLQJLQVHFRQGVDQGFORVHWKHWH[WƬOHEXƪHU can include your own code and continue your program. Here’s the code:
7KHƬQDOSDUWRIWKHFRGH0DLQ&RGH6WDUWLVZKHUH\RXoOOFOHDUWKH
import os
screen (CLS for Windows, Clear for Linux and macOS) and call the import time
function, together with the output number of seconds to wait for each
line to be written to the screen – in this case, .5 of a second. def loading _ bar(seconds):
for loading in range(0,seconds+1):
Save the code as screens.
percent = (loading * 100) // seconds
py, drop into a Command print(“\n”)
Prompt or Terminal and print(“Loading...”)
execute it. The screen print(“<” + (“-” * loading) + (“ “ * (seconds-
will clear and your ASCII loading)) + “> “ + str(percent) + “%”)
DUWLQVLGHWKHWH[WƬOH print(“\n”)
will load in line-by-line, time.sleep(1)
creating a loading os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
VFUHHQHƪHFW

Loading… def loading _ screen(seconds):


screens=open(“screens.txt”, ‘r’)
for lines in screens:
print(lines, end=’’)
time.sleep(seconds)
screens.close()

#Main Code Start


loading _ bar(10)
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
loading _ screen(.5)
Another favourite introduction screen is that of a simple loading
animation, where the word loading is displayed followed by some
characters and a percentage of the program loaded. While it may not print (“\nYour code begins here...”)
WDNHORQJIRU\RXU3\WKRQFRGHWRORDGWKHHƪHFWFDQEHLQWHUHVWLQJ
Create a New File in Python and enter the following code:

import os You can of course pull those functions up wherever and whenever you
import time want in your code and they’ll display, as they should, at the beginning.
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!! <”

#Start the countdown


for counter in range(start, 0, -1):
if counter == 10:
ten()
elif counter == 9:
nine()
elif counter == 8:
eight()
elif counter == 7:
seven()
elif counter == 6:
six()
elif counter == 5:
¿YH
elif counter == 4:
four()
elif counter == 3:
three()
elif counter == 2:
two()
elif counter == 1:
one()
Let’s begin with some example code that will display a large countdown time.sleep(1)
from ten, then clear the screen and display a message. The code itself is os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
quite simple, but lengthy. You will need to start by importing the OS and
Time modules, then start creating functions that display the numbers:
$QGƬQDOO\ZHFDQDGGDGLVSOD\IRUWKHPHVVDJH

#Display the message


print(“v^v^v^v^v^v^v^v^v^v^v^v^v^v^v”)
print(“< >”)
print(message)
print(“< >”)
print(“v^v^v^v^v^v^v^v^v^v^v^v^v^v^v”)
print(“\n\n\n”)

The code in its entirety can be viewed


from within our Code Repository: KWWSV
EGPSXEOLFDWLRQVFRPFRGHSRUWDO, where
you’re free to copy it to your own Python IDLE
DQGXVHLWDV\RXVHHƬW7KHHQGHƪHFWLVTXLWH
good and it’ll be worth adding to your own
games, or presentations, in Python.

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

You may need to tweak the


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

www.SFOpublications.com 181
Coding Projects & Tips

Tracking the ISS with Python


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

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.

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


of the location of the ISS, we need the image to be reasonably small so it
doesn’t drown out the locations on the map, but also prominent enough As we’re going to be using Turtle, a component of tkinter, the downloaded
to see when the map is loaded. We opted for an image that’s 32 x 22 images will need to be converted to GIF, since this is the default and
SL[HOVLQVL]H'RQoWZRUU\WRRPXFKLI\RXoUHQRWDEOHWRƬQGRQHWKDWVPDOO recommended image format. You can easily look up a converter online, but
you can always resize it in an image-editing app such as Paint or GIMP. XVLQJ3DLQWLQ:LQGRZVRU*,03ZKLFKLVFURVVSODWIRUPZLOOVXƯFH

182 www.SFOpublications.com
Tracking the ISS with Python

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

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


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

First, we need to import the modules used in the code: json, turtle, urlib.
request, time and webbrowser. The json and urlib.request modules deal
with the data being pulled from the APIs, turtle will display the graphics,
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

#Setup world map in Turtle


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

screen.register _ shape(“iss.gif”)
iss = turtle.Turtle()
iss.shape(“iss.gif”)
iss.setheading(45)
iss.penup()

This section of the code sets up the graphical window containing the
world map and the ISS icon. To begin we set up the turtle screen, using
the resolution of the world map image we downloaded at the start of
this tutorial (1280 x 720). The screen.setworldcoordinates syntax will
mark the boundaries of the screen, creating the x and y coordinates of

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

#Update the ISS location on the map


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

www.SFOpublications.com 185
Coding Projects & Tips

Using Text Files


for Animation
Animation in Python can be handled with the likes of the Tkinter and Pygame modules,
however, there’s more than one way to achieve a decent end result. Using some clever, text
ƬOHUHDGLQJFRGHZHFDQFUHDWHFRPPDQGOLQHDQLPDWLRQV

$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

67(3 7RUHFDSZHKDYHDEDWFKƬOHFDOOHGEDWS\EDW, 67(3 Drop into a Windows command prompt, and


which asks the user their name and stores the navigate to the folder Batpy. To run a Windows
info as a system variable called QDPH. It will then print a message EDWFKƬOHVLPSO\HQWHUWKHFRPPDQG
WRWKHVFUHHQUXQWKH3\WKRQFRGHDQGƬQDOO\SULQWp,WZRUNHGq
EDWS\EDW
The Python code, called EDWS\S\, uses the OS module to call
RVHQYLURQ>nQDPHo@, stored as n. It’ll then print the value of n after Enter your name as instructed, and the reply will be passed to
a message. 3\WKRQWKHQEDFNWRWKHEDWFKƬOHWRHQG

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

Glossary of Python Terms


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

Argument Expression
The detailed extra information used by Python to perform more Essentially, Python code that produces a value of something.
detailed commands. Can also be used in the command prompt to
specify a certain runtime event. Float
$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.

Interactive Shell Random


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

Kernel Range
The core of an operating system, which handles data processing, $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

For a full list of titles available please visit:


www.pclpublications.com
Get Your Exclusive
FREE Gift Worth
£9.99 Here!
Download
Your FREE
Copy of
Tech Shopper
Magazine
Head over to your web
browser and follow these
simple instructions...

1/ Enter the following URL: www.pclpublications.com/exclusives


2/ Sign up/in and from the listings of our exclusive customer downloads, highlight
the Tech Shopper Magazine option.
3/ Enter your unique download code (Listed below) in the “Enter download code” bar.
4/ Click the Download Now! Button and your file will automatically download.
5/ Your file is a high resolution PDF file, which is compatible with the majority of
customer devices/platforms.

Exclusive Download Code: PCL37862RE

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!

Visit us at: www.pclpublications.com


%6CD@58;CACD!?>7?;D&C=BC<# 9C.B:C-D$AD=C5?B><DA6CD87=:6?<C= <D<@;CD=C<8@><B3B;BA2DA@D9CAC=5B>C +B>7D!B>A0D',&,0D?>9D,88;C-D,99BAB@>?;DB5?1C<D:@>A?B>C9D/BA6B>
A6CD<7BA?3B;BA2D@4DA6B<D3@@*D?>9DBA<D:@>AC>AD4@=D/6?AC.C=D87=8@<C-D A6B<D873;B:?AB@>D?=CD=C8=@97:C9D7>9C=D;B:C>:CD4=@5D&67AAC=<A@:*-
      CD?9.B<CD?;;D8@AC>AB?;D372C=<DA@D:6C:*D;B<AB>1D8=B@=DA@D87=:6?<C ,>2DB5?1C<D=C8=@97:C9D@>DA6CD4=@>AD:@.C=D?=CD<@;C;2D4@=D9C<B1>
D D$&'#D((( ( 4@=D:@>4B=5?AB@>D@4D?:A7?;D:@>AC>A-D,;;DC9BA@=B?;D@8B>B@>D6C=CB>DB< 87=8@<C<D?>9D?=CD>@AD=C8=C<C>A?AB.CD@4D:@>AC>A-
)73;B<6C9D32#D)?8C=:7AD+B5BAC9D A6?AD@4DA6CD=C.BC/C=D(D?<D?>DB>9B.B97?;D(D?>9DB<D>@AD=C8=C<C>A?AB.CD@4 )=B:C<0DB>AC=>?AB@>?;D?.?B;?3B;BA20D=?AB>1<0DABA;C<D?>9D:@>AC>AD?=CD
A6CD873;B<6C=D@=D?>2D@4DBA<D?44B;B?AC<-D%6C=C4@=CDA6CD873;B<6C=D6@;9< <73C:ADA@D:6?>1C-D,;;DB>4@=5?AB@>D/?<D:@==C:AD?ADAB5CD@4D
B1BA?;D9B<A=B37AB@>D32#D)@:*CA5?1<DDB>B@DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DD)?8C=:7AD+B5BAC9D,;;D=B16A<D=C<C=.C9-D'@D8?=AD@4DA6B<D >@D=C<8@><B3B;BA2DB>D=C1?=9DA@DC9BA@=B?;D@8B>B@>D?>9D:@>AC>A- 873;B:?AB@>-D&@5CD:@>AC>AD5?2D6?.CD3CC>D8=C.B@7<;2D873;B<6C9DB>
873;B:?AB@>D5?2D3CD=C8=@97:C9DB>D?>2D4@=50D<A@=C9DB>D?D=CA=BC.?; %6B<DB<D?>DB>9C8C>9C>AD873;B:?AB@>D?>9D?<D<7:6D9@C<D>@AD @A6C=D.@;75C<D@=DABA;C<-
<2<AC5D@=DB>AC1=?AC9DB>A@D?>2D@A6C=D873;B:?AB@>0D9?A?3?<CD@=D >C:C<<?=B;2D=C4;C:ADA6CD.BC/<D@=D@8B>B@><D@4DA6CD5?>74?:A7=C=<D@=
:@55C=:B?;D8=@1=?5<D/BA6@7ADA6CDC8=C<<D/=BAAC>D8C=5B<<B@>D@4 6?=9/?=CD?>9D<@4A/?=C0D?88;B:?AB@><D@=D8=@97:A<D:@>A?B>C9D/BA6B>-  
A6CD873;B<6C=-D>9C=D>@D:B=:75<A?>:C<D<6@7;9DA6B<D873;B:?AB@>D?>9 %6B<D873;B:?AB@>DB<D>@ADC>9@=<C9D@=D?<<@:B?AC9DB>D?>2D/?2D/BA6D "C1B<AC=C9DB>D>1;?>9DD?;C<D'@#D 
BA<D:@>AC>A<D3CD=C<@;90D;@?>C9D@7AD@=D7<C9DB>D?>2D4@=5D32D/?2D@4 )2A6@>0D%6CD+B>7D@7>9?AB@>0D%6CD"?<83C==2D)BD@7>9?AB@>0D,"!
A=?9CD/BA6@7ADA6CD873;B<6C= <D/=BAAC>D8C=5B<<B@>-D6B;CD/CD8=B9CD @;9B>10D?>@>B:?;D+A90D C3B?>D)=@C:A0D+B>7D!B>A0D!B:=@<@4A0 , "%$&$'DDD@=D@7=D;?AC<AD5C9B?D8?:*<D8;C?<CD:@>A?:A#D
@7=<C;.C<D@>DA6CD7?;BA2D@4DA6CDB>4@=5?AB@>D/[email protected])?8C=:7A +C>@.@0D C;;0DC/;CAA()?:*?=90D,88;CD?>9D&?5<7>1D@=D?>2D ?5C<D?;CD(D1?;C8:;873;B:?AB@><-:@5
+B5BAC9D=C<C=.C<DA6CD=B16AD>@ADA@D3CD6C;9D=C<8@><B3;CD4@=D?>2D ?<<@:B?ACD@=D?44B;B?ACD:@58?>2-D,;;D:@82=B16A<0DA=?9C5?=*<D?>9D @=DC5?B;D(D?9.C=AB<B>18:;873;B:?AB@><-:@5
5B<A?*C<D@=DB>?::7=?:BC<D4@7>9D/BA6B>DA6CDACAD@4DA6B<D873;B:?AB@>- =C1B<AC=C9DA=?9C5?=*<D4@=DA6CD=C<8C:AB.CD:@58?>BC<D?=CD $'%"',%$',+D+$'&$'DD)?8C=:7AD+B5BAC9D6?<D5?>2D1=C?A
7CDA@DA6CD>?A7=CD@4DA6CDAC:6DB>97<A=20DA6CD873;B<6C=D:?>>@AD ?:*>@/;C91C9-D"C;C.?>AD1=?86B:DB5?1C=2D=C8=@97:C9D/BA6D 873;B:?AB@><D?>9D?;;D?=CD?.?B;?3;CD4@=D;B:C><B>1D/@=;9/B9C-D
17?=?>ACCDA6?AD?;;D?88<D?>9D<@4A/?=CD/B;;D/@=*D@>DC.C=2D.C=<B@>D@4 :@7=AC<2D@4D+C>@.@0DC/;CAA(D)?:*?=90D C;;0D!B:=@<@4A0D&?5<7>10 @=D5@=CDB>4@=5?AB@>DC5?B;#D1?;C8:;873;B:?AB@><-:@5

You might also like