Python Coding Manual & Tutorials
Python Coding Manual & Tutorials
CODING MANUAL
FREE
DIGITAL
MAGAZINE
DOWNLOAD
Worth £9.99
See inside for details
100% INDEPENDENT
Save a Huge
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...
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
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
fff_R[_dQ[XRPcX^]bR^\ 5
Index
6 3\WKRQ&RGLQJ 3URJUDPPLQJ
Getting Started
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
“It’s up to you
creating something from a few lines of BASIC code was achievable and so
the Ƭrst generation of home-bred programmer was born.
your coding
game. This of course led to the programmer becoming more than simply
someone who could fashion a sprite on the screen and make it move at the
press of a key.
adventure!” Naturally, time has moved on and with it the technology that we use.
However, the fundamentals of programming remain the same; but what
exactly does it take to be a programmer?
Being able to see the big picture is certainly beneƬcial for the modern
programmer. Undoubtedly, as a programmer, you will be part of a team
of other programmers, and more than likely part of an even bigger team
of designers, all of whom are creating a Ƭnal product. While you may only
be expected to create a small element of that Ƭnal product, being able to
understand what everyone else is doing will help you create something
that’s ultimately better than simply being locked in your own coding cubicle.
ZZZSFOSXEOLFDWLRQVFRP 9
Getting Started
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.
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.
ZZZSFOSXEOLFDWLRQVFRP 11
Getting Started
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.
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.
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.
in 202
PYTHON AND
LINUX SKILLS
N UMBERS
14 3\WKRQ&RGLQJ 3URJUDPPLQJ
Python in Numbers
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.
£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
Java is a powerful
language that’s used in
web pages, set-top boxes,
TVs and even cars.
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.
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
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
20 3\WKRQ&RGLQJ 3URJUDPPLQJ
Using Virtual Machines
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
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.
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
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
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.
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.
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.
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
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.
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.
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.
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
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
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
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
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
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
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
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 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
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.
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
ZZZSFOSXEOLFDWLRQVFRP 61
Index
62 3\WKRQ&RGLQJ 3URJUDPPLQJ
Working with Data
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.
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.
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
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.
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.
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 = “”
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()
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?
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?
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.
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:
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
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.
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.
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”’)
ZZZSFOSXEOLFDWLRQVFRP 93
Using Modules
E = MC2
The Math module provides access to a plethora of mathematical functions, from simply displaying the value of Pi, to helping
you create complex 3D shapes.
STEP 1 The Math module is built-in to Python 3; so there’s STEP 3 As you will no doubt be aware by now, if you know
no need to PIP install it. As with the other modules the name of the individual functions within the
present, you can import the module’s function by simply entering module you can speciƬcally import them. For instance, the 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.
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 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]()
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 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.
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.
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 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.
ZZZSFOSXEOLFDWLRQVFRP 105
Using Modules
BUILDING MODULES
Modules are Python Ƭles, containing code, that you save using a .py extension. These are then imported into Python using the
now familiar import command.
STEP 1 Let’s start by creating a set of basic mathematics STEP 3 Now 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.
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.
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.
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
ZZZSFOSXEOLFDWLRQVFRP 111
Code Repository
def Read():
SDWK LQSXW ³(QWHUWKH¿OHSDWKWRUHDG´
¿OH RSHQ SDWK´U´
SULQW ¿OHUHDG 2
LQSXW µ3UHVV(QWHU¶
¿OHFORVH
def Write():
SDWK LQSXW ³(QWHUWKHSDWKRI¿OHWRZULWHRUFUHDWH´
LIRVSDWKLV¿OH SDWK
SULQW µ5HEXLOGLQJWKHH[LVWLQJ¿OH¶
else:
SULQW µ&UHDWLQJWKHQHZ¿OH¶
WH[W LQSXW ³(QWHUWH[W´
¿OH RSHQ SDWK´Z´
¿OHZULWH WH[W
def Add():
SDWK LQSXW ³(QWHUWKH¿OHSDWK´
WH[W LQSXW ³(QWHUWKHWH[WWRDGG´
¿OH RSHQ SDWK´D´
¿OHZULWH µ?Q¶WH[W
def Delete():
This part of the code imports the necessary modules. SDWK LQSXW ³(QWHUWKHSDWKRI¿OHIRUGHOHWLRQ´
1 The OS and Subprocess modules deal with the LIRVSDWKH[LVWV SDWK
SULQW µ)LOH)RXQG¶
operating system elements of the program.
RVUHPRYH SDWK
SULQW µ)LOHKDVEHHQGHOHWHG¶
Each def XXX() functions store the code for each
2 of the menu’s options. Once the code within the
else:
SULQW µ)LOH'RHVQRWH[LVW¶
function is complete, the code returns to the main
menu for another option. def Dirlist():
SDWK LQSXW ³(QWHUWKH'LUHFWRU\SDWKWRGLVSOD\´
This is part of the code that checks to see what OS VRUWOLVW VRUWHG RVOLVWGLU SDWK
3 the user is running. In Windows the CLS command i=0
clears the screen, whereas in Linux and macOS, the ZKLOH LOHQ VRUWOLVW
SULQW VRUWOLVW>L@¶?Q¶
Clear command wipes the screen. If the code tries
L
to run CLS when being used in Linux or macOS, an
error occurs, which then prompts it to run the Clear def Check():
command instead. IS LQW LQSXW µ&KHFNH[LVWHQFHRI?Q)LOH?Q
'LUHFWRU\?Q¶
These are the options, from 1 to 12. Each executes LIIS
4 the appropriate function when the relevant number SDWK LQSXW ³(QWHUWKH¿OHSDWK´
is entered. RVSDWKLV¿OH SDWK
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
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
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.
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
ZZZSFOSXEOLFDWLRQVFRP 117
Code Repository
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
ZZZSFOSXEOLFDWLRQVFRP 119
Code Repository
URRW 7N
URRWWLWOH ³)LOH%URZVHU´
URRWPDLQORRS
ZZZSFOSXEOLFDWLRQVFRP 121
Code Repository
screen = Screen()
\HUWOH 7XUWOH
GHIN
VFUHHQRQVFUHHQFOLFN FOLFN B KDQGOHU
VFUHHQOLVWHQ
VFUHHQPDLQORRS
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.
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
,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¶
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
def update(self):
LISJWLPHJHW B WLFNV VHOIWLPHU!VHOIGHOD\
VHOIWLPHU SJWLPHJHW B WLFNV
IRU WH[W UHFW LQ VHOIWH[W
UHFW\
GHIUHQGHU VHOIVXUI
IRUWH[WUHFWLQVHOIWH[W
VXUIEOLW WH[WUHFW
ZKLOHUXQQLQJ
IRUHYHQWLQSJHYHQWJHW
LIHYHQWW\SH 48,7
running = False
VFUHHQ¿OO
FUHGXSGDWH
FUHGUHQGHU VFUHHQ
SJGLVSOD\XSGDWH
FORFNWLFN
ZZZSFOSXEOLFDWLRQVFRP 125
Code Repository
FORFNDIWHU WLFN
URRW WN7N
FORFN WN/DEHO URRWIRQW µDULDO¶µEROG¶
EJ ¶JUHHQ¶
FORFNSDFN ¿OO ¶ERWK¶H[SDQG
tick()
URRWPDLQORRS
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
ZZZSFOSXEOLFDWLRQVFRP 127
Code Repository
llC = 65
O&
O'E
O'
O(E
O(
O)
O*E
O*
O$E
O$
O%E
O%
&
'E
'
(E
(
) 2
*E
*
$E
A = 440
%E
%
K&
hDb = 554
hD = 587
K(E
hE = 659
hF = 698
hGb = 740
hG = 784
K$E
hA = 880
K%E
K%
WLPHVOHHS
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.
ZZZSFOSXEOLFDWLRQVFRP 129
Code Repository
SULQW µ¶¶<RX¿QG\RXUVHOIDWDVPDOOLQQ7KHUH¶V
OLWWOHJROGLQ\RXUSXUVHEXW\RXUVZRUGLVVKDUS
DQG \RX¶UH UHDG\ IRU DGYHQWXUH
:LWK \RX DUH WKUHH RWKHU FXVWRPHUV
$ UDJJHG ORRNLQJ PDQ DQG D SDLU RIGDQJHURXV
ORRNLQJ JXDUGV¶¶¶
def start():
SULQW ³?Q´
SULQW ³'R \RX DSSURDFKWKH´
SULQW ³?Q´
SULQW ³ 5DJJHGORRNLQJPDQ´
SULQW ³ 'DQJHURXV ORRNLQJ JXDUGV´
FPGOLVW >³´³´@
cmd=getcmd(cmdlist)
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.
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
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
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´
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
| |
O |
|
|
|
¶¶¶µ¶¶
| |
O |
| |
|
|
¶¶¶µ¶¶
| |
O |
__
|
|
¶¶¶µ¶¶
| |
O |
_?_
|
|
¶¶¶µ¶¶
| |
O |
_?_
_
ZZZSFOSXEOLFDWLRQVFRP 135
Index
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.
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.
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.
ZZZSFOSXEOLFDWLRQVFRP 139
Understanding Linux
GETTING AROUND
To drop into the Terminal, click on the fourth icon from the left along the top of the Raspberry Pi desktop, the one with a right-
facing arrow and an underscore. This is the shell, or Terminal.
STEP 1 First, you’re going to look at directories and the STEP 3 Enter: ls to view the contents of the current
directory path. A directory is the same thing as a directory. You should see Desktop, Documents,
folder, however in Linux it’s always called a directory. These are and Downloads and Scratch in Blue. You may also see other items
placed inside each other using a “/” character. So when you see / depending on how much you have used your Raspberry Pi. The
home/pi it means the pi directory is inside the home directory. colour code is worth knowing: directories are blue while most Ƭles
Enter: clear and press return to clean the screen. Now enter: pwd. are white. As you go on you’ll see other colours: executable Ƭles
This stands for Print Working Directory and displays /home/pi. (programs) are bright green, archived Ƭles are red and so on. Blue
and white are the two you need to know to get started.
STEP 2 When you log in to your Raspberry Pi, you don’t STEP 4 Now you’re going to move from the pi directory into
start at the base of the hard drive, known as the the Documents directory. Enter: cd Documents.
‘root’ (also known as the topmost directory). Instead you begin Note the capital “D”. Linux is case sensitive, which means you have
inside your user directory, which is named ‘pi’ by default and is to enter the exact name including correct capitalisation. The cd
itself in a directory called ‘home’. Directories are indicated by the ‘/’ command stands for change directory. Now enter: pwd again to
symbol. So, “‘/home/pi’” tells you that in the root is a directory called view the directory path. It will display /home/pi/ Documents. Enter:
home, and the next “‘/’” says that inside “home” is a directory called ls to view the Ƭles inside the Documents directory.
“pi”. That’s where you start.
STEP 5 How do you get back up to the pi directory? By using STEP 6 The “ls” and “cd” commands can also be used with
a command “cd ..”. In Linux two dots means the more complex paths. Enter: ls Documents/
directory above, also known as the parent directory. Incidentally, a Pictures to view the contents of a Pictures directory inside
single dot “.” is used for the same directory. You never use “cd .” to your Documents directory. You can switch to this directory using
switch to the same directory but it’s worth knowing because some cd Documents/Pictures; use cd ../.. to move back up two
commands need you to specify the current directory. parent directories.
STEP 1 By default, commands like “ls” use the working STEP 3 The second command (“ls /Documents/Pictures”)
directory. This is the current directory that you’re attempts to list the content of Pictures in a
looking at and is set to your home directory by default (/users/ directory called Documents inside the root directory (because the
pi). Using “pwd” (Print Working Directory) lets you know what the path started with ‘/’, which is root). There is typically no Documents
working directory is, and using “cd” changes the working directory. directory in root, so you will get a “No such Ƭle or directory”
error. Starting a path with ‘/’ is known as an “absolute path”, while
starting without the ‘/’ is known as a “relative path” because it is
relative to your working directory.
STEP 2 The root directory is always ‘/’. Entering: ls / STEP 4 There is also an absolute path shortcut to your
lists the contents of root, and entering: cd / user directory, and that is the tilde “~” character.
switches to the root directory. This is important because there is a Entering: ls ~ always lists the contents of your home directory,
diƪerence between “ls Documents/Pictures” and “ls /Documents/ while “cd ~” moves straight to your home directory, no matter
Pictures”. The Ƭrst command lists the contents of the Pictures what your working directory is. You can also use this shortcut
directory in Documents inside the working directory (which, if you wherever you are: enter: ls ~/Documents/Pictures to display
are in the home directory, will work). the contents of the Pictures.
ZZZSFOSXEOLFDWLRQVFRP 141
Understanding 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.
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”.
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 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.
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
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.
STEP 5 To create a directory path you need to pass in the STEP 6 Now you’re starting to get a bit more advanced,
“p” option to mkdir (which stands for “parents”). we’re going to just reiterate something. In Linux
Options, if you remember, come after the command and start with the command structure is always: command, option and argument,
a ‘-’. So enter: mkdir -p articles/reports. Enter: ls to view in that order. The command is the function, next are the options
the articles directory, or “ls articles” to view the reports directory (typically single letters starting with “-”) and Ƭnally the argument
sitting inside. (often a Ƭle, or directory structure). It’s always command, option
then argument.
STEP 1 We’re going to remove one of the directories we STEP 3 To delete a directory containing Ƭles or other
created earlier using the “rmdir” command. Enter: directories, you return to the “rm” command used
ls to view the Ƭles and directories in the current directory. We’ll to remove Ƭles, only now we need to use the “-R” option (which
start by getting rid of one of the test directories. Enter: rmdir stands for “recursive”.) Using “rm –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
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.
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.
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
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 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
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 5 Scroll to the bottom of the man page to discover STEP 6 The man command can be used for just about every
more information. Typically you will Ƭnd the command you use in Linux. You can even enter:
author’s name and information on reporting bugs, including web man man to get information on using the man tool. From now on,
links that can be useful for more information. Press Q to exit the whenever you come across a new command in this book, such as
man page and return to the command line. “nano” or “chmod”, take time to enter: man nano or man chmod
and read the instructions.
STEP 1 Entering: man man enables you to view some of STEP 3 One of the most powerful man options is the -k
the options, but sometimes you’ll just want a quick option, which is for “apropos”. This enables you
overview. Fortunately man has a built-in help option that quickly to search a wider range of man pages than the exact command.
lists the options. Press Q if you’re in a man page and enter: man –h Enter: man -k directory to view all of the man pages relating
at the command line. to directories “(man -k directory _ less” to view one page at a time).
Here you’ll Ƭnd commands like “ls”, “mkdir” and “cd” along with
their description.
STEP 2 If you’re fast you may have noticed the start of the STEP 4 Entering the man page for all the commands
text Ʈew up oƪ the page. This is because the “man you come across can be a little long-winded,
–h” option doesn’t use the less command by default (less is what although ultimately productive. If you simply want to know what a
enables you to move down text one screen at a time). We’ll look command does you can read just the description using the “whatis”
into pipes (“_”) later on, but for now just use “man -h _ less” to read command. Enter: whatis pwd to read the description of the
long text one page at a time. “pwd” command (“print name of current/working directory”).
ZZZSFOSXEOLFDWLRQVFRP 153
Understanding Linux
STEP 1 The Ƭrst text editor for the Raspberry Pi is the STEP 3 Vi is the original Unix command but in this case it
default desktop environment app: Leafpad. To launches VIM, the new Linux version of Vi. Although
use, you can either double-click an existing text Ƭle or click the simple looking, Vi is considered, even by today’s standards, to be
Raspberry Pi menu icon (in the top left of the desktop) and from the one of the most widely used text editors, There’s a lot you can do
Accessories menu, choose Text Editor. with it, so check out the man pages for more Vi information.
STEP 2 From the Terminal there are even more options, STEP 4 Nano is another favourite, and simple, text editor
although using the correct command, you can available for Linux. Enter: nano into the Terminal
launch any of the desktop apps via the Terminal. One of the to launch it. You can use Nano for editing code, creating scripts or
simplest, and a classic text editor that’s carried over from the Unix writing your own help Ƭles. To exit Nano, press Ctrl + X, followed by
days, is vi. In the Terminal, enter: vi. Y to save the Ƭle or N to exit without saving.
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
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]
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.
ZZZSFOSXEOLFDWLRQVFRP 157
Understanding Linux
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
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
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
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.
Integer Python
A number data type that must be a whole number and not An awesome programming language that’s easy to learn and use,
a decimal. whilst still being powerful enough to enjoy.
Kernel Range
The core of an operating system, which handles data processing, A function that used to return a list of integers, deƬned by the
memory allocation, input and output, and processes information arguments passed through it.
between the hardware and programs.
Root
Linux The bottom level user account used by the system itself. Root is the
An open source operating system that’s modelled on UNIX. overall system administrator and can go anywhere, and do anything,
Developed in 1991 by Finnish student Linus Torvalds. on the system.
Lists Sets
A Python data type that contains collections of values, which can be Sets are a collection of unordered but unique data types.
of any type and can readily be modiƬed.
Strings
Local Variable Strings can store characters that can be modiƬed. The contents of
A variable that’s deƬned inside a function and is only useable inside a string are alphanumerical and can be enclosed by either single or
that function. double quote marks.
Loop Terminal
A piece of code that repeats itself until a certain condition is met. Also Console or Shell. The command line interface to the operating
Loops can encase the entire code or just sections of it. system, namely Linux, but also available in macOS. From there you
can execute code and navigate the Ƭlesystem.
Module
A Python Ƭle that contains various functions that can be used within Tkinter
another program to further extend the eƪectiveness of the code. A Python module designed to interact with the graphical
environment, speciƬcally the tk-GUI (Tool Kit Graphical User
Operating System Interface).
Also OS. The program that’s loaded into the computer after the
initial boot sequence has completed. The OS manages all the other Try
programs, graphical user interface (GUI), input and output and A try block allows exceptions to be raised, so any errors can be
physical hardware interactions with the user. caught and handled according to the programmer’s instructions.
Output Tuples
Data that is sent from the program to a screen, printer or other An immutable Python data type that contains an ordered set of
external peripheral. either letters or numbers.
PIP UNIX
Pip Installs Packages. A package management system used to install A multitasking, multiuser operating system designed in the ‘70s at
and manage modules and other software written in Python. the Bell Labs Research Centre. Written in C and assembly language
Print Variables
A function used to display the output of something to the screen. A data item that has been assigned a storage location in the
computer’s memory.
Prompt
The element of Python, or the Command Line, where the user X
enters their commands. In Python it’s represented as >>> in the Also X11 or X-windows. The graphical desktop used in Linux-based
interactive shell. systems, combining visual enhancements and tools to manage the
core operating system.
Pygame
A Python module that’s designed for writing games. It includes Zen of Python
graphics and sound libraries and was Ƭrst developed in When you enter: 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
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...
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 .