The Complete Manual Series
C++ &
Python
a > The essential coding manual for
ey a) » C++ and Python programming
PAGEs!Want to master your Code?
Then don’t miss our NEW Coding
magazine on =: Readly now!The Complete Manual Series
Unleash the power of Python and C++
Having a basic knowledge of programming can open many different
doors for the newcomer to explore. You can gain a better understanding
of how hardware and software work together, how your computer or
device functions and how incredible open-world gaming environments
are converted from ones and zeros to what's on your monitor or TV.
Technology is everywhere and it's all connected through programming.
Your TV, microwave, in-car entertainment and the Internet itself are all
reliant on good programming to make them work the way you want
them to. Within these pages are the building blocks to help you take
your first steps into the world of programming. We've taken two of the
most powerful and versatile programming languages available, Python
and C++ and broken them down into bite-sized tutorials and guides to
help you learn how they work, and how to make them work for you
Learn how to install them, print simple messages to the screen, ask for
user input and manipulate the data to produce amazing results. By the
end of this book you will understand how Python and C++ work and
what potential lies beyond. Ready? Let's get programming!@ contents
a
ontents
oe Say Hello to Python
Cet
EC est ena rn eae)
Pada Tin
cr less ee ed
ST lea aa eI
SCM sa oar ara Een RUC
esa igi
tS
CN i
Cerny
a
Pen tages
eet
aie G))_Using Modules
eer encom tae
ea ain
EC seen ee Cee aera
Ere et
EP Meer eho Lense
Ee sg Leet
Eee nea Leer
Creo ensene hes) ern iRoner es
Cre ed
Say Hello to C++
(44) Working withData
ats Equipment Needed
ca ey EA ta hee AUR oy
Ee
Eee Ea nese
Pea ee
Gord reece
How to Set Up C++ in Linux.
Other C++ IDEs to Install
Onccy
cro)
102
rT)
Your First C++ Pr
atte eerie
omen
Using Comments
veo
Peay
Sans
ar
(C++ Input/Output
esate
erie mera
Defining Constants
File Input/Output
138
or
ord
cr)
(contents @
Rae
For Loop
Do... While Loop
IF Statement
assent
Working with Code
Common Coding Mistakes
een ene
Eee Renn eels
Where Next?
oe ce}Say Hello |
toPython ~Say Hello to Python CH
‘There are many different programming
languages available to learn and use.
Some are complex and incredibly
powerful and some are extremely basic
and used as minor utilities for operating
systems. Python sits somewhere in the
middle, combining ease of use with a
generous helping of power that allows
the user to create minor utilities, a range
of excellent games and performance
heavy computational tasks.
However, there’s more to Python than
simply being another programming
language. It has a vibrant and lively
community behind it that shares
knowledge, code and project ideas; as
well as bug Fixes for Future releases.
It’s thanks to this community that the
language has grown and thrived and now
it's your turn to take the plunge and learn
how to program in Python.
The first half of this book helps you
get started with the latest version of
Python and from there guide you on how
to use some of the most common and
interesting Functions and features of the
language. Before long, you will be able to
code your own helpful system tools, text
adventures and even control a character
as they move around the screen.
8 Why Python?
10 Equipment You will Need
12 Getting to Know Python
14 How to Set Up Python in Windows
16 How to Set Up Python on a Mac
How to Set Up Python in Linux
wmbiniaiosonED) stron)
Why Python?
Der usc ened eee selcims keene
PI eee eee cach ccmlcrcmsouct ams eurle ss
are designed for scientific work, others for mobile platforms and such. So why choose
Lav ane let aol i-l Muara siecg
PYTHON POWER
Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away untilthe wee
hours, saving over an overheating heap of circuitry to create something akin to magic.
‘These pioneers of programming carved their way nto a new Regardless of whether you use an Android device, 10S device, PC,
Frontier, Forging smal routines that enabled the letter’ toscroll_ Mac, Linux, Smart TV, games console, MP3 player, GPS device builtin
‘across the screen. It may not sound terribly exciting toa generation toa car, settop box or a thousand other connected and ‘smart’
that’s used to ultra-high definition graphics and open world, multi appliances, behind them alls programming.
player online gaming. However, Forty-something years ago it was
blindingly brillant. All those aforementioned digital devices need instructions to tell,
them what to-do, and allow them to be interacted with. These
Naturally these bedroom coders helped form the Foundations for _instructions Form the programming care ofthe device and that core
‘every piece oF digital technology we use today. Some went on to _can be built using a variety of programming languages.
become chief developers for top software companies, whereas
‘thers pushed the avalable hardware to itslimits and founded the The languages in use today differ depending on the situation, the
billion pound gaming empire that continually amazes us platform, the device's use and how the device wil interact with its
eee ee
ee ee)
Setcursor(p.y):
certsschitsentrocus(;
>em
void Arraycerts:chitéLostrocue()
it(ecursor >= 0}
sieteeeioe area
void seraycertsspaant{oraus w) (
‘IMENT Paine
Getsiz00s
cb):
header. cetserotL)
1 < colum.catcount|)
Tbe oadsr sea abai dito
APT age ews veregrad *
breaks
jo
coum, cetceunt() = 10) >= 0)
Gator fe = Blendiscoloroisabled, ScolorPaper):
sitet) ree
Mists ntcome) ¢
fitop crestuiner() ~ sbp
Ti(teop o stne.6)) besa
apt cettinscy i);
Cave Ge treacun
i sass coh
Sitters Gono
1S frenesters> Seo
Hi Sewer Oger
Somme Stan co
1 canmian — Greaveonnsce
C++ i usually reserved for more complex
programs, operating systems, games and s0.0n.
EE «serestcnonson
J jes 4 < colum.cetcount(; is4) {
Int by header eerapengthO)senvironment or users, Operating systems, such as Windows, macOS
‘and such are usually a combination of C++, C#, assembly and some
Form of visual based language. Games generally use C++ whilst web
pages can use a plethora of available languages such as HTML, Java,
Python and so on.
More general-purpose programming is used to create programs,
‘apps, software or whatever else you want to cal them. They're
‘widely sed across all hardware platforms and suit virtually every
conceivable application. Some operate Faster than others and some
{are easier to learn and use than others, Python is one such general-
purpose language.
Python is what's known as a High-Level Language, in that it ‘tals’
to the hardware and operating system using a variety of arrays,
variables, objects, arithmetic, subroutines, loops and countless
‘more interactions. Whilst it’s not as streamlined as a Low-Level
Language, which can deal rectly with memory adresses, cal
stacks and registers its benefitis that it's universally accessible
and easy to lear,
Five: Tvoke Jai
finport java. lang.reflect.*;
‘lass_ Invoke
public static void main¢ string (args ) ¢
Class. fornane( args{ol );
= Tigectethodt atgSlA0 én class
beck tee = mciovokeC null, nu 93
Syatgn.out printing
yetstivokee. state method: ” + args (2)
2 MGfcrass: © Sargs{o]
T+ Michio aras\neesetes: * » ret 5
» catch ¢ Classhortoundexception e ) f
Glass torname cD can't Fond the class
} Garch'C hosuchtethodexeeption e2 3
thas method doesn't exist
> Gacch'( ETtegensccessexception 3) (
Fre Son'e have permission to invoke that
» Eaten c i jon ef )
Eaten ( anvocationrargetexception
Fan exception ocurred white invoking that
System. out prinein¢
Shethod threw an: * 64.
gettargettxeeption( “)°3!
Javaisa powerful language
that’s used in web pages,
set-top boxes, TVs and
even cars.
-
(Why Python? Cl
Python was created over twenty sixyears ago and has evolved to
become an ideal beginners language for learning how to programa
‘computer. ts perfect forthe hobbyist, enthusiast, student, teacher
and those who simply need to create their own unique interaction
between either themselves ora piece of extemal hardware and the
computer itself
Python is free to download, install and use ands available for Linux,
‘Windows, macOS, MS-DOS, 05/2, BeOS, IBM iseries machines, and
‘even RISC OS. ithas been voted one ofthe top five programming
languagesin the world and is continually evolving ahead of the
hardware and internet development curve.
So to answer the question: why python? Simply put. its Free, easy to
learn, exceptionally powerful, universally accepted, effective and a
superb learning and educational tool
BASIC was once the starter language that early
‘s-bit home computer users learned.
riot,
me ap eH
Python s a more madern take on BASIC, it's easy tolearn
and makes for an ideal beginner's programming language.
vombineiceon CIEz= Say Hello to Python)
Equipment You
Will Need
You can learn Python with very little hardware or initial Financial investment. You
don’t need an incredibly powerful computer and any software that’s required is
LTE 9)
WHAT WE'RE USING
‘Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linux, Raspberry Pi and more. IF
you have one of those systems, then you can easily start using Python.
|_| COMPUTER
Cbvioudy you're going to needa computer inorder to eam how to programin
Python and to test your code. You can use Windows (from XP onward) on either a 32
or 64 processor an Apple Macor Linux installed PC.
{J AN IDE
An IDE (Integrated Developer Environment) is used to enter and execute Python:
code. tenables you to inspect your program code andthe values within the code 35
tla offering advanced features. There ae mary dfferent IDEs avalble, sind
the one that works foryou and gues the best ests
{_] 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'l caver shorty
(-) TEXT EDITOR
Whilst a text editoris an ideal environment to enter code into, i'snotan absolute
necessity. You can enter and execute code directly from the IDLE but atext editor,
such as Sublime Text or Notepads, offers more advanced features and colour coding
when entering code,
{_] INTERNET ACCESS
Python isan ever evolving environment and as such new versions often introduce
‘new concepts or change existing commands and code structure to makeita more
efficient language. Having access to the Internet will keep you up-to-date, help you
‘out when you get stuck and give access to Python's immense number of modules.
{_| TIME AND PATIENCE
Despite what other books may lead you to believe, you won't become a programmer
in24-hours. Leaning to code in Python takes time, and patience. You may become
stuckattimes and other times the code wil flow tke water. Understand you're learning
something entirely new, and youwill get there.THE RASPBERRY PI
( Equipment You Will Need cl
Why use a Raspberry Pi? The Raspberry Piis a tiny computer that’s very cheap to purchase but offers the user a Fantastic learning
platform. its main operating system, Raspbian, comes preinstalled with the latest Python along with many Modules and extras
Ss aa]
The Raspberry P3is the latest version, incorporating a more
powerful CPU, more memory, Wii and Bluetooth support.
You can pick up Pifor around €32 or asa part of kt For €50+,
depending on the kityou'e interested in,
“The Raspberry P's main operating system Isa Debian-based
Linux distribution that comes with everything you need in
a simple to use package. I's streamlined for the Pi and isan
ideal platform for hardware and software projects, Python.
programming and even as a desktop computer.
FUZE PROJECT
The FUZEis learning environment built on the latest model
‘of the Raspberry P. You can purchase the workstations that
‘come with an electronics kit and even a robot arm For you to
build and program. You can find more information on the FUZE
at wwvwrfuze.co.uk.
Es
a
Odin
webmesevertgreatcocing for Begg 9g
titles available via www. inetz= Say Hello to Python )
Getting to
Know Python
VeRO iccnceda cates miu | cs ee kerr ceM eel
NoMa UNM en Lem Ke CEN late Te (ear eke UC
to understand.
WHAT IS PROGRAMMING?
Ithelps to understand what a programmi
look at how Python came about and how
‘A programming language
IsalistoFinstructions that
2 computer follows. These
instructions can be as simple
as dsplaying yourname
cr playing a music file, or
as complexas building a
whole virtual world. Python
language is before you try to learn one, and Python is no different. Let’s take a
relates to other languages.
PROGRAMMING RECIPES "cS
ut 200 grass of eelf-raising flour in # boul.
fd 100 grams of butter to the bod.
Programs are like recipes for computers. A
recipe to bake a cake could go lke this:
Put 100 grams of selfaising Flour in bow.
‘Add 100 grams of butter to the bowl.
‘Add 100 mililtres of milk.
Bake for half an hour.
‘sa programming angvage : CODE
Peateueanosean | Juste a recipe program consists ofnstructions that you fallow 2
ikeoreveies inorder. A program that describes acake might un ike this si
Informatica (Cw) in the pn cea
Netherlands as a successor to ‘se
the ABC language. ise’: Ye
Bite = 100 Fat eSacinor tetera)
Guido van Rossum, the ont. append flour butter mitk}) abt
father of Python. ‘cake. cook(bowL)
PROGRAM COMMANDS
‘You might not understand some of the Python commands, like bowLappend and cake.cook(bow).
“he first isa list, the second an object; well 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
Figure out how a program works.
ED wruddmpubtationscamHIGH-LEVEL LANGUAGES
Computer languages that are easy to read are known as high-level”
This is because they fiy high above the hardware (also referred to as
“the metat’. Languages that “fly close to the metal” ike Assembly,
are known as towdevel". Lowsievel languages commands read a bit
like this msg db ,0xa len equ $ ~ msg.
PYTHON 3 VS PYTHON 2
Getting to Know Python E L
ZEN OF PYTHON
Python lets you access allthe power of a computer in a language
that humans can understand. Behind this is an ethos called “The
Zen of Python." Ths isa collection of 20 software principles that
influences the design of the language. Principles include “Beautiul
is better than ugly’ and "Simple s better than complex." Type
‘import this into Python and twill display all the principles.
Dee sew eau ee aetna ur
Drees t)
WORLD OF PYTHON Ji a
eee
nr)
oer
Sieearals
Sete cust ata)
DC ct eas ee Te Tu ed
ERATED 50 why tw07 Well, Python 2 was originally
Pte Inee einen
mite
pin eee ie
a)
cor
eee eerea
eee ete
etre
pene
PYTHON 3.X
er
eer vu
mpatib
Petes
Creech
Sean)
ones
See ets
ME eros as ee
forecast tor etd
eat:
Many development companies, such as SpaceX and NASA use
ogden Ts
woradmpubicstionscom Eyz= Say Hello to Python
How to Set Up
Python in Windows
Windows users can easily install the latest version of Python via the main Python
Downloads page. Whilst most seasoned Python developers may shun Windows as the
platform of choice for building their code, it’s still an ideal starting point for beginners.
INSTALLING PYTHON 3.X
Microsoft Windows doesn’t come with Python preinstalled as standard, so you're going to have to install it yourself manually.
‘Thankfully, it's an easy process to follow.
BETESERD St2*tby opening your web browser to www.python, [EEE choosing the Customise option allows you to
‘rg/downtoads/. Look for the button detaling the specify certain parameters, and whist you may
‘download link For Python 32.x (in our case this's Python 3.62 butas stay with the defaults, it's a good habit to adopt as sometimes (not
mentioned you may see later versions of 3). \with Python thankfully) installers can include unwanted additional
Features. On the frst screen available, ensure all boxes are ticked,
and click the Next button,
J Optional Features
ea
es ca yf oocrr a marta
wind wa a (ea
BASE ickthe download button for version 3.x, and EETEEPD The next page of options include some interesting
save the file to your Downloads folder When the adeltions to Python. Ensure the Associate file with
File is downloaded, double-click the executable and the Python __—Python, Create Shorteuts, Add Python to Environment Variables,
installation wizard wil launch, From here youhave two choices: _—Precompile Standard Library and instal fr All Users options are
instal Now and Customise instalation. We recommend opting for ticked, These make using Python later much easier. CckInstall when
the Customise Installation link you're ready to continue.
J Install Python 3.6.2 (32-bit) | Advanced Options
|
[ itepes coe ——
puth a puth
windows Dasreaiecnn ee} wind me Great [ena
senseiESTES You may need to confirm the installation with the
Windows authentication notification. Simply click
‘Yes and Python wil begin to install, Once the installation is complete
the final Python wizard page will alow youto view the latest release
notes, and follow some online tutorials.
Setup was successful
python
wind
ws
Before you cose the ntl wizard window
SUES however, it’s best to click on the link next to the
‘held etal sable Path Length int. Ths willow Python
tobypass the Windows 260 character Imitation, enabling youto
execte Python programs stored in dep folders rangement
gan cick Yes to authentcatethe proces then you can lose the
Istaltion window
path length imi
ese
Windows 10 users will now
Find the installed Python
3.x within the Start button
Recently Added section. The
First link, Python 3.6 32-bit)
will launch the command
line version of Python when
clicked (more¢on that in a
moment). To open the IDLE,
type IDLE into Windows start
How to Set Up Python in Windows E mm
Clicking on the IDLE (Python 3.6 32-bit link wil
launch the Python Shell, where you can begin
your Python programming journey. Don't worry iFyour version
is newer, as ong asit's Python 3.x our code will work inside your
Python 3 interface.
STEP 8
you now lek onthe Windows Start button agi,
su) and this time type: CMD, you'll be presented with the
Command Prompt nk Ck to getto the Windows command tne
tnronment,Toente Python win the conmand ine, au need
totyperpython and press Enter
The commandline version af Python works in
much the same way as the Shell you opened in
‘Step 8; note the three left Facing arrows (>>>). Whilst it’s a perfectly
Fine environment, i's not too user friendly, so leave the command
ine for now. Enter: Exit) to leave and close the Command
Prompt window,z= Say Hello to Python _)
How to Set Up
Python on a Mac
Te ME Neca ne tten La nanan Ns ae ta
version of Python is already installed. However, you should make sure you're running
ute cia Tol
INSTALLING PYTHON
Apple's operating system comes with Python installed, so you don't need to install it separately. However, Apple doesn’t
update Python very often and you're probably running an older version. So it makes sense to check and update first.
FSTESEID 220 2 new Terminal window by clicking Go> ESTED ickonthe latest version of Python 3. in our
Utilities, then double-click the Terminal icon, Now case thisis the download button For Python 3.6.2
enter: python’ =-version. You should see “Python2.5.1" and _This will automaticaly download the latest version of Python and
even later, iF Apple has updated the OS and Python installation depending on how you've got your Mac configured, it automatically
Either way, it's bestto check forthe latest version starts the installation wizard
Faeeem ben Sefari and head over to www.python.ora/ FETE With the Python installation wizard open, clickon,
downloads. Just as withthe Windows setup the Continue button to bein the installation. I's
procedure on the previous pages, you can see two yellow download worth taking a moment to read through the Important Information
buttons: one for Python 3.6.2, and the other For Python 2.7.13,
section, in case it references something that applies to your version
Note, that version numbers may be different due tothe frequent of macOS. When ready, click Continue again,
releases of Python.
Pr Re Uae(" How to Set Up Python ona Mac Cl
BETTE The next section details the Software License
‘Agreement, and whilst not particularly interesting
tomost folks, t's probably worth a read. When you're ready, click on
the Continue button once again.
Finally you're be presented with the amount of
space Python wil take up on your systern and an
Install button, which you need to click to start the actual installation
‘oF Python 3.xon to your Mac. You may need to enter your password
to-authenticatethe installation process.
BEPED) The instalation shouldn't take too long; the older
‘Mac Mini we used in this section isa ite slower
than more modern Mac machines and it only took around thirty
‘seconds forthe instalation Successful prompt to be displayed.
‘There's nothing much ee left to dointhe Python
SHED installation wizard so you can click the Close button.
Ifyou now dra backinto Terminal session andreenter the
command: python3 —-version, you cansee the new versions
now listed To enter the command ine version of Python, you need
toenter:python3. Tox, ts exitO
You need to search in Finder forthe Python 1OLE:
when you've Found it, clickit to launch andit
should look similar to that ofthe Windows IDLE version shown on
the previous page. The only ifference being the Mac detected
hardware platform t's running on,
Doane See
AigFMBeAL, dee 27-26, 17:23:19)
Dy] on ercin
CES) in use ny be esta
ae
Python 3-6. 60.6
PEPTSET ER) Older Mac versions may have trouble with the
newer versions of Python, in which case you will,
eed to revert to a previous Python 3.x bull; slong as you're using
Python 3x. the code inthis book will work For you.
‘Python 3.1.2 (£312:79360M Mar 24 2010, 01:33:18)
[écc 4.0/1" (apple Ine. build 5493)] on’ darwin
Type "copyright", “credits” or "license()" for mo
Ee incormation.
sebagaiSay Hello to Python _)
How to Set Up
Python in Linux
PYTHON PENGUIN
Linux is such a versatile operating system that i's often difficult to nail down just one way of doing something. Different
distributions go about installing software in different ways, so we will stick to Linux Mint 18.1 for this particular tutorial.
FSTESEDD fist youncedtto ascertain which version of Python
iscurrenty installed in your Linuxsystem; as we
‘mentioned, we're going to be using Linux Mint 18.1 For this section,
‘As with macOS, drop into a Terminal by pressing Ctrl+Atle.
david davidemint
Fle Ede View Search Terminal Help
version 2.x of Python in the display. Ours inthis particular case is
Python 2.7.12.
david@david-mint
File Edit View Search Terminal Help
D
wera dmpublications com
FeeeED Next enter: python =-version into the Terminal
screen. You should have the autput relating to
ESSER Some Linux distros will automaticaly update
the installation of Python to the latest versions
whenever the system is updated, To check, ist doa system update
and upgrade with
sudo apt-get update && sudo apt-get upgrade
Enter your password and let the system do any updates.
ESTEEM Orce the update and upgrade is complete, you
may need to answer’ to authorise any uparades,
center: python3 =-version to see if Python 3.xis updated or even
Installed. In the case of Linux Mint, the version we have is Python
3.52, whichis Fine For our purposes.How to Set Up Python in Linux (c
EEED reece tettetsesions62sece EERE went ron tt ote
tha Puhon websee ath ine of win, seu oeed
-/configure
to build Python From source, Start by entering these commands into SS inl
the Terminal:
sudo opt-get install build-essential checkinstall
sudo apt-get install Libreadline-gplv2-dev
Libncursesn5-dev Libssl-dev Libsqlite3-dev tk-dev
Libgdbm-dev Libc6-dev libbz2-dev
This could alittle while depending on the speed of your computer
(Once finished, enter: python3.6.=-version to check the
Installed latest version.
BRP D o5en vp yourtinxweb browser and goto Forthe GUIDE you needto enter the Following
downloads Clk on the Download Python 362 (0 whichever
version it's on when you look) to download the source Python- sudoTaptsget-installatales
Se2toreie TheIDLE can then be started withthe command: ide Note, that
IDLErunea ferent version fromthe one you tad rom source
ED creas netoors ey ERR Yc scnecne prt an
Ryon-3-6-2:tor a Nowentethe rey epee ptr tac chck forthe et unde wh
pip3 install: =-upgrade pip
When complete close the Terminal and Python 3 willbe available
via the Programming section in your distro’s menu.
wmtinosictincn QlY indexGetting Started with Python Cl
Getting started with Python may seema
little daunting at First but the language
has been designed with simplicity in mind.
Like most things, you need to start slowly,
learn how to get a result and how to get
what you want From the code.
In this section, we cover variables,
numbers and expressions, user input,
conditions and loops; and the types of
errors you may well come across in your
time with Python,
Starting Python for the First Time
Your First Code
Saving and Executing Your Code
Executing Code from the Command Line
Numbers and Expressions
Using Comments
Working with Variables
User Input
Creating Functions
Conditions and Loops
Python Modulesz= Getting Started with Python
Starting Python for
the First Time
eS enemcssiNiaceteCh EME crest um
latest version of Raspbian comes preinstalled with Python 3, version 3.4.2 to be exact,
Orolo R eee Ul Gel esol (RVG Tolg
STARTING PYTHON
‘We're not going to go into the details of getting the Raspberry Pi up and running, there's plenty of material already available
on that subject. However, once you're ready, fire up your Pi and get ready for coding.
STEERED With the Raspbian desktop loaded, click on the ESEEERD for example, in the Shellenter: 242
‘Menu button Followed by Programming > Python After pressing Enter, the next ine displays the
3 (DLE). This opens the Python 3 Shell Windows and Mac users can answer: 4 Bascal, Python has taken the ‘code’ and produced the
Find the Python 3 IDLE Shell From within the Windows Start button relevant output.
menu and via Finder,
BR TeeE AD The Shelliswhere you canentercodeandseethe — ERTESWAIB The Python Shel acts very much ike a calculator,
responses and output of code you've programmed since code is basically a series of mathematical
into Python. This isa kind of sandbox, where you're able totry out interactions with the system. Integers, which ae the infinite
some simple code and processes. sequence of whole numbers can easily be added, subtracted,
‘multiplied and so on.(Starting Python for the First Time E mm
While that’s very interesting i's not particularly The Python IDLEis a configurable environment. iF
UEP exciting. Instead, try this: SEAS
you don't ike the way the colours are represented,
7 1 then you can always change them via Options» Configure IDLE and
FARSI dlicking on the Highlighting tab. However, we dont recommend
ustlike the code we enteredin Sublime inthe Installing Text _that,asyouwon't be seeing the same as our screenshots.
Editor section ofthis book.
Thisis alittle more lke it, since you've just produced ust tke most programs available, egardless ofthe
Your First bie of code. The Prine command is Fairly ‘operating system, there are numerous shortcut
self-explanatory t prints things. Python 3 requiresthe brackets as __ keys available. We don't have room for them allhere but within the
‘well as quote marks in order to output content to the screen, in this Options > Configure IDLE and under the Keys tab, you can see alist
case the ‘Hello everyone! bit. (of the current bindings.
>>> print(“Hello everyone!)
fe everyone!
Breer You may have noticed the colour coding within BEPESET) The Python IDLE isa powerinterface and one
the Python IDLE. The colours represent different that’s actually been written in Python using one
elements of Python code. They are: of the avallable GUI toolkits. Ifyou want to know the many ins and
‘outs ofthe Shell we recommend you take a few moments to view
Black Data and Variables Ble User Functions 7 f
Geto ease ane ereterepsieneralthecrteen whchotseoreneet
Purple— Functions Light Red ~ Error Messages *
Orange Commands asee
IDLE Colour Coding
[eoteur [vse tor] Exampies |
a ie wena crate
Fetons | ian) print eS
ark
aired [Enormesseges | syntanneeae
Commins | Proseaber Wi
worahdmpubisions. cmED) ctor)
Your First Code
eee cuN gs kgs ae alae)
everyone!")’ function from the previous tutorial. However, let's expand that and look at
Scie euch outa on easels
PLAYING WITH PYTHON
‘With most languages, computer or human, it's all about remembering and applying the right words to the right situation.
‘You're not born knowing these words, so you need to learn them.
BITE ERED youve closed Python 3 IDLE, reopen itn ESTISEM You can see that instead ofthe 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 defining what's being outputted
cnt ctletom tothe IDLE Shell to print the total of 2+2 you need to remove
print*Hello") asics
print(2+2)
SR meas icwadreionposnne REED soon san ening nese
BED sive wiceneactaecearee tees
ST eee ee mr ee coors
nowt ane
printc*242") a=2(Your First Code CH
Whatyou have done here is assign the letters a
and b two values: 2 and 2. These are now variables,
which can be called upon by Python to output, add, subtract, divide
and 50 0n For as ong as their numbers stay the same. Try this
print¢a)
printcb)
(eS Sol ap Sta reo 7
ERD essncccvantair en
them tobe printed separately. F you want to add them up, you can.
use the following:
printCasb)
‘This code simply takes the values of a and b, adds them together
‘and outputs the result
ef Sot boop Sas tran He
eee
You can play around with diferent kinds of variables
isd
RD sec ce a
assign variables for someone's name:
name="David”
print(name)
le Gat teh abn deere Meson 1
FS ae oe TT
is tet aie
PEPE Nowletsaddasumame:
‘surname="Hayward”
print(surname)
‘You now have two variables containing a firstname and a surname
and you can print them independently
IF we were to apply the same routine as before,
using the + symbol, the name wouldn't appear
correctly in the output in the Shel. Try it:
print (name+surname)
You need a space between the two, defining them as two separate
values and not something you mathematically play around with.
In Python 3 you can separate the two variables
with a space using @ comma:
printCname, surname)
Alternatively, you can add the space yourself:
print(name+” “+surname)
‘The use of the comma fs much neater, as you can see.
Congratulations, you've just taken your first steps into the wide
world of Python.
ombinesiaiocon CEC7) Getting Started with Python
Saving and Executing
Your Code
Whilst working in the IDLE Shell is perfectly fine for small code snippets, it’s not
Ces om a cuneLOus ksc cl tM aes tend |code
eter fa eal MN RRO eM
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.
STEERED ist open the Python DLE Shell andwhenit’sup, ESTES You can see thatthe same colour coding is in place
lick on File> New File. Ths will opena new window in the IDLE Editor asitisin the Shell, enabling you
“with Untitled as its name, This isthe Python IDLE Editor and withinit 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 first save it. Press FS and you get 2
Save...Check box open.
ETE Tie OLE Editor's, for allintents and purposes, a ETRE
Save As from within the Editor
to create abackup.
BEF vv ccons noun docinetacs aes
ED vinci concn
Enter the following and save tas hello.py:
a="Python”
boris”
c="cool!”
print(a, b, ¢)
You willuse this code in the next tutorial
ombinesiaioon CIGetting Started with Python
Executing Code from
the Command Line
COMMAND THE CODE
Using the code we created in the previous tutorial, the one we named hello.py, let's see how you can run code that was made
in the GUI at the command line level.
wasiswithPython zwilsttie ther usesthe Python 3irares command python ar pes Ener This put outa the
and soon. First though, drop into the commat Terminalon command ine version of the Shell, withthe
your operating system facing arrows as the cursor (>>>),
EB —: - ED
Raspberry P: Windows users will
need to click the Start button and a
search For CMD, then dick the
ond
print(a)
Youcan see that actly the same
to their command line by click
o> Utlities > Terminal
vwvnubémpublctionscomExecuting Code From the Command Line
ESTES ow enter: exit to leave the command tie Python
session and return you backto the command
prompt. Enter the Folder where you saved the code from the
previous tutorial and lst the available files within; hopefully you
should see the hello.py file
command ine:
python3 hello. py
From within the same Folder as the code you're
‘ing to run, enter the Following into the
This will execute the code we created,
a="Python”
ee
ca"cool!™
print(a, b, ¢)
toremind you's:
Naturally, since this s Python 3 code, using the
usar syntax and layout that’s unique to Python 3, it only
works when you use the python3 command, IFyou tke try the same
with Python 2 by entering:
python hello.py
The result of running Python 3 code from the
Python 2 command tine s quite obvious. Whitt
ces between the
doesn't error aut in any way, due to the if
‘way Python 3 handles the Print command over Python 2, the result
isn't as we expected, Using Sublime for the moment, open the
hallo.py file
Since
at me Text isn't available for the Raspberry
Pi, you're going to temporarily leave the Pi forthe
moment and use Sublime as an example that you don't necessarily
need to use the Python IDLE. With the hello.py file open, alter itto
include the Following
nane=input (“What is your name? “)
print(‘Hello,”, name)
Dy -- =
The result willbe the original Python is cool! statement, together
with the added input command asking you for your name, and
displaying it in the command window.CJ) Getting Started with Python
Numbers and Expressions
Mee cee reer eure ote neue leas
like. Let's expand on that now and see just how powerful Python is as a calculator. You
elena len amano |e) osha) Kole ann ae) Koln an eLUN Uc
IT’S ALL MATHS, MAN
‘You can get some really i
languages, maths is the driving force behind the code.
FR ovens tncresonct wn mene
EEE ore catescieees ree
coerce remeranae
muscle, which we believe isa small gland located at the back ofthe
brain or no)
ESTER the shell enter the following
242
54396134553245
99867344*27344484221
‘You can see that Python can handle some quite large numbers.
essive results with the mathematical powers of Python; as with most, if not all, programming
‘You can use all the usual mathematical operations:
Jamaica onasaara nets
few, For example:
we
or
24283
(e244)
You've no doubt noticed, division produces 2
SMD oot umber inytnon these are sled fot
‘or floating point arithmetic. However, Fyou need an integer as
‘opposed toa decimal answer, then you can use a double slash:Numbers and Expressions CH
You can also use an operation to see the remainder
left over From division, For example:
10/3
will isplay 3333333333, which sof course 3.3-ecuring. IF you
owenter:
103,
This will display 1, which isthe remainder left over From dividing 10
into 3
TER ioxv we hve the power operator or
exponentiation if you want tobe technical. To work
‘ut the power of something you can use a double multiplication
‘symbol or double-star on the keyboard:
2083
10*10
Essentially, i's 2x2x2 but we'e sure you already know the basics
behind maths operators. This show you would work tout in Python,
BETTE umbersand expressions don't stop there. Python
has numerous builtin functions to work out ets
‘of numbers, absolute values, complex numbers and a host of
‘mathematical expressions and Pythagorean tongue twisters. For
‘example, to convert a number to binary, use
bina)
Tis ibe deployed 0611, commetng the
BAS integer into binary and adding the prefix Ob to the
Front. you want to remove the 0b prefix, then you can use:
format(3, ‘b?)
‘The Format command converts a value, the number 3,02
formatted representation as controlled by the Format specification,
the b’ part,
FETED) 4 00lean Expression sa logical statement that will
‘either be true or false. We can use these to compare
data and test to see ifi’s equal to, less than or greater than. Try this
ina New le:
o-6
b=7
print(l, a == 6)
print(2, a == 7)
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
print(7, a = 7 or b
print(8, not (a == 7 and b = 6))
print(9, not a == 7 and b = 6)
Execute the cade from Step 9, and you can see a
series of True or False statements, depending on
the result ofthe two defining values: 6 and 7.’ an extension of
what you've looked at, and an important part of programming.
entiation QECJ) Getting Started with Python
Using Comments
When writing your code, the Flow of it, what each variable does, how the overall
program will operate and so onis all inside your head. Another programmer could
follow the code line by line but over time, it can become difficult to read.
#COMMENTS!
Programmers use a method of keeping their code readable by commenting on certain sections. Ifa variable is used, the
programmer comments on what it’s supposed to do, for example. I's just good practise.
ESTED starchy creating anewinstance ofthe OLE Editor RINE resave the code and executeit. You can see that the
(ile > New File) and create a simple variable and ‘output inthe IDLE Shells stil the same as before,
print command: despite the extra ines being added. Simply put, the hash symbol (#)
an denotes line of text the programmer can insert to inform them,
Drtne CETERVALIISTORIARLSNETOD {and others, of what's going on without the user being aware,
‘Save the fileand execute the code,
Tyoend 2
oe 6a 8 a en
BETeEE Running the code willretumn the ine: The value of A ENTESWAIM Let's assume that the variable A that we've created
Is, 10 nto the IDLE Shell windaw, which s what we isthe number of lvesin a game. Every time the
‘expected. Now, add some ofthe typesof 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 osa-1
1-10 print(*You've just lost a tife!”)
# Print the current value of A print(*You now have”, a, “lives left!”)
print("The value of A is,”, a)Using Comments CH
BEG) ite BRB was hee
that the player has just lost one, a casual viewer or of code. Take our examples From above, instead of
tentang esis” ug sat the star vol of. t010
print(“The value of A is,”, a) # Print the current
aa
a concen
print(“You’ve just lost a life!
a
player, and display current value of A (lives)
Rapa E-Ee Essentially, the new code together with comments Eypaekemm The comment, the hash symbol, can also be used to
ao mer sosenecfeictootent venta
‘executed in your program. For instance, if you wanted to remove:
# Set the stort vole of A to 10 Satecwtcisbor etna
# Print the current value of A # print(“The value of A is,”, a)
print(*The value of A is,”, a)
# Inform player, and display current value of A nee an See ee
Gives) fF sat the Sew vale GFA
print “You've just lost a life!” Fic a ct he BA
printc*You now have", a, “Lives left!" prantthe value oF A fas. 0]
# Biapet Tose's tite!
F Fafor otayer. and display current value of A (Lives)
Frint(tpoune just test a Titel)
Print(-You towhavets a, olives deft")
|
BEPTSEMD Youcanuse comments in different ways, For PEP ET MD) You also use three single quotes to comment
‘example, Block Comments area large section of ‘outa Block Comment or multiline 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 gane ever, and has been i
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.
wmbineiaiocon QECJ) Getting Started with Python
Working with Variables
We've seen some examples of variables in our Python code already but it’s always
Meron eer cu neue eu eee nse ae iy
Ne UT-sa CoE NUT-1o1(3
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 Shelt to clear up any old code.
Insome programming languages you're required
Pee aeunirracreereeiet
variable made up of multiple characters, such as a name of a person.
In Python tis isn't necessary. For example, inthe Shell enter
name="David Hayward” (or use your own name, unless you're
also called David Hayward)
[Be ESS tn Grr som Hep
You can check the type of variable in use by
issuing the type Q command, placing the name of
the variable inside the brackets. In our example, this would be:
‘type (name). Add a new string variable: title="Descended
from Vikings”.
You've seen previously that variables can be
‘concatenated using the plus symbol between the
variable names. in our example we can use: print (name + ‘2
+ title). The middle part between the quotations allows us to
‘adda colon and a space, as variables are connected without spaces,
so we need to add them manually.
Youcanalso
combine variables
within another variable. For
‘example, to combine both name
and title variablesinto anew
variable we use:
character=name +“: +
title
‘Then output the content of the
new variable as:
print (character)
Numbers are stored as different
variables:
age=44
Type Cage)
Which, as we know, are integers
SiarBETTI However, you can't combine both strings and
integer type variables in the same command, as you
‘would a set of similar variables. You need to either turn one into the
‘other or vice versa. When you do try to combine both, you get an
‘error message:
print (name + age)
BRTESEERD Thisis a process known as TypeCasting, The Python
code's
print character + “is “+ strCage) + “ years
old."
‘or you can use:
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
>>> print (name + age)
Traceback (gost recent call last):
File "
‘print! (none " age)
Typetrror: Can't convert “int’ object to str implicitly
20S"prine (character +." is" + str(age) * "years old.)
David Hayward: Descended from Vikings 15 44 years old.
So>lprane (character, "is", age, “years old.")
David Hayward: Descended from Vikings 1s 48 years old.
BEPED) Ancther example of Typecasting is when you ask For
input from the user, such asa name. for example,
center:
‘age= input C*How old are you? “)
‘All data stored from the Input commands stored asa string variable.
le Shed Debug opto widows Hap
Pymben 34.2 Caefoule Ok 19 014, TTT
chage see
at
Working with Variables
BETTS This presents a bit ofa problem when you want to
‘work with a number that's been inputted by the
ser, as age + 10 won't work due to being a string variable and an
integer. Instead, you need to enter:
‘intCage) + 10
This ill TypeCast the age string into an integer that can be
worked with.
BETESEDD The use of Typecastingis also important when
~ for wore information
embiiaiocon QECJ) Getting Started with Python
User Input
CRY ET Teel oy tea nee AVL Reele Ace Keen CI}
Smee la artes cular nck camel ay
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 del
PEPER icsnotatready, open the Python 3 IDLE Shell,
and start a New File in the Editor. Let’s begin with
‘something realy simple, enter:
print¢*Hello")
firstname=input “What is your first nane? “)
printC*Thanks.")
surnane=inputC*And what is your surname? “)
ESTEE DD Seve and execute the code, and as you already no
doubt suspected, nthe IDLE Shell the program wil
ask or your firstname, string it as the variable firstname, flowed
by your surname; also stored ints cwn variable (surname).
Now that we have the user's name stored ina
‘couple of variables we can call them up whenever
we want:
print(‘Welcome”, firstname, surnane, “. T hope
youre well today.”)
Run the code and you can see a slight issue, the
suare full stop after the surname follows a blank space.
To-lmiate that we cn ad alu sgn instead ofthe commain
the code:
printC‘Welcome”, firstnane, surnanes*. T hope
you’re well today.”)User Input
‘You don't always have toinclude quoted text within
the input command. For example, you can ask the
User their name, and have the input in the tine below
print(“Hello. What’s your name?")
rame= input)
userinput py - horne/pi/Documents/Python Code/us\
Edt Format Bun Options windows Help
[print(-Hello. what's your name?)
| Bowes input)
‘The code from the previous step is often regarded
as being little neater than having a lenathy
‘amount of textn the input command, but it’s not arule that’s set in
‘stone, so do as you lke in these situations. Expanding on the code,
try this:
printC*Halt! Who goes there?”)
nane=input()
eat Fama Ban Stns roe
BPTI i's 2 good start toa text adventure game, perhaps?
Now you can expand on it and use the raw input
From the user to fesh out the game a litle:
if name=—"David":
print(Welcone, good sir. You may pass.”)
else:
printC*I know you not. Prepare for battl
m0!
BEPESEDD What youve createdhere isa condition, which we
will over soon. In short, we're using the input From
the user and measuring t against a condition, So, iFthe user enters
David as their name, the guard willaliow them to pass unhindered.
Else, iFthey enter a name other than Davi, the guard challenges
them toafight.
ESTER) ust 25900 learned previously, any input from a
user is automatically a string, so you need to apply a
‘TypeCast in order to turn it into something else. Thiscreates some
Interesting additions to the input command. For example:
# Code to calculate rate and distance
print(“Input a rate and a distance”)
floatCinput(“Rate: “))
Fate's flsstciopartate!
PPT SETR %o finalise the ate and distance cade, we can ad¢:
distance = floatCinput(“Distance: “))
print(Time:”, (distance / rate))
Save and execute the code and enter some numbers. Using the
Roat{input element, we've told Python that anything entered is 2
Fating point number rather than a string.
wmbingiaicon QECJ) Getting Started with Python
Creating Functions
Nana ta reer ate cig cir Caen ean aac Telete cs
ne oR cee tate nearer icedracl acer)
enables you to define your own Functions.
FUNKY FUNCTIONS
‘Afunction 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.
Its notjust data thata function works on. They can
do all manner of useful things in Python, such as
‘sort data, change items from one format to another and check the
length or type of items Basically, a Function isa short word that’s,
Followed by brackets. For example len), ist) or type(.
‘Afunction takes data, usualy a variable, works on
Tdepending on what the function is programmed
todo and returnsthe end value. The data being worked on goes
inside the brackets, sof you wanted to know how mary letters
are in the word antidisestablishmentarianism, then you'd enter:
Len¢“antidisestabl ishmentariani sn”) and the number 28
‘would return,
‘You can pass variables through functions in much
BALD tree manner Lets assume you wont the
‘numberof letters in a person's surname, you could use the Following
code (enter the text editor For this example):
nane=input (“Enter your surname: “)
‘count=Len(name)
print ("Your surname has", count, “Letters in
i
ress FS and save the code to executelt
ESTED Python hastens of functions built nti, Fartoo
many to get into inthe limited space available here.
However, to view the lst of builtin Functions available to Python 3,
navigate to wwwdocs python.ora/3/ibrary/functions html. These
are the predefined functions, but since usershave created many
‘more, theyre notthe only ones available,(_ Creating Functions CH
sionitncerscandessisrorsiee ESTEE) Toor function tomamedi et the net
EPS through modules. Python has a vast range of EHO
the madule Followed by afullstop, 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 canbe imported as and when required. For _ustimportedit into Python, you can ulise the square root Function
example, to se advanced mathematics Functions enter: Todo so, enter:
import math math.sqrt(16)
Once entered, you have accesstoall the math module Functions. You can se that the code is presented as madule.function(data)
aimee . set = '
eI
FORGING FUNCTIONS
There are many different 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.
ster 1 Feenteetecemsceeseiee 1ST? 2 tee neues
Ee a
Premera e
Hef HeltoO:] Gomi
print Hel 1o™)) ifron Hello import Hello}
Hel Loc) Hel LoC*David” )}
Press F5to save and run the tet
Reece
er terns) PD what you'velust done an
eer ets a From the: a
to say hello to David. Thi retio
import the module then use the Function. Try this ong,
Rarer:
preipernaete
an now pas variabCJ) Getting Started with Python
Conditions and Loops
Conditions and loops are what makes a program interesting; they can be simple or
Pemeucme trate caer ean ardiel ee ta atc)
achieve; they could be the number of lives left in a game or just displaying a countdown,
TRUE CONDITIONS
Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let's start then by checking
1g is TRUE, then doing something else rt.
FE ccsccncnroncenmbacutah RRB noua serene
step 1 Eeersiant ales Pectstees teense ton
sec
word=input (“Please enter a four-letter word: )
nord=input(“PLease enter a four-letter word: “) _word_Length=Len(word)
if word_tength == 4:
print (word, “is a four-letter word. Well done.)
The double equal sign (==) means check if something is equal to
something else
BEPSPR) Nowwecancreate anewvariable, then use the len [EFM the colon at the end of tells Python thatif this
Function and pass the word variable through it to
statement true do everything after the colon
‘get the total numberof letters the user has just entered: that's indented. Next, move the cursor back to the beginning of
wordzinput(*Please enter a four-letter word: «) Se Ector
vword_length=Len(word) wordeinput(“Please enter a four-letter word: “)
word_Length=LenCword)
if word_length == 4:
print word, “is @ four-letter word. WeLL
done”)
else:
print (word, “is not @ four-letter word.
ree ord st 9 tr ter sr) 1Press 5 and save the codeto execute. enter
UH a four-letter word in the Shell to begin with, you
should have the retuned mesage thats the word our eters
Now press FS agar and rerun te program butts time entra
fheletter word The Sell dapay hat t's nto fourier word
LOOPS
( Conditions and Loops Cl
Now expand the code to include another conditions.
Eventually it could become quite complex. We've
added a condition for three-letter words:
word=input(“Please enter a four-letter word: “)
word_length=Len(word)
‘if word_length
print Grord,
done”)
elif word_length = 3:
print (word, “is a three-letter word. Try again.”)
else:
print (word, “is not @ four-letter word.)
‘sa four-letter word. Well
eer ache ae ue ue Te od
feed
cam
=
print
eee ee ees
Ree ee while
sTeP2
gets to the end of the indented code, it goes back
Seems
of code a number of times, usually with the support of a condition.
STEP 3 Wicdbules desdeebaceuineai act
ee
brords=[Cat™, Dog", "Unicorn™|
for word in words:
inside square bra
he For 0 be used in the
eas
STEP 4
for x in range (1, 10):)
print Gy
co
eee et
ee eee
nthe First and last numbers used,Getting Started with Python
Python Modules
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:
BETTER thouoh good, the builtin functions within Python [REI the result isan errorinthe 1OLE Shell asthe
are limited, The use of modules, however, allows us ygame module isnt recognised or installed in
to make more sophisticated programs. Asyou are aware, modules Python. Toinstall a module we can use PIP (Pip Installs Packages)
are Python scripts that are imported, such asimport math, Close down the IDLE Shell and drop into a command prompt or
Terminal session. At an elevated admin command prompt, enter
pip instal pygane
somenodierczecstyone Raver SEEM ter stlston eis encode
SUENe are included by default, the math module being a SUarS due it installing components at different locations.
prime example. Sach oter modules aren aways avalable.A good Windows uses can sare for CMO vite tare button and
‘example on non-Pi platforms is the pygame module, which contains click the result then click Run as Administrator. Linux and
many Functions to help create games. Try: import pygame. ‘an use the Sudo command, with sudo pip instal package,
vwvmubémpublcationscom(Python Modules Cl
Clos the command prompt Terminal and
Sue5 relaunch the IDLE Shell. When you now enter:
‘import: pygame, the module will be imported into the code
without any problems. Yul find that mest cade downloaded or
Copied from thenteret wllontine module, mantream of
Unique, these are usual the source of erors mn evecton due to
them being missing
Siar
‘The modules contain the extra code needed to
achieve a certain result within your own code, as
‘we've previously experimented with. For example:
‘import random
Brings in the code from the random number generator module. You
‘ean then use this module to create something ike:
for i in range(10):
print(random.randint(1, 25))
BEPTSED This code, when saved and executed, will display ten
random numbers From 1 to 25. You can play around
vith the code to display more or less, and from a great or lesser
range. For example:
‘import random
for i in range(2s):
printCrandom.randint(1, 100))
Multiple modules can be imported within your code,
SES ‘To extend our example, use:
‘import random
‘import math
for I in range(S)
print(random.randint(1, 25))
print(math.pi)
‘The result isa string of random numbers Followed
by the value ofPias pulled from the math module
sing the print(math pi function, You can aso pul in certain
Functions From a module by using the From and import commands,
suchas:
from random import randint
for i in range(S):
print(randint(1, 25)
PEP har cones svins apse
ED ee eset
‘which willimpost everything defined within the named module.
However, ts often regarded as a waste of resources butit works.
nonetheless. Finally, modules can be imported as aliases:
‘import math as m
print(m.pi)
OF course, adding comments helps to tell others what's going on
D tette:cihesinidOnimenentd tine DER =a R
sembobetisonBE) veterrttctonconWorking with Data
Data is everything. With it you can
display, control, add, remove, create
and manipulate Python to your every
demand, Over these coming pages we
look at how you can create lists, tuples,
dictionaries and multi-dimensional lists;
and see how to use them to forge exciting
and useful programs.
‘Then, you can learn how to use date
and time Functions, write to files in your
system and even create graphical user
interfaces that take your coding skills to
new levels and into new project ideas.
46 Lists
48 Tuples
50 Dictionaries
52 Splitting and Joining Strings
54 — Formatting Strings
56 Date and Time
58 Opening Files
60 Writing to Files,
62 Exceptions
Python Graphics
woradmpublistions. cmED) wring wot)
Lists
Mee LN Tue OM kee Reiter TMU eon cerca)
Python. A list is simply a collection of items, or data if you prefer, that can be accessed
as a whole, or individually if wanted.
WORKING WITH LISTS
Lists are extremely handy in Python. A list can be strings, integers and also variables. You can even include Functions in lists,
‘and lists within lists.
BRTISEDD Alistisasequence of data values called tems. You [ENB vou can also access, or index, the lastiteminalistby
create the name of your lst followed by an equals using the minus sign before the item number [1],
‘sign, then square brackets and the tes separated by commas; __or the second tolast item with [2] and so on. Trying to reference an
ote that strings use quotes: item that sot inthe lst, such 3s [10] wil return an error:
numbers = [1, 4, 7, 21, 98, 156] ‘unbers[=1)
mythical_creatures - [“Unicorn”, “Balrog”, mythical_creatures[=4]
‘“Varpire”, “Dragon”, *Minotaur™]
ED ox piecineseutasovcncatean — EEPB singin toindengnayoucn rie
SHER ‘by referencing its name, followed by a number. Lists. suare multiple items in a list by separating item numbers.
startthefirstitem entry as 0, Followed by 1,2, 3 and soon. witha colan. Far example:
For example: unbers[1:3]
unbers
\Willoutput the 4 and 7, being item numbers 1 and 2. Note that the
‘Tocall up the entire contents ofthe lst. returned values don't include the second index position (asyou
amen would numbers{1:3] to return 4, 7 and 21).
‘Tocall the third from zero iterin the lst (21 in this case). EE putiobessYou can update items within an existing list, remove
items and even join lists together. For example, to
join two lists you can use:
everything = nunbers + mythical_creatures
‘Then view the combined list with:
everything
Items can be added to alist by entering:
nunbers=nunbbers+[202]
Or Forstrings:
mythical_creatres-nythical_creatures+{“Griffin”]
Orby using the append function:
mythical creatures. append(“Nessie”
numbers -append(278)
fe se ne
Removal of items can be done in two ways. The Fist
isby the tem number:
del nunbers{7]
Alternatively, by item name:
mythical _creatures. renove(“Nessie”,
X
BETESEBD You con view what canbe done with ists by entering
ist) into the Shell. The output isthe available
Functions, for example, inset and pop are used to add and remove
items at certain positions. To insert the number 62 at item index 4:
numbers insert (4, 62)
Toremave it:
‘nunbers .popC4)
You also use thelist function to breaka string down
Into its components. For example:
ListC*Davia")
\'v,T, 4. This can then be passed
nane=List*David Hayward”)
name
age= [44]
user = name + age
BEPIED) 82:e3onthar youcancreatea program tore
someone's name and age 28 at
name=inputC“What’s your name? “)
‘[name=ListCname)
age=intCinputC*How old are you: “))
lage=Lege]
user = Inone + Lage
Thecombined name and age ist ical ser, which canbe called
by entering usr ins the Snel. Expermentandse what you cn do.
semubobetnsonEwen innons
Tuples
Tuples are very much identical to lists. However, where lists can be updated, deleted or
changed in some way, a tuple remains constant. This is called immutable and they're
Peucedeceulincekec en cues
THE IMMUTABLE TUPLE.
Reasons for having tuples vary dependin
special but they're also used for exampl:
‘what the program is intended to do. Normally, a tuple is reserved for something
in an adventure game, where non-playing character names are stored.
PEPE Atupleiscreated the sameway asalistbutin this ERRIBB You can create grouped tuples into lists that contain
instance you use curved brackets instead of square multiple sets of data. For instance, here isa tuple
brackets. For example: called NPC (Non-Playable Characters) containing the character name
ionths=C*January", February"; “March; aprit%y) andtheir combat rating Foran adventure game:
“way”, “June”) NPC=[C“Conan”, 100), (*Belit”, 80), CValeria”,
months 95))
OE. aay a a. me
FTTeGED usteswith lists theitems within anamedtuple can [ESTESWAIM Each ofthese 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, ie. Indexed according to their position NPC[O). You can also indexthe
ruse Individual tuples within the NPC lst:
months [5] NPCce} (1)
However any attempt at deleting or adding to the tuple willesuit will display 100.
in an errorin the Shel.
‘It's worth noting that when referencing multiple
tuples within alist, the indexing f slightly diferent
From the norm. You would expect the 95 combat rating ofthe
‘character Valeria to be NPC(4I[S], but i’ not. It’ actually:
NPCE2IE1]
ee em
BETESEE) This means of course thatthe indexing follows thus
ua
‘Which as you can imagine, getsa little confusing when you've got a
lot of tuple data to deal with,
ete Ss
Be corn iestonanclusipns
ED ees tre cease
set Phscenuthtcosad nee ated
‘combat rating):
NPC=¢*Conan”, 100)
Now unpack the tuple into two
corresponding variables:
Chane, conbat_rating)=NPC
‘You can now check the values by entering name and combat_rating..
Sis}
BETESERD Remember, as with lists, you can also indextuples
using negative numbers which count backwards
From the end ofthe data it. For our example, using the tuple with
‘multiple data items, you would reference the Valera character with:
Npc[2][-0]
PEEP von rosacea ae
BERD sccitinwnceeenet
‘numbers. For example:
runbers-C10.3, 23, 45.2, 109.3, 6.1, 56.7, 99)
‘The numbers can be integers and floats. To output the highest and
lowest, use:
print (maxCnumbers))
print (minCnumbers))
a;Ewen innons
Dictionaries
Meee ecu ites eee iru arene ua actu eae ey
of dealing with data items. They can be tricky to get to grips with at first but you'll soon
Peel Leen te ners
KEY PAIRS
A dictionary is lke 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.
Let's say you want to create ¢ phonebook in Python, ‘As with ists 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 colon phonebook, inthis example. This will display the data items you've
Key:Vallue. For example: entered ina similar Fashion to alist, which you're no doubt familiar
phonebooke={“Emna”: 1234, “Daniel”: 3456, “Hannah”; th bynow
6789}
ED evinmattsn sisson tine — EIB reteset wings dctonsysttyou
SuER need be enclosed in quotes (single or double), SUF -canenter the key to index the value. Using the
wh ntagers can bee open Remember thatthe valecanbe phonebook example framthe predates you can ener
tthe asingoraninteger you jst need encose he reevant eokttnea")
one gues phonebook[*Haanah")
phonebook2={"David": “0987 654 321”)ictionaries ( cH
[Adding toa dictionary is easy too. You can include
’ new data item entry by adding the new key and
value items tke:
honebook[“David"] = “0987 654 321”
phonebook |
ESTESEED Youcanalso remove items froma dictionary by
Issuing the del command followed by the item's
key; the value willbe removed as well, since both work as a pair of,
data items:
del. phonebook [“David”)
FER cis cuptrne towsin cea
aD er ereieeblay
lesan econ Poa sa
codingin a new, blank dictionary:
phonebook={}
Next, you need to define the user inputs and
SALE oats one for the person's are, the other
for their phone number (let's keep it simple to avoid lengthy
Python code):
nane=input Center name: “)
nunber=intCinputC“Enter phone number: “))
Note we've kept the number as an integer instead
‘of astrina, even though the value can be both
{aninteger or a string. Now you need to add the users inputted
variables to the newly created blank dictionary. Using the same
process asin Step 5, you can enter:
phonebook[name] = number
| ponsmaine = mane
r
BER sour rsssaindeoam dacaie rte
ERD viecerccereme nee
those entries into the phonebook dictionary, which you can test by
entering nto the Shell:
phonebook
phonebook[“David")
\Fthe number needs to contain spaces you need to make it string,
so remove the int partof the input.
ombinesiaicon QEz= Working with Data
Splitting and
Joining Strings
Meas celae Ree V Means steel roe Le eri enon tole 07
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
tostrings.
The maintoolinthe sng function arsenals soto. RRM note tra tne texts part asthe brackets,
‘With it you're able to split apart a string of data, quotes, then a space followed by closing quotes
based onthe arqumert within the rockets Forexarple,herésa_andbractets The paces the separator, nag tha echt
‘string with three items, each separated bya space: ‘item entry is separated by a space. Likewise, CSV (Comma Separated
‘texte"Dantel! Honnab Ema” Value) content has 8 comma, so you'd use:
exes anory February March ae aye
months=text.split(“,”)
ETE Now lets tum the string into alist and spitthe TEED You've previously seen how you can spit astring
content accordingly into individual letters asa list, using a name:
nanes=text split “) nane=List(*David”)
rane
‘Then enter the name of the new list, names, to see the three items.
The returned values‘, av, 7,‘ Whilst it may seem alittle
useless under ordinary circumstances, it could be handy For creating
spelling game for example.Splitting and Joining Strings Cl
BETTER) The opposite ofthe spit functionis join, where BETTER) with the split Function, the separator doesn't
you will have separate items inastring and can join have tobea space, itcan also be acomma, a full
themall together to Form a word or just a combination of tems, _stop, a hyphen or whatever you like:
depending on the program you're writing. For instance:
‘alphabet="”.join(["a”,"b","c","a”,”e"})
alphabet
‘This wil display ‘abcde’ in the Shel
colours=(“Red”, “Green”, “Blue
join(colours)
EETISEED Youcentherefore apply join to the separated name EIEN there's some interesting Functions you apply toa
you made in Step 4, combining the letters again to string, such as capitalize and title. For example:
Form the name:
titLee"conan the cimmerian”
name="". joinCname) title.copitalize)
ame title.titleQ
|We've joined the string back together, and retained the list called
name, passing it through the Join Function.
SW ccccocscwcrcsciancy rca SAMOS vcr cexssuscchuna
ED crac cca mesenee
sentence: youto check Fastring contain or does not contain asequence
Tist=[“Conan”, “raised”, “his”, “mighty”, “sworar, Fcharactes
“and”, “struck”, “the”, “demon”] message="Have a nice day”
texte” “.joinCList) “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 spaces inthe Step sin) “night” in message
1 Ea Soh Dr in
sep sesh met ae mma
—
B |
sembanbletosonz= Working with Data
Formatting Strings
Wee Me ce Rec Tsetelecurn ener cch Mr ce cun cis
RePee ag acen Mere aneen ake eit once Aeron
Cm tamara hehe lettuces
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.
FE icctarcunncwon stckces RBBB oconcrcxsecso nase mesesmotens
ERD occ ccciie
nuniber=10000
‘nane="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
{}”. FormatCname)) merchant..”.format(name, place, nunber))
BEPTIPR Remember to close the print function with twosets [FAVA there are mary different 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 prin Function in another. You can include multiple cases of you here; thers can be significantly mare complex. all depends
string formatting ina single print Function: ‘on what you want from your program. A good place to reference:
a Frequentiy regarding string formatting i the Python Docs webpage,
place=*chaierta® Found at www.docs.python.org/3./ibrary/string.html, Here, you
printC"{} hailed from the North; ina'cotd tang“ finétons helo,
known as {}".Format(nane, place))>
(Fe tting Stri
(_ Formatting Strings cl
BEI terestinaly you can reference alist using the string FIM) vou can also print out the content of a user'sinput
Formatting Function. You need to place an asteriskin inthe same Fashion:
Front ofthe lst name: nput(*What's your name? *)
runbers=1, 3, 45, 567546, 3425346345 print(*Hello {}.".formatname)
printC*Sone numbers: {}, t, th, Oh, O-
format(*nunbers))
ESTEE) Withindexing in ists, the same applies to calling a
Uist using string formatting, You can index each tem
‘according to its postion (rom 0 to however many are present):
You can extend this simple code example to display
the Fist letter ina person's entered name:
nane=inputC“What”s your name? *)
runbers=1, 4, 7,9 printC*Hello {}.”.Format(name))
print(“More numbers: {3}, {0}, {2}, ‘Uname=List name)
{i}.”. Format numbers), printC*The first letter of your nane is a {0}".
format(*Lnane))
1 Ea So py ers nes Hp
BR ysensyansec ovcnmaoa” RREBIPR ocansonano paras once
ED oceans Set itn coestc es
format function: Looking back the code from Step 7, you can alter it with:
characters=[“Conan”, “Belit”, “Valeria”, 19, 27, “Conan”, “Belit”, “Valeria”)
20) ‘ages=[25, 21, 22]
print C“{0} is {3} years old. Whereas {1} is {4}
Creating two lists. Now you can cal each lst and individual tems:
print({O[01} is {1[]} years old. Whereas {O17}
is {1[1]} years old.”.formatCnanes, ages))
format(*characters))
ombinpsiaiocon QEEwen innons
Date and Time
WAM Mere Nee MMM eel Ty Meee cme
ROME Museums Mca cece nt)
Rem M eee nn ccu Meco meh elaine cs
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.
ERTeGEED rst you need to import the time module. t's one
that’s builtin to Python 3 so you shouldn't need to
{drop into a command prompt and pip install. Once i’simported,
you can call the current time and date with a simple command:
‘import time
‘time.asctimeQ)
The time Function is split. nto nine tuples, these are
divided up into indexed itere, as with any other
tuple, and shown in the screen shot below.
Index Feld values
0 age year ans
1 oe tw
: seona (01061 (60 or 61 areeap-sconts)
5 aver vee 6 206 (0 Hondoy)
7 Baya yae 1 to 36 (an dy)
8 Davghtsamngs 1, 0,2, -t means rary determines OST
wera dmpublieations com
‘You can see the structure of how time's presented
was
time. local timed)
‘The outputis displayed as such: “time .struct_timeCtm.
year=2017, tmmon-9, tmmday=7, tm.hour=9,
‘mmine6, tmsec=13, tmnday=3, tmyday=250, tm
‘isdst=0)'; obviously dependent on your current time as opposed
to the time shown above,
“There are numerous functions built nto the time
LEED otc. One of te most common cf these le
strftime(). With i, you're able to present a wide range of arguments
asit converts the time tuple into a string. For example, to display the
current day of the week you can use:
‘time. strftimeC‘A’)Date and Time ( cH
ESTEE This naturally means you can incorporate various ESTED Yousswatthe end ofthe 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
‘time. strftime“Ka")
time. str#timeC*%B") the code from above and alter itslightly by including:
‘time. strftime“%b”) start_time=time .time()
time. strftimeC“sH”)
‘time. strFtime “si” Then there's:
endtime=time.timeC)-start_time
Ge Fam tre in tp
SOC cata aa eS Man
BETISEE) ote the last two entries, with %H and %H94M, 2s ETI the output will look similar tothe screenshot below.
you can see these are the hours and minutes and as. ‘The timer Function needs to be either side ofthe
the last entry indicates, entering them as %6H%M doesn't display the input statement, as that’s when the variable name's being created,
time correctly inthe Shell, You can easy rectify this with: depending on how long the user took to login, The length of time is
‘Speen then displayed on the last line ofthe code asthe endtime variable.
ere Fora ae ee
‘ungettncoe eS SSP ath ce tonto te aco.
Settimca Ea
FREE icmessresiraioechecossiy RPEREPR, hows: nce serene
ste 7 inane atatetie oluenntengamoeate ahs
A enters helpCtime) to display the current Python version help file
nane=inputC“Enter Login name: “)
printc*welcone”, nane, “\d”)
print(*User:", nate, “logged in at”, tine.
strftimeC"H:900°))
‘Try to extend it Further to include day, month, year and so on.
ip Ea mee
sembanblatoionz= Working with Data
Opening Files
Tavira CANO ls em ole Cone Tol CH
Pe eouCenntn Mer ela tetsu ee h rey obi tures)
Ciena eceorer Moule re Teee
OPEN, READ AND WRITE
In Python you create a File object, similar to creating a variable, only passin the file using the open() Function. Files are usually
‘categorised as text or binary.
EERE St2tby entering some text into yoursystemstext ESTEEM IF younow enter poem nto the Shell, you will et
euitor. The text editors best, not aword processor, some information regarding the text file you've just
‘as word processors include background Formatting and other acked to be opened, You can now use the paem variable to read the
‘elements, n our example, we have the poem The Cimmerian, by contents ofthe fie:
Robert E Howard, You need to save the file as poem.txt.
poem. readC)
"Note than a/n entryin the text represents a newline as you
used previously.
f
ay ie
ED ieectecomancientonmte sino ERE Souci roenend asd tine youl
Suze variable as an object. You can name the file object Sere notice that the text has been removed from the file.
anything you like, but you will eed to tell Python the name and You willneed to enter: poem=open(“/home/pi/Documents/
location of the textile you're opening: Poem. txt”) again to recreate the file. This time, however, enter:
poem=open("/home/pi/Documents/Poem. txt”) print(poem.read())
‘Thistime, the /n entries are removed in Favour of newlines and
readable text.
[aE