100% found this document useful (1 vote)
188 views162 pages

Python Coding Manual & Tutorials

Uploaded by

brahimmousaid932
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
188 views162 pages

Python Coding Manual & Tutorials

Uploaded by

brahimmousaid932
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Papercut’s Features Python & Linux

CODING MANUAL

FREE
DIGITAL
MAGAZINE
DOWNLOAD
Worth £9.99
See inside for details

Learn more about Python


to improve your coding OVER
and programming skills
160 PAGES

Discover how Python


820+
Professional tricks,
works, what it can do tips and step-by-step
and how to code it tutorials + projects

100% INDEPENDENT
Save a Huge

ALL Digital Manuals!*

have teamed up with


to bring you this incredible offer. Not only can you learn new skills and
master your tech, but you can now SAVE 50% off all of our coding,
photography and consumer tech digital manuals!

To take advantage of this amazing offer visit:


[Link]/product-category/digital/
Make your selection(s) and then simply use the following exclusive
code at checkout to get your purchase at half price:

ZINIO50
*Please note this exclusive single use per user discount code requires sign up for activation.
Discount cannot be applied against discounted items, print titles or used with an additional discount code.
Papercut’s

CODING MANUAL
Unlock your imagination with Python...

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
ˬˢ˨Ϡ˟˟Ѓˡ˗˘˩˘˥ˬ˧˛˜ˡ˚ˬˢ˨ˡ˘˘˗˧ˢ˞ˡˢ˪˧ˢ˕˘˖ˢˠ˘
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.

M a s te r yo u r te c h @ w w w. p c l p u b l i c a ti o n s .c o m
Contents

Contents
6 Getting Started
8 Being a Programmer 16 Why Python?
10 A Brief History of Coding 18 Python on the Pi
12 What can You Do with Python? 20 Using Virtual Machines
14 Python in Numbers 22 Creating a Coding Platform

Hello World 24
26 Equipment You Will Need 44 Using Comments
28 Getting to Know Python 46 Working with Variables
30 How to Set Up Python in Windows 48 User ,nput
32 How to Set Up Python in Linux 50 Creating Functions
34 Starting Python for the First Time 52 Conditions and Loops
36 Your First Code 54 Python Modules
38 Saving and Executing Your Code 56 Python Errors
40 Executing Code from the 58 Combining What You Know So Far
Command Line
60 Python in Focus: Stitching
42 Numbers and Expressions Black Holes

62 Working with Data


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

4 3\WKRQ&RGLQJ 3URJUDPPLQJ
Contents

Using Modules 88
90 Calendar Module 100 Pygame Module
92 OS Module 104 Basic Animation
94 Using the Math Module 106 Create Your Own Modules
96 Random Module 108 Python in Focus:
98 Tkinter Module ArtiƬcial ,ntelligence

110 Code Repository


112 Python File Manager 124 Vertically Scrolling Text
114 Number Guessing Game 126 Python Digital Clock
116 Random Number Generator 128 Playing Music with the Winsound
117 Random Password Generator Module
118 Text to Binary Convertor 130 Text Adventure Script
120 Basic GU, File Browser 132 Python Scrolling Ticker Script
122 Mouse Controlled Turtle 133 Simple Python Calculator
123 Python Alarm Clock 134 Hangman Game Script

Understanding Linux 136


138 What is Linux? 150 Useful System and
Disk Commands
140 Using the Filesystem
152 Using the Man Pages
142 Listing and Moving Files
154 Editing Text Files
144 Creating and Deleting Files
156 Linux Tips and Tricks
146 Create and Remove Directories
158 A-Z of Linux Commands
148 Copying, Moving and
Renaming Files 160 Glossary of Python Terms

fff_R[_dQ[XRPcX^]bR^\ 5
Index

6 3\WKRQ&RGLQJ 3URJUDPPLQJ
Getting Started

Python is a high-level, general-purpose


programming language that was
developed by Guido van Rossum in the
late eighties and is based upon a number
of other languages, while being the
successor to the popular ABC language.
It has been devised to work on a human
level, so it’s readable and understandable
without needing to delve into obscure
volumes of machine code, hexadecimal
characters, or even ones and zeros. It’s
clear, logical, comprehensive, powerful
and functional, yet also easy to follow
and learn.
<ou will Ƭnd Python at the heart of some
of the most interesting and cutting-edge
technologies in the world. It’s the code
that binds supercomputer algorithms
together; it’s used in the space industry,
and in science and engineering. AI, and
the likes of Alexa and Siri, Cortana and
the Google Assistant all utilise Python for
their powerful voice recognition
technology. It’s simply an amazing,
versatile and incredible language to learn.
So let’s get started and explore what you
need to become a Python programmer.

8 Being a Programmer
10 A Brief History of Coding
12 What can You Do with Python?
14 Python in Numbers
16 Why Python?
18 Python on the Pi
20 Using Virtual Machines
22 Creating a Coding Platform

ZZZSFOSXEOLFDWLRQVFRP 7
Getting Started

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 3\WKRQ&RGLQJ 3URJUDPPLQJ
Being a Programmer

MORE THAN CODE


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

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


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

“It’s up to you
creating something from a few lines of BASIC code was achievable and so
the Ƭrst generation of home-bred programmer was born.

how far to take


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

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

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

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


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

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


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

Being able to see the big picture is certainly beneƬcial for the modern
programmer. Undoubtedly, as a programmer, you will be part of a team
of other programmers, and more than likely part of an even bigger team
of designers, all of whom are creating a Ƭnal product. While you may only
be expected to create a small element of that Ƭnal product, being able to
understand what everyone else is doing will help you create something
that’s ultimately better than simply being locked in your own coding cubicle.

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


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

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


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

ZZZSFOSXEOLFDWLRQVFRP 9
Getting Started

A Brief History of Coding


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

01000011 01101111 01100100 01101001 01101110 01100111


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

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

It’s diƯcult to pinpoint an exact


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

Ada Lovelace translated


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

10 3\WKRQ&RGLQJ 3URJUDPPLQJ
A Brief History of Coding

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

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

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

The Internet age brought a wealth of new


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

The Ƭrst true computer code was


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

ZZZSFOSXEOLFDWLRQVFRP 11
Getting Started

What can You


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

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

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


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

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

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

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

12 3\WKRQ&RGLQJ 3URJUDPPLQJ
What can You Do with Python?

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

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


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

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


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

A lot of the online MM25PG MassiYely MultiSlayer 2nline 5ole


WEB DEVELOPMENT Playing Game games aYailable utilise Python as a comSanion
language for the serYerside elements 7hese include code to
search for Sotential cheating load balancing across the gameos
Web development has moved on considerably since the early
serYers Slayer sNill matchmaNing and to checN whether the Slayeros
days of HTML scripting in a limited text editor. The many
clientside game matches the serYeros Yersions 7hereos also a
frameworks and web management services available now
Python module that can be included in a Minecraft server, enabling
means that building a page has become increasingly complex.
the server admin to add blocNs, send messages and automate a lot
of the bacNground comSle[ities of the game
With Python, the web developer has the ability to create
dynamic and highly secure web apps, enabling interaction with
other web services and apps such as Instagram and Pinterest.
Python also allows the collection of data from other websites
and even apps built within other websites.
PYTHON EVERYWHERE
As you can see, Python is quite a versatile
programming language. By learning Python,
you are creating a well-rounded skillset that’s
able to take you into the next generation of
computing, either professionally or simply as
a hobbyist.

Whatever route you decide to take on your


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

ZZZSFOSXEOLFDWLRQVFRP 1
Getting Started
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
some ama]ing facts and Ƭgures
surrounding one of the most popular
programming languages of recent years.

Alexa, Amazon’s Virtual Data analysis and


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

in 202
PYTHON AND
LINUX SKILLS
N UMBERS

As of the end of 202,


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

OVER 75 OF 90 OF ALL IT’S ESTIMATED


RECOMMENDED FACEBOOK POSTS THAT OVER 75 OF
CONTENT FROM NETFLIX ARE FILTERED NASA’S WORKFLOW
IS GENERATED FROM THROUGH PYTHONǕ AUTOMATION
MACHINE LEARNING ǟ CODED MACHINE SYSTEMS ONǕBOARD
CODED BY PYTHON. LEARNING. THE I.S.S. USE PYTHON.

14 3\WKRQ&RGLQJ 3URJUDPPLQJ
Python in Numbers

16,000 PYTHON SKILLǕBASED


POSITIONS ARE THE

th
MOST SOUGHTǕAFTER
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 USE 10 DEVELOPERS
AND STILL USE, PYTHON , WHEREAS PYTHON ON A DAYǕTOǕ USE PYTHON 
PYTHON AS THEIR 25 STILL USE THE DAY BASIS, 21 USE AS THEIR MAIN
PRIMARY OR OUTDATED PYTHON 2 IT AS A SECONDARY PROGRAMMING
SECONDARY LANGUAGE. VERSION. LANGUAGE. LANGUAGE.

ZZZSFOSXEOLFDWLRQVFRP 15
Getting Started

Why Python?
There are many diƪerent programming languages available for the modern computer,
and some still available for older 8 and 16-bit computers too. Some of these languages
are designed for scientiƬc work, others for mobile platforms and such. So why choose
Python out of all the rest?

PYTHON POWER
Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee
hours, slaving over an overheating heap of circuitry to create something akin to magic.

7hese Sioneers of Srogramming 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, /inu[, Smart 7V, games console, MP Slayer, GPS device builtin
across the screen ,t may not sound terribly e[citing to a generation to a car, settoS bo[ or a thousand other connected and ‘smart’
that’s used to ultra highdeƬnition graShics and oSen world, multi aSSliances, behind them all is Srogramming
Slayer online gaming However, fortysomething 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 7hese
Naturally these bedroom coders helSed form the foundations for instructions form the Srogramming core of the device and that core
every Siece of digital technology we use today Some went on to can be built using a variety of Srogramming languages
become chief develoSers for toS software comSanies, whereas
others Sushed the available hardware to its limits and founded the 7he languages in use today diƪer deSending on the situation, the
billion Sound gaming emSire that continually ama]es us Slatform, the device’s use and how the device will interact with its

16 3\WKRQ&RGLQJ 3URJUDPPLQJ
Why Python?

environment or users OSerating 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 Srogram a
form of visualbased language Games generally use C++ whilst web comSuter ,t’s Serfect for the hobbyist, enthusiast, student, teacher
Sages can use a Slethora of available languages such as H7ML, -ava, and those who simSly need to create their own uniTue interaction
Python and so on between either themselves or a Siece of external hardware and the
comSuter itself
More generalSurSose Srogramming is used to create Srograms,
aSSs, software or whatever else you want to call them 7hey’re Python is free to download, install and use and is available for Linux,
widely used across all hardware Slatforms and suit virtually every Windows, macOS, MSDOS, OS, BeOS, ,BM iseries machines, and
conceivable aSSlication Some oSerate faster than others and some even R,SC OS ,t has been voted one of the toS Ƭve Srogramming
are easier to learn and use than others Python is one such general languages in the world and is continually evolving ahead of the
SurSose language hardware and ,nternet develoSment curve

Python is what’s Nnown as a HighLevel Language, in that it ‘talNs’ So to answer the Tuestion why Python? SimSly Sut, it’s free, easy to
to the hardware and oSerating system using a variety of arrays, learn, exceStionally Sowerful, universally acceSted, eƪective and a
variables, obMects, arithmetic, subroutines, looSs and countless suSerb learning and educational tool
more interactions Whilst it’s not as streamlined as a LowLevel
Language, which can deal directly with memory addresses, call
stacNs and registers, its beneƬt is that it’s universally accessible
and easy to learn

BASIC was once the starter language that early


8-bit home computer users learned.

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

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


and makes for an ideal beginner’s programming language.

ZZZSFOSXEOLFDWLRQVFRP 17
Getting Started

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

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

While having a far more powerful coding platform on which to kits available will provide the Pi with a pre-loaded SD card (with the
write and test your code is ideal, it’s not often feasible. Most of us latest Raspbian OS), a case, power socket and cables, this is a good
are unable to jump into a several hundred-pound investment when idea as you could, with very little eƪort, leave the Pi plugged into the
we’re starting oƪ and this is where the Raspberry Pi can help out. wall under a desk, while still being able to connect to it and code.

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

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

18 [Link]
Python on the Pi

There’s no such
thing as too
much Pi!

THE PI TAKE 5!
Introduced on 28th September 2023, the Raspberry Pi 5 was
a signiƬƬcant leap in terms of Pi performance and hardware
speciƬcations. It was also one of the biggest leaps in functionality
and user interaction. You’ll also Ƭnd a pair of USB 3.0 ports, Bluetooth 5.0, and a GPU
that’s capable of handing K resolutions and OpenGL graphics.
With a new 2.GHz, 6-bit, quad-core ARM Cortex-A76 processor, In short, the Pi 5 is the most powerful of the current Raspberry Pi
and a choice of GB, or 8GB memory versions, the Pi 5 is models. However, the diƪerent memory versions have an increased
one step closer to becoming a true desktop computer. In addition, cost. The GB version costs around £50, and the 8GB Pi 5 will set
the Pi 5 was launched to continue with the decision to include dual you back around £80. Remember to also factor in one or two micro-
monitor support, in the form of a pair of two micro-HDMI ports. HDMI cables with your order.

RASPBERRY PI OS BOOKWORM
In addition to releasing the Pi 5, the Raspberry Pi team also compiled
a new version of the Raspberry Pi OS operating system, which has
been codenamed as Bookworm. In conjunction with the new
hardware the Pi 5 boasts, Bookworm does oƪer a few updates.

Although on the whole it’s very similar inappearance and operation


to the previous version of Raspberry Pi OS. The updates are mainly
in-line with the graphical and visual enhancements, playback and
security, to fully exploit the Pi 5’s new set of graphical drivers and
performance enhancements. In short, what you see in this book will
work with the Raspberry Pi 5 and Raspberry Pi OS Bookworm!

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.

[Link] 19
Getting Started

Using Virtual Machines


A Virtual Machine allows you to run an entire operating system from within an app
RQ\RXUGHVNWRS7KLVZD\\RXoUHDEOHWRKRVWPXOWLSOHV\VWHPVLQDVHFXUHVDIHDQG
isolated environment. In short, it’s an ideal way to code.

Sounds good, but what exactly is a Virtual Machine (VM) and


how does it work?
7KHRƯFLDOGHƬQLWLRQRIDYLUWXDOPDFKLQHLVnDQHƯFLHQWLVRODWHG
GXSOLFDWHRIDUHDOFRPSXWHUPDFKLQHo7KLVEDVLFDOO\PHDQVWKDWD
YLUWXDOPDFKLQHLVDQHPXODWHGFRPSXWHUV\VWHPWKDWFDQRSHUDWHLQ
H[DFWO\WKHVDPHZD\DVDSK\VLFDOPDFKLQHEXWZLWKLQWKHFRQƬQHV
RIDGHGLFDWHGYLUWXDOPDFKLQHRSHUDWRURU+\SHUYLVRU

7KH+\SHUYLVRULWVHOILVDQDSSWKDWZLOODOORZ\RXWRLQVWDOOD
VHSDUDWHRSHUDWLQJV\VWHPFUHDWLQJDYLUWXDOFRPSXWHUV\VWHP
ZLWKLQLWVHOIFRPSOHWHZLWKDFFHVVWRWKH,QWHUQHW\RXUKRPH
QHWZRUNDQGVRRQ

7KH+\SHUYLVRUZLOOWDNHUHVRXUFHVIURPWKHKRVWV\VWHP\RXU
SK\VLFDOFRPSXWHUWRFUHDWHWKHYLUWXDOFRPSXWHU7KLVPHDQVWKDW
SDUWRI\RXUSK\VLFDOFRPSXWHUoVPHPRU\&38KDUGGULYHVSDFH
and other shared resources, will be set aside for use in the virtual You’re able to install Linux, and code inside a virtual
PDFKLQHDQGWKHUHIRUHZRQoWEHDYDLODEOHWRWKHSK\VLFDOFRPSXWHU machine on a Windows 10 host.
XQWLOWKHK\SHUYLVRUKDVEHHQFORVHGGRZQ

This resource overhead


VIRTUAL OS
FDQEHFULSSOLQJIRUWKH )URPZLWKLQDK\SHUYLVRU\RXoUHDEOHWRUXQDQXPEHURIGLƪHUHQW
SK\VLFDOPDFKLQHLI\RX RSHUDWLQJV\VWHPV7KHW\SHRI26GHSHQGVJUHDWO\RQWKH
don’t already have enough K\SHUYLVRU\RXoUHUXQQLQJDVVRPHDUHEHWWHUDWHPXODWLQJD
memory, or hard drive SDUWLFXODUV\VWHPRYHURWKHUV)RUH[DPSOH9LUWXDO%R[DIUHHDQG
VSDFHDYDLODEOHRU\RXU HDV\WRXVHK\SHUYLVRUIURP2UDFOHLVJUHDWDWUXQQLQJ:LQGRZV
FRPSXWHUKDVDSDUWLFXODUO\ DQG/LQX[YLUWXDOPDFKLQHVEXWLVQoWVRJRRGDW$QGURLGRUPDF26
VORZSURFHVVRU:KLOHLWoV 4(08LVJRRGIRUHPXODWLQJ$50SURFHVVRUVWKHUHIRUHLGHDOIRU
HQWLUHO\SRVVLEOHWRUXQ $QGURLGDQGVXFKEXWLWFDQEHGLƯFXOWWRPDVWHU
virtual machines on as little
DV*%RIPHPRU\LWoVQRW 7KHUHDUHSOHQW\RIK\SHUYLVRUVDYDLODEOHWRWU\IRUIUHHZLWKDQ
DGYLVDEOH,GHDOO\\RXZLOO 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,
\RXUSK\VLFDOFRPSXWHU :LWKLQDK\SHUYLVRU\RXoUHDEOHWRVHWXSDQGLQVWDOODQ\RIWKH
ZLOOEHJLQWRVXƪHUZLWK newer distributions of Linux, or if you feel the need, you’re also able
the loss of memory to the WRLQVWDOOVRPHRIWKHPRUHDQWLTXDWHGYHUVLRQV<RXFDQLQVWDOOHDUO\
YLUWXDOPDFKLQH DWOHDVW YHUVLRQVRI:LQGRZVHYHQDVIDUEDFNDV:LQGRZVFRPSOHWHZLWK
Our Linux titles contain WR*%RIIUHHVSDFHRQ '26sDOWKRXJK\RXPD\ƬQGVRPHIXQFWLRQDOLW\RIWKH90ORVW
steps on how to install a \RXUKDUGGULYHDQGDTXDG GXHWRWKHROGHUGULYHUV VXFKDVDFFHVVWRWKHQHWZRUN 
hypervisor and OS. FRUHSURFHVVRU DJDLQ\RX
FDQKDYHDGXDOFRUH&38 With this in mind then, you’re able to have an installation of Linux
EXWWKDWFDQFDXVHDERWWOHQHFNRQ\RXUSK\VLFDOFRPSXWHU  0LQWRUWKHODWHVWYHUVLRQRI8EXQWXUXQQLQJLQDQDSSRQ\RXU
:LQGRZV3&7KLVLVWKHEHDXW\RIXVLQJDYLUWXDOPDFKLQH
7KHOLPLWWRKRZPDQ\GLƪHUHQWYLUWXDOPDFKLQHV\RXKRVWRQ\RXU &RQYHUVHO\LI\RXUSK\VLFDOFRPSXWHUKDV/LQX[DVLWVLQVWDOOHG
SK\VLFDOFRPSXWHULVUHVWULFWHGWKHUHIRUHE\WKHDPRXQWRISK\VLFDO RSHUDWLQJV\VWHPWKHQZLWKDK\SHUYLVRU\RXoUHDEOHWRFUHDWHD
system resources you can allocate to each, while still leaving enough :LQGRZVYLUWXDOPDFKLQHsDOWKRXJK\RXZLOOQHHGWRKDYHD
IRU\RXUSK\VLFDOFRPSXWHUWRRSHUDWHRQ OLFHQFHFRGHDYDLODEOHWRUHJLVWHUDQGDFWLYDWH:LQGRZV

20 3\WKRQ&RGLQJ 3URJUDPPLQJ
Using Virtual Machines

Using virtual machines removes the need to dualboot Dualbooting


is having two, or more, Shysical oSerating systems installed on
ADVANTAGES FOR CODERS
the same, or multiSle, hard drives on a single comSuter As the )or the coder, having a virtual machine setuS oƪers many
comSuter Sowers uS, you’re given the oStion to choose which OS advantages, the most SoSular being crossSlatform code Meaning if
you want to boot into While this sounds liNe a more ideal scenario you write code within Windows , then with an installation of a
it isn’t always as straight forward as it sounds, as all the oSerating Linux distro in a hyServisor, you’re able to TuicNly and eƪortlessly
systems that are booted into will have full access to the comSuter’s Sower uS the virtual machine and test your code in a comSletely
entire system resources diƪerent oSerating system )rom this, you’re able to iron out any
bugs, tweaN the code so it worNs better on a diƪerent Slatform and
The Sroblems with dualbooting come when one of the oSerating exSand the reach of your code to nonWindows users
systems is uSdated Most uSdates cover security Satching, or bug
Ƭxing, however, some uSdates can alter the core  the Nernel, of 7he advantage of being able to conƬgure a develoSment
the OS When these changes are aSSlied, the uSdate may alter the environment, in sSeciƬc ways for sSeciƬc SroMects, is Tuite
way in which the OS starts uS, meaning the initial boot choice you invaluable Using a virtual machine setuS greatly reduces the
made could be overwritten, leaving you without the ability to access uncertainties that are inherent to having multiSle versions of
the other oSerating systems installed on the comSuter To rectify Srogramming languages, libraries, ,D(s and modules installed, to
this, you’ll need to access the Master Boot Record and alter the suSSort the many diƪerent SroMects you may become involved in as
conƬguration to reallow booting into the other systems There’s a coder (lements of code that ‘talN’ directly to sSeciƬcs of an
also the danger of Sossibly overwriting the Ƭrst installed OS, or oSerating system can easily be overcome, without the need to
overwriting data and more often than not, most oSerating systems clutter uS your main, host system with crossSlatform libraries,
don’t Slay well when running sidebyside ,ndeed, while good, dual which in turn may have an eƪect on other libraries within the ,D(
booting has more than its fair share of Sroblems ,n contrast, using a
virtual machine environment, while still Sroblematic at times, taNes Another element to consider is stability ,f you’re writing code
out some of the more nasty and disastrous asSects of using multiSle that could Sotentially cause some instability to the core OS
oSerating systems on a single comSuter during its develoSment Shase, then executing and testing that
code on a virtual machine maNes more sense than testing it on your
main comSuter where having to reSeatedly reboot, or reset
Even old operating systems can be run inside a
something due to
virtual machine.
the code’s
instabilities, can
become
ineƯcient and
Must Slain
annoying

The virtual
machine
environment can
be viewed as a Coding in Python on the Raspberry
sandbox, where Pi Desktop OS inside a VM on
you’re able to test Windows 10!
unsecure, or
unstable code without it causing harm, or doing damage, to your
main, worNing comSuter Viruses and malware can be isolated
within the VM without infecting the main comSuter, you’re able
to set uS anonymity ,nternet use within the VM and you’re able
to install thirdSarty software without it slowing down your
Virtual machines can be as simple, or as complex as your
main comSuter
needs require.

GOING VIRTUAL
While you’re at the early stages of coding, using a virtual machine
may seem a little excessive However, it’s worth looNing into because
coding in Linux can often be easier than coding in Windows, as some
versions of Linux have ,D(s Sreinstalled (ither way, virtualisation of
an oSerating system is how many of the Srofessional and successful
coders and develoSers worN, so getting used to it early on in your
sNill set is advantageous

To start, looN at installing VirtualBox Then consider taNing a looN


at our Linux titles, [Link]
type=product, to learn how to install Linux in a virtual environment
and how best to utilise the oSerating system

ZZZSFOSXEOLFDWLRQVFRP 21
Getting Started

Creating a
Coding Platform
The term ‘Coding Platform’ can denote a type of hardware, on which you can code,
or a particular operating system, or even a custom environment that’s pre-built and
designed to allow the easy creation of games. In truth it’s quite a loose term, as a
Coding Platform can be a mixture of all these ingredients, it’s simply down to what
programming language you intend to code in and what your end goals are.

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


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

The trick is to slow down and, to begin with, not look too deeply
into coding. Like all good projects, you need a solid foundation
on which to build your skill and to have all the necessary tools
available to hand to enable you to complete the basic steps. This
is where creating a coding platform comes in, as it will be your
learning foundation while you begin to take your Ƭrst tentative
steps into the wider world of coding.

HARDWARE SOFTWARE
ThanNfully, coding at the ,n terms of software,
foundation level doesn’t most of the develoSment
reTuire sSecialist eTuiSment, environments  the tools
or a toS of the range, liTuid that allow you to code,
hydrogencooled PC ,f you comSile the code and
own a comSuter, no matter execute it  are freely
how basic, you can begin to learn how to code Naturally, if available to download and install There are some sSecialist
your comSuter in Tuestion is a Commodore  then you may tools available that will cost, but at this level they’re not
have some diƯculty following a modern language tutorial, but necessary so don’t be fooled into thinNing you need to Surchase
some of the best Srogrammers around today started on an any extra software in order to start learning how to code
bit machine, so there’s hoSe yet
Over time, you may Ƭnd yourself changing from the
Access to the ,nternet is necessary to download, install and mainstream develoSment environment and using a collection
uSdate the coding develoSment environment, alongside a of your own, discovered, tools to write your code in ,t’s all
comSuter with either Windows , macOS, or Linux installed Sersonal Sreference in the end and as you become more
You can use other oSerating systems, but these are the ‘big exSerienced, you will start to use diƪerent tools to get the
three’ and you will Ƭnd that most code resources are written Mob done
with one, or all of these, in mind

22 3\WKRQ&RGLQJ 3URJUDPPLQJ
Creating a Coding Platform

OPERATING SYSTEMS VIRTUAL MACHINES


Windows  is the most A virtual machine is a Siece of software that allows you to install a
used oSerating system in fully worNing, oSerating system within the conƬnes of the software
the world, so it’s natural itself The installed OS will allocate userdeƬned resources from the
that the vast majority of host comSuter, Sroviding memory, hard drive sSace etc, as well as
coding tools are written for Microsoft’s leading oSerating sharing the host comSuter’s ,nternet connection
system However, don’t discount macOS and esSecially Linux
The advantage of a virtual
macOS users enjoy an eTual number of coding tools to their machine is that you can worN
Windows counterSarts ,n fact, you will Srobably Ƭnd that a with Linux, for examSle, without
lot of Srofessional coders use a Mac over a PC, simSly because it aƪecting your currently
of the fact that the Mac oSerating system is built on toS of installed host OS This means
Unix the commandline OS that Sowers much of the world’s that you can have Windows 
Ƭlesystems and servers  This Unix layer lets you test Srograms running, launch your virtual machine client, boot into Linux and use
in almost any language without using a sSecialised ,DE all the functionality of Linux while still being able to use Windows

Linux, however, is by far one of the most SoSular and This, of course, maNes it a fantastic coding Slatform, as you can
imSortant, coding oSerating systems available Not only have diƪerent installations of oSerating systems running from
does it have a UnixliNe bacNbone, but also it’s also free to the host comSuter while using diƪerent coding languages
download, install and use and comes with most of the tools You can test your code without fear of breaNing your host OS
necessary to start learning how to code Linux Sowers most of and it’s easy to return to a Srevious conƬguration without the
the servers that maNe uS the ,nternet ,t’s used on nearly all of need to reinstall everything again
the toS suSercomSuters, as well as sSeciƬcally in organisations
such as NASA, CERN and the military and it forms the base of Virtualisation is the Ney to most big comSanies now You will
AndroidSowered devices, smart TVs and incar systems Linux, Srobably Ƭnd, for examSle, rather than having a single server
as a coding Slatform, is an excellent idea and it can be installed with an installation of Windows Server, the ,T team have
inside a virtual machine without ever aƪecting the installation instead oSted for a virtualised environment whereby each
of Windows or macOS Windows Server instance is a virtual machine running from
several Sowerful machines This cuts down on the number
of Shysical machines, allows the team to better manage
resources and enables them to deSloy an entire server
dedicated to a Sarticular tasN in a fraction of the time
THE RASPBERRY PI
,f you haven’t already heard
of the RasSberry Pi, then
we suggest you head over MINIX NEO N42CǕ4
to [Link], and
checN it out ,n short, the RasSberry The NEO NC is an extraordinarily
Pi is a small, fully functional comSuter that comes with its own small comSuter from miniPC develoSer,
customised Linuxbased oSerating system, Sreinstalled with M,N,; Measuring just  x  x mm, this ,ntel N CPU
everything you need to start learning how to code in Python, Sowered, Windows  Pro Sreinstalled comSuter is one of the
C++, Scratch and more best coding Slatforms we’ve come across

,t’s incredibly cheaS, costing around ~ and allows you to utilise The beauty, of course, lies in the fact that with increased storage
diƪerent hardware, in the form of robotics and electronics and memory available, you’re able to create a comSuter that can
Srojects, as well as oƪering a comSlete desNtoS exSerience easily host multiSle virtual machines The virtual machines can
Although not the most Sowerful comSuting device in the world, cover Linux, Android and other oSerating systems, allowing you
the RasSberry Pi has a lot going for it, esSecially in terms of to write and test crossSlatform code without fear of damaging,
being one of the best coding Slatforms available or causing Sroblems, with other Sroduction or home comSuters

The M,N,; NEO NC starts at around ~, with the base
GB eMMC and GB of memory You’ll need to add another
YOUR OWN CODING PLATFORM hundred and Ƭfty, or so, to increase the sSeciƬcations, but
consider that a license for Windows  Pro alone costs ~
Whichever method you choose, remember that your coding
from the Microsoft Store and you can begin to see the beneƬts
Slatform will Srobably change, as you gain exSerience and favour
of oSting for a more imSressive hardware foundation over the
one language over another Don’t be afraid to exSeriment along
liNes of the RasSberry Pi
the way, as you will eventually create your own uniTue Slatform
that can handle all the code you enter into it

ZZZSFOSXEOLFDWLRQVFRP 2
Index

24 3\WKRQ&RGLQJ 3URJUDPPLQJ
Hello, World

Getting started with Python may seem a


little daunting at Ƭrst, but, thankfully, the
language has been designed with
simplicity in mind. Like most things, you
need to start slow, master the basics,
learn how to get a result, and how to get
what you want from the code.
This section covers numbers and
expressions, user input, conditions and
loops and the types of errors you will
undoubtedly come across in your time
with Python: the core foundations of
good coding and Python code.

26 Equipment You Will Need


28 Getting to Know Python
30 How to Set Up Python in Windows
32 How to Set Up Python in Linux
34 Starting Python for the First Time
36 Your First Code
38 Saving and Executing Your Code
40 Executing Code from the Command Line
42 Numbers and Expressions
44 Using Comments
46 Working with Variables
48 User Input
50 Creating Functions
52 Conditions and Loops
54 Python Modules
56 Python Errors
58 Combining What You Know So Far
60 Python in Focus: Stitching Black Holes

ZZZSFOSXEOLFDWLRQVFRP 25
Hello, World

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

WHAT WE’RE USING


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

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

AN IDE
An IDE (Integrated Developer Environment) is used to enter and execute Python
code. It enables you to inspect your program code and the values within the code, as
well as oƪering advanced features. There are many diƪerent IDEs available, so Ƭnd
the one that works for you and gives the best results.

PYTHON SOFTWARE
macOS and Linux already come with Python preinstalled as part of the operating
system, as does the Raspberry Pi. However, you need to ensure that you’re running
the latest version of Python. Windows users need to download and install Python,
which we’ll cover shortly.

TEXT EDITOR
Whilst a text editor is an ideal environment to enter code into, it’s not an absolute
necessity. You can enter and execute code directly from the IDLE but a text editor,
such as Sublime Text or Notepad++, oƪers more advanced features and colour coding
when entering code.

INTERNET ACCESS
Python is an ever evolving environment and as such new versions often introduce
new concepts or change existing commands and code structure to make it a more
eƯcient language. Having access to the Internet will keep you up-to-date, help you
out when you get stuck and give access to Python’s immense number of modules.

TIME AND PATIENCE


Despite what other books may lead you to believe, you won’t become a programmer
in 24-hours. Learning to code in Python takes time, and patience. You may become
stuck at times and other times the code will Ʈow like water. Understand you’re learning
something entirely new, and you will get there.

26 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
Equipment You Will Need

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

RASPBERRY PI
The Raspberry Pi  Model is the latest version,
incorporating a more powerful CPU, a choice of 4GB or
GB memory versions and Wi-Fi and Bluetooth support.
You can pick up a Pi  from around £, increasing up to
£ for the GB memory version, or as part of a kit
depending on the Pi model you’re interested in.

FUZE PROJECT
The FUZE is a learning environment built on the latest model
of the Raspberry Pi. You can purchase the workstations that
come with an electronics kit and even a robot arm for you
to build and program. You can Ƭnd more information on the
FUZE at [Link].

BOOKS
We have several great Raspberry Pi titles available via ZZZ
SFOSXEOLFDWLRQVFRP. Our Pi books cover how to buy your
Ƭrst Raspberry Pi,
set it up and use
RASPBIAN
it; there are some great step-
by-step project examples and
The Raspberry Pi’s main operating system is a Debian-based
guides to get the most from
Linux distribution that comes with everything you need in
the Raspberry Pi too.
a simple to use package. It’s streamlined for the Pi and is an
ideal platform for hardware and software projects, Python
programming and even as a desktop computer.

ZZZSFOSXEOLFDWLRQVFRP 27
Hello, World

Getting to
Know Python
Python is the greatest computer programming language ever created. It enables
you to fully harness the power of a computer, in a language that’s clean and easy
to{understand.

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

PYTHON PROGRAMMING RECIPES


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

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

28 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
Getting to Know Python

HIGHǕLEVEL LANGUAGES ZEN OF PYTHON


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

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

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

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

ZZZSFOSXEOLFDWLRQVFRP 29
Hello, World

How to Set Up
Python in Windows
Windows users can easily install the latest version of Python via the main Python
Downloads page. Whilst most seasoned Python developers may shun Windows as the
platform of choice for building their code, it’s still an ideal starting point for beginners.

INSTALLING PYTHON 3.X


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

STEP 1 Start by opening your web browser to [Link]. STEP 3 Choosing the Customise option allows you to
org/downloads/. Look for the button detailing the specify certain parameters, and whilst you may
Download link for Python 3.x. Python is regularly updated, changing stay with the defaults, it’s a good habit to adopt as, sometimes (not
the last digit for each bug Ƭx and update. Therefore, don’t worry if with Python, thankfully), installers can include unwanted additional
you see Python 3.8, or more, as long as it’s Python 3, the code in this features. On the Ƭrst screen available, ensure all boxes are ticked
book will work Ƭne. and click the Next button.

STEP 2 Click the Download button for version 3.x and STEP 4 The next page of options include some interesting
save the Ƭle to your Downloads folder. When the additions to Python. Ensure the Associate Ƭle with
Ƭle is downloaded, double-click the executable and the Python Python, Create Shortcuts, Add Python to Environment Variables,
installation wizard will launch. From here, you have two choices: Precompile Standard Library and Install for All Users options are
Install Now and Customise Installation. We recommend opting for ticked. These make using Python later much easier. Click Install when
the Customise Installation link. you’re ready to continue.

30 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
How to Set Up Python in Windows

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

STEP 6 Before you close the install wizard window STEP 9 If you now click on the Windows Start button again,
however, it’s best to click on the link next to the and this time type: CMD, you’ll be presented with
shield detailed Disable Path Length Limit. This will allow Python the Command Prompt link. Click it to get to the Windows command
to bypass the Windows 260 character limitation, enabling you to line environment. To enter Python within the command line, you
execute Python programs stored in deep folders arrangements. need to type: python and press Enter.
Click Yes again, to authenticate the process, then you can Close the
installation window.

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

ZZZSFOSXEOLFDWLRQVFRP 31
Hello, World

How to Set Up
Python in Linux
While the Raspberry Pi’s operating system contains the latest, stable version of Python,
other Linux distros don’t come with Python 3 pre-installed. If you’re not going down
the Pi route, then here’s how to check and install Python for Linux.

PYTHON PENGUIN
Linux is such a versatile operating system that it’s often diƯcult to nail down just one-way of doing something. Diƪerent
distributions go about installing software in diƪerent ways, so for this particular tutorial we will stick to Linux Mint.

First you need to ascertain which version of Python Once the update and upgrade completes, enter:
STEP 1 STEP 4
is currently installed in your Linux system. To begin python3 --version again to see if Python 3.x is
with, drop into a Terminal session from your distro’s menu, or hit the updated, or even installed. As long as you have Python 3.x, you’re
Ctrl+Alt+T keys. running the most recent major version, the numbers after the 3.
indicate patches plus further updates. Often they’re unnecessary,
but they can contain vital new elements.

Next, enter: python --version into the Terminal


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

However, if you want the latest, cutting edge


STEP 5
version, you’ll need to build Python from source.
Start by entering these commands into the Terminal:
sudo apt-get install build-essential checkinstall
sudo apt-get install libreadline-gplv2-dev
libncursesw5-dev libssl-dev libsqlite3-dev tk-dev
In our case we have both Python 2 and 3 installed.
STEP 3 libgdbm-dev libc6-dev libbz2-dev
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.

32 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
How to Set Up Python in Linux

Open up your Linux web browser and go to the For the GUI IDLE, you’ll need to enter the following
STEP 6 STEP 9
Python download page: [Link] command into the Terminal:
downloads. Click on the Downloads, followed by the button under
sudo apt-get install idle3
the Python Source window. This opens a download dialogue box,
choose a location, then start the download process. The IDLE can then be started with the command: idle3. Note, that
IDLE runs a diƪerent version to the one you installed from source.

In the Terminal, go to the Downloads folder


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

Within the Python folder, enter:


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

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

ZZZSFOSXEOLFDWLRQVFRP 33
Hello, World

Starting Python for


the First Time
The Raspberry Pi oƪers one of the best all-round solutions on which to learn and code,
in particular, Python. Raspbian, the Pi’s recommended OS, come pre-installed with the
latest stable version of Python 3, which makes it a superb coding platform.

STARTING PYTHON
Everything you need to begin programming with Python is available from the Raspberry Pi desktop. However, if you want,
drop into the Terminal and update the system with: sudo apt-get update.

STEP 1 With the Raspbian desktop loaded, click on the STEP 3 For example, in the Shell enter: 2+2
Menu button followed by Programming > Python After pressing Enter, the next line displays the
3 (IDLE). This opens the Python 3 Shell. Windows and Mac users can answer: 4. Basically, Python has taken the ‘code’ and produced the
Ƭnd the Python 3 IDLE Shell from within the Windows Start button relevant output.
menu and via Finder.

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, where you’re able to try out interactions with the system. Integers, which are the inƬnite
some simple code and processes. sequence of whole numbers can easily be added, subtracted,
multiplied and so on.

34 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
Starting Python for the First Time

STEP 5 While that’s very interesting, it’s not particularly STEP 8 The Python IDLE is a conƬgurable environment. If
exciting. Instead, try this: you don’t like the way the colours are represented,
then you can always change them via Options > ConƬgure IDLE and
print(“Hello everyone!”)
clicking on the Highlighting tab. However, we don’t recommend
Just enter it into the IDLE as you’ve done in the previous steps. that, 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 Just like most programs available, regardless of the
your Ƭrst bit of code. The Print command is fairly operating system, there are numerous shortcut
self-explanatory, it prints things. Python 3 requires the brackets as keys available. We don’t have room for them all here but within the
well as quote marks in order to output content to the screen, in this Options > ConƬgure IDLE and under the Keys tab, you can see a list
case the ‘Hello everyone!’ bit. of the current bindings.

STEP 7 You may have noticed the colour coding within STEP 10 The Python IDLE is a power interface and one
the Python IDLE. The colours represent diƪerent that’s actually been written in Python using one
elements of Python code. They are: of the available GUI toolkits. If you want to know the many ins and
outs of the Shell, we recommend you take a few moments to view
Black – Data and Variables Blue – User Functions
[Link]/3/library/[Link], which details many of
Green – Strings Dark Red – Comments
the IDLE’s features.
Purple – Functions Light Red – Error Messages
Orange – Commands

ZZZSFOSXEOLFDWLRQVFRP 35
Hello, World

Your First Code


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

PLAYING WITH PYTHON


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, reopen it in STEP 3 You can see that instead of the number 4, the
whichever operating system version you prefer. In output is the 2+2 you asked to be printed to the
the Shell, enter the familiar following: screen. The quotation marks are deƬning what’s being outputted
to the IDLE Shell; to print the total of 2+2 you need to remove
print(“Hello”)
the quotes:
print(2+2)

STEP 2 Just as predicted, the word Hello appears in the STEP 4 You can continue as such, printing 2+2, 464+2343
Shell as blue text, indicating output from a string. and so on to the Shell. An easier way is to use a
It’s 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

36 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
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:
You now have two variables containing a Ƭrst name and a surname
print(a)
and you 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 both a and b individually, as you’ve asked using the + symbol, the name wouldn’t appear
them to be printed separately. If you want to add them up, you can correctly in the output in the Shell. Try it:
use the following:
print(name+surname)
print(a+b)
You need a space between the two, deƬning them as two separate
This code simply takes the values of a and b, adds them together values and not something you mathematically play around with.
and outputs the result.

STEP 7 You can play around with diƪerent kinds of variables STEP 10 In Python 3 you can separate the two variables
and the Print function. For example, you could with a space using a comma:
assign variables for someone’s name:
print(name, surname)
name=”David”
Alternatively, you can add the space yourself:
print(name)
print(name+” “+surname)
The use of the comma is much neater, as you can see.
Congratulations, you’ve just taken your Ƭrst steps into the wide
world of Python.

ZZZSFOSXEOLFDWLRQVFRP 37
Hello, World

Saving and Executing


Your Code
While working in the IDLE Shell is perfectly Ƭne for small code snippets, it’s not
designed for entering longer program listings. In this section you’re going to be
introduced to the IDLE Editor, where you will be working 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 and when it’s up, STEP 3 You can see that the same colour coding is in place
click on File > New File. This will open a new window in the IDLE Editor as it is in the Shell, enabling you
with Untitled as its name. This is the Python IDLE Editor and within it to better understand what’s going on with your code. However, to
you can enter the code needed to create your future programs. execute the code you need to Ƭrst save it. Press F and you get 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; much in the same vein as Sublime. You enter The destination can be a dedicated folder called Python or you
code as you would within the Shell, so taking an example from the can just dump it wherever you like. Remember to keep a tidy drive
previous tutorial, enter: though, to help you out in the future.
print(“Hello everyone!”)

38 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
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. Once the from the previous tutorial:
Python code is saved it’s executed and the output will be detailed in
a=2
the IDLE Shell. In this case, the words ‘Hello everyone!’.
b=2
name=”David”
surname=”Hayward”
print(name, surname)
print (a+b)
If you press F5 now you’ll be asked to save the Ƭle, again, as it’s been
modiƬed from before.

STEP 6 This is how the vast majority of your Python code STEP 9 If you click the OK button, the Ƭle will be
will be conducted. Enter it into the Editor, hit F5, overwritten with the new code entries, and
save the code and look at the output in the Shell. Sometimes things executed, with the output in the Shell. It’s not a problem with just
will diƪer, depending on whether you’ve requested a separate these few lines but if you were to edit a larger Ƭle, overwriting can
window, but essentially that’s the process. It’s the process we will become an issue. Instead, use File > Save As from within the Editor
use throughout this book, unless otherwise stated. to create a backup.

STEP 7 If you open the Ƭle location of the saved Python STEP 10 Now create a new Ƭle. Close the Editor, and open
code, you can see that it ends in a .py extension. a new instance (File > New File from the Shell).
This is the default Python Ƭle name. Any code you create will be Enter the following and save it as [Link]:
[Link] 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)
You will use this code in the next tutorial.

ZZZSFOSXEOLFDWLRQVFRP 39
Hello, World

Executing Code from


the Command Line
Although we’re working from the GUI IDLE throughout this book, it’s worth taking
a look at Python’s command line handling. We already know there’s a command line
version of Python but it’s also used to execute code.

COMMAND THE CODE


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

STEP 1 Python, in Linux, comes with two possible ways of STEP 3 Now you’re at the command line we can start
executing code via the command line. One of the Python. For Python 3 you need to enter the
ways is with Python 2, whilst the other uses the Python 3 libraries command python3 and press Enter. This will put you into the
and so on. First though, drop into the command line or Terminal on command line version of the Shell, with the familiar three right-
your operating system. facing arrows as the cursor (>>>).

STEP 2 Just as before, STEP 4 From here you’re able to enter the code you’ve
we’re using a looked at previously, such as:
Raspberry Pi: Windows users will
a=2
need to click the Start button and
print(a)
search for CMD, then click the
Command Line returned search; You can see that it works exactly the same.
and macOS users can get access
to their command line by clicking
Go > Utilities > Terminal.

40 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
Executing Code from the Command Line

STEP 5 Now enter: exit() to leave the command line Python STEP 8 The result of running Python 3 code from the
session and return you back to the command Python 2 command line is quite obvious. Whilst it
prompt. Enter the folder where you saved the code from the doesn’t error out in any way, due to the diƪerences between the
previous tutorial and list the available Ƭles within; hopefully you way Python 3 handles the Print command over Python 2, the result
should see the [Link] Ƭle. isn’t as we expected. Using Sublime for the moment, open the
[Link] Ƭle.

STEP 6 From within the same folder as the code you’re STEP 9 Since Sublime Text isn’t available for the Raspberry
going to run, enter the following into the Pi, you’re going to temporarily leave the Pi for the
command line: moment and use Sublime as an example that you don’t necessarily
need to use the Python IDLE. With the [Link] Ƭle open, alter it to
python3 [Link]
include the following:
This will execute the code we created, which to remind you is:
name=input(“What is your name? “)
a=”Python” print(“Hello,”, name)
b=”is”
c=”cool!”
print(a, b, c)

STEP 7 Naturally, since this is Python 3 code, using the STEP 10 Save the [Link] Ƭle and drop back to the
syntax and layout that’s unique to Python 3, it only command line. Now execute the newly saved
works when you use the python3 command. If you like, try the same code with:
with Python 2 by entering:
python3 [Link]
python [Link]
The result will be the original Python is cool! statement, together
with the added input command asking you for your name, and
displaying it in the command window.

ZZZSFOSXEOLFDWLRQVFRP 41
Hello, World

Numbers and Expressions


We’ve seen some basic mathematical expressions with Python, simple addition and the
like. Let’s expand on that now 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 with the mathematical powers of Python; as with most, if not all, programming
languages, maths is the driving force behind the code.

STEP 1 Open up the GUI version of Python 3, as mentioned STEP 3 You can use all the usual mathematical operations:
you can use either the Shell or the Editor. For the divide, multiply, brackets and so on. Practise with a
time being, you’re going to use the Shell just to warm our maths few, for example:
muscle, which we believe is a small gland located at the back of the
1/2
brain (or not).
6/2
2+2*3
(1+2)+(3*4)

STEP 2 In the Shell enter the following: STEP 4 You’ve no doubt noticed, division produces a
decimal number. In Python these are called Ʈoats,
2+2
or Ʈoating point arithmetic. However, if you need an integer as
54356+34553245
opposed to a decimal answer, then you can use a double slash:
99867344*27344484221
1//2
You can see that Python can handle some quite large numbers.
6//2
And so on.

42 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
Numbers and Expressions

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

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

STEP 7 Numbers and expressions don’t stop there. Python STEP 10 Execute the code from Step 9, and you can see a
has numerous built-in functions to work out sets series of True or False statements, depending on
of numbers, absolute values, complex numbers and a host of the result of the two deƬning values: 6 and 7. It’s an extension of
mathematical expressions and Pythagorean tongue-twisters. For what you’ve looked at, and an important part of programming.
example, to convert a number to binary, use:
bin(3)

ZZZSFOSXEOLFDWLRQVFRP 43
Hello, World

Using Comments
When writing your code, the Ʈow, what each variable does, how the overall program
will operate and so on is all inside your head. Another programmer could follow the
code line by line but over time, it can become diƯcult to read.

COMMENTS!
Programmers use a method of keeping their code readable by commenting on certain sections. If a variable is used, the
programmer comments on what it’s supposed to do, for example. It’s just good practise.

STEP 1 Start by creating a new instance of the IDLE Editor STEP 3 Resave the code and execute it. You can see that the
(File > New File) and create a simple variable and output in the IDLE Shell is still the same as before,
print command: despite the extra lines being added. Simply put, the hash symbol (#)
denotes a line of text the programmer can insert to inform them,
a=10
and others, of what’s going on without the user being aware.
print(“The value of A is,”, a)
Save the Ƭle and execute the code.

STEP 2 Running the code will return the line: The value of A STEP 4 Let’s assume that the variable A that we’ve created
is, 10 into the IDLE Shell window, which is what we is the number of lives in a game. Every time the
expected. Now, add some of the types of comments you’d normally player dies, the value is decreased by 1. The programmer could
see within code: insert a 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)

44 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
Using Comments

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

STEP 6 Essentially, the new code together with comments STEP 9 The comment, the hash symbol, can also be used to
could look like: comment out sections of code you don’t want to be
executed in your program. For instance, if you wanted to remove
# Set the start value of A to 10
the Ƭrst print statement, you would use:
a=10
# Print the current value of A # print(“The value of A is,”, a)
print(“The value of A is,”, a)
# Player lost a life!
a=a-1
# Inform player, and display current value of A
(lives)
print(“You’ve just lost a life!”)
print(“You now have”, a, “lives left!”)

STEP 7 You can use comments in diƪerent ways. For STEP 10 You also use three single quotes to comment
example, Block Comments are a large section of out a Block Comment or multi-line section of
text that details what’s going on in the code, such as telling the code comments. Place them before and after the areas you want to
reader what variables you’re planning on using: comment for them to work:
# 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 who haven’t
being very smelly, the code at least slept or washed in weeks. Despite being very
# works really well. smelly, the code at least works really well.
’’’

ZZZSFOSXEOLFDWLRQVFRP 45
Hello, World

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
You’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 You’ve seen previously that 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. For example, in the Shell enter: “ + title). The middle part between the quotations allows us to
name=”David Hayward” (or use your own name, unless you’re add a colon and a space, as variables are connected without spaces,
also called David Hayward). so we need to add them manually.

STEP 2 You can check the type of variable in use by STEP 4 You can also
issuing the type () command, placing the name of combine variables
the 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 Vikings”. and title variables into a new
variable we use:
character=name + “: “ +
title
Then output the content of the
new variable as:
print (character)
Numbers are stored as diƪerent
variables:
age=44
Type (age)
Which, as we know, are integers.

46 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
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 to
integer type variables in the same command, as you work with a number that’s been inputted by the
would a set of similar variables. You need to either turn one into the user, as age + 10 won’t work due to being a string variable and an
other or vice versa. When you do try to combine both, you get an integer. Instead, you need to enter:
error message:
int(age) + 10
print (name + age)
This will TypeCast the age string into an integer that can be
worked with.

STEP 6 This is a process known as TypeCasting. The Python STEP 9 The use of TypeCasting is also important when
code is: dealing with Ʈoating point arithmetic; remember:
numbers that have a decimal point in them. For example, enter:
print (character + “ is “ + str(age) + “ years
old.”) shirt=19.99
or you can use: Now enter type(shirt) and you’ll see that Python has allocated
the number as a ‘Ʈoat’, because the value contains a decimal point.
print (character, “is“, age, “years old.”)
Notice again that in the last example, you don’t need the spaces
between the words in quotes as the commas treat each argument
to print separately.

STEP 7 Another example of TypeCasting is when you ask for STEP 10 When combining integers and Ʈoats Python
input from the user, such as a name. for example, usually converts the integer to a Ʈoat, but should
enter: the reverse ever be applied it’s worth remembering that Python
doesn’t return the exact value. When converting a Ʈoat to an
age= input (“How old are you? “)
integer, Python will always round down to the nearest integer,
All data stored from the Input command is stored as a string variable. called truncating; in our case instead of 19.99 it becomes 19.

ZZZSFOSXEOLFDWLRQVFRP 47
Hello, World

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 would 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. For example, a game may
ask for a character’s name, whereas a database can ask for personal details.

STEP 1 If it’s not already, open the Python 3 IDLE Shell, STEP 3 Now that we have the user’s name stored in a
and start a New File in the Editor. Let’s begin with couple of variables we can call them up whenever
something really simple, enter: we want:
print(“Hello”) print(“Welcome”, firstname, surname, “. I hope
firstname=input(“What is your first name? “) you’re well today.”)
print(“Thanks.”)
surname=input(“And what is your surname? “)

STEP 2 Save and execute the code, and as you already no STEP 4 Run the code and you can see a slight issue, the
doubt suspected, in the IDLE Shell the program will full stop after the surname follows a blank space.
ask for your Ƭrst name, storing it as the variable Ƭrstname, followed To eliminate that we can add a plus sign instead of the comma in
by your surname; also stored in its own variable (surname). the code:
print(“Welcome”, firstname, surname+“. I hope
you’re well today.”)

48 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
User Input

STEP 5 You don’t always have to include quoted text within STEP 8 What you’ve created here is a condition, which we
the input command. For example, you can ask the will cover soon. In short, we’re using the input from
user their name, and have the input in the line below: the user and measuring it against a condition. So, if the user enters
David as their name, the guard will allow them to pass unhindered.
print(“Hello. What’s your name?”)
Else, if they enter a name other than David, the guard challenges
name=input()
them to a Ƭght.

STEP 6 The code from the previous step is often regarded STEP 9 Just as you learned previously, any input from a
as being a little neater than having a lengthy user is automatically a string, so you need to apply a
amount of text in the input command, but it’s not a rule that’s set in TypeCast in order to turn it into something else. This creates some
stone, so do as you like in these situations. Expanding on the code, interesting additions to the input command. For example:
try this:
# Code to calculate rate and distance
print(“Halt! Who goes there?”) print(“Input a rate and a distance”)
name=input() rate = float(input(“Rate: “))

STEP 7 It’s a good start to a text adventure game, perhaps? STEP 10 To Ƭnalise the rate and distance code, we can add:
Now you can expand on it and use the raw input
distance = float(input(“Distance:
from the user to Ʈesh out the game a little:
“))
if name==”David”: print(“Time:”, (distance / rate))
print(“Welcome, good sir. You may pass.”)
Save and execute the code and enter some numbers. Using the
else:
Ʈoat(input element, we’ve told Python that anything entered is a
print(“I know you not. Prepare for battle!”)
Ʈoating point number rather than a string.

ZZZSFOSXEOLFDWLRQVFRP 49
Hello, World

Creating Functions
Now that you’ve mastered the use of variables and user input, the next step is to tackle
functions. You’ve already used a few functions, such as the print command but Python
enables you to deƬne your own functions.

FUNKY FUNCTIONS
A function is a command that you enter into Python 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 just data that a function works on. They can STEP 3 You can pass variables through functions in much
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 that’s code (enter the text editor for this example):
followed 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 3,
inside the brackets, so if you wanted to know how many letters navigate to [Link]/3/library/[Link]. These
are in the word antidisestablishmentarianism, then you’d enter: are the predeƬned functions, but since users have created many
len(“antidisestablishmentarianism”) and the number 28 more, they’re not the only ones available.
would return.

50 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
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 you’ve
They add functions and can be imported as and when required. For just imported it into Python, you can utilise the square root function.
example, to use advanced mathematics functions enter: To do so, enter:
import math [Link](16)
Once entered, you have access to all the Math module functions. You can see that the code is presented as [Link](data).

FORGING FUNCTIONS
There are many diƪerent functions you can import created by other Python programmers and you will undoubtedly come
across some excellent examples in the future; you can also create your own with the def command.

STEP 1 Choose File > New File to enter the editor, let’s STEP 3 To modify it further, delete the Hello(“David”) line,
create a function called Hello, that greets a user. the last line in the script and press Ctrl+S to save
Enter: the new script. Close the Editor and create a new Ƭle (File > New
File). Enter the following:
def Hello():
print (“Hello”) from Hello import Hello
Hello() Hello(“David”)
Press F5 to save and run the script. You can see Hello in the Shell, Press F5 to save and execute the code.
type in Hello() and it returns the new function.

STEP 2 Let’s now expand the function to accept a STEP 4 What you’ve just done is import the Hello function
variable, the user’s name for example. Edit your from the saved [Link] program and then used it
script to read: to say hello to David. This is how modules and functions work: you
import the module then use the function. Try this one, and modify
def Hello(name):
it for extra credit:
print (“Hello”, name)
def add(a, b):
Hello(“David”)
result = a + b
This will now accept the variable name, otherwise it prints Hello
return result
David. In the Shell, enter: name (“Bob”), then: Hello(name). Your
function can now pass variables through it.

ZZZSFOSXEOLFDWLRQVFRP 51
Hello, World

Conditions and Loops


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

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

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

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

52 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
Conditions and Loops

STEP 5 Press F5 and save the code to execute it. Enter STEP 6 Now expand the code to include another 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 it’s the word is four letters. added a condition for three-letter words:
Now press F5 again and rerun the program but this time enter a
word=input(“Please enter a four-letter word: “)
Ƭve-letter word. The Shell will display that it’s not a four-letter word.
word_length=len(word)
if word_length == 4:
print (word, “is a four-letter word. Well
done.”)
elif word_length == 3:
print (word, “is a three-letter word. Try again.”)
else:
print (word, “is not a four-letter word.”)

LOOPS
A loop looks quite similar to a condition but they are somewhat diƪerent in their operation. A loop will run through the same
block of code a number of times, usually with the support of a condition.

STEP 1 Let’s start with a simple While statement. Like IF, STEP 3 The For loop is another example. For is used to
this will check to see if something is TRUE, then run loop over a range of data, usually a list stored as
the indented code: variables inside square brackets. For example:
x = 1 words=[“Cat”, “Dog”, “Unicorn”]
while x < 10:
for word in words:
print (x)
print (word)
x = x + 1

STEP 2 The diƪerence between if and while is when while STEP 4 The For loop can also be used in the countdown
gets to the end of the indented code, it goes back example by using the range function:
and checks the statement is still true. In our example x is less than
for x in range (1, 10):
10. With each loop it prints the current value of x, then adds one to
print (x)
that value. When x does eventually equal 10 it stops.
The x=x+1 part isn’t needed here because the range function
creates a list between the Ƭrst and last numbers used.

ZZZSFOSXEOLFDWLRQVFRP 53
Hello, World

Python Modules
We’ve mentioned modules previously, (the Math module) but as modules are such a
large part of getting the most from Python, it’s worth dedicating a little more time to
them. In this instance we’re using the Windows version of Python 3.

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, STEP 4 The PIP installation requires an elevated status
are included by default, the Math module being a due it installing components at diƪerent locations.
prime example. Sadly, other modules aren’t always available. A good Windows users can search for CMD via the Start button and right-
example on non-Pi platforms is the Pygame module, which contains click the result then click Run as Administrator. Linux and Mac users
many functions to help create games. Try: import pygame. can use the Sudo command, with sudo pip install package.

54 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
Python Modules

STEP 5 Close the command prompt or Terminal and STEP 8 Multiple modules can be imported within your code.
relaunch the IDLE Shell. When you now enter: To extend our example, use:
import pygame, the module will be imported into the code
import random
without any problems. You’ll Ƭnd that most code downloaded or
import math
copied from the Internet will contain a module, mainstream of
unique, these are usually the source of errors in execution due to for I in range(5):
them being missing. print([Link](1, 25))
print([Link])

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, as by the value of Pi as pulled from the Math module
we’ve previously experimented with. For example: using the print([Link]) function. You can also pull in certain
functions from a module by using the from and import commands,
import random
such as:
Brings in the code from the Random Number Generator module.
from random import randint
You can then use this module to create something like:
for i in range(5):
for i in range(10):
print(randint(1, 25))
print([Link](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 great or lesser which will import everything deƬned within the named module.
range. For example: However, it’s often regarded as a waste of resources but it works
nonetheless. Finally, modules can be imported as aliases:
import random
import math as m
for i in range(25):
print([Link](1, 100)) print([Link])
Of course, adding comments helps to tell others what’s going on.

ZZZSFOSXEOLFDWLRQVFRP 55
Hello, World

Python Errors
It goes without saying that you’ll eventually come across an error in your code, where
Python declares it’s not able to continue due to something being missed out, wrong or
simply unknown. Being able to identify these errors makes for a good programmer.

DEBUGGING
Errors in code are called bugs and are perfectly normal. They can often be easily rectiƬed with a little patience. The important
thing is to keep looking, experimenting and testing. Eventually your code will be bug free.

STEP 1 Code isn’t as Ʈuid as the written word, no matter STEP 3 Thankfully Python is helpful when it comes to
how good the programming language is. Python is displaying error messages. When you receive an
certainly easier than most languages but even it is prone to some error, in red text from the IDLE Shell, it will deƬne the error itself
annoying bugs. The most common are typos by the user and whilst along with the line number where the error has occurred. Whilst in
easy to Ƭnd in simple dozen-line code, imagine having to debug the IDLE Editor this is a little daunting for lots of code; text editors
multi-thousand line code. help by including line numbering.

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

56 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
Python Errors

STEP 5 Pesky brackets are also a nuisance in programming STEP 8 An excellent way to check your code step-by-step
errors, especially when you have something like: is to use Python Tutor’s Visualise web page, found
at [Link]/[Link]#mode=edit. Simply
print(balanced_check(input()))
paste your code into the editor and click the Visualise Execution
Remember that for every ‘(‘ there must be an equal number of ‘)’. button to run the code line-by-line. This helps to clear bugs and
any misunderstandings.

STEP 6 There are thousands of online Python resources, STEP 9 Planning makes for good code. Whilst a little old
code snippets and lengthy discussions across forums school, it’s a good habit to plan what your code
on how best to achieve something. Whilst 99 per cent of it is good will do before sitting down to type it out. List the variables that will
code, don’t always be lured into copying and pasting random code be used and the modules too; then write out a script for any user
into your editor. More often than not, it won’t work and the worst interaction or outputs.
part is that you haven’t learnt anything.

STEP 7 Indents are a nasty 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 as Mark II electromechanical computer. According to legend Hopper
long as it’s true? Missing the indent, or having too much of indent, found a moth stuck in a relay, thus stopping the system from
will come back with an error. working. Removal of the moth was hence called debugging.

ZZZSFOSXEOLFDWLRQVFRP 57
Hello, World

Combining What
You Know So Far
We’ve reached the end of this section so let’s take a moment to combine everything
we’ve looked at so far, and apply it to writing a piece of code. This code can then be
used and inserted into your own programs in future; either part of it 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 learnt, and a little more.

STEP 1 Start by opening Python and creating a New File in STEP 4 The previous step deƬnes the rules that make
the Editor. First we need to get hold of an equation up the algorithm and creates the string that will
that can accurately calculate Pi without rendering the computer’s eventually display the value of Pi, according the Chudnovsky
CPU useless for several minutes. The recommended calculation brothers’ algorithm. You have no doubt already surmised that it
used in such circumstances is the Chudnovsky Algorithm, you would be handy to actually output the value of Pi to the screen. To
can Ƭnd more information about it at [Link]/wiki/ rectify that you can add:
Chudnovsky_algorithm.
print(calc(1))

STEP 2 You can utilise the Chudnovsky Algorithm to create


STEP 5 You can save and execute the code at this point if
your own Python script based on the calculation.
you like. The output will print the value of Pi to 27
Begin by importing some important modules and functions within
decimal places: 3.141592653589734207668453591. Whilst pretty
the modules:
impressive on its own, you 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 You can insert an input line before the Pi calculation
module, both of which deal with large decimal place numbers and Def command. It needs 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 you 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)*([Link]
(Decimal(6)*k))*(13591409 +545140134*k)
deno = [Link](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)

58 3\WKRQ&RGLQJ
RGLQJ 3URJUDPPLQJ
3
Combining What You Know So Far

STEP 7 You can execute the code now and it asks the user STEP 9 Now we need to import the Colorama module
how many decimal places they want to calculate Pi (which will output text in diƪerent colours) along
to, outputting the result in the IDLE Shell. Try it with 1000 places with the Fore function (which dictates the foreground, ink, colour)
but don’t go too high or else your computer will be locked up in and the Time module to start a virtual stopwatch to see how long
calculating Pi. our calculations take:
import time
STEP 8 Part of programming is import colorama
being able to modify code, from colorama import Fore
making it more presentable. Let’s include
an element that times how long it takes our
computer to calculate the Pi decimal places
and present the information in a diƪerent
colour. For this, drop into the command line
and import the Colorama module (RPi users
already have it installed):
pip install colorama

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


Colorama module and start the time function at pi = Decimal(0)
the point where the calculation starts, and when it Ƭnishes. The end deno = Decimal(0)
result is a coloured ink displaying how long the process took (in the k = 0
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 = [Link](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)/
[Link]()
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 = [Link]() print([Link] + “\nTime taken:”, [Link]() -
def calc(n): start_time)

ZZZSFOSXEOLFDWLRQVFRP 59
Hello, World

Python in Focus:
Stitching Black Holes
One of the biggest scientiƬc, engineering and space-based projects came to a head in
2019, revealing humanity’s Ƭrst glimpse at the universe’s most elusive object: a black
hole. But what’s that got to do with Python?
Imaging a black hole is pretty diƯcult. The very nature of a in curved spacetime predicts that event horizons emit Hawking
black hole means that nothing can escape its immense gravitational radiation, with the same spectrum as a black body of a temperature
Ƭeld, even light itself. To quote the Wikipedia entry for a black hole: inversely proportional to its mass. This temperature is on the order
of billionths of a kelvin for black holes of stellar mass, making it
“A black hole is a region of spacetime exhibiting gravitational essentially impossible to observe.”
acceleration so strong that nothing—no particles or even
electromagnetic radiation such as light—can escape from it. The Not that long ago a black hole was just a collection of theories
theory of general relativity predicts that a suƯciently compact mass and mathematics written down on paper, speculated only by the
can deform spacetime to form a black hole. The boundary of the brightest minds of our time. However, as with most things scientiƬc,
region from which no escape is possible is called the event horizon. our understanding of the universe and our abilities to read it have
Although the event horizon has an enormous eƪect on the fate and greatly improved and, with the culmination of years of
circumstances of an object crossing it, no locally detectable features hard work by a collaboration of observatories,
appear to be observed. In many ways, a black hole acts like an ideal scientists and engineers, we got our Ƭrst
black body, as it reƮects no light. Moreover, quantum Ƭeld theory image of a black hole.

EVENT HORIZON TELESCOPE


One of the problems regarding the imaging of such an object is
angular resolution. In Astronomy, the size of the objects in the night
sky is referred to by the amount of the sky they take up - units of
arc. An arc, or arc second, is a measurement (1/3600 of a degree)
that describes the size of an angle in degrees, designated by the
symbol °. A full circle is divided into 360° and a right-angle measures
90°. One degree can be divided into 60 arcminutes (abbreviated 60
arcmin or 60’). An arcminute can also be divided into 60 arcseconds
(abbreviated 60 arcsec or 60”).{

For example, looking at the moon, which is roughly 31 arcminutes,


imagine drawing a line from you to one side of the moon and
another to the opposite side of the moon, the angle between the
two lines is the angular size, or angular resolution.

The black hole at the centre of the Messier 87 galaxy, the one that
was imaged, is 55 million light years from Earth and has an angular
size of 40 microarc seconds, or one millionth of an arcsecond. So,
in order to see it, we would need a telescope with a diameter of
around 8Km, which simply isn’t possible as a single unit.

This is where the Event Horizon Telescope project comes into play.
Using a network of eight radio telescopes, scientists were able to
take images of the black hole over a period of around six months.
Critically timed, using atomic clocks, the telescopes imaged the area
of sky containing the black hole and collected the data, swapping
from one telescope array to the next as the Earth rotated.

60 3\WKRQ&RGLQJ 3URJUDPPLQJ
Python in Focus: Stitching Black Holes

BIG DATA AND PYTHON RESULTS


This data was then collated across all the telescope arrays to the The end result is, of course, the image of the black hole at the centre
tune of over a thousand hard drives, which came to an astonishing 5 of the M87 galaxy that’s surrounded by a ring of burning gasses. The
Petabytes of raw data. The problem now was collating all that data resolution isn’t great, as the team have since admitted, but, as they
into a workable form and presenting it as an image. also state, give it a couple of years and they’ll be able to increase the
image resolution signiƬcantly.
Katie Bouman, a Ph.D. in electrical
engineering and computer science All this is thanks to some clever Python code and some very brilliant
from MIT, was pivotal in creating the scientists and engineers.
Python code that was able to stitch
all that data together and form the
eventual, historic image of a black hole.

Bouman used a number of Python


libraries to achieve the result, Numpy,
Scipy, Pandas, Jupyter, Matplotlib
and Astropy, plus some unique custom Python code – which can be
found on Github at [Link]

ZZZSFOSXEOLFDWLRQVFRP 61
Index

62 3\WKRQ&RGLQJ 3URJUDPPLQJ
Working with Data

Data is everything; it can topple


governments, change election results,
and tell us the secrets of the universe.
Over these coming pages we look at how
you can create lists, tuples, dictionaries
and multi-dimensional lists, and then how
you can use them to forge exciting and
useful programs.
In addition, you will learn how you can
use the date and time functions, write to
Ƭles to your system and even create
graphical user interfaces that will take
your coding skills to new levels and into
new project ideas.

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

ZZZSFOSXEOLFDWLRQVFRP 63
Working with Data

Lists
Lists are one of the most common types of data structures you will come across in
Python. A list is simply a collection of items, or data if you prefer, that 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 equals using the minus sign before the item number [-1],
sign, then square brackets and the items separated by commas; or the second to last item with [-2] and so on. Trying to reference an
note that strings use quotes: item that isn’t in the list, such as [10] will return an error:
numbers = [1, 4, 7, 21, 98, 156] numbers[-1]
mythical_creatures – [“Unicorn”, “Balrog”, mythical_creatures[-4]
“Vampire”, “Dragon”, “Minotaur”]

STEP 2 Once you’ve deƬned your list you can call each STEP 4 Slicing is similar to indexing but you can retrieve
by referencing its name, followed by a number. Lists multiple items in a list by separating item numbers
start the Ƭrst item entry as 0, followed by 1, 2, 3 and so on. with a colon. For example:
For example:
numbers[1:3]
numbers
Will output the 4 and 7, being item numbers 1 and 2. Note that the
To call up the entire contents of the list. returned values don’t include the second index position (as you
would numbers[1:3] to return 4, 7 and 21).
numbers[3]
To call the third from zero item in the list (21 in this case).

64 3\WKRQ&RGLQJ 3URJUDPPLQJ
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 you can use: functions, for example, insert and pop are used to add and remove
items at certain positions. To insert the number 62 at item index 4:
everything = numbers + mythical_creatures
[Link](4, 62)
Then view the combined list with:
To remove it:
everything
[Link](4)

STEP 6 Items can be added to a list by entering: STEP 9 You also use the list function to break a string down
into its components. For example:
numbers=numbers+[201]
list(“David”)
Or for strings:
Breaks the name David into ‘D’, ‘a’, ‘v’, ‘i’, ‘d’. This can then be passed
mythical_creatres=mythical_creatures+[“Griffin”]
to a new list:
Or by using the append function:
name=list(“David Hayward”)
mythical_creatures.append(“Nessie”) name
[Link](278) age=[44]
user = name + age
user

STEP 7 Removal of items can be done in two ways. The Ƭrst STEP 10 Based on that, you 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)
Alternatively, 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.

ZZZSFOSXEOLFDWLRQVFRP 65
Working with Data

Tuples
Tuples are very much 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 they’re
perfect for storing Ƭxed data items.

THE IMMUTABLE TUPLE


Reasons for having tuples vary depending on what the program is intended to do. Normally, a tuple is reserved for something
special but they’re also used for 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 is a tuple
brackets. For example: 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 Just as with lists, the items within a named tuple can STEP 4 Each of these data items can be accessed as a
be indexed according to their position in the data whole by entering NPC into the Shell; or they can be
range, i.e.: indexed according to their position NPC[0]. You can also index the
individual tuples within the NPC list:
months[0]
months[5] NPC[0][1]
However, any attempt at deleting or adding to the tuple will result Will display 100.
in an error in the Shell.

66 3\WKRQ&RGLQJ 3URJUDPPLQJ
Tuples

STEP 5 It’s worth noting that when referencing multiple STEP 8 Now unpack the tuple into two
tuples within a list, the indexing is slightly diƪerent corresponding variables:
from the norm. You would expect the 95 combat rating of the
(name, combat_rating)=NPC
character Valeria to be NPC[4][5], but 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. For our example, using the tuple with
0, 0 2
multiple data items, you would reference the Valeria character with:
0, 1 2, 0
1 2,1 NPC[2][-0]
1, 0
Which as you can imagine, gets a little confusing when you’ve got a
lot of tuple data to deal with.

STEP 7 Tuples though utilise a feature called unpacking, STEP 10 You can use the max and min functions to Ƭnd the
where the data items stored within a tuple are highest and lowest values of a tuple composed of
assigned variables. First create the tuple with two items (name and numbers. For example:
combat rating):
numbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99)
NPC=(“Conan”, 100)
The numbers can be integers and Ʈoats. To output the highest and
lowest, use:
print(max(numbers))
print(min(numbers))

ZZZSFOSXEOLFDWLRQVFRP 67
Working with Data

Dictionaries
Lists are extremely useful but dictionaries in Python are by far the more technical way
of dealing with data items. They can be tricky to get to grips with at Ƭrst but 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 whereas 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 enter of a dictionary by giving the dictionary a 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 Just as with most lists, tuples and so on, strings STEP 4 The beneƬt of using a dictionary is that you
need be enclosed in quotes (single or double), can enter the key to index the value. Using the
whilst integers can be left open. Remember that the value can be phonebook example from the previous steps, you can enter:
either a string or an integer, you just need to enclose the relevant
phonebook[“Emma”]
one in quotes:
phonebook[“Hannah”]
phonebook2={“David”: “0987 654 321”}

68 3\WKRQ&RGLQJ 3URJUDPPLQJ
Dictionaries

STEP 5 Adding to a dictionary is easy too. You can include STEP 8 Next, you need to deƬne the user inputs and
a new data item entry by adding the new key and variables: one for the person’s name, the other
value items like: for their phone number (let’s 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 You can also remove items from a dictionary by STEP 9 Note we’ve kept the number as an integer instead
issuing the del command followed by the item’s of a string, even though the value can be both
key; the value will be removed as well, since both work as a pair of an integer or a string. Now you need to add the user’s inputted
data items: variables to the newly created blank dictionary. Using the same
process as in Step 5, you can enter:
del phonebook[“David”]
phonebook[name] = number

STEP 7 Taking this a step further, how about creating a STEP 10 Now when you 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 you 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 need to make it a string,
so remove the int part of the input.

ZZZSFOSXEOLFDWLRQVFRP 69
Working with 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
You’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 [Link] part has 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 you’d use:
text=”Daniel Hannah Emma”
text=”January,February,March,April,May,June”
months=[Link](“,”)
months

STEP 2 Now let’s turn the string into a list and split the STEP 4 You’ve previously seen how you can split a string
content accordingly: into individual letters as a list, using a name:
names=[Link](“ “) name=list(“David”)
name
Then enter the name of the new list, names, to see the three items.
The returned value is ‘D’, ‘a’, ‘v’, ‘i’, ‘d’. Whilst it may seem a little
useless under ordinary circumstances, it could be handy for creating
a spelling game for example.

70 3\WKRQ&RGLQJ 3URJUDPPLQJ
Splitting and Joining Strings

STEP 5 The opposite of the .split function is .join, where STEP 8 As with the .split function, the separator doesn’t
you will have separate items in a string and can join have to be a space, it can also be a comma, a full
them all together to form a word or just a combination of items, stop, a hyphen or whatever you like:
depending on the program 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 You can therefore apply .join to the separated name STEP 9 There’s some interesting functions you apply to a
you made in Step 4, combining the letters again to string, such as .capitalize and .title. For example:
form the name:
title=”conan the cimmerian”
name=””.join(name) [Link]()
name [Link]()
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 a with the ‘in’ and ‘not in’ functions. These enable
sentence: you 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

ZZZSFOSXEOLFDWLRQVFRP 71
Working with Data

Formatting Strings
When you work with data, creating lists, dictionaries and objects you may often want
to print out the results. Merging strings with data is easy especially with Python 3, as
earlier versions of Python 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.
It’s a more logical and better formed approach than previous versions.

STEP 1 The basic formatting in Python is to call each STEP 3 You can of course also include integers into the mix:
variable into the string using the curly brackets:
number=10000
name=”Conan” print(“{} of {} was a skilled mercenary,
print(“The barbarian hero of the Hyborian Age is: and thief too. He once stole {} gold from a
{}”.format(name)) merchant.”.format(name, place, number))

STEP 2 Remember to close the print function with two sets STEP 4 There are many diƪerent ways to apply string
of brackets, as you’ve encased the variable in one, formatting, some are quite simple, as we’ve shown
and the print function in another. You can include multiple cases of you here; others can be signiƬcantly more complex. It all depends
string formatting in a single print function: on what you want from your program. A good place to reference
frequently regarding string formatting is the Python Docs webpage,
name=”Conan”
found at [Link]/3.1/library/[Link]. Here, you
place=”Cimmeria”
will Ƭnd tons of help.
print(“{} hailed from the North, in a cold land
known as {}”.format(name, place))

72 3\WKRQ&RGLQJ 3URJUDPPLQJ
Formatting Strings

STEP 5 Interestingly you can reference a list using the string STEP 8 You can also print out the content of a user’s input
formatting function. You need to place an asterisk in in the same fashion:
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 With indexing in lists, the same applies to calling a STEP 9 You can extend this simple code example to display
list using string formatting. You can index each item the Ƭrst letter in a person’s entered name:
according to its position (from 0 to however many are present):
name=input(“What’s your name? “)
numbers=1, 4, 7, 9 print(“Hello {}.”.format(name))
print(“More numbers: {3}, {0}, {2}, lname=list(name)
{1}.”.format(*numbers)) print(“The first letter of your name is a {0}”.
format(*lname))

STEP 7 And as you probably suspect, you can mix strings STEP 10 You can also call upon a pair of lists and reference
and integers in a single list to be called in the them individually within the same print function.
.format function: Looking back the code from Step 7, you 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 you 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))

ZZZSFOSXEOLFDWLRQVFRP 73
Working with 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. Luckily acquiring the date and time is easy, thanks to the Time module.

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

STEP 1 First you need to import the Time module. It’s one STEP 3 You can see the structure of how time is presented
that’s built-in to Python 3 so you shouldn’t need to by entering:
drop into a command prompt and pip install it. Once it’s imported,
[Link]()
you can call the current time and date with a simple command:
The output is displayed as such: ‘time.struct_time(tm_
import time
year=2017, tm_mon=9, tm_mday=7, tm_hour=9, tm_
[Link]()
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 Time
divided up into indexed items, as with any other module. One of the most common of these is
tuple, and shown in the screen shot below. .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 you can use:
[Link](‘%A’)

74 3\WKRQ&RGLQJ 3URJUDPPLQJ
Date and Time

STEP 5 This naturally means you can incorporate various STEP 8 You saw at the end of the previous section, in the
functions into your own code, such as: code to calculate Pi to however many decimal places
the users wanted, you can time a particular event in Python. Take
[Link](“%a”)
the code from above and alter it slightly by including:
[Link](“%B”)
[Link](“%b”) start_time=[Link]()
[Link](“%H”)
Then there’s:
[Link](“%H%M”)
endtime=[Link]()-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. You 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.
[Link](“%H:%M”)

STEP 7 This means you’re going to be able to display STEP 10 There’s a lot that can be done with the Time
either the current time or the time when module; some of it is quite complex too, such as
something occurred, such as a user entering their name. Try displaying the number of seconds since January 1st 1970. If you
this code in the Editor: want to drill down further into the Time module, then in the Shell
enter: help(time) to display the current Python version help Ƭle
import time
for the Time module.
name=input(“Enter login name: “)
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.

ZZZSFOSXEOLFDWLRQVFRP 75
Working with Data

Opening Files
In Python you can read text and binary Ƭles in your programs. You can also write to Ƭle,
which is something we will look at next. Reading and writing to Ƭles enables you to
output and store data from your programs.

OPEN, READ AND WRITE


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

STEP 1 Start by entering some text into your system’s text STEP 3 If you now enter poem into the Shell, you will get
editor. The text editor is best, not a word processor, some information regarding the text Ƭle you’ve just
as word processors include background formatting and other asked to be opened. You can now use the poem variable to read the
elements. In our example, we have the poem The Cimmerian, by contents of the Ƭle:
Robert E Howard. You need to save the Ƭle as [Link].
[Link]()
Note than a /n entry in the text represents a new line, as you
used previously.

STEP 2 You use the open() function to pass the Ƭle into a STEP 4 If you enter [Link]() a second time you will
variable as an object. You can name the Ƭle object notice that the text has been removed from the Ƭle.
anything you like, but you will need to tell Python the name and You will need to enter: poem=open(“/home/pi/Documents/
location of the text Ƭle you’re opening: [Link]”) again to recreate the Ƭle. This time, however, enter:
poem=open(“/home/pi/Documents/[Link]”) print([Link]())
This time, the /n entries are removed in favour of new lines and
readable text.

76 3\WKRQ&RGLQJ 3URJUDPPLQJ
Opening Files

STEP 5 Just as with lists, tuples, dictionaries and so on, STEP 8 Extending this further, you can use readlines() to
you’re able to index individual characters of the grab all the lines of the text and store them as
text. For example: multiple lists. These can then be stored as a variable:
[Link](5) poem=open(“/home/pi/Documents/[Link]”)
lines=[Link]()
Displays the Ƭrst Ƭve characters, whilst again entering:
lines[0]
[Link](5) lines[1]
lines[2]
Will display the next Ƭve. Entering (1) will display one character at
a time.

STEP 6 Similarly, you can display one line of text at a time by STEP 9 You can also use the for statement to read the lines
using the readline() function. For example: of text back to us:
poem=open(“/home/pi/Documents/[Link]”) for lines in lines:
[Link]() print(lines)
Will display the Ƭrst line of the text with: Since this is Python, there are other ways to produce the same output:
[Link]() poem=open(“/home/pi/Documents/[Link]”)
for lines in poem:
Displaying the next line of text once more.
print(lines)

STEP 7 You may have guessed that you can pass the STEP 10 Let’s imagine that you want to print the text one
readline() function into a variable, thus allowing you character at a time, like an old dot matrix printer
to call it again when needed: would. You can use the Time module mixed with what you’ve looked
at here. Try this:
poem=open(“/home/pi/Documents/[Link]”)
line=[Link]() import time
line poem=open(“/home/pi/Documents/[Link]”)
lines=[Link]()
for lines in lines:
print(lines, end=””)
[Link](.15)
The output is fun to view, and easily incorporated into your own code.

ZZZSFOSXEOLFDWLRQVFRP 77
Working with Data

Writing to Files
The ability to read external Ƭles within Python is certainly handy but writing to a Ƭle is
better still. Using the write() function, you’re able to output the results of a program to
a Ƭle, that you can then read() back into Python.

WRITE AND CLOSE


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

STEP 1 Start by opening IDLE and enter the following: STEP 3 However, the actual text Ƭle is still blank (you can
check by opening it up). This is because you’ve
t=open(“/home/pi/Documents/text.
written the line of text to the Ƭle object but not committed it to the
txt”,”w”)
Ƭle itself. Part of the write() function is that you need to commit the
Change the destination from /home/pi/Documents to your own changes to the Ƭle; you can do this by entering:
system. This code will create a text Ƭle called [Link] in write mode
[Link]()
using the variable ‘t’. If there’s no Ƭle of that name in the location, it
will create one. If one already exits, it will overwrite it, so be careful.

STEP 2 You can now write to the text Ƭle using the write() STEP 4 If you now open the text Ƭle with a text editor,
function. This works opposite to read(), writing lines you can see that the line you created has been
instead of reading them. Try this: written to the Ƭle. This gives us the foundation for some interesting
possibilities: perhaps the creation of your own log Ƭle or even the
[Link](“You awake in a small, square room. A
beginning of 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.

78 3\WKRQ&RGLQJ 3URJUDPPLQJ
Writing to Files

STEP 5 To expand this code, you can reopen the Ƭle using STEP 8 You can pass variables to a Ƭle that you’ve created
‘a’, for access or append mode. This will add any text in Python. Perhaps you want the value of Pi to be
at the end of the original line instead of wiping the Ƭle and creating written to a Ƭle. You can call Pi from the Math module, create a new
a new one. For example: Ƭle and pass the output of Pi into the new Ƭle:
t=open(“/home/pi/Documents/[Link]”,”a”) import math
[Link](“\n”) print(“Value of Pi is: “,[Link])
[Link](“ You stand and survey your surroundings. print(“\nWriting to a file now…”)
On top of the table is some meat, and a cup of
water.\n”)

STEP 6 You can keep extending the text line by line, STEP 9 Now let’s create a variable called pi and assign it the
ending each with a new line (\n). When you’re value of Pi:
done, Ƭnish the code with [Link]() and open the Ƭle in a text
pi=[Link]
editor to see the results:
You also need to create a new Ƭle in which to write Pi to:
[Link](“The door is made of solid oak with iron
strips. It’s bolted from the outside, locking you t=open(“/home/pi/Documents/[Link]”,”w”)
in. You are a prisoner!.\n”)
Remember to change your Ƭle location to your own particular
[Link]()
system setup.

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

ZZZSFOSXEOLFDWLRQVFRP 79
Working with Data

Exceptions
When coding, you’ll naturally come across some issues that are out of your control.
Let’s assume you ask a user to divide two numbers and they try to divide by zero. This
will create an error and break your code.

EXCEPTIONAL OBJECTS
Rather than stop the Ʈow of your code, Python includes exception objects which handle unexpected errors in the code. You
can combat errors by creating conditions where exceptions may occur.

STEP 1 You can create an exception error by simply trying STEP 3 You 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 the assume your code has you warping around the cosmos, too much
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, you can create a
custom exception:
raise Exception(“warp core breach”)

STEP 2 Most exceptions STEP 4 To trap any errors in the code you 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, else do something else.
inherently wrong with the code.
However, you can create your
own exceptions that are designed
to contain the potential error and
react to it, as opposed to letting
the code fail.

80 3\WKRQ&RGLQJ 3URJUDPPLQJ
Exceptions

STEP 5 For example, use the divide by zero error. You can STEP 8 Naturally, you can quickly Ƭx the issue by changing
create an exception where the code can handle the the “r” read only instance with a “w” for write. This,
error without Python quitting due to the problem: as you already know, will create the Ƭle and write the content then
commit the changes to the Ƭle. The end result will report a diƪerent
try:
set of circumstances, in this case, a successful execution of the code.
a=int(input(“Enter the first number: “))
b=int(input(“Enter the second number: “))
print(a/b)
except ZeroDivisionError:
print(“You have tried to divide by zero!”)
else:
print(“You didn’t divide by zero. Well done!”)

STEP 6 You can use exceptions to handle a variety of useful STEP 9 You can also use a Ƭnally: block, which works in a
tasks. Using an example from our previous tutorials, similar fashion but you can’t use else with it. To use
let’s assume you want to open a file and write to it: our example from Step 6:

try: try:
txt = open(“/home/pi/Documents/[Link]”, txt = open(“/home/pi/Documents/[Link]”,
“r”) “r”)
[Link](“This is a test. Normal service try:
will shortly resume!”) [Link](“This is a test. Normal service will
except IOError: shortly resume!”)
print (“Error: unable to write the file. finally:
Check permissions”) print (“Content written to file successfully.
else: Have a nice day.”)
print (“Content written to file successfully. [Link]()
Have a nice day.”) except IOError:
[Link]() print (“Error: unable to write the file. Check
permissions”)

STEP 7 Obviously this won’t work due to the Ƭle textƬle. STEP 10 As before an error will occur as you’ve used the
txt being opened as read only (the “r” part). So in “r” read-only permission. If you change it to a “w”,
this case rather than Python telling you that you’re doing something then the code will execute without the error being displayed in the
wrong, you’ve created an exception using the IOError class IDLE Shell. Needless to say, it can be a tricky getting the exception
informing the user that the permissions are incorrect. code right the Ƭrst time. Practise though, and you will get the hang
of it.

ZZZSFOSXEOLFDWLRQVFRP 81
Working with Data

Python Graphics
While dealing with text on the screen, either as a game or in a program, is great, there
will come a time when a bit of graphical representation wouldn’t go amiss. Python 3
has numerous ways in which to include graphics and they’re surprisingly powerful too.

GOING GRAPHICAL
You can draw simple graphics, lines, squares and so on, or you can use one of the many Python modules available, to bring out
some spectacular eƪects.

STEP 1 One of the best graphical modules to begin learning STEP 3 The command [Link](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 beyond; you can draw an arc by entering: [Link](50,
of paper on the Ʈoor. The Turtle module can be imported with: 180), where the size is 50, but you’re telling Python to only draw
import turtle. 180° of the circle.

STEP 2 Let’s begin by drawing a simple circle. Start a New STEP 4 The last part of the circle code tells Python to keep
File, then enter the following code: the window where the drawing is taking place to
remain open, so the user can click to close it. Now, let’s make a square:
import turtle
import turtle
[Link](50)
[Link]()._root.mainloop() print(“Drawing a square…”)
As usual press F5 to save the code and execute it. A new window will for t in range(4):
now open up and the ‘Turtle’ will draw a circle. [Link](100)
[Link](90)
[Link]()._root.mainloop()
You can see that we’ve inserted a loop to draw the sides of the square.

82 3\WKRQ&RGLQJ 3URJUDPPLQJ
Python Graphics

STEP 5 You can add a new line to the square code to add STEP 8 Now let’s get the code by importing the Pygame module:
some colour:
import pygame
[Link](“Red”) [Link]()
Then you can even change the character to an actual turtle by entering: img = [Link](“[Link]”)
[Link](“turtle”) white = (255, 255, 255)
w = 900
You can also use the command turtle.begin_fill(), and
h = 450
turtle.end_fill() to Ƭll in the square with the chosen colours;
screen = [Link].
red outline, yellow Ƭll in this case.
set_mode((w, h))
[Link]((white))
[Link]((white))
[Link](img,(0,0))
[Link]()
while True:
for event in [Link]():
if [Link] == [Link]:
[Link]()

STEP 6 You can see that the Turtle module can draw STEP 9 In the previous step you imported pygame, initiated
out some pretty good shapes and become a little the pygame engine and asked it to import our saved
more complex as you begin to master the way it works. Enter Raspberry Pi logo image, saved as [Link]. Next you deƬned the
this example: background colour of the window to display the image and the
window size as per the actual image dimensions. Finally you have a
from turtle import *
loop to close the window.
color(‘red’, ‘yellow’)
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()
It’s a diƪerent method,
but very eƪective.

STEP 7 Another way in which you can display graphics is STEP 10 Press F5 to save and execute the code and your
by using the Pygame module. There are numerous image will be displayed in a new window. Have a
ways in which pygame can help you output graphics to the screen play around with the colours, sizes and so on and take time to look
but for now let’s look at displaying a predeƬned image. Start by up the many functions within the Pygame module too.
opening a browser and Ƭnding an image, then save it to the folder
where you save your Python code.

ZZZSFOSXEOLFDWLRQVFRP 83
Working with Data

Combining What
You Know So Far
Based on what you’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 creates user logins and then allows them to log into the system and write
the time they logged in at. You can even include an option to quit the program by pressing ‘q’.

STEP 1 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 you can use the q=quit element without it being
the program: changed inside the function. We’ve also referenced some newly
deƬned functions: oldUser and newUser which we’ll get to next.
import time
users = {}
status = “”

STEP 4 The newUser function is next:


def newUser():
STEP 2 Next you need to deƬne some functions. You can createLogin = input(“Create a login name: “)
begin by creating the main menu, where all users
if createLogin in users:
will return to after selecting the available options:
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(“/home/pi/Documents/[Link]”,
oldUser() “a”)
elif status == “n”: [Link](“\n” + createLogin + “ “ +
newUser() createPassw)
elif status == “q”: [Link]()
quit()
This creates a new user and password, and writes the entries into a
Ƭle called [Link].

84 3\WKRQ&RGLQJ 3URJUDPPLQJ
Combining What You Know So Far

STEP 5 You will need to specify your own location for the STEP 8 Finally, you need to continually check that the ‘q’ key
[Link] Ƭle, since we’re using a Raspberry Pi. 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, so the key and value structure
while status != “q”:
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:”, [Link]())
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, then log in with their
names and passwords, with the [Link] Ƭle
being created to store the login data and successful logins being
time-stamped. Now it’s up to you to further improve the code.
Perhaps you can import the list of created users from a previous
session and display a graphic upon a successful login?

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


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

ZZZSFOSXEOLFDWLRQVFRP 85
Working with Data

Python in Focus:
Gaming
Although not always considered as the ideal programming language for developing
games, Python has come a long way in recent years and is now one of the contributing
elements to a huge number of titles.
The video game industry generates something in the region of $140 billion each year, and that number is growing fast. It’s a long way from
the 8-bit days of the Commodore 64 and ZX Spectrum; the arcade titles that used to devour our pocket money and the wood panelled
home consoles that Atari lovingly developed. These days, it’s all about teams of coders, graphic artists, musicians, PR, projects and
development platforms.

GAME CODE
Coding a game from scratch, using raw code, has become
something of the past. Most games these days are created using
a range of development tools. These tools can be oƪ-the-shelf
engines, such as the Unreal Engine, while others are custom built
around an original product, such as the world generating engine
that Bethesda use for the Skyrim and Fallout series of games.
Others examples can be coded from the ground up, but these
are generally few and far between. So where does Python Ƭt
into all this?

The limiting factor with Python is performance. While most


games require a huge degree of performance from the platform BUILDING TOOLS
for which they are written, Python’s code, which is good, isn’t
really designed to cope with the fast-paced formula on which In the game industry, Python is mostly limited to the
games such as BattleƬeld or the Call of Duty series are based. development of in-game tools used by the developers of the
These games are often coded with C++, or some other form of game, or to help bridge the gaps between diƪerent areas of
low-level programming language. But that doesn’t mean Python code. For example, in-game tools coded in Python can be used by
is left out in the cold when it comes to game development, in designers to create levels for the game, or speciƬc elements that
fact it’s quite the opposite. would make up a character’s inventory, or even creating dialog
between the player and non-playing characters in the game.

You will also Ƭnd that Python can be used to control the game’s
AI (ArtiƬcial Intelligence), which will give the characters in a game
a certain element of life. As an example, the popular Sims games
consist of characters other than the one the gamer controls.
These Sims will go about their business with their actions
determined by the player’s choices, this involves an advanced
form of ArtiƬcial Intelligence that is coded using Python.

Other examples include many of the available open world


games, where the introduction of the player will change the
course of a village’s, Town’s, or even city’s inhabitant’s behaviour.
Blow up a few cars in the middle of the street and it’ll aƪect
the way the other drivers behave; jump up and down on top of
a market stall in the middle of a medieval village and the folk
around you will react. This, again, is all down to Python code
written within the main code of the game, alongside the game
development engine.

86 3\WKRQ&RGLQJ 3URJUDPPLQJ
Python in Focus: Gaming

PYTHONǕPOWERED GAMES
Some good examples of the types of games in which Python is
used are the following:

%attleƬeld 2 – Python is used for the game’s add-ons and


functionality of the player elements.
The Sims – AI, and many of the game’s interactions.
CiYilisation – Python is used throughout the Civ games,
controlling movement and the non-player AI.
EYe Online – Utilises Python for Ʈoating point number
calculations and other tasks.
World of Tanks – Python is used to control AI objects and detail
the large amount of graphical data.

In particular, it’s worth noting that Python’s use in games is due


to its ability to automate repetitive tasks quickly. While another
programming language may be faster at drawing the graphics
on the screen, Python can quickly repeat resizing hundreds of
textures in batches. There’s also Python’s excellent and sizeable
libraries that can be tweaked for certain tasks, speciƬcally
in-game tasks freeing up other components to deliver the
performance that modern games need.

KEEP ON
GAMING
In short, while Python may
not be the ideal language
with which to create a
modern game entirely, its
use is often behind the
scenes, in areas where other
programming languages
will struggle. Python can
be used as the glue that
sticks elements of game
technologies together,
creating complex AI or simply
designing a dialog box.

ZZZSFOSXEOLFDWLRQVFRP 87
Index

88 3\WKRQ&RGLQJ 3URJUDPPLQJ
Using Modules

A Python module is a Python-created


source Ƭle that contains the necessary
code for classes, functions and global
variables. You can bind and reference
modules to extend functionality,
and create even more spectacular
Python programs.
Are you curious about how to improve
your use of these modules to add a
little something extra to your code?
Then read on and learn how they can be
used to fashion fantastic code with
graphics, animations and operating
system speciƬc commands.

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
108 Python in Focus: ArtiƬcial Intelligence

ZZZSFOSXEOLFDWLRQVFRP 89
Using Modules

Calendar Module
Beyond the Time module, the Calendar module can produce some interesting results
when executed within your code. It does far more than simply display the date in the
Time module-like format, you can actually call up a wall calendar type display.

WORKING WITH DATES


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

STEP 1 Launch Python 3 and enter: import calendar to STEP 3 There are numerous functions within the Calendar
call up the module and its inherent functions. Once module that may be of interest to you when
it’s loaded into memory, start by entering: forming your own code. For example, you can display the number of
leap years between two speciƬc years:
sep=[Link]([Link])
[Link](2019, 9) leaps=[Link](1900, 2019)
print(leaps)
The result is 29, starting from 1904 onward.

STEP 2 You can see that the days of September 2019 are STEP 4 You could even fashion that particular example into
displayed in a wall calendar fashion. Naturally you a piece of working, user interactive Python code:
can change the 2019, 9 part of the second line to any year and
import calendar
month you want, a birthday for example (1973, 6). The Ƭrst line
print(“>>>>>>>>>>Leap Year Calculator<<<<<<<<<<\n”)
conƬgures TextCalendar to start its weeks on a Sunday; you can opt
y1=int(input(“Enter the first year: “))
for Monday if you prefer.
y2=int(input(“Enter the second year: “))
leaps=[Link](y1, y2)
print(“Number of leap years between”, y1, “and”,
y2, “is:”, leaps)

90 3\WKRQ&RGLQJ 3URJUDPPLQJ
Calendar Module

STEP 5 You can also create a program that will display all STEP 8 You’re also able to print the individual months, or
the days, weeks and months within a given year: days, of the week:
import calendar import calendar
year=int(input(“Enter the year to display: “) for name in calendar.month_name:
print([Link](year)) print(name)
We’re sure you’ll agree that’s quite a handy bit of code to have import calendar
to hand. for name in calendar.day_name:
print(name)

STEP 6 Interestingly we can also list the number of days in a STEP 9 The Calendar module also allows us to write the
month by using a simple: for loop: functions in HTML, so that you can display it on a
website. Let’s start by creating a new Ƭle:
import calendar
cal=[Link]([Link]) import calendar
for i in [Link](2019, 6): cal=open(“/home/pi/Documents/[Link]”, “w”)
print(i) c=[Link]([Link])
[Link]([Link](2019, 1))
[Link]()
This code will create an HTML Ƭle called cal, open it with a browser
and it displays the calendar for January 2019.

STEP 7 You can see that, at the outset, the code produced STEP 10 Of course, you can modify that to display a given
some zeros. This is due to the starting day of the year as a web page calendar:
week, Sunday in this case, plus overlapping days from the previous
import calendar
month. Meaning the counting of the days will start on Saturday 1st
June 2019 and will total 30, as the output correctly displays. year=int(input(“Enter the year to display as a
webpage: “))
cal=open(“/home/pi/Documents/[Link]”, “w”)
[Link]([Link]([Link]).
formatyear(year))
[Link]()
This code asks the user for a year and then creates the necessary
webpage. Remember to change your Ƭle destination.

ZZZSFOSXEOLFDWLRQVFRP 91
Using Modules

OS Module
The OS module allows you to interact directly with the built-in commands found in your
operating system. Commands vary depending on the OS you’re running, as some will
work with Windows whereas others will work with Linux and macOS.

INTO THE SYSTEM


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

STEP 1 You can start the OS module with some simple STEP 3 The Windows output is diƪerent as that’s the
functions to see how it interacts with the operating current working directory of Python, as determined
system environment that Python is running on. If you’re using Linux by the system; as you might suspect, the [Link]() function is
or the Raspberry Pi, try this: asking 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=[Link]()
print(home)

STEP 2 The returned result from printing the variable home STEP 4 Yet another interesting element to the OS module,
is the current user’s home folder on the system. is its ability to launch programs that are installed
In our example that’s /home/pi; it will be diƪerent depending on in the host system. For instance, if you wanted to launch the
the user name you log in as and the operating system you use. Chromium browser from within a Python program you can use
For example, Windows 10 will output: C:\Program Files (x86)\ the command:
Python36-32.
import os
browser=[Link](“/usr/bin/chromium-browser”)

92 3\WKRQ&RGLQJ 3URJUDPPLQJ
OS Module

STEP 5 The [Link]() function is what allows interaction STEP 8 The ability to manipulate directories, or folders if
with external programs; you can even call up you prefer, is one of the OS module’s best features.
previous Python programs using this method. You will obviously For example, to create a new directory you can use:
need to know the full path and program Ƭle name for it to work
import os
successfully. However, you can use the following:
[Link](“NEW”)
import os
This creates a new directory within the Current Working Directory,
[Link](‘start chrome “[Link]
named according to the object in the mkdir function.
feed/music”’)

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


by entering:
import os
[Link](“NEW”, “OLD”)
To delete them:
STEP 6 For Step 5’s example we used Windows, to show
that the OS module works roughly the same across import os
all platforms. In that case, we opened YouTube’s music feed page, so [Link](“OLD”)
it is therefore possible to open speciƬc pages:
import os
[Link](‘chromium-browser “http://
[Link]/”’)

STEP 10 Another module that goes together with OS is


shutil. You can use the Shutil module together
with OS and time to create a time-stamped backup directory, and
copy Ƭles into it:
import os, shutil, time
root_src_dir = r’/home/pi/Documents’
root_dst_dir = ‘/home/pi/backup/’ + [Link]()
for src_dir, dirs, files in [Link](root_src_dir):
dst_dir = src_dir.replace(root_src_dir, root_
STEP 7 Note in the previous step’s example the use of dst_dir, 1)
single and double-quotes. The single quotes encase if not [Link](dst_dir):
the entire command and launching Chromium, whereas the double [Link](dst_dir)
quotes open the speciƬed page. You can even use variables to call for file_ in files:
multiple tabs in the same browser: src_file = [Link](src_dir, file_)
dst_file = [Link](dst_dir, file_)
import os
if [Link](dst_file):
a=(‘chromium-browser “[Link]
[Link](dst_file)
com/”’)
[Link](src_file, dst_dir)
b=(‘chromium-browser “[Link]
[Link](a + b) print(“>>>>>>>>>>Backup complete<<<<<<<<<<”)

ZZZSFOSXEOLFDWLRQVFRP 93
Using Modules

Using the Math Module


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

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

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

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

94 3\WKRQ&RGLQJ 3URJUDPPLQJ
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 Floor from Math and renaming it precise values:
to f. Although where lengthy code is in use, this process can quickly
from math import exp, expm1
become confusing:
exp(1e-5) – 1 # value accurate to 11 places
from math import floor as f expm1(1e-5) # result accurate to full precision
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 done by entering: quite niche for the most part. Probably the two
most used functions are e and Pi, where e is the numerical constant
from math import *
equal to 2.71828 (where the circumference of a circle is divided by
While certainly handy, this is often frowned upon by the developer its diameter):
community as it takes up unnecessary resources and isn’t an
import math
eƯcient way of coding. However, if it works for you then go ahead.
print(math.e)
print([Link])

STEP 7 Interestingly, some functions within the Math STEP 10 The wealth of mathematical functions available
module are more accurate, or to be more precise are through the Math module is vast and covers
designed to return a more accurate value, than others. For example: everything from factors to inƬnity, powers to trigonometry and
angular conversion to constants. Look up [Link]
sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
library/[Link]# 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.

ZZZSFOSXEOLFDWLRQVFRP 95
Using Modules

Random Module
The Random module is one you will likely come across many times in your Python
programming lifetime; as the name suggests, it’s designed to create random numbers
or letters. However, it’s not exactly random but it will suƯce for most needs.

RANDOM NUMBERS
There are numerous functions within the Random module, which when applied can create some interesting and very useful
Python programs.

STEP 1 Just as with other modules you need to import STEP 4 However, the Random module isn’t used exclusively
random before you can use any of the functions for numbers. You can use it to select an entry from a
we’re going to look at in this tutorial. Let’s begin by simply printing a list from random, and the list can contain anything:
random number from 1 to 5:
import random
import random [Link]([“Conan”, “Valeria”, “Belit”])
print(randomint(0,5))
This will display one of the names of our adventurers at random,
which is a great addition to a text adventure game.

STEP 2 In our example


the number four
was returned. However, enter
the print function a few more
times and it will display diƪerent
integer values from the set of
numbers given, zero to Ƭve. The
overall eƪect, although pseudo-
STEP 5 You can extend the previous example somewhat by
random, is adequate for the
having [Link]() select from a list of mixed
average programmer to utilise in
variables. For instance:
their code.
import random
lst=[“David”, 44, “BDM Publications”, 3245.23,
“Pi”, True, 3.14, “Python”]
rnd=[Link](lst)
STEP 3 For a bigger set of numbers, including Ʈoating
print(rnd)
point values, you can extend the range by using the
multiplication sign:
import random
print([Link]() *100)
Will display a Ʈoating point number between 0 and 100, to the tune
of around Ƭfteen decimal points.

96 3\WKRQ&RGLQJ 3URJUDPPLQJ
Random Module

STEP 6 Interestingly, you can also use a function within the STEP 9 Let’s use an example piece of code which Ʈips a
Random module to shuưe the items in the list, thus virtual coin ten thousand times and counts how
adding a little more randomness into the equation: many times it will land on heads or tails:
[Link](lst) import random
print(lst) output={“Heads”:0, “Tails”:0}
coin=list([Link]())
This way, you can keep shuưing the list before displaying a random
item from it. for i in range(10000):
output[[Link](coin)]+=1
print(“Heads:”, output[“Heads”])
print(“Tails:”, output[“Tails”])

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


of numbers. For example, within a given range:
import random
lst=[[i] for I in range(20)]
[Link](lst) STEP 10 Here’s an interesting piece of code. Using a text
print(lst) Ƭle containing 466 thousand words, you can pluck
a user generated number of words from the Ƭle (text Ƭle found at:
Keep shuưing the list and you can have a diƪerent selection of
[Link]/dwyl/english-words):
items from 0 to 20 every time.
import random
print(“>>>>>>>>>>Random Word Finder<<<<<<<<<<”)
print(“\nUsing a 466K English word text file I can
pick any words at random.\n”)
wds=int(input(“\nHow many words shall I choose?
“))
with open(“/home/pi/Downloads/[Link]”, “rt”) as
f:
words = [Link]()
words = [[Link]() for w in words]

STEP 8 You can also select a random number from a given print(“--------------------”)
range in steps, using the start, stop, step loop:
for w in [Link](words, wds):
import random print(w)
for i in range(10):
print(“--------------------”)
print([Link](0, 200, 7))
Results will vary but you get the general idea as to how it works.

ZZZSFOSXEOLFDWLRQVFRP 97
Using Modules

Tkinter Module
While running your code from the command line, or even in the Shell, is perfectly Ƭne,
Python is capable of so much more. The Tkinter module enables the programmer to set
up a Graphical User Interface to interact with the user, and it’s surprisingly powerful too.

GETTING GUI
Tkinter is easy to use but there’s a lot more you can do with it. Let’s start by seeing how it works and getting some code into it.
Before long you will discover just how powerful this module really is.

STEP 1 Tkinter is usually built into Python 3. However, if it’s STEP 3 The ideal approach is to add mainloop() into the
available when you enter: import tkinter, then code to control the Tkinter event loop, but we’ll
you need to pip install tkinter from the command prompt. get to that soon. You’ve just created a Tkinter widget and there are
We can start to import modules diƪerently than before, to save on several more we can play around with:
typing and by importing all their contents:
btn=Button()
import tkinter as tk [Link]()
from tkinter import * btn[“text”]=”Hello everyone!”
The Ƭrst line focuses on the newly created window. Click back into
the Shell and continue the other lines.

STEP 2 It’s not recommended to import everything from a STEP 4 You can combine the above into a New File:
module using the asterisk but it won’t do any harm
import tkinter as tk
normally. Let’s begin by creating a basic GUI window, enter:
from tkinter import *
wind=Tk() btn=Button()
[Link]()
This creates a small, basic window. There’s not much else to do at
btn[“text”]=”Hello everyone!”
this point but click the X in the corner to close the window.
Then add some button interactions:
def click():
print(“You just clicked me!”)
btn[“command”]=click

98 3\WKRQ&RGLQJ 3URJUDPPLQJ
Tkinter Module

STEP 5 Save and execute the code from Step 5 and a STEP 8 You can create radio buttons too. Try:
window appears with ‘Hello everyone!’ inside. If you
from tkinter import *
click the Hello everyone! button, the Shell will output the text ‘You
just clicked me!’. It’s simple but shows you what can be achieved root = Tk()
with a few lines of code.
v = IntVar()
Label(root, [Link](“Options”), text=”””Choose
a preferred language:”””,
justify = LEFT, padx = 20).pack()
Radiobutton(root,
text=”Python”,
padx = 20,
variable=v,
value=1).pack(anchor=W)
Radiobutton(root,
text=”C++”,
padx = 20,
variable=v,
STEP 6 You can also display both text and images within value=2).pack(anchor=W)
a Tkinter window. However, only GIF, PGM or PPM
mainloop()
formats are supported. So Ƭnd an image and convert it before using
the code. Here’s an example using the BDM Publishing logo:
STEP 9 You can also create check boxes, with buttons and
from tkinter import *
output to the Shell:
root = Tk()
from tkinter import *
logo = PhotoImage(file=”/home/pi/Downloads/BDM_logo.
root = Tk()
gif”)
w1 = Label(root, [Link](“BDM Publications”), def var_states():
image=logo).pack(side=”right”) print(“Warrior: %d,\nMage: %d” % ([Link](),
content = “”” From its humble beginnings in 2004, [Link]()))
the BDM brand quickly grew from a single publication
Label(root, [Link](“Adventure Game”),
produced by a team of just two to one of the biggest
text=”>>>>>>>>>>Your adventure role<<<<<<<<<<”).
names in global bookazine publishing, for two simple
grid(row=0, sticky=N)
reasons. Our passion and commitment to deliver the
var1 = IntVar()
very best product each and every volume. While
Checkbutton(root, text=”Warrior”, variable=var1).
the company has grown with a portfolio of over 250
grid(row=1, sticky=W)
publications delivered by our international staff,
var2 = IntVar()
the foundation that it has been built upon remains
Checkbutton(root, text=”Mage”, variable=var2).
the same, which is why we believe BDM isn’t just
grid(row=2, sticky=W)
the first choice it’s the only choice for the smart
Button(root, text=’Quit’, command=[Link]).
consumer. “””
grid(row=3, sticky=W, pady=4)
w2 = Label(root,
Button(root, text=’Show’, command=var_states).
justify=LEFT,
grid(row=3, sticky=E, pady=4)
padx = 10,
text=content).pack(side=”left”) mainloop()
[Link]()

STEP 10 The code from Step 9 introduced some new


STEP 7 geometry elements into Tkinter. Note the
sticky=N, E and W arguments. These describe the locations of the
The previous code is check boxes and buttons (North, East, South and West). The row
quite weighty, mostly argument places them on separate rows. Have a play around and
due to the content see what you get.
variable holding a part
of BDM’s About page
from the company
website. You can
obviously change the
content, the [Link]
and the image to suit
your needs.

ZZZSFOSXEOLFDWLRQVFRP 99
Using Modules

Pygame Module
We’ve had a brief look at the Pygame module already but there’s a lot more to it that
needs exploring. Pygame was developed to help Python programmers create either
graphical or text-based games.

PYGAMING
Pygame isn’t an inherent module to Python but 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 you need to load up the Pygame modules STEP 3 Sadly you can’t close the newly created Pygame
into memory before you’re able to utilise them. window without closing the Python IDLE Shell,
Once that’s done Pygame requires the user to initialise it prior to which isn’t very practical. For this reason, you 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
[Link]() from [Link] import *
[Link]()
gamewindow=[Link].set_mode((800,600))
[Link].set_caption(“Adventure Game”)
running=True
while running:
for event in [Link]():
if [Link]==QUIT:
running=False
[Link]()

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


it a title:
gamewindow=[Link].set_mode((800,600))
[Link].set_caption(“Adventure Game”)
You can see that after the Ƭrst line is entered, you need to click back
into the IDLE Shell to continue entering code; also, you can change
the title of the window to anything you like.

100 3\WKRQ&RGLQJ 3URJUDPPLQJ


Pygame Module

STEP 4 If the Pygame window still won’t


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

STEP 5 You’re going to shift the code around a bit now, img=[Link](“/home/pi/Downloads/
running the main Pygame code within a while loop; [Link]”)
it makes it neater and easier to follow. We’ve downloaded a graphic
def sprite(x,y):
to use and we need to set some parameters for pygame:
[Link](img, (x,y))
import pygame
x=(800*0.45)
[Link]()
y=(600*0.8)
running=True
[Link](white)
while running: sprite(x,y)
[Link]()
gamewindow=[Link].set_mode((800,600))
[Link].set_caption(“Adventure Game”) for event in [Link]():
black=(0,0,0) if [Link]==[Link]:
white=(255,255,255) running=False

STEP 6 Let’s quickly go through the code changes. We’ve downloaded image called [Link] and allocated it to the
deƬned two colours, black and white together variable img; and also deƬned a sprite function and the Blit function
with their respective RGB colour values. Next we’ve loaded the will allow us to eventually move the image.

ZZZSFOSXEOLFDWLRQVFRP 101
Using Modules

STEP 7 Now we can change the code around again, this imgspeed=0
time containing a movement option within the
while running:
while loop, and adding the variables needed to move the sprite
for event in [Link]():
around the screen:
if [Link]==QUIT:
import pygame running=False
from [Link] import *
if [Link] == [Link]:
[Link]()
if [Link]==pygame.K_LEFT:
running=True xchange=-5
elif [Link]==pygame.K_RIGHT:
gamewindow=[Link].set_mode((800,600))
xchange=5
[Link].set_caption(“Adventure Game”)
if [Link]==[Link]:
black=(0,0,0)
if [Link]==pygame.K_LEFT or event
white=(255,255,255)
key==pygame.K_RIGHT:
img=[Link](“/home/pi/Downloads/sprite1.
xchange=0
png”)
x += xchange
def sprite(x,y):
[Link](img, (x,y)) [Link](white)
sprite(x,y)
x=(800*0.45)
[Link]()
y=(600*0.8)
[Link]()
xchange=0

STEP 8 Copy the code down and using the left and right arrow keys on the keyboard you can move your sprite across the bottom of
the screen. Now, it looks like you have the makings of a classic arcade 2D scroller in the works.

102 3\WKRQ&RGLQJ 3URJUDPPLQJ


Pygame Modules

STEP 9 You can now implement a few additions and utilise [Link]()
some previous tutorial code. The new elements are [Link](60)
the Subprocess module, of which one function allows us to launch a continue
second Python script from within another; and we’re going to create a break
New File called [Link]:
[Link]()
import pygame
import time
import subprocess
[Link]()
screen = [Link].set_mode((800, 250))
clock = [Link]()
font = [Link](None, 25)
[Link].set_timer([Link], 200)
def text_generator(text):
tmp = ‘’
for letter in text:
tmp += letter
if letter != ‘ ‘:
yield tmp
class DynamicText(object):
def __init__(self, font, text, pos,
autoreset=False):
[Link] = False
[Link] = font
[Link] = text
self._gen = text_generator([Link])
[Link] = pos
[Link] = autoreset
[Link]()
def reset(self):
self._gen = text_generator([Link])
[Link] = False
[Link]()
def update(self):
if not [Link]:
try: [Link] = [Link]. STEP 10 When you run this code it will display a long,
render(next(self._gen), True, (0, 128, 0)) narrow Pygame window with the intro text
except StopIteration: scrolling to the right. After a pause of ten seconds, it then launches
[Link] = True the main game Python script where you can move the warrior sprite
[Link](10) around. Overall the eƪect is quite good but there’s always room
[Link](“python3 /home/pi/Documents/ for improvement.
Python\ Code/[Link] 1”, shell=True)
def draw(self, screen):
[Link]([Link], [Link])
text=(“A long time ago, a barbarian strode from the
frozen north. Sword in hand...”)
message = DynamicText(font, text, (65, 120),
autoreset=True)
while True:
for event in [Link]():
if [Link] == [Link]: break
if [Link] == [Link]: message.
update()
else:
[Link]([Link](‘black’))
[Link](screen)

ZZZSFOSXEOLFDWLRQVFRP 103
Using Modules

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

LIGHTS, CAMERA, ACTION


The Tkinter module is an ideal starting point for 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 STEP 3 Insert the new code between the ball1
will need to create a canvas (window) and the ball = canvas.create_oval(5,5,60,60,
to animate: fill=’red’) line and the [Link]() line. Save it and
Run. You will now see the ball move from the top left corner of the
from tkinter import *
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
gui = Tk() [Link](.01) line. Try (.05).
[Link](“800x600”)
[Link](“Pi Animation”)
canvas = Canvas(gui,
width=800,height=600,bg=’white’)
[Link]()
ball1 = canvas.create_oval(5,5,60,60, fill=’red’)
[Link]()

STEP 2 Save and Run the code. You will see a blank window
appear, with a red ball sitting in the upper left
corner of the window. While this is great, it’s not very animated.
Let’s add the following code:
a = 5
b = 5
for x in range(0,100):
[Link](ball1,a,b)
[Link]()
[Link](.01)

STEP 4 The [Link](ball1,a,b) line is the part


that moves the ball from one corner to the other;
obviously with both a and b equalling 5. We can change things around
a bit already, such as the size and colour of the ball, with the line:
ball1 = canvas.create_oval(5,5,60,60, fill=’red’)
and we can change the values of a and b to something else.

104 3\WKRQ&RGLQJ 3URJUDPPLQJ


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.
def main():
xa = 5
[Link]()
ya = 10
screen = [Link].set_mode((640,480))
while True: [Link].set_caption(“Starfield
[Link](ball1,xa,ya) Simulation”)
pos=[Link](ball1) clock = [Link]()
if pos[3] >=600 or pos[1] <=0:
init_stars(screen)
ya = -ya
if pos[2] >=800 or pos[0] <=0: while True:
xa = -xa # Lock the framerate at 50 FPS
[Link]() [Link](50)
[Link](.025)
# Handle events
for event in [Link]():
STEP 6 Remove the code you entered in Step 2 and insert if [Link] == [Link]:
the code from Step 5 in its place; again, between the return
ball1 = canvas.create_oval(5,5,60,60, fill=’red’)
[Link]((0,0,0))
and the [Link]() lines. Save the code and Run it as normal.
move_and_draw_stars(screen)
If you’ve entered the code correctly, then you will see the red ball
[Link]()
bounce oƪ the edges of the window until you close the program.
if __name__ == “__main__”:
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 pos=[Link](ball1) line
takes the value of the ball’s location in the
window. When it reaches the limits of the
window, 800 or 600, it will make the values
negative; moving the ball around the screen.

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


producing higher-end animations. Begin by creating
a New File and entering:
import pygame
from random import randrange
MAX_STARS = 250
STAR_SPEED = 2
def init_stars(screen): STEP 10 Save and Run the code. You will agree that the
“”” Create the starfield “”” simulated starƬeld code looks quite impressive.
global stars Imagine this as the beginning of some game code, or even the start
stars = [] to a presentation? Using a combination of Pygame and Tkinter, your
for i in range(MAX_STARS): Python animations will look fantastic.
# A star is represented as a list with this
format: [X,Y]
star = [randrange(0,screen.get_width() - 1),
randrange(0,screen.get_height() - 1)]
[Link](star)
def move_and_draw_stars(screen):
“”” Move and draw the stars “””
global stars
for star in stars:
star[1] += STAR_SPEED
if star[1] >= screen.get_height():
star[1] = 0
star[0] = randrange(0,639)
screen.set_at(star,(255,255,255))

ZZZSFOSXEOLFDWLRQVFRP 105
Using Modules

Create Your Own Modules


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

BUILDING MODULES
Modules are Python Ƭles, containing code, that you save using a .py extension. These are then imported into Python using the
now familiar import command.

STEP 1 Let’s start by creating a set of basic mathematics STEP 3 Now you’re going to take the function deƬnitions
functions. Multiply a number by two, three and out of the program and into a separate Ƭle.
square or raise a number to an exponent (power). Create a New File Highlight the function deƬnitions and choose Edit > Cut. Choose File
in the IDLE and enter: > New File and use Edit > Paste in the new window. You now have
two separate Ƭles, one with the function deƬnitions, the other with
def timestwo(x):
the function calls.
return x * 2
def timesthree(x):
return x * 3
def square(x):
return x * x
def power(x,y):
return x ** y

STEP 2 Under the above code, enter functions to call the STEP 4 If you now try and execute the basic_math.py code
code: again, the error ‘NameError: name ‘timestwo’ is
not deƬned’ will be displayed. This is due to the code no longer
print (timestwo(2))
having access to the function deƬnitions.
print (timesthree(3))
print (square(4))
print (power(5,3))
Save the program as basic_math.py and execute it to get the results.

STEP 5 Return to
the newly
created window containing
the function deƬnitions, and
click File > Save As. Name this
[Link] and save it in the
same location as the original
basic_math.py program. Now
close the [Link] window,
so the basic_math.py window is
left open.

106 3\WKRQ&RGLQJ 3URJUDPPLQJ


Create Your Own Modules

STEP 6 Back to the basic_math.py window: at the top of the STEP 9 Finally, you can now create a range of if statements
code enter: to determine what to do with the number and
utilise the newly created function deƬnitions:
from minimath import *
if choice == ‘1’:
This will import the function deƬnitions as a module. Press F5 to
print(timestwo(num1))
save and execute the program to see it in action.
elif choice == ‘2’:
print(timesthree(num1))
elif choice == ‘3’:
print(square(num1))
elif choice == ‘4’:
num2 = int(input(“Enter second number: “))
print(power(num1, num2))
else:
print(“Invalid input”)

STEP 7 You can now use the code further to make the
program a little more advanced, utilising the newly
created module to its full. Include some user interaction. Start by
creating a basic menu the user can choose from:
print(“Select operation.\n”)
print(“[Link] by two”)
print(“[Link] by Three”)
print(“[Link]”)
print(“[Link] of”)
choice = input(“\nEnter choice (1/2/3/4):”)

STEP 8 Now we can add the user input to get the number
the code will work on:
num1 = int(input(“\nEnter number: “))
This will save the user-entered number as the variable num1.
STEP 10 Note that for the last available options, the Power
of choice, we’ve added a second variable, num2.
This passes a second number through the function deƬnition called
power. Save and execute the program to see it in action.

ZZZSFOSXEOLFDWLRQVFRP 107
Using Modules

Python in Focus:
ArtiƬcial Intelligence
ArtiƬcial Intelligence (AI) and Machine Learning (ML) are the new hot topics of the IT
industry. AI is fast becoming the working science Ƭction that it has been portrayed as in
the past, and behind it is Python.
Despite how close AI and ML are, there are distinct diƪerences
between the two technologies. AI refers to the study of how to train a
computer to accomplice the things that humans can do signiƬcantly
better and faster. Whereas, ML is the ability for a computer to learn
from its experiences, so that the outcome and performance will
eventually become more accurate and accomplished.

While diƪerent, they are both essentially discussing the same


element: training a system to learn and do things independently.
Where AI is said to lead to wisdom, ML reportedly leads to knowledge
and, thanks to Python, that gap is getting closer every day.

APPLICATIONS DIGITAL ASSISTANTS


Both AI and ML are hugely present in today’s technology. Where, The rise of digital assistants has been one of the kick-starters of
just a few years ago, most of us associated AI with the rise of a AI and ML programming. Siri, Cortana, Alexa and Google Assistant
super-intelligent legion of killer robots, nowadays you’d be amazed are all coded using Python, and are designed to listen, learn and
at the numerous examples of AI in your house, and even being respond to what we ask of them. With Python, this level of AI is
carried around with you. surprisingly simple, thanks to the many libraries and customisation
of the language. These frameworks make creating AI and ML easy
Let’s begin with the obvious use of AI and ML, the smartphone. for intelligent coders, cutting down on the development time in
These devices have inƬltrated most of our modern world, with other languages and, thanks to Python’s easy to read code and
global coverage reaching 5.5 billion for 2019 and set to rise to over complex algorithms, these developers can devote signiƬcant time to
6 billion by the end of 2020, it’s little surprise to discover that AI and improving the performance and accuracy of AI.
ML are advancing in leaps and bounds.
Every time we ask one of these digital assistants for something, the
With nearly all of the population of humanity within reach of a Python-driven AI code is reading our voice, determining what it is
smartphone, the coding behind these devices has been developed we’re asking by plucking out key words and acting on them. If we
to take individuals into account. These devices are designed to ask for a thirty second countdown, it’ll start the device’s stopwatch
learn what the user requires, or uses, the device for. Common function; if we ask for dinner suggestions, it’ll open a speciƬc set of
numbers called are pushed to the top of the list, in-app and in-game web pages, and if we ask it to play some music, it’ll interrogate the
advertising is moulded around our browser and search preferences, available music apps to select what it is we wanted. All the time,
as well as other apps we’ve installed in the past. And even our the AI code is being trained to listen more intently, while the ML
voices, Ƭngerprints and faces are stored and analysed by AI and ML is learning from the AI results so that its accuracy is improved for
in order to recognise who we are. future questions and requests.

108 3\WKRQ&RGLQJ 3URJUDPPLQJ


Python in Focus: ArtiƬcial Intelligence

BEYOND THE SMARTPHONE


Consider Google, social media and the content you look up. How many times
have you entered a search string into Google, such as car parts for a Mk1
Ford Escort and, when you’ve opened Facebook, you suddenly Ƭnd a group
suggestion of Ford Escort owners? That’s AI and ML injecting themselves into
your everyday computing tasks.

Another example of AI and ML working together is Gmail’s recent addition of


suggested completions for sentences you are typing. If you frequently sign
oƪ with ‘See you soon’, or ‘All the best’, then typing ‘See’ or ‘All’ will prompt
the ML side of the equation to autoƬll the remainder of the words for you. All
the time, the ML is learning while the AI is telling it what to improve on.

Facial recognition is another element of AI and ML that’s been the target of


the popular press for some time. Throughout 2019, facial recognition systems
on both smartphones and CCTV footage have improved dramatically.
Agencies controlling this level of AI now have the ability to single out an
individual from a crowded street and, while that’s great for law and order,
it does pose a potential threat to our privacy. After all, who watches the
watcher?

Tesla’s work on self-driving cars means they are getting closer to being the
norm, and it’s Python along with its controlling AI and ML work that’s, excuse
the pun, driving it forward. In these circumstances, Python is doing a lot
of the heavy lifting, providing the connective tissue and libraries that are
designed to implement AI and ML. In the background, you’ll usually Ƭnd
C++, or some other language, that’s supporting the performance and
overall program in which the AI and ML are working.

While it’s easy to portray a bleak AI future, let’s not forget


the many great instances of AI we currently enjoy: optical
character recognition, handwriting recognition, image
processing, helping people with visual and hearing
disabilities, advancements in space exploration,
engineering improvements, conservation,
pharmaceutical and drug improvements and
greater freedom for those limited in their
ability to travel. It’s not all about two AI bots
arguing about eliminating the human race.

THE FUTURE
OF AI
Whether we’ll end up creating true
AI, killer robots and self-aware
androids is up for debate. There are
plenty of arguments for and against
the evolution of AI, with many
believing that AI will be the worst
possible future humans can create
– worse even than nuclear war. For
the moment, however, we’re at the
early stages of AI development,
but with Python’s continual
advancements and improved
libraries, it may not be too long
before we’ve got an AI system
that’s getting better by the hour.

ZZZSFOSXEOLFDWLRQVFRP 109
Index

SHARE YOUR CODE!


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

110 3\WKRQ&RGLQJ 3URJUDPPLQJ


Code Repository

We’ve included a vast Python code


repository for you to freely use in
your own programs. There’s plenty in
here to help you create a superb piece of
programming, or extend your project ideas.
We’ve got code for making backups of
your Ƭles and folders, number guessing
games, random number generators,
Google search code, game code,
animation code, graphics code, text
adventure code and even code that plays
music stored on your computer. We’ve
broken down some of the newer, and
extended, concepts of the code to help
you better understand what’s going on.
This way you can easily adapt it to your
own uses.
This is an excellent resource that you
won’t Ƭnd in any other Python book. So
use it, take it apart, adapt it to your own
programs and see what you can create.

112 Python File Manager


114 Number Guessing Game
116 Random Number Generator
117 Random Password Generator
118 Text to Binary Convertor
120 Basic GUI File Browser
122 Mouse Controlled Turtle
123 Python Alarm Clock
124 Vertically Scrolling Text
126 Python Digital Clock
128 Playing Music with the Winsound Module
130 Text Adventure Script
132 Python Scrolling Ticker Script
133 Simple Python Calculator
134 Hangman Game Script

ZZZSFOSXEOLFDWLRQVFRP 111
Code Repository

Python File Manager


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

def Read():
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

112 3\WKRQ&RGLQJ 3URJUDPPLQJ


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  Imports
ZKLOH UXQ   There are three modules to import here: Shutil, OS and
try: Time. The Ƭrst two deal with the operating system and Ƭle
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

ZZZSFOSXEOLFDWLRQVFRP 113
Code Repository

Number Guessing Game


This is a simple little piece of code [Link]
but it makes good use of the Copy the code and see if you can beat the computer within
Random module, print and input, Ƭve guesses. It’s an interesting bit of code that can be quite
handy when your implementing a combination of the Random
and a while loop. The number of module alongside a while loop.
guesses can be increased from 5
and the random number range can import random 1
easily be altered too. guessesUsed = 0
1DPH LQSXW µ+HOOR:KDWLV\RXUQDPH"µ
QXPEHU UDQGRPUDQGLQW  
SULQW µ*UHHWLQJV µ  1DPH  µ,?¶PWKLQNLQJRID
QXPEHU EHWZHHQ  DQG ¶
ZKLOH JXHVVHV8VHG  
JXHVV LQW LQSXW µ*XHVVWKHQXPEHUZLWKLQJXHVVHV¶
JXHVVHV8VHG JXHVVHV8VHG  
LI JXHVV  QXPEHU
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
number=[Link](1, 30) end value of 30; don’t make
it too high though or the player will never be able to guess it.
If the player guesses too low or too high, they are given the
appropriate output and asked to try again, while the number
of guesses is less than Ƭve. You can also increase the number of
guesses from 5 by altering the while guessesUsed  5: value.
If the player guessed the correct number then they are given a
3 ‘well done’ output, along with how many guesses they used up.
If the player runs out of guesses, then the game over output is
displayed instead, along with revealing the number the computer
was thinking of. Remember, if you do alter the values of the
random number chosen by the computer, or the number of
guesses the player can take, then along with the variable values,
you also need to amend the instructions given in the print
statements at the start of the code.

114 3\WKRQ&RGLQJ 3URJUDPPLQJ


Number Guessing Game

Code Improvements
Since this is such as simple script to apply to a situation, there’s For example, as per the screenshot provided, you could use
plenty of room to mess around with it and make it more something along the lines of:
interesting. Perhaps you can include an option to take score, the
best out of three rounds. Maybe an elaborate way to congratulate Endurance=0
the player for getting a ‘hole in one’ correct guess on their Ƭrst try. CR=0
/XFN 
Moreover, the number guessing game code does oƪer some room (QGXUDQFH UDQGRPUDQGLQW 
&5 UDQGRPUDQGLQW 
for implementing into your code in a diƪerent manner. What
/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
character creation deƬned function within an adventure game. 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.

ZZZSFOSXEOLFDWLRQVFRP 115
Code Repository

Random Number Generator


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

program, one that allows the user SULQW ³?Q!!!!!!!!!!5DQGRP1XPEHU*HQHUDWRU?Q´


QPE LQW LQSXW ³(QWHU WKH VWDUW QXPEHU ³
to interact and see the results of QPE LQW LQSXW ³(QWHU WKH ODVW QXPEHU ³
that interaction. [ UDQGLQW QPEQPE
SULQW ³?Q7KH UDQGRP QXPEHUEHWZHHQ´QPE´DQG´QPE´LV?Q´
print(x)

More Input
While an easy code to follow, it could be more interesting if you For example, the code could be edited to this:
prompt the user for more input. Perhaps you can provide them
with addition, subtraction, multiplication elements with their from random import *
numbers. If you’re feeling clever, see if you can pass the code import turtle
through a Tkinter window or even the Ticker window that’s
available on Page 98. 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³
game, where the character Ƭghts something and their health, nmb4=int(input(“Enter the fourth number: “))
along with the enemy’s, is reduced by a random number. This can
be mixed with the previous code from Page 114’s Number
Guessing Game, where we defined the stats for the adventure WXUWOHIRUZDUG QPE
game’s character. WXUWOHOHIW 
WXUWOHIRUZDUG QPE
You can also introduce the Turtle module into the code and WXUWOHOHIW 
perhaps set some deƬned rules for drawing a shape, object or WXUWOHIRUZDUG QPE
WXUWOHOHIW 
something based on a user inputted random value from a range
WXUWOHIRUZDUG QPE
of numbers. It takes a little working out but the eƪect is certainly WXUWOHOHIW 
really interesting.
Whilst it’s a little rough around the edges, you can easily make it
more suitable.

116 3\WKRQ&RGLQJ 3URJUDPPLQJ


Random Number Generator/Password Generator

Random Password
Generator
We’re always being told that our [Link]
passwords aren’t secure enough; well Copy the code and run it; each time you’ll get a random string
here’s a solution for you to implement of characters that can easily be used as a secure password
which will be very diƯcult for a password cracker to hack.
into your own future programs. The
random password generator code import string
import random
below will create a 12-letter string of
GHIUDQGRPSDVVZRUG 
words (both cases) and numbers each FKDUV VWULQJDVFLL B XSSHUFDVHVWULQJDVFLL B
time it’s executed. ORZHUFDVH  VWULQJGLJLWV
size= 8
UHWXUQ µ¶MRLQ UDQGRPFKRLFH FKDUV IRU[LQ
UDQJH VL]H

SULQW UDQGRPSDVVZRUG

Secure Passwords
There’s plenty you can do to modify this code and improve it Adding a loop to print a password Ƭfty times is extremely easy, for
further. For one, you can increase the number of characters the example:
generated password displays and perhaps you can include special
characters too, such as signs and symbols. Then, you can output import string
the chosen password to a Ƭle, then securely compress it using the import random
previous random number generator as a Ƭle password and send it
to a user for their new password.
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

This will output Ƭfty random passwords based on the previous


random selection of characters.

ZZZSFOSXEOLFDWLRQVFRP 117
Code Repository

Text to Binary Convertor


While it may not seem too exciting, [Link]
this text to binary convertor is Naturally we’re using the format function to convert the
actually quite good fun. It also user’s entered text string into its binary equivalent. If you
want to check its accuracy, you can plug the binary into an
only uses two lines of code, so it’s online convertor.
extremely easy to insert into your
own script. WH[W LQSXW ³(QWHUWH[WWRFRQYHUWWR%LQDU\³

SULQW µµMRLQ IRUPDW RUG [ µE¶ IRU[LQWH[W

118 3\WKRQ&RGLQJ 3URJUDPPLQJ


Text to Binary Convertor

1000010 1101001 1101110 1100001 1110010


1111001
The text to binary convertor does oƪer some room for
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
from page 100. You could also ask the user if they wanted to have %LQDU\ µµMRLQ IRUPDW RUG [ µE¶ IRU[
another go, or even ask if they wanted the binary output to be LQFRQYHUVLRQ
saved to a Ƭle.
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

ZZZSFOSXEOLFDWLRQVFRP 119
Code Repository

Basic GUI File Browser


Here’s a helpful and interesting [Link]
piece of code. It’s an extremely basic Tkinter is the main module in use here but we’re also using
Ƭle browser that’s presented in a idlelib, so you may need to pip install any extras if the
dependencies fail when you execute the code.
graphical user interface using the
Tkinter module. There’s a lot you can
IURPWNLQWHULPSRUW7N
learn from this code and implement
into your own programs. IURPLGOHOLE7UHH:LGJHWLPSRUW6FUROOHG&DQYDV
)LOH7UHH,WHP 7UHH1RGH
import os

URRW 7N
URRWWLWOH ³)LOH%URZVHU´

VF 6FUROOHG&DQYDV URRWEJ ´ZKLWH´


KLJKOLJKWWKLFNQHVV  WDNHIRFXV 
VFIUDPHSDFN H[SDQG  ¿OO ´ERWK´VLGH ´OHIW´

LWHP )LOH7UHH,WHP RVJHWFZG


QRGH 7UHH1RGH VFFDQYDV 1RQHLWHP
QRGHH[SDQG

URRWPDLQORRS

120 3\WKRQ&RGLQJ 3URJUDPPLQJ


Basic GUI File Browser

Advanced Filing try:


When executed, the code will display the current directory’s ZLWKRSHQ QDPH¶U¶ DV8VH)LOH
contents. If you want to see the contents of another directory, you   SULQW 8VH)LOHUHDG
except:
can run the code from a command line within the chosen directory;
SULQW ³1R¿OHVRSHQHG´
just remember to call the code from where it’s located on your
system, as per the second screenshot. You can also double-click any
of the Ƭle names shown in the directory tree and rename them. 7LWOH URRWWLWOH ³)LOH2SHQHU´ 
ODEHO WWN/DEHO URRWWH[W ´)LOH
This is an interesting piece of code and one that you can insert into 2SHQ´IRUHJURXQG ´UHG´IRQW ³+HOYHWLFD´
your own programs. You can extend the code to include a user ODEHOSDFN
speciƬed directory to browse, perhaps your own unique Ƭle icons
too. If you’re using Linux, create an alias to execute the code and
then you can run it from wherever you are in the system. menu = Menu(root)
URRWFRQ¿J PHQX PHQX
Windows users may have some trouble with the above code, an
¿OH 0HQX PHQX
alternative can be achieved by using the following:
¿OHDGG B FRPPDQG ODEHO µ2SHQ¶FRPPDQG 2SHQ)LOH
from tkinter import * ¿OHDGG B FRPPDQG ODEHO µ([LW¶FRPPDQG 
from tkinter import ttk lambda:exit())
IURPWNLQWHU¿OHGLDORJLPSRUWDVNRSHQ¿OHQDPH
PHQXDGG B FDVFDGH ODEHO µ)LOH¶PHQX ¿OH
URRW 7N 
URRWPDLQORRS
def OpenFile():
QDPH DVNRSHQ¿OHQDPH LQLWLDOGLU ´&´
¿OHW\SHV ³7H[W)LOH´³ W[W´  ³$OO
)LOHV´´  ´ 
It’s not quite the same but this code allows you to open Ƭles
WLWOH ³&KRRVHD¿OH´
in your system via the familiar Windows Explorer. It’s worth
)
print (name) experimenting with to see what you can do with it.

ZZZSFOSXEOLFDWLRQVFRP 121
Code Repository

Mouse Controlled Turtle


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

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

122 3\WKRQ&RGLQJ 3URJUDPPLQJ


Mouse Controlled Turtle/ Python Alarm Clock

Python Alarm Clock


Ever taken a quick break from working try:
at the computer, then suddenly realised LIPLQXWHV!
SULQW ³6OHHSLQJIRU³VWU PLQXWHV XQLW B ZRUG
many minutes later that you’ve spent all sleep(seconds)
that time on Facebook? Introducing the SULQW ³:DNHXS´
for i in range(5):
Python alarm clock code, where you can SULQW FKU  
 VOHHS 
drop into the command prompt and tell H[FHSW .H\ERDUG,QWHUUXSW
the code how many minutes until the SULQW ³,QWHUUXSWHGE\XVHU´
V\VH[LW 
alarm goes oƪ.
Wakey Wakey
[Link] There’s some good use of try and except blocks here, alongside
some other useful loops that can help you get a Ƭrmer
This code is designed for use in the command prompt, be that
understanding of how they work in Python. The code itself
Windows, Linux or macOS. There are some instructions on how
can be used in a variety of ways: in a game where something
to use it in the main print section but essentially it’s: python3
happens after a set amount of time or simply as a handy
[Link] 10 (to go oƪ in ten minutes).
desktop alarm clock for your tea break.

import sys Linux users, try making the alarm clock code into an alias, so
import string you can run a simple command to execute it. Then, why not
from time import sleep integrate a user input at the beginning to ask the user for the
length of time they want until the alarm goes oƪ, rather than
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´
print (“Press Ctrl-C to terminate the alarm
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´ Ƭle and even set a schedule to activate the alarm at certain
times of the day.

ZZZSFOSXEOLFDWLRQVFRP 123
Code Repository

Vertically Scrolling Text


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

WH[W B OLVW µ¶¶

,UHPHPEHU
7KH GDUN ZRRGVPDVNLQJVORSHVRIVRPEUHKLOOV
7KH JUH\ FORXGV¶ OHDGHQ HYHUODVWLQJ DUFK
7KH GXVN\ VWUHDPV WKDW ÀRZHG ZLWKRXW D VRXQG
$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
2QO\ WKH VWLOOQHVV RI WKDW VRPEUH ODQG
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¶

124 3\WKRQ&RGLQJ 3URJUDPPLQJ


Vertically Scrolling Text

class Credits:
GHIB B LQLW B B VHOIVFUHHQ B UHFWOVW  A Long Time Agof
VHOIVUHFW VFUHHQ B UHFW The obvious main point of enhancement is the actual text
VHOIOVW OVW itself. Replace it with a list of credits, or an equally epic opening
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 

ZZZSFOSXEOLFDWLRQVFRP 125
Code Repository

Python Digital Clock


There is already a clock displayed [Link]
on the desktop of most operating This is a surprisingly handy little script and one that we’ve
systems but it’s always handy to have used in the past instead of relying on a watch or even the
clock in the system tray of the operating system.
one on top of the currently open
window. To that end, why not create import time
import tkinter as tk
a Python digital clock that can be a
GHIWLFN WLPH ¶¶ 
companion desktop widget for you. JHWWKHFXUUHQWWLPHIURPWKH3&
WLPH WLPHVWUIWLPH µ+06¶
LI WLPH  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

126 3\WKRQ&RGLQJ 3URJUDPPLQJ


Python Digital Clock

Tick Tock
This is a piece of code we’ve used many times in the past to keep
track of time while working on multiple monitors and with just a URRWWLWOH µ6WRS:DWFK¶
quick glance to where we’ve placed it on the screen. URRWUHVL]DEOH 7UXH)DOVH
URRWJULG B FROXPQFRQ¿JXUH ZHLJKW 
The Tkinter box can be moved around without aƪecting the time, 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
including diƪerent time zones: Rome, Paris, London, New York, 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

ZZZSFOSXEOLFDWLRQVFRP 127
Code Repository

Playing Music with the


Winsound Module
Of course, instead of playing an [Link]
existing MP3, you can always make The code utilises both the Time and Winsound modules,
your own music. The code below deƬning the tone and pitch and inserting small pauses of .5
of a second.
will play out Pachelbel’s Canon in D,
no less. 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
%E 
% 

K& 
hDb = 554
hD = 587
K(E 
hE = 659
hF = 698
hGb = 740
hG = 784
K$E 
hA = 880
K%E 
K% 

WLPHVOHHS 

128 3\WKRQ&RGLQJ 3URJUDPPLQJ


Playing Music with the Winsound Module

for i in range (5): Sweet Music


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
Naturally you can swap out the [Link] frequency and
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
is setting the duration, while p equals .5, which you can use for
the [Link] function.

These variables set the frequencies, with the corresponding


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

[Link] requires a frequency and duration within the


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

ZZZSFOSXEOLFDWLRQVFRP 129
Code Repository

Text Adventure Script


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

end is up to you. SULQW ³?Q´ 


SULQW ³!!!!!!!!!!$ZHVRPH$GYHQWXUH?Q´
SULQW ³?Q´ 
WLPHVOHHS 
SULQW ³?Q$ ORQJWLPHDJRDZDUULRUVWURGHIRUWKIURP
WKH IUR]HQ QRUWK´
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)

130 3\WKRQ&RGLQJ 3URJUDPPLQJ


Text Adventure Script

LIFPG ³´ def getcmd(cmdlist):


ragged() FPG LQSXW QDPH´!´
HOLI FPG ³´ if cmd in cmdlist:
guards() return cmd
HOLI FPG ³KHOS´
def ragged(): SULQW ³?Q(QWHU\RXUFKRLFHVDVGHWDLOHGLQ
SULQW ³?Q´  WKH JDPH´
SULQW µ¶¶<RX ZDON XSWRWKHUDJJHGORRNLQJPDQDQG SULQW ³RU HQWHUµTXLW¶WROHDYHWKHJDPH´
JUHHW KLP return getcmd(cmdlist)
+HVPLOHVDWRRWKOHVVJULQDQGZLWKDVWUDQJH HOLIFPG ³TXLW´
DFFHQW VD\V SULQW ³?Q´
³%X\ PH D FXSRIZLQHDQG,¶OOWHOO\RXRI WLPHVOHHS 
JUHDW WUHDVXUH¶¶¶ SULQW ³6DGO\ \RX UHWXUQWR\RXUKRPHODQGZLWKRXW
WLPHVOHHS  IDPH RU IRUWXQH´
WLPHVOHHS 
def guards(): exit()
SULQW ³?Q´ 
SULQW µ¶¶<RX ZDONXSWRWKHGDQJHURXVORRNLQJJXDUGV
DQG JUHHW WKHP LIB B QDPH B B ´ B B PDLQ B B ´
7KHJXDUGVORRNXSIURPWKHLUGULQNVDQG start()
VQDUO DW \RX
³:KDW GR \RX ZDQWEDUEDULDQ"´2QHJXDUGUHDFKHV
IRU WKH KLOW RI KLV VZRUG¶¶¶
WLPHVOHHS 

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

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


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

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


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

Finally, how about introducing the Random module. This will


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

Needless to say, your text adventure can grow exponentially


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

ZZZSFOSXEOLFDWLRQVFRP 131
Code Repository

Python Scrolling
Ticker Script
You may be surprised to hear that [Link]
one of the snippets of code we’re We’re using Tkinter here along with the Time module to
determine the speed the text is displayed across the window.
often asked for is some form of
scrolling ticker. Whilst we’ve covered
various forms of scrolling text import time
previously, the ticker is something import tkinter as tk
that seems to keep cropping up. So, URRW WN7N
here it is. FDQYDV WN&DQYDV URRWURRWWLWOH ³7LFNHU&RGH´ 
KHLJKW  ZLGWK  EJ ´\HOORZ´
FDQYDVSDFN
IRQW µFRXULHU¶µEROG¶
Ticker Time 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
Yet another interesting element that could be PHVVDJH E\ LQFOXGLQJ PRUH YDULDEOHV ³
V ³7KH YDULDEOHV DUH ZLWKLQ WKH VYDOXHVLQ
introduced is one of the many text to Speech modules
WKH FRGH ³
available for Python 3. You could pip install one, import it, 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

132 3\WKRQ&RGLQJ 3URJUDPPLQJ


Python Scrolling Ticker Script/Simple Python Calculator

Simple Python Calculator


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

SULQW ³6LPSOH3\WKRQ&DOFXODWRU?Q´

GHIDGG [\ 
UHWXUQ[\

GHIVXEWUDFW [\ 
return x - y

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
Improved Calculations
HOLIFKRLFH µ¶ The obvious contender for improvement here is using the
SULQW QXP´´QXP´ ´VXEWUDFW QXPQXP Create Your Own Modules route and extracting the function
deƬnitions as a module. You can then call the module and focus
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.

ZZZSFOSXEOLFDWLRQVFRP 133
Code Repository

Hangman Game Script


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

other elements. It can also be quite ERDUG >µ¶¶


simple. Here we have a mix between !!!!!!!!!!+DQJPDQ
the two.

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


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


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


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


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


| |
O |
_?_
_

134 3\WKRQ&RGLQJ 3URJUDPPLQJ


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
4UIT()
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)
due to the diƪerences between using the Python IDLE editor
GHIKDQJPDQ B ZRQ VHOI  and pasting the code into a word processor (which formats
LIµ B ¶QRWLQVHOIKLGH B ZRUG  things diƪerently).
 UHWXUQ7UXH
return False There’s plenty you can do to improve, enhance and expand on
what we’ve presented here. You can include a routine that
GHIKLGH B ZRUG VHOI  returns an error if the user enters a number or character. You
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
more diƯcult. If you download [Link]/dwyl/english-
GHIUDQG B ZRUG  words you can Ƭnd a text document with over 466,000 words.
EDQN µDELOLW\DERXWDERYHDEVROXWHDFFHVVLEOH Perhaps you could swap the words in the bank to instead read
accommodation accounting beautiful bookstore the contents of the text Ƭle:
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\

ZZZSFOSXEOLFDWLRQVFRP 135
Index

136 3\WKRQ&RGLQJ 3URJUDPPLQJ


Understanding Linux

Linux is a remarkably versatile and


powerful operating system. It’s used
throughout the programming and
engineering world, in science, space
exploration, education, gaming and
everything else in between. It’s the OS
of choice for high-performance servers,
it’s the backbone of the Internet and it
powers the fastest supercomputers in
the world.
Knowing how to use Linux, and how it’s
structured, is key to being able to create
better Python content. The Raspberry Pi,
for example, uses a Linux-based OS and,
as such, makes for an excellent coding
platform. Regardless of whether you’re
using a Pi, like us, or a Linux Mint or
Ubuntu, these pages will prove invaluable
for your Python learning. Master Linux,
master Python, and start engineering
your coding future.

138 What is Linux?


140 Using the Filesystem
142 Listing and Moving Files
144 Creating and Deleting Files
146 Create and Remove Directories
148 Copying, Moving and Renaming Files
150 Useful System and Disk Commands
152 Using the Man Pages
154 Editing Text Files
156 Linux Tips and Tricks
158 A-Z of Linux Commands
160 Glossary of Python Terms

ZZZSFOSXEOLFDWLRQVFRP 137
Understanding 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 it, but
there’s more to Linux than you might imagine.

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

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

BOOTLOADER GRAPHICAL SERVER


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

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

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

138 3\WKRQ&RGLQJ 3URJUDPPLQJ


What is Linux?

SHELL
The Linux shell is a command-line interface environment that a
Linux user can use to enter commands to the OS that directly
aƪect it. Within the shell you can add new users, reboot the
system, create and delete Ƭles and folders, and much more.
BASH (Bourne Again Shell)
is the most popular shell
used in Linux, although
more are available. The
shell is also known as the
Terminal, and it’s where
you’re going to work
Linus Torvalds, the creator of the
from through this section
Linux kernel.
of the book.
Linux is used throughout the world, in a number of basic and
quite unique uses. While it may look radically diƪerent from one
Tux, the environment to the next, the actual Linux kernel, can be found
Linux in modern smart TVs, in-car entertainment systems and GPS,
mascot supercomputers, IoT devices and the Raspberry Pi. It’s used by
(Linus likes NASA, both in the command centre and on-board the ISS. Linux
penguins). servers 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 your fridge,
freezer, oven and washing machine.

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


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

A Desktop Environment can


be as complex or as simple as
the user desires.

ZZZSFOSXEOLFDWLRQVFRP 139
Understanding Linux

Using the Filesystem


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

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

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

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

140 3\WKRQ&RGLQJ 3URJUDPPLQJ


Using the Filesystem

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

ABSOLUTE VS RELATIVE PATHS


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

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

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

ZZZSFOSXEOLFDWLRQVFRP 141
Understanding Linux

Listing and Moving Files


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

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

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

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

142 3\WKRQ&RGLQJ 3URJUDPPLQJ


Listing and Moving Files

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

SOME COMMON DIRECTORIES


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

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

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

ZZZSFOSXEOLFDWLRQVFRP 143
Understanding Linux

Creating and Deleting Files


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

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

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

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

144 3\WKRQ&RGLQJ 3URJUDPPLQJ


Creating and Deleting Files

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

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

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

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

ZZZSFOSXEOLFDWLRQVFRP 145
Understanding Linux

Create and Remove


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

MANAGING FILES AND DIRECTORIES


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

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

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

146 3\WKRQ&RGLQJ 3URJUDPPLQJ


Create and Remove Directories

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

GETTING RID OF DIRECTORIES


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

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

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

ZZZSFOSXEOLFDWLRQVFRP 147
Understanding Linux

Copying, Moving and


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

USING THE MOVE COMMAND


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

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

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

148 3\WKRQ&RGLQJ 3URJUDPPLQJ


Copying, Moving and Renaming Files

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

RENAMING FILES AND DIRECTORIES


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

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

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

ZZZSFOSXEOLFDWLRQVFRP 149
Understanding Linux

Useful System and


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

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

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

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


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

150 3\WKRQ&RGLQJ 3URJUDPPLQJ


Useful System and Disk Commands

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

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

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

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

ZZZSFOSXEOLFDWLRQVFRP 151
Understanding Linux

Using the Man Pages


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

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

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

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

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


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

152 3\WKRQ&RGLQJ 3URJUDPPLQJ


Using the Man Pages

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

USING MAN OPTIONS


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

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

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

ZZZSFOSXEOLFDWLRQVFRP 153
Understanding Linux

Editing Text Files


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

THE JOY OF TEXT


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

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

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

154 3\WKRQ&RGLQJ 3URJUDPPLQJ


Editing Text Files

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

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

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

ZZZSFOSXEOLFDWLRQVFRP 155
Understanding Linux

Linux Tips and Tricks


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

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

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

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

156 3\WKRQ&RGLQJ 3URJUDPPLQJ


Linux Tips and Tricks

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

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


someone with the right software being able to
retrieve it. However, Ƭles can be securely and permanently deleted
using Shred:
DIRECTORY TREES If you want to create an entire
shred -zvu [Link] directory (or folder) tree with a
single command, you can use:
Replace NAMEOFFILE with the name of the Ƭle to delete.
mkdir -p New-Dir/
{subfolder1,subfolder2,subfolder3,subfolder4}
This creates a New-Dir with four sub folders within.

ASCII ART ASCII art can be quite striking when applied to


some images. However, it’s often diƯcult to FORGOTTEN COMMANDS It’s not easy trying
get just right. You can create some great ASCII art from the images to remember all the
you already have on the Raspberry Pi by using img2txt: available Linux commands. Thankfully, you can use apropos to help.
Simply use it with a description of the command:
img2txt [Link]
apropos “copy files”
Replace NAMEOFIMAGEFILE with the actual name of the image Ƭle
apropos “rename files”
on your system.

ZZZSFOSXEOLFDWLRQVFRP 157
Understanding Linux

A-Z of Linux Commands


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

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

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

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

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

cp
line by line
Copy one or more Ƭles to
F
factor Print prime factors
J
another location join Join lines on a
fdisk Partition table common Ƭeld
crontab Schedule a command to
manipulator for Linux
run at a later time
csplit Split a Ƭle into context-
determined pieces
fgrep Search Ƭle(s) for lines that
match a Ƭxed string K
kill Stop a process
find Search for Ƭles that meet
cut Divide a Ƭle into from running
a desired criteria
several parts

L
fmt Reformat paragraph text

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

158 3\WKRQ&RGLQJ 3URJUDPPLQJ


A-Z of Linux Commands

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

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

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

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

P
sum the user’s path
symlink Make a new name for who Print all usernames
a Ƭle currently logged in
passwd Modify a user password
paste Merge lines of Ƭles sync Synchronise data on disk whoami Print the current user id
with memory and name
pathchk Check Ƭle name portability
pr Convert text Ƭles
for printing
Printer capability database
T
tac Concatenate and write
X
printcap xargs Execute utility, passing
Ƭles in reverse
printenv Print environment variables constructed argument list(s)
tail Output the last part
Format and print data of Ƭles

Y
printf
tar Tape Archiver

Q tee Redirect output to


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

quotacheck Scan a Ƭle system for time Measure Program


disk usage Resource Use

quotactl Set disk quotas touch Change Ƭle timestamps


top List processes running on

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

ZZZSFOSXEOLFDWLRQVFRP 159
Glossary of Python Terms

Glossary of Python Terms


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

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

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

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

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

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

160 3\WKRQ&RGLQJ 3URJUDPPLQJ


Glossary of Python Terms

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

Interactive Shell Random


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

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

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

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

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

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

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

ZZZSFOSXEOLFDWLRQVFRP 161
Get Your Exclusive
FREE Gift Worth
£9.99 Here!
Download Your NE
W

FREE Copy PYTHON


of The
ॼॽॴ९
Ultimate Python ঔ঵লভনদষশ॰ঘব঳শ
४ঋসবধনশ

Coding Manual
Head over to your web
PAGES
browser and follow these Learn the latest
version of Python
Featuring Python
program listings
Packed with top
tips and tutorials

simple instructions...

1/ Enter the following URL: [Link]/exclusives


2/ Sign up/in and from the listings of our exclusive customer
downloads, highlight the The Ultimate Python Coding Manual option.
3/ Enter your unique download code (Listed below) in the “Enter
password to download” bar.
4/ Click the Download Now! Button and your digital manual 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: PCL64792CM


NOTE: This is a limited reader offer running from 1st ʽ˨˟ˬ 202ʨ to ʦ1st ʷ˘˖˘ˠ˕˘˥ 202ʨ.
Terms and conditions apply and can be found at [Link]

$5BC?47:B@BC>=6>:C%B<AB;# 8B-A9B,C"@C<B4>A=;C@5BC76<95>;B<;C;?:BC<B;7?=;A2A:A@1C@?C8B@B<4A=B )A=6CA=@/C&+%+/C>=8C+77:B,C+88A@A?=>:CA4>.B;C9?=@>A=B8C0A@5A=


@5BC;6A@>2A:A@1C?3C@5A;C2??*C>=8CA@;C9?=@B=@C3?<C05>@B-B<C76<7?;B,C @5A;C762:A9>@A?=C><BC<B7<?869B8C6=8B<C:A9B=9BC3<?4C%56@@B<;@?9*,
      BC>8-A;BC>::C7?@B=@A>:C261B<;C@?C95B9*C:A;@A=.C7<A?<C@?C76<95>;B +=1CA4>.B;C<B7<?869B8C?=C@5BC3<?=@C9?-B<C><BC;?:B:1C3?<C8B;A.=
CC"% &#C ''!!!' ' 3?<C9?=3A<4>@A?=C?3C>9@6>:C9?=@B=@,C+::CB8A@?<A>:C?7A=A?=C5B<BA=CA; 76<7?;B;C>=8C><BC=?@C<B7<B;B=@>@A-BC?3C9?=@B=@,
(62:A;5B8C21#C(>7B<96@C)A4A@B8C @5>@C?3C@5BC<B-AB0B<C'C>;C>=CA=8A-A86>:C'C>=8CA;C=?@C<B7<B;B=@>@A-BC?3 (<A9B;/CA=@B<=>@A?=>:C>->A:>2A:A@1/C<>@A=.;/C@A@:B;C>=8C9?=@B=@C><BC
A.A@>:C8A;@<A26@A?=C21#C(?9*B@4>.;CCA=A?CCCCC @5BC762:A;5B<C?<C>=1C?3CA@;C>33A:A>@B;,C$5B<B3?<BC@5BC762:A;5B<C5?:8;
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ;62B9@C@?C95>=.B,C+::CA=3?<4>@A?=C0>;C9?<<B9@C>@C@A4BC?3C
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
CC(>7B<96@C)A4A@B8C+::C<A.5@;C<B;B<-B8,C&?C7><@C?3C@5A;C =?C<B;7?=;A2A:A@1CA=C<B.><8C@?CB8A@?<A>:C?7A=A?=C>=8C9?=@B=@, 762:A9>@A?=,C%?4BC9?=@B=@C4>1C5>-BC2BB=C7<B-A?6;:1C762:A;5B8CA=
762:A9>@A?=C4>1C2BC<B7<?869B8CA=C>=1C3?<4/C;@?<B8CA=C>C<B@<AB->: $5A;CA;C>=CA=8B7B=8B=@C762:A9>@A?=C>=8C>;C;695C8?B;C=?@C ?@5B<C-?:64B;C?<C@A@:B;,
;1;@B4C?<CA=@B.<>@B8CA=@?C>=1C?@5B<C762:A9>@A?=/C8>@>2>;BC?<C =B9B;;><A:1C<B3:B9@C@5BC-AB0;C?<C?7A=A?=;C?3C@5BC4>=63>9@6<B<;C?<
9?44B<9A>:C7<?.<>4;C0A@5?6@C@5BCB7<B;;C0<A@@B=C7B<4A;;A?=C?3 5><80><BC>=8C;?3@0><B/C>77:A9>@A?=;C?<C7<?869@;C9?=@>A=B8C0A@5A=,  
@5BC762:A;5B<,C=8B<C=?C9A<964;@>=9B;C;5?6:8C@5A;C762:A9>@A?=C>=8 $5A;C762:A9>@A?=CA;C=?@CB=8?<;B8C?<C>;;?9A>@B8CA=C>=1C0>1C0A@5C B.A;@B<B8CA=C=.:>=8CC>:B;C&?#C!
A@;C9?=@B=@;C2BC<B;?:8/C:?>=B8C?6@C?<C6;B8CA=C>=1C3?<4C21C0>1C?3 (1@5?=/C$5BC)A=6C?6=8>@A?=/C$5BC >;72B<<1C(AC?6=8>@A?=/C+ 
@<>8BC0A@5?6@C@5BC762:A;5B<;C0<A@@B=C7B<4A;;A?=,C5A:BC0BC7<A8BC ?:8A=./C>=?=A9>:C)@8/CB2A>=C(<?B9@/C)A=6CA=@/CA9<?;?3@/ + $"%"& CCC?<C?6<C:>@B;@C4B8A>C7>9*;C7:B>;BC9?=@>9@#C
?6<;B:-B;C?=C@5BC6>:A@1C?3C@5BCA=3?<4>@A?=C0BC7<?-A8B/C(>7B<96@ )B=?-?/CB::/CB0:B@@'(>9*><8/C+77:BC>=8C%>4;6=.C?<C>=1C 1HTLZ.HSLC'CB4>A:#CQNHSL'WJSW\ISPJH[PVUZJVT
)A4A@B8C<B;B<-B;C@5BC<A.5@C=?@C@?C2BC5B:8C<B;7?=;A2:BC3?<C>=1C >;;?9A>@BC?<C>33A:A>@BC9?47>=1,C+::C9?71<A.5@;/C@<>8B4><*;C>=8C B2C'C000,[Link]>@A?=;,9?4
4A;@>*B;C?<CA=>996<>9AB;C3?6=8C0A@5A=C@5BC@B@C?3C@5A;C762:A9>@A?=, <B.A;@B<B8C@<>8B4><*;C3?<C@5BC<B;7B9@A-BC9?47>=AB;C><BC "&$ &+$"&+)C)"&%"& CC(>7B<96@C)A4A@B8C5>;C4>=1C.<B>@
6BC@?C@5BC=>@6<BC?3C@5BC@B95CA=86;@<1/C@5BC762:A;5B<C9>==?@C >9*=?0:B8.B8,C B:B->=@C.<>75A9CA4>.B<1C<B7<?869B8C0A@5C 762:A9>@A?=;C>=8C>::C><BC>->A:>2:BC3?<C:A9B=;A=.C0?<:80A8B,C
.6><>=@BBC@5>@C>::C>77;C>=8C;?3@0><BC0A::C0?<*C?=CB-B<1C-B<;A?=C?3 9?6<@B;1C?3C)B=?-?/CB0:B@@'C(>9*><8/CB::/CA9<?;?3@/C%>4;6=./ ?<C4?<BCA=3?<4>@A?=CB4>A:#C.>:B [Link]>@A?=;,9?4

Common questions

Powered by AI

Learning basic shell commands in Linux is critical for Python development on the Raspberry Pi because it allows developers to efficiently navigate the file system, manage files, and execute scripts in a command-line interface. This knowledge enables developers to automate tasks, troubleshoot issues, and optimize workflows, which are essential skills for effective programming in a Linux-based environment like the Raspberry Pi .

The challenges of using Python modules in a multi-platform environment include handling differences in operating systems that may affect module compatibility or installation. Best practices include ensuring the use of platform-independent modules and maintaining updated versions to counter compatibility issues. Utilizing virtual environments can isolate dependencies and configurations to maintain consistent functionality across platforms .

The Raspberry Pi's operating system, Raspbian, is a Debian-based Linux distribution optimized for the hardware. It enhances Python programming by providing a pre-configured environment with numerous Python modules and development resources. This removes barriers associated with setting up a coding environment, allowing beginners to focus on learning Python. Additionally, the Pi's support for remote connectivity expands its educational applications, facilitating an interactive and hands-on learning experience .

When writing and executing Python scripts using IDLE, it is essential to capitalize on its features such as syntax highlighting, code completion, and debugging tools. Best practices include organizing code for readability, utilizing IDLE's interactive shell for testing snippets, and saving scripts frequently to prevent data loss. Furthermore, using the debugging tools in IDLE can help identify and fix syntax or logical errors efficiently, enhancing code robustness and functionality .

Python is an ideal programming language for beginners due to its readability, simplicity, and ease of use. The Raspberry Pi enhances this learning experience by offering an affordable, flexible, and user-friendly platform, which comes pre-installed with the Raspbian OS. This OS supports Python extensively with numerous modules and extensions, making it an excellent environment for learning to code . Additionally, the Raspberry Pi can be used as a headless node allowing remote access and control, further enhancing its utility .

An Integrated Development Environment (IDE) is recommended for Python programming because it offers advanced features such as code inspection, debugging tools, and syntax highlighting that surpass the capabilities of basic text editors. This enables more efficient coding, easier error detection, and an overall enhanced user experience, which can be critical for learning and developing complex applications .

Python 2 and Python 3 differ primarily in their feature sets; Python 3 introduced several new, enhanced features for a stable and efficient programming environment not found in Python 2. Although Python 2 has a large collection of modules and a wide user base, Python 3's new features are incompatible with Python 2 scripts. Despite initial unpopularity, Python 3 is now preferred for new projects due to its cutting-edge improvements and long-term support from the Python community .

Python handles user input primarily through the `input()` function, which takes data entered by users and assigns it to variables for processing. This enables programs to interact dynamically with users, responding to inputs with tailored outputs. For instance, a program may ask for a user's name and greet them accordingly, thereby enhancing interactivity and user engagement .

The Zen of Python, a set of 20 guiding principles, strongly influences Python's design. Notable principles include "Beautiful is better than ugly" and "Simple is better than complex." These principles manifest in Python's clean and readable syntax, making it user-friendly and widely accessible. The language prioritizes simplicity and clarity, allowing code to be easily understood and maintained .

Conditional statements in Python, including if, elif, and else, allow developers to create decision-making processes within programs. This contributes to building complex applications by enabling them to perform different actions based on varying conditions, thus tailoring flow and functionality. Conditions enable programs to process user input, operate in dynamic environments, and implement intricate business logic .

You might also like