RY LEARN PYTHON & C++ CODING < ib
y The Complete
C++
& Python
OVER
PTAA re) 0 Cece re) ae) eee 100% INDEPENDENTThe Complete
Manual Series
Available on Lx=rala|[U]
rr
|
Taye a &iPadOS @
ae User Manual
“he Complete 2 Complete 7 te Compete ‘the Complete
\g
Windows 11 Oogle FH Chromebook
User Manual
User Manual User Maal
bres
ed vest
ie
Networkii Computin
Manual ng re re ¥
f
Cara.
£5) Papercut
For a full list of titles available please visit:
www.pclpublications.comThe Complete
C++
& Python
Manual
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.
£3) Popercut
www.pclpublications.comMD =)
Contents Ss
The Complete C++ & Python Manual
8 _WwhyPython?
10 Equipment You will Need
12 _ Getting to Know Python
14 How to Set Up Python in Windows
16 How toSet Up Python on a Mac
18 _ How toSet Up Python in Linux
CUR euch ue ae
22__ Starting Python for the First Time
24 Your First Code
26 Saving and Executing Your Code
28 _ Executing Code from the Command Line
30 Numbers and Expressions
32__Using Comments
34 Working with Variables
36 User Input
38 Creating Functions
40 Conditions and Loops
42 _ Python Modules ae =
44) Working with Data
46 Lists
48 Tuples
50 Dictionaries
52__ Splitting and Joining Strings
54 Formatting Strings
— —
Ahonen)
Date and Time
Opening Files
\Writing to Files
Exceptions
Python Graphics
68 Calendar Module
70 _OSModule
72__ Random Module
74 Tkinter Module
76 _Pygame Module
80 Create Your Own Modules
(nouekon
84 WhyCH?
86 Equipment Needed
18 Howto Set Up C++ in Windows
90 _ Howto Set Up C++ on aMac
92 Howto Set Up C++ in Linux
94
Other C++ IDEs to Install( Contents
ast ae) 3) 5
DOWNLOAD!
SMe Leb Cy al ai ey
CTO mature ut ule cy CeO ETDS Ube eC Lr)
98 Your First C++ Program 126 While Loop
100 Structure of a C++ Program 128 ForLoop
102 Compile and Execute 130 Do... While Loop
104 Using Comments 132 _F Statement
106 Variables 134 If... Else Statement
108 Data Types
110 Strings aes
412 C++ Maths 136) Working with Code
QRS ens 138 Common Coding Mistakes
. 140 Beginner Python Mistakes
116 User interaction 142 Beginner C++ Mistakes
118 Character Literals 144 Where Next?
120 Defining Constants
122 File Input/Output
wor pepublations.comA
P
( Say Hello to Python
‘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 helpfulsystem tools, text
adventures and even control a character
as they move around the screen.
8 WhyPython?
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
18 How to Set Up Python in Linux
wom pepubliationscomz= Say Hello to Python
Why Python?
Deena ae cumin) uct eee eee keel cn
PI Reuee eric nciemac ecru h aides tcicee ete cle acters
Ere Kelcsre Cece e nl AMM Com Cell PCr eRe mca enol
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, saving over an overheating heap of circuitry to create somet
‘These pioneers of programming carved their way into anew
Frontier, Forging small routines that enabled the letter‘ to scroll
‘across the screen, It may not sound terribly exciting to a generation
{that's used to ultrahigh definition graphics and open world, multi
player online gaming, However, Forty-something years agoit was
blindingly biliant.
[Naturally these bedroom coders helped form the Foundations for,
every piece of digital technology we use today. Some went on to
become chief developers for top software companies, whereas
‘others pushed the available hardware tots limits and founded the
billion pound gaming empire that continually amazes us.
akin to magic
Regardless of whether you use an Android device, iOS device, PC,
Mac, Linux, Smart TV, games console, MP3 player, GPS device builtin
tocar, settop box ora thousand other connected and smart’
appliances, behind them alis programming,
‘All those aforementioned digital devices need instructions to tell,
them what to do, and allow them to be interacted with, These
instructions form the programming core ofthe device and that core
‘canbe built using a variety of programming languages.
‘The languages in use today differ depending onthe situation, the
platform, the device's use and how the device wil interact with ts
ee
=
=a]
|
pra 1 eet ArrayCtrl::ChildLostFocus(),
BR wece > ce
sricisor ony)?
ctrl: soutasotracus th:
itlcurgor > 0)
Pefreshrow (cursor):
curt chr tacaserocus0?
eee eae mY
Semis Factors
Reece Sree | void scractrt:esint(orme w) {
Since” Seemn” ol “uanbt sine
Siete So OS
Sams’ (Goarmerce ||) fbetion
sates Sonate boot Ranft = sarecvsoeer (0:
= He Neeettaoatanhs
arenes ay Bit he header eaters
Bement” Soto 2
= 0)
Soriitice Retr oo 7
Sephora rac
Sinpaocse Btwcny olor fe = sland(scoloroiesbled, scoloreaper):
f
cree fermen, eeatea
ue rt ara
st Re sre
samen lores Tires) onl
ores ema He Pe ett:
Saran” overs pares jo 1 cltn cecal, Sc
eeutlleseene im ox heperSetabinatntns
C++-is usually reserved For more complex
‘programs, operating systems, games and so on.
resenvironment 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 call them. They're
Widely used across all hardware platforms and sult 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 ‘talks!
to the hardware and operating system using a variety of arrays,
variables, objects, arthmetic, subroutines, loops and countless
‘more interactions. Whilst it's not as streamlined asa Low-Level
Language, which can deal drectiy with memory addresses, call
stacks and registers, ts benefitis that it's universally accessible
and easy to learn.
Fi Te_ revoke Java
opore java lang. reFlect.*;
‘lass invoke {
Public static void main( string [] args ) {
try
Gass ¢
Method m
Dita D5
Object rét = m.inyoke( nul1, nul7
Systen.out printinc
Class.forvane( args{0) );
‘cugetwethod( args(1), new class
‘Thvoked static method: " + args (1)
+ of class: + args(0]
+" with no args\nesults: " + ret);
catch ¢ ClasshocFoundexcepeion e }.£
77 Class. fornane(”) can't find the class
catch’ ( NosuchMethodexception 2)
17 that method doesn't exist
auch ( Tilegalaccesstxcept ion 3 ) {
ZL ye gon’t'Rave' permission to invoke that
inetho
} Catch ( tnvocationtargetexception ef ) {
77-an exception ocurred while invoking that
inethod’ re
System out .princin
yeeshethod threw an: " + e4.
getTargetexception( ")");
Javaisa powerful language
that's used in web pages,
set-top boxes, TVs and
7
(why Python? Cll
Python was created over twenty sixyears ago and has evolved to
become an ideal beginner's language for learning how to program a
‘computer. I's perfect for the hobbyist, enthusiast, student, teacher
‘and those who simply need to create their own unique interaction
between either themselves ora piece of external hardware and the
computer itself
Python is free to download, install and use and is available or Linux,
‘windows, macOS, MS:DOS, 05/2, BeOS, IBM iseries machines, and
‘even RISC OS. Ichas been voted one of the tap Five programming
languages inthe world and s continually evolving ahead of the
hardware and Internet development curve.
So to answer the question: why python’ Simply put, i's Free, easy to
lear, exceptionally powerful, universally accepted, effective and a
superb learning and educational tool.
BASIC was once the starter language thatearly
‘-bithome computer users learned.
Seats cee a
aa
Python isa more modern take on BASIC, i's easy to learn
‘and makes for an ideal beginner's programming language.
nnay
z= SayHello to Python )
Equipment You
Will Need
pte ave eunnndieeCur eer Sem Unease ua ll
Celotta eka anol] Ng Leet Reon) .0 UOT o ENR Men AR Le Ke
iN ll] Com
WHAT WE'RE USING
‘Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linux, Raspberry Pi and more. If
you have one of those systems, then you can easily start using Python.
COMPUTER
Obviously you're going to need a computer in order to learn how to program in
Python and to test your cade. You can use Windows (fram XP onward) on either a 32
‘or 64-bit pracessor, an Apple Mac or Linux installed PC.
AN IDE
AnIDE (Integrated Developer Environment) is used to enter and execute Python
code. Itenables you to inspect your program code and the values within the code, 35,
‘wells offering advanced features. There are many different IDEs available so find
the one that works For you and givesthe 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 well cover shortly
TEXT EDITOR
Whilst atext editor isan ideal erviconment.to enter code int, it'snot an absolute
recessity, You can enter and execute code directly From the IDLE but text editor,
suchas Sublime Text or Notepad'+, offers 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 amore
efficient language. Having access to the Internet will keep you up-to-date, help you
lout when you get stuck and give access to Python's immense number of modules.
TIME AND PATIENCE
Despite what other books may lead you to believe, you won't become a programmer
in 24¢hours. Learning to code in Python takes time, and patience. You may become
stuck at times and other times the cade wilflow ike water. Understand you'e leaning
something entirely new, and you wil et there.
BED oiscaunnentvouwineed CE
THE RASPBERRY PI
‘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.
Sa Ta aad
‘The Raspberry PiS isthe latest version incorporating a more
powerful CPU, more memory, WiFi and Bluetooth support.
You can pick up aPi 5 for around £59 or as part of akit
‘depending on the Pi madel you're interested in
FUZE PROJECT
‘The FUZE's a learning environment built onthe latest modet
of the Raspberry Pi, You can purchase the workstations that
‘ome with an electronicskitand even a robat arm for you to
build and program. You can find more information on the FUZE
at www.fuze.co.uk
We have several great coding
tiles available vi worm.
‘elpublications.com. Our Pi
books cover how to buy your
First Raspberry Pi, setit up and
SAT
‘The Raspberry Ps main operating system isa Debian-based
Linux distribution that comes with everything you need in
‘a simple to use package's streamlined forthe Piand is an
idea platform for hardware and software projects, Python
programming and even asa desktop computer.
use it; there are some great
step-by-step project examples
‘and guides to get the most
From the Raspberry too,
vwmpapaictonscon QTEay
z= SayHello to Python )
Getting to
Know Python
unr ee col re emule) Cute kerr let rl
SUE A AINA en eee Reo TMs (Ure enlace]
to understand.
WHAT IS PROGRAMMING?
Ithelps to understand what a programming language is before you try to learn one, and Python is no different. Let’s take a
look at how Python came about and how it relates to other languages.
PROGRAMMING RECIPES
Programs ae like recipes for computers. A
recipe to bake a cake could go tke this:
‘Aprogramming language
isallistof instructions that
a computer folows. These
instructions can be as simple
as displaying your name
or playing a music file, or
as complex a building a
‘whole virtual word, Python
isa programming language
conceivedin the late 1980s
by Guido van Rossum
at Centrum Wiskunde &
pot 100 grans of seif-raising flour in # boul
16s t00 sstianitres of wie
ut 100 grams of selfralsing flour ina bowl
‘Add 100 grams of butter to the bowl,
‘Add 100 millilitres of milk
Bake forhalf an hour
CODE
Just tke a recipe, @ program consists of instructions that you follow
inorder. A program that describes a cake might run tke this
Informatica (Cw) in the bowl = 0
Netherlands asa successor to flour = 100
the ABC language. [| butter = 50 Savi
aes SEE Stace nee ay
bon .append( [four buttermi KT)
If cake. cookCbonl)
Guido van Rossum, the
father of Python.
PROGRAM COMMANDS
You might not understand some of the Python commands, lke bowl append and cake.cook(bowi)
The first i alist, the second an object; we'l look at both inthis book. The main thing to know is
that it’s easy to read commands in Python. Once you learn what the commands do, i's ea5y to
Figure out how a program works.
EBD een c+ coangHIGH-LEVEL LANGUAGES
Computer languages that are easy to ead are known as *highvtevel
Thisis because they fly high above the hardware (also referred to as
‘the metal’) Languages thatTly close to the metal" like Assembly,
‘are known as “low-level”. Low-level languages commands read abit
lice this:msg db ,@xa len equ $ ~ msg,
PYTHON 3 VS PYTHON 2
(cetingtoroonxion CREE
ZEN OF PYTHON
Python lets you access ll the power ofa computer ina language
that humans can understand, Behind all this isan ethos called “The
Zen of Python." Ths sa collection of 20 software principles that
influences the design ofthe language. Principles include “Beautiful
isbetter than ualy” and “simpleis better than complex" Type
import: this into Python and it wil display al the principles.
ene e e t ee nce areetecoeeg eet
re Lee
eset
eet nerd
eee
At ee
ent! ee case
eet
Pee Recs a una urn
pe ele eee ee
{90 to programming languages For b
nee
ats
PYTHON 3.x Jit
perenne
ent are eg eters
pose ae eee ere a
Pees Deore tg
Seon
etic cast
eects
See uae
wooweehubicaionscon CEIz= Say Hello to Python)
How to Set Up
Python in Windows
WVU lee aurea tui aro
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, i's an easy process to follow.
FETED s2tbyopeningyourmeb browser towww.python, [ERIN choosing the Customise option allows you to
‘0ra/downloads/. Look for the button detailing the
specify certain parameters, and whilst you may
download link or Python 3.xx (in our case thsis Python 36.2 but as stay with the defaults, t'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 fist screen available, ensure all boxes are ticked
and click the Next button,
J} Optional Features
@
pyth
windov oe a aaa
pen ir tars ag cng
FEPTSPRD click the download button for version 3x, and ESTEE The next page of options include some interesting
save the file to your Downloads folder. When the
File is downloaded, double-ick the executable and the Python
installation wizard wil launch, From here you have two choices
Install Now and Customise Installation, We recammend opting For
the Customise instalation lnk.
J Install Python 3.6.2 (32-bit)
a.
wind iad Python 346 to PATHE cone
BED osc:
additions to Python. Ensure the Associate file with
Python, Create Shortcuts, Add Python to Environment Variables,
recompile Standard Library and install for All Users options are
ticked. These make using Python later much easier. Click install when
you're ready to continue.
‘Advanced Options
mt rane
(acm nth fn fp yt)
awl
agar Fi aE aYes and Python will begin to install. Once the installation is complete
he Final Python wizard page wil allow you to view the latest release
notes, and Follow sorne online tutorials
Setup was successful
a
&
How to Set Up Python in Windows Cl
icking 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 iF your version
ismewer, as tong as’s Python 3.x our code will work inside your
Python 3interface,
windows
FETTER Before you close the install wizard win
however it'sbestto dick on the link next tothe
shield detalled Disable Path Lenoth Limit This will allow Python
0 bypass the Windows 260 character limitation, enabling you to
‘execute Python programs stored in deep Folders arrangements.
‘Again, click Yes to authenticate the process; then you can Close the
installation window.
© Disable path length limit
lose
Windows 10 users will now
find the installed Python a
3.x within the Start button
Recently Added section, The
first ink, Python 3.6 (32-bit) Me
wil aunch the command
ine version of Python when
licked (more on that in a
moment) To open the IDLE,
ype IDLE into Windows start.
ur oem 26.1
f you now clk onthe Windows Sat button aga
SHEP) and this time type: CMD, you'll be presented with the
Command Prompt ink, cick to gett the Windows commandline
envionment. Toenter Python vin he command ine, ou need
touype-python and press Ener
BESERB) the command tne version of Python worksin
much the samme way asthe Shell you opened in
Step 8; note the three leftfacing arrows (>>>). Whilst its @ perfectly
fine environment, it’s not too user friendly, so leave the command
line For now. Enter: XTEC) to leave and close the Comman
Prompt windowSay Hello to Python
How to Set Up
Python on a Mac
Teer aia Ea CA Meena ner te ten Sen alee NSA a
Aero la Kola ANON ELK Te Vane) (Lea OMA Uem OL Col CORMIER Role MATTIANe)
TAC) Ca oOo
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.
FETTER Oven anew Terminal window by clicking Go> FETTER ick on the latest version of Python 3x in our
Utlities, hen double-click the Terminal icon. Now ase thsi the download button for Python 3.6.2.
enter: python’ =-version. Youshould see Python 2.5.1" and This will automatically download the latest version of Python and
even later, i Apple has updated the OS and Python instalation. ‘depending on how you've got your Mac configured, it automatically
Either way, i's best to check forthe latest version starts the installation wizard
PEPER) open safariang head over to www.python.org/ FETS withthe Python installation wizard open, click on
downloads, Just as with the Windows setup the Continue button to begin the installation. Its
procedure on the previous pages, ou 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 Coe Emad
BED 2228-0FPTSEDD The next section details the Software License
‘Agreement, and whilst not particulary interesting
to most folks it's probably worth a read. When you're ready, click on
the Continue button once again.
FETED Final you're be presented with the amount of
space Python will take up on your system and an
Install button, which you need to click to stat the actual installation
‘of Python 3.x on to your Mac. You may need to enter your password
to authenticate the installation process.
FSPTSEM) The installation shouldnt take too long; the older
‘Mac Mini we used inthis section isa little slower
than more modern Mac machines andit only took around thirty
seconds For the Installation Successful prompt tobe displayed,
How to Set Up Python on a Mac Cl
ESTEE There's nothing much else left to doin the Python
Installation wizard so you can click the Close button.
IF you now drop back into a Terminal session and re-enter the
‘command: python3 ==version, you can see the new version's,
now listed, To enter the command ine version of Python, you need
tocenter:python3. To ext, is: exitO.
BETESED You nced to search in Finder For the Python IDLE;
when you've found it, click to launch and it
should look similar to that of the Windows IDLE version shown on,
the previous page. The only difference being the Mac detected
hardware platform it's running on.
° Pen 80 Se
Pytnon 3.6.0 G9.6.8ehaF06Re3, bee 22 236, 17:23:0)
PC 4.23 Cppie nc. bute Se6) Cant 2] on arcin
ype Scorgsohty “crditet or svcaneeQ? for sore inforatin.
‘ws te Tam GiR (ancy eatin
PEPPER Older Macversions may have trouble with the
newer versions of Python, in which case you will
need to revert toa previous Python 3.xbuild;as long as you're using
Python 3.x the code in this book will work for you.
Python 3.1-2 (r312;79360M, Mar 24 2010, 01:33:18)
{6ce 4.0:1 (apple Ine. build 5493)} on’ darwin
Type "copyright", “credits” or "1icense()" for mo
pelnronmition.
wowpepubletions comSay Hello to Python
How to Set Up
Python in Linux
PYTHON PENGUIN
Linux is such a versatile operating system that it'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
FETTER) Fistyouncedto ascertain which version of Python EINEM some Linux distros will automatically update
iscurrently installed in your Linuxsystem; as we the instalation of Python to the latest versions
‘mentioned, we're going to be using Linux Mint 18.1 for this section. whenever the system is updated. To check, First do asystem update
‘Aswith macOS, drop intoa Terminal by pressing CtrlrAteT, and upgrade with
aa sudo apt-get update && sudo apt-get upgrade
Sere Enter your password and et the system do any updates.
PEPER Nextenter:python =-version into the Terminal VFM once the update and upgrade is complete, you
screen. You should have the output relating to ‘may need to answer'Y’ to authorise ary upgrades,
version 2.x of Python inthe display. Ours inthis particular caseis _enter: python. --version to see iF Python 3xs updated or even
Python 2.7.12. installed, n the case of Linux Mint, the version we have is Python
3.5.2, whichis Fine For our purposes.
davidedavid-mint
Fle Edit View Search Terminal Help
erst
oat
yon & Co CodingFETED Howeves iF you want the latest version, 3.6.2 as per
the Python website atthe time of writing, youneed
to build Python from source. Start by entering these commands into
the Terminal:
sudo apt-get install build-essential checkinstall
sudo apt-get install Libreadline-gplv2-dev
Libncursesw5-dev libssl-dev libsqlite3-dev tk-dev
Libgdbm-dev Libc6-dev Libbz2-dev
Open upyur Linx web browser ard to
EUERG the Python download page: www.python.org/
downloads. Clckonthe Download Pthon 3.62 (0 whee
version son vhen au oot to dwicadthe source Python
Seataocfle
Cee ure)
Inthe Teminal, go the Downloads folder by
Suey entering: ed Downloads/. Then unzip the
contents ofthe Gounladed Pytonsoure coce with tat AVE
Python-3.6.2. tar xz Now enterthe newly unpped folder
with ed Python-3.6.2/.
( How to Set Up Python in Linux
\within the Python folder, enter:
configure
sudo make altinstall
Sd
‘This could alittle while depending on the speed of your computer.
Once Finished, enter:python3.6 ==version to check the
installed latest version
For the GUIIDLE, you need to enter the Following
SIP) command into the Terminal:
sudo apt-get install idle3
‘The IDLE can then be started with the command: idLe3. Note, that
IDLE runs a different version from the one you installed from source.
ESTESET RD) You also need PiP(Pipinstalls Packages) whichis a
tool to help you install more modules and extras.
Enter: sudo apt-get install python3-pip
PIP then installed; check For the latest update with
pip3 install --upgrade pip
‘When complete, close the Terminal and Python 3x willbe available
via the Programming section in your distro's menu.
vwwwvpcgubezonscom — |Getting Started _
VViuan oa eaten ins
——»( Getting Started with Python
Getting started with Python may seem a
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.
Intthis 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 forthe 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
q
“Condit
Python Modules
wor plpubliationscomz= Getting Started with Pytho »)
Starting Python For
the First Time
WereSonic em
latest version of Raspbian comes preinstalled with Python 3, version 3.4.2 to be exact,
so as long as you have a version 3 Shell, all our code will work.
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
con that subject. However, once you're ready, fire up your Pi and get ready for coding.
FETTSEDD With the Raspbian desktop loaded, click on the FSTISED For cxample, inthe Shell enter: 242
‘Menu button followed by Programming > Python After pressing Enter, the next line displays the
3 (DLE). This opens the Python 3 Shell. Windows and Macuserscan answer: 4. Basically, Python has taken the ‘cade’ and produced the
Find the Python 3 IDLE Shell from within the windows Start button relevant output.
‘meni and via Finder.
‘The Shell is where you can enter code and see the ‘The Python Shell acts very much lke a calculator,
responses and output of code you've programmed since cade is basically a series of mathematical
into Python. This sa kind of sandbox, where you're able totry out interactions withthe system. Integers, which are 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 yo
ESTER While thats vey interesting it's not particularly
exciting. Instead, try this:
print(“Hello everyone!”)
ust lke the code we enteredin Sublime in the Installing a Text
itor section ofthis book
well as quote marks in order to output content to the screen, inthis
case the ‘Hello everyone! bit
>>> print(“Hello everyone! ™)
Helo everyone!
ES Te eA You may have noticed the colour coding within
the Python IDLE. The colours represent different
elements of Python code. They are:
Black Data and Variables
Green—Strings
Purple — Functions
Orenge- Commands
Blue — User Functions
Dark Red ~ Comments
Light Red -Error Messages
IDLE Colour Coding
[eotour [usetor [examples |
Purple [Functor | ten print
Daekred | Comments | Aaneaber VAR
FERED) The Python OLE isa configurable environment. IF
you don't like the way the colours are represented,
then you can always change them via Options > Configure IDLE and
licking on the Highlighting tab, However, we dont recommend
that, as you won't be seeing the same as our screenshots.
ae = Ss
PED ust tke most programs available, regardless of the
‘operating system, there are numerous shortcut
keys avallable. We don’t have room for them all ere but within the
Options > Configure IDLE and under the Keys tab, you can see alist
(of the current bindings.
PEPPER Te Pithon IDLE is apower interface and one
that’s actually been written in Python using one
‘of the available GUI toolkts. Fyou want to know the many ins and
‘outs ofthe Shel, we recommend you take afew moments to view
‘www.docs.python.org/3/library/idle.html, which details many oF
the IDLE’ Features.
a:z= Getting Started with Python
Your First Code
Essentially, you've already written your First piece of code with the ‘print("Hello
everyone!”)’ Function From the previous tutorial. However, let's expand that and look at
entering your code and playing around with some other Python examples.
PLAYING WITH PYTHON
With most languages, computer or human, it’s all about remembering and applying the right words to the right situation,
You're not born knowing these words, so you need to learn them.
TERED you've closed Python 3 IDLE, reopen itin
whichever operating system version you prefer. In
the Shell enter the Familiar following
print(*Hello”)
gee
ips eet a" fr mre train,
PEER sos v renin dovrtatonpensine
BED sosscetteoee,
's fairly straightforward and doesn't require too much explanation.
Now try
print(*212")
You can see that instead ofthe number 4, the
‘outputs the 2+2 you asked to be printed tothe
screen. The quotation marks are defining what's being outputted
tothe IDLE Shell to print the total of 2+2 you need to remove
the quotes:
print(2+2)
You can continue as such, printing 2+2, 46442343
{and soon ta the Shell. An easier way sto use a
variable, which s something we wil cover in more depth later. For
now, enter:Your First Code ¢ CG
\hatyouhave done here isassign the tesa
SuePS and b two values: 2 and 2. These are now variables,
which can be called upon by Python to output, add, subtract, divide
‘and So.on for as long as their numbers stay the same, Try this:
print(a)
print(b),
Ee ESB Spine Hwee
ESTEE The output ofthe last step displays the current
valves of both a and b individually as you've asked
them tobe printed separately. IF you want to add them up, you can
use the following:
print(avb)
‘This code simply takes the values of aand b, adds them together
and outputs the result
oe bash bn ean ee
FETED Yu can play around with different kinds of variables
and the Print Function. For example, you could
‘assign variables for someone's name:
nane="David”
print(name)
FEED ow let'sadda surname:
surnane="Hayward”
print(surname)
‘You now have two variables containing a frst name and a surname
‘and you can print them independently,
ie beh pg ons nds be
BETTER ve were to apply the same routine as before,
sing the + symbol, the name wouldnt appear
New File. This will open a new window Inthe IDLE Editorasitisin the Shel, enabling you
with Untitied as its name. Thisis the Python IDLE Ealtor and within it to better understand what's going on with your code. However, to
Yyou can enter the code needed ta create your Future programs. ‘execute the code you need to first save it Press FS and you get a
Save...Checkbox open,
le ee
FTE The OLE Editors, forall intents and purposes, a FeTe DD ick on the OK button in the Save box and select a
simple text editor with Python features, colour destination where you't save all your Python code.
coding and so on; much in the same vein as Sublime. You enter ‘The destination can be a decicated Folder called Python or you
code as you would within the Shell so taking an example from the _canjust dump it wherever you lke, Remember to keepatidy drive
previous tutorial, enter: though to help you out inthe Future.
print(*Hello everyone!") eneera neersC Saving and Executing Your Code Cl
Enter aname for your code, ‘print hello’ for
‘example, and clickon the Save button. Once the
Python code is savedit's executed and the output willbe detailed in
the IDLE Shell n this case, the words Hello everyone!
FERED Thisishow the vast majority of your Python code
willbe conducted, Enter itinto the Editor, hit 5,
save the code and look atthe output inthe Shell Sometimes things
will fer, depending on whether you've requested a separate
‘window, but essentially that’s the process.’ the process we will
se throughout this book, unless otherwise stated
Ifyou open the file Location ofthe saved Python
code, you can see that it ends in a py extension.
Thisis the default Python file name. Any code you create will be
\whateverpy and any code downloaded from the many Internet
Python resource sites willbe. Just ensure that the code is written
for Python 3
Lets extend the code and entra few examples
Sues from the previous tutorial:
a2
b=?
‘name="David”
surnane="Haynard”
print(nane,. surname)
print (asb)
IF you press FS now youll be asked to save the fe, again, as t’sbeen
modified from before.
FETED you click the OK button, the filewill be
‘overwritten with the new code entries, and
‘executed, withthe output in the Shell k’snot a problem with just
these few lines but if you were to edt a larger file, overwriting can
become an issue. Instead, use File > Save As from within the Editor
tocreatea backup,
motes,
FEET RD) Now create a new file. Clase the Editor, and open
‘anew instance File» New Fie from the Shel).
Enter the following and save tas hellopy:
‘ax"Python”
beris”
c="cool!”
print(a, b, ¢)
‘You will use this code in the next tutorial
ninGetting 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
inthe GUI at the command line level.
Dihonintnnoneswintopestiewnsct EEG) vow oreatine canard ine we cos
theres the Python 3tbraries command python and press Enter Ts wl pu you othe
hough, drop into the command tine or Terminal on ynand line version of the Shel, withthe Familiar three right
FETED fom here you're able to enter th
looked at previously, suchas:
a-2
printCa)
‘You can see that it works exactly the same.
and macOS u get access
10 their command line by clicking
Go> Utities» Terminal
yon & Co CodingExecuting Code from the Command Line Cl
ERED terccert0:cteteconnontinesion EEEEPB sh esting eon cae rom te
mpt. Enter the Folder where you saved the code from the joesn't error out in any way, due to the differences between the
previous tutorial and list the available Files within; hopefully you way Python 3 handles the Print command over Python 2, the result
should see the helo.py ile isn't as we expected, Using Sublime forthe moment, open the
hellopy file,
aa -
FETTER From within the same folder asthe code you're FETED Since Sublime Text isn't avallable For the Raspberry
‘ong 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 hello. file open, alter itto
include the following:
python3 hello. py
This will execute the.
fe we created, which to remind you's: . «
nane=input(“What is your name? “)
a="Python” print(*Hello,”, name)
boris?
c="cool!” a
print(a, b, <)
ay
python3 hello. py
PCLT. ‘The result wil be the original Python is cool! statement, toge
with the added input command asking you For your name, and
displaying iin the commat
woowpemubicsionscon CERIN@) Getting Started with Python
Numbers and Expressions
Met eeu oe ear uel can Area RICE CMM n Ts
MR ork a MEU Cd eam eM aaa] at Ikon (oll)
UML AUN ent PA RSIn1 Col meat ee oR UATen AUREL Co
IT’S ALL MATHS, MAN
You can get some really impressive results with the mathematical powers of Python; as with most, if not all, programming
languages, maths is the driving Force behind the code.
Speipthecuvesionatton3.cimentones TREE Youceniae te nmatensta opto
em you can use either the Shell or the Editor. For the Sua? divide, multiply, brackets and so on. Practise with a
time being, you're going to use the Shelljustto warm our maths ew, For example:
smuscle, which we believe isa small gland located at the back ofthe
ve
brain or not)
o2
24283
G2)+"4)
ee Sets tt me bon
PEPER the shell enter the following: PEI You've no doubt notice, division produces a
— decimal number. In Python these are called oats,
‘oF floating point arithmetic. However, you need an integer as,
4356434953245,
Se ‘opposed to adecimal answer, then you can use a double lash:
ve
You can see that Python can handle some quite large numbers —
‘And soon,C Numbers and Expressions Cl
‘oun also wean operation tosee the remainder
SuePS left over From division. For example:
10/3
‘ill display 3.333333333, which i of course 3.3-ecurting Ifyou
nowenter:
103,
‘This ill display 1, which i the remainder let over From dividing 10
into 3,
FETED Next upwe have the power operator or
exponentiation f you want to be technical. To work
‘ut the power of something you can use 3 double multiplication
symbol or double-star on the keyboard:
a3,
10°10
Essentially, is 2x2x2 but we're sure you already know the basics
bbehind maths operators. This show you would workit out Python,
BETA) This willbe splayed as‘0b11, converting the
integerinto binary and adding the prefixOb tothe
front. Fyou want to remove the Ob prefix, then you can use
Format(3, ‘b")
‘The Format command converts value, the number 3,t03
Formatted representation as controlled by the Format specication,
the’ part
ESTESED 4 800lean Expression isa logical statement that wil
either be true or False, We can use these to compare
data and test to see fit's equalt, less than or greater than. Try this
ina NewFile:
a-=6
i -
print(1, a == 6) 5
print(2, a == 7) i
print(3, a == 6 and b == 7) E
print(4, a == 7 and b == 7) EE
print(S, not == 7 and b == 7)
print(6, a == 7 or b == 7)
print(?, a == 7 or b == 6)
print(s, not (a == 7 and b == 6))
print(9, not a == 7 and b == 6)
Numbers and expressions don't stop there. Python
has numerous builtin Functions to work out sets
(of numbers, absolute values, complex numbers and a host of
‘mathematical expressions and Pythagorean tongue-buisters. For
‘example, to convert @ number to binary, use:
bina)
Execute the code from Step 9, and you can see a
series of True or False statements, depending on
the result of the two defining values: 6 and 7. t's an extension of
‘what you've looked at, and an important part of programming.
wncncnn CS@) Getting Started with Python
Using Comments
ICU AO Rm REN CIC a Tar
Perce MR oll Ne se OTe Mola Telekom aol]
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. fa variable is used, the
‘programmer comments on what it’s supposed to do, for example. I's just good practise.
PETER) Seercby creating anewinstance ofthe OLE Editor — RINE esave the code and execute it. You can see thatthe
(File > New Fle) and create a simple variable and ‘output in the IDLE Shell is stil the same as before,
print command: despite the extra lines being added. imply put, the hash symbol (#)
a ‘denotes ane of text the programmer can insert to inform them,
print(“The value of A is,”, a) ~and others, oF what's going on without the user being aware.
Save the file and execute the code. i Phen 42 Sel EE J
Gaorer gy paralplbonmen fyten Comtamnerpra) = = =
(ie ea Fame in tnt dom te
ESTEE Punning the code willreturn the ine:The value of A [ESTESAWM Let's assume that the variable that we've created
is, 10intothe IDLE Shell window, which is what we Is the number of lives ina game. Every time the
expected. Now, add some ofthe types of comments you'd normally player dis, the value is decreased by 1. The programmer could
seewithin code: insert aroutine along the lines of
# Set the start value of A to 10 asa-1
0-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)vs
(Us Ce It:
(Using Comments Cl
hist we now that the variable Ais ves and
Gus that the player has just lost one, a casual viewer or
someone checking the code may nat now: Iagine fora moment
thatthe coe s twenty thousand Ines lon, stead of stout
seven, Youcan se howhands comments ar
nine comment ar comments that follow asecton
Gua3 of code. Take our examples from above, instead of
inserting the code on a separate tne, we could use:
0-10 # Set the start value of A to 10
print(“The value of A is,”, a) # Print the current
value of 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)
Essentially the new code together with comments
STEP
could look tke:
# Set the start value of A to 10
o-10
# Print the current value of A
print(“The value of A is,”, a)
# Player lost a life!
ana-1
4 Inform player, and display current value of A
lives)
print(*You've just lost a life!”)
print(*You now have”, a, “Lives left!")
FETED The comment, the hash symbol, an also be used to
comment out sections of code you don't want to be
‘executed in your program. For instance if you wanted to remove
the fist print statement, you would use:
# print(“The value of A is”, a)
eee
[eset the start value of A to 10
F Peine the current value of A
Je peintc"The value of & is.", ail
fe Player lost'a ite!
oot
#Toform player, and display current value of A (Lives)
prine(-You've just lost a life!"
Heranct-vou now have", a, “lives left
You can use commentsin different ways, For
example, Black Comments are a large section of
text that details what's going on in the code, such as telling the code
reader what variables you're planning on using:
4 This is the best game ever, and has been
developed by a crack squad of Python experts
¥ who haven’t slept or washed in weeks. Despite
being very smelly, the code at Least
# works really well.
You also use three single quotes to comment.
‘out a Block Comment or multiline section of
‘comments. Place ther before and after the areas you want to
‘comment for them ta work:
This is the best game ever, and has been developed
by a crack squad of Python experts who haven't
slept or washed in weeks. Despite being very
smelly, the code at least works really well.z= Getting Started with Python
Working with Variables
AWARE Con ecu) LLANE 1 CMe LM ene K soe F-]k-2-[eh At ELEN S
Merona iituReercnanenbece tues eitecaeia)
NUTONE
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 pr
IDLE Shell to clear up any old code.
FS on vcswomsinnssonanecasce
nane="David Hayward’ (or use your own name, unless you're
also called David Hayward).
ie at Sh Guy pens wn
‘You've seen previously that variables can be
Sua? concatenated using the plus symbol between the
variable names. In our example we can use: print Cname + “:
“ + title). The middle part between the quotations allows us to
adda oon anda space, asvaibesare connected tout spaces,
Sowe edo add them menvaly
[Be ESS) on Ete om ne
PEPISPD) You can check the type of variable in use by
issuing the type ()cornmand, placing the name of
the variable inside the brackets. In our example, this would be:
type name). Add anew string variable: title="Descended
from Vikings”.
PIR Youcanaiso
combine variables
within another variable. For
‘example, to combine both name
and title variables into anew
variable we use:
charactersname +“: “+
title
‘Then output the content of the
new variable as:
print (character)
Numbers are stored as different
variables:
age~44
‘Type (age)
(Which, as we know, are integers.@ Working with Variables Cl
BEER Howeves, you can’t combine both strings and
integer type variables inthe sare command, a5 You
would a set of similar variables. You need to either turn one into the
‘other or vce versa. When you do try to combine both, youget an
error message:
print (name + age)
Thispreset bit oF roblem when wan to
SS work with a number that's been inputted by the
use a5 age + 10 wont work due to beng astrng arable and an
inteoe.nstend, you need enter
int(age) + 10
‘This ill TypeCast the age string into an integer that can be
‘worked with,
FETTER Thisis2 process known as TypeCasting. The Python
codes:
print (character + “is “ + str(age) + “ years
old.)
or youcan use:
print (character, “is, age, “years old.”)
‘Notice again that inthe last example, you dont need the spaces
between the words in quotes as the commas treat each argument
to print separately
>>> print (nane + age)
Traceback (ost recent call last):
File “", Line 1, in
rine’ (name * age)
typebrror: can't convert “int* object to str implicitly
BiB sprine (character's. is'= + str(age) +" years. old’
David Haynard: Descended from Vikings iz “4 years old.
S3Sprant (character, "is", age, "years old."
David Hayward: Descended from Vikings is 44 years old.
Sa
FETED The use of Typecastingis aso important when
dealing with floating point arithmetic; remember:
‘numbers that have a decimal point in them. For example, enter:
shirt=19.99
Now enter type(shirt) and you'llsee that Python has allocated
the number as a oat’, because the value contains a decimal point.
Python 54.7 Coefoule, Get TB 2048, 13:31 TV)
ee 9.1 ot hie
SB enaeeeiatbs
Méredits” or “License()* for nore information.
FETED “nother example of TypeCastingis when you ask For
input from the user, such as a name. for example,
enter
‘age= input (“How old are you? “)
All data stored from the Input command isstored asa string variable.
fle Gat Shel Debug Options wndows Hee
‘when combining integers and floats Python
usually converts the integer to a float, but should
the reverse ever be applied i's worth remembering that Python
doesn't return the exact value, When converting a oat to an
integer, Python will always round down to the nearest integer,
‘called truncating; in our case instead of 19.99 t becomes 19,
eat 8 og prs sna
Re eae ee a TT
FE Se eta cmt fr me inant
saree
Ey
onc@) Getting Started with Python
User Input
WASTE Co) uid erie ee Leno a ea Reels ice Ro mn elu od
earlier, so now would be a good time to Focus solely on how you would get information
Tee mace ahe ccna
USER FRIENDLY
The type of input you want From the user will depend greatly on the type of program you're coding. For example, 2 game may
‘ask for a character's name, whereas a database can ask For personal details.
ESTEE it’s not already, open the Python 3 IDLEShell, Bene Now that we have the user's name stored ina
and tart a New Fie inthe Editor Let's begin with couple of variables we can call them up whenever
‘something really simple, enter: we want:
print(“Hello") printC‘Welcone”, firstname, surname, “. T hope
firstname=input(“What is your first nane? “) you're well today.”)
print(*Thanks.")
‘surnane=input(“And what is your surname? “)
FREED Se and execute the code, and as you alreadyno ES EESPIB Run the code and you can see a sight issue, the
doubt suspected, in the IDLE Shel the program will full stop after the surname follows a blank space.
ask for your first name, storing its the variable Firstname, followed To eliminate that we can add a plus sign instead ofthe comma in
by your surname; also stored in its own variable (surname). the code:
printC‘Welcone”, firstname, surnames‘. I hope
you’re well today.”)(User input Cl
iG P|
‘ou dort abays haeto nude quoted tex thin
SuePS the input command. For example, you can ask the
User thername, and have the nput inthe Ine below
print(“Hello. What’s your name?”)
name=inputQ
serinput py - Jhome/pi/Documents/Python Code/us!
[Ele Edt Farmat fun Options Windows Help
What youve create heres codon, which we
Sues will cover soon. In short, we're using the input From
theuser and mesuingit against condton So the ser enters
Davids ther name, the guard willow them to pass unhindered
Ete, they enter name other than Da, the guardchalenges
themto afight
iprant( elle, What's your ane?)
F ramesinpst()
ESTEE te cove from the previousstep soften regarded
asbeing alittle neater than having alenathy
amount of text inthe input command, but t's not rue thats etn
stone, so do as you likin these situations. Expanding onthe code,
ythis:
print(*Halt! Who goes there?”)
rnane=input)
ESTEE DD st 25,00 learned previously, any input from a
Users automatically string, soyou needto apply a
“TypeCastin order to turn it into something ese. This creates some
interesting adctions tothe input command. For example:
# Code to calculate rate and distance
print(“Input a rate and a distance”)
rate = floatCinput(“Rate: “))
ES TeGEAD 52 g00d tart to atext adventure game, perhaps?
Now you can expand on t and use the raw input
from the user to flesh out the game alittle:
if nane=="David":
printC*Welcome, good sir. You may pass.")
else:
print(*I know you not. Prepare for battle!
BPTD) %o finalise the rate and distance code, we can ade:
distance = float Cinput(“Distance: “))
printCTime:”, (distance / rate))
Save and execute the code and enter some numbers. Using the
Float(input element, we've told Python that anything enteredisa
floating point number rather than a string
wnoncnnz= Getting Started with Python
Creating Functions
INC e RTT Cel R CREE econ RUS iR NT] ONCE Ne MSM aoe ea Mn cto eLel dC
CiMten (oie UAUELCcTeMUSteRCAW AT ee Se CA eS eco eho a ea1e0A)
enables you to define your own functions.
FUNKY FUNCTIONS
‘A function isa command that you enter into Python to do something. It's alittle piece of self-contained code that takes data,
‘works on it and then returns the result,
RS x natnnremtonusoen heen
length or type oftems. Basically, a function isa short word that's
Followed by brackets. For example, len(,list0 or type().
et aro tm oe teri,
‘Afunction takes data, usually variable, works on
Tedepending on what the Function is programmed
to do andreturnsthe end value. The data being worked on goes
Inside the brackets, so if you wanted to know how many letters
are in the word antidisestablishmentarianism, then you'd enter:
Len¢“antidisestablishmentarianisn’) and the number 28
would return,
Fare RD You can pass variables through functions in much
the sare manner. Let's assume you want the
number of letters in person's surname, you could use the following
code (enter the text editor for this example):
‘name=input “Enter your surmane: “)
count=Len(nane)
print (*Your surname has“, count, “Letters in
it.”)
Press FS and save the code to execute it.
Python has tens of functions builint i, Fartoo
‘many to get intoin the limited space availabe here.
However, o view the list of builtin functions available to Python 3,
navigate to wwww.docs.python.org/3/library/Functions.htm, These
arethe predefined functions but since users have created many
more, theyrenot the only anes available.( Creating Functions Cl
Additional functions can be added to Python
through modules. Python has vast range of
‘modules availabe that can cover numerous programming duties,
‘They ad functions and can be imported as and when required, For
‘example, to use advanced mathematics Functions enter
‘import math
‘Once entered, you have access to all the math module Functions.
Tose funcionfrom a module ete the name of
SIS the module followed by a full stop, then the name
(of the Function. For instance, using the math modu, since you've
just imported it into Python, you can utilise the square root Function,
To.doso, enter
math. sqrt(16)
‘You can see thatthe code is presented as module function(data.
FORGING FUNCTIONS
fF
i Es Cee pena arr cid
pee oe eeu a eee Seu ees
e
ee eee:
print (“Hel to™)|
Reto)
Cee
(ile
Paes
Eee
ecu eals
Ey
{def HelloCnane):)
print C"Helto™, nane)}
HeLloC David}
en ee
eerie
oe
eee aad
ar
the last line in th
cre
co
What you've just done i import the Hella Function
From the saved Hello.py program and then usedit
i, This is how modules and functions work: you
wuwwecgubicatonscam —z= Getting Started with Python
Conditions and Loops
(eon ORE CO Se MURA eT es ered en eT LL
ele meoly ol eag OWA UMM Tu Ke one Sek CNMI Ane Cele NRK}
achieve; they could be the number of lives left in a game or just displaying a countdown.
TRUE CONDITIONS
Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let's start then by checking
if something is TRUE, then doing something else iftisn't.
eG RED t's create 2 new Python program that wil ask FETED Now you can use anif statement to check ifthe
the user to input a word, then check ito see it's word length variable is equal to Four and print a
a fourletter word or not, Startwith Fie > New Fle, andbeginwith friendly conformation fit applies tothe ule:
ea 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 (nord, “is a four-letter word. Well done.
‘The double equal sign (-=) means check something is equal to
something else.
PEPTSP DD Now we can create anewvariable,then use helen [EBB the colon atthe end off tells Python that if this
Function and pass the word variable through it to
statement i true do everything after the colon
‘get the total number of letters the user has just entered: that'sindented. Next, move the cursor back to the beginning of
word=input (“Please enter a four-letter word: el
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
re een ert 7
else:
print (word, “is not a four-letter word.)Press FS and save the code to excite Enter
Gu a four-letter word in the Shell to begin with, you
should havethe returned message that tthe word four eters
Now pest apn an rerun te rogram baths tne enter,
fetter word The Sell play tats nota foucltter word
LOOPS
(Conditions and Loops Cl
Now expand the code to include another concitions.
SUS 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 == 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.)
‘Aloop looks quite similar to a condition but they are somewhat different in their operation. A loop will run through the same
ee Re iene ee nse eae
f
recat
Ce ney
ore
check tos
PEPER the citference between if and while is when while
Cee are
Pee
pniee vec:
sete ey
ints the current value of x, then adds on
Seemed
that value, When x do
ae ees
eet er tee)
eee terse roe ae
jrords-[*Cat™, “Dog™, “Unicorn™
for word in words:|
print Cword))
ae nse ieee
STEP 4
ates
for xin range C1, 10):)
print Go]
ec
eee
semenGetting 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,
Although good, the builtin functions within Python
are limited. The use of modules, however, allows us
10 make more sophisticated programs. As you are aware, modules
| step2 ) ‘Some modules, espedially on the Raspberry Pi
are included by default, the math module being a
prime example. Sadly, other madules aren't always avallable. A good
‘example on non-Pi platformss the pygame module, which contains
many functions tol Ty: import pygame.
yon & Co Coding
FED The resuttis an errorin the DLE Shell asthe
pygame module isn't recognised or installed in
Python. To install a module we can use PIP (Pip Installs Packages)
Close down the IDLE Shell and drop into a command prompt or
Terminal session, At an elevated admin command prompt, enter:
pip install pygane
BEEP the PP installation requresan elevated status
due it installing components at different locations.
Windows users can search for CMD via the Start button a
the result then click Run as Administrator. Linux a
the Sudo command, with sudo pipr
(Python Modules Cl
Close the command promt or Terminal and
SuePS relaunch the IDLE Shell. When you now enter:
import. pygane, the mode wl be Imported into te code
whout ary problems, Yul find that most code downloaded o
Copied from the tenet il contain a module, manstream of
trigue, thes are sul the source of eosin exeation veto
them bing missing
‘Multiple modules can be imported within your code.
To extend our example, use:
import random
import math
for I in range(s):
print(random.randint(1, 25))
print(math.pi)
a
“The modules contain the extra code needed to
Siar
achieve a certain result within your own code, as
we've previously experimented with. For example:
‘import random
Brings in the cade From the random number generator module. You
can then use this module to create something ike:
for i in range(10):
printCrandom.randint(1, 25))
a
‘The result is string of random numbers Followed
bythe value of Pi as pulled from the math module
using the print(math,pi Function, You can also pullin certain
Functions from a module by using the From and import commands,
such as:
from random import randint
for i in range(s):
printCrandint(1, 25))
a
This code, when saved and executed, will display ten
random numbers from 1 to 25. You can play around
with the code to display more or less, nd from a great or lesser
range. For example:
‘import random
for i in range(25):
printCrandom.randint(1, 100))
‘This helps create a more streamlined approach to
STEP 10
programming. You can also use import modules,
‘which wil import everything defined within the named module.
However, it's often regarded as a waste of resources but it works
nonetheless. Finally, modules can be imported as aliases:
import math as m
print(m.pi)
‘Of course, adding comments helps to tel others what's going on,
Daten evita A - ax
oncom CSa
woe
aah i)
oi fe( Working 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 lis
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
64 Python Graphicseer eon Toe Rated aU Celery
Python. A list is simply a collection of items, or data if you prefer, that can be accessed
Pee emu ict na Tench
WORKING WITH LISTS
Lists are extremely handy in Python. list can be strings, integers and also variables. You can even include Functions
and lists within lists.
ists,
Aliisasecunceof asad er cu EREERE Youcon stones rinse Renny
SIE create the name of your list Followed by an equals Sua? using the minus sign before the item number [1],
sign, then square brackets and the tems separated by commas; _orthe second to last item with [2] and so on. Trying to reference an
ote that strings use quotes: iter that iat in the list, such as [10} wil return an exror:
numbers = [1, 4, 7, 21, 98, 156] unbers [1]
mythical_creatures - [“Unicorn”, “Balrog”, imythical_creatures[=4]
“Vanpire”, “Dragon”, “Minotaur"]
FETED <2 you've defined your list you can call each FETED Stcing issimitar to indexing but you can retrieve
by referencing its name, followed by anumber. Lists ‘multiple tems na lst by separating tem numbers
start the first item entry as 0, Followed by 1, 2,3 and so on, with a colon. For example:
For example: unbers[1:3]
GinbsrE will outputthe 4 and 7, being item numbers 1 and 2. Note that the
Tocall up the entire contents of the list. returned values dontinclude the second index postion (as you
3021 would numbers[t:3] to retum 4, 7 and 21)
To call the third From zera temin the lst (21 in this case).‘You 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=nunbers+[201]
Or for strings:
nythical_creatres-nythical_creatures+[“Griffin"]
(Or by using the append Function
mythical_creatures.append(“Nessie”)
‘nunber's .append(278)
Removal of tems can be done in two ways. The first
Sis
Isby the tem number:
del nunbers[7]
Altematively, by item name:
mythical_creatures. renoveC“Nessie”)
Youcanview what can be dane wth sts by entering
IS dir(list) Into the Shell. The output is the available
Functions, for exemple, insert and pop are used to add and remove
items at certain positions To insert the number 62 at item index 4
hunbers-insert(4, 62)
To remove:
runberspopC4)
Bcd
ito its components. For example:
list(“David”)
Breaks the name David into
toanewlist
You also use the list function to break a string down
Thiscan then be passed
ane=List*David Hayward”)
rane
oge=[44)
User = nane + age
user
Based on that, you can create a program to store
STEP 10
someone's name and age as alist:
hane=inputCWhat”s your name? “)
‘Uname=List(name)
‘age=intCinput (“How old are you: “))
‘Lage-[age]
user = Inane + lage
‘The combined name and age lists called user, which canbe called
by entering user into the Shel. Experiment and see what you can do,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
Pred OMe Ke lcd
THE IMMUTABLE TUPLE
Reasons for having tuples vary depending on what the program is intended to do. Normally, a tuple is reserved for something
special but they/re also used for example, in an adventure game, where non-playing character names are stored.
FETED stuvieiscreated the samewayasalistbutin this EIB youcan create grouped tuples into lists that contain
instance you use curved brackets instead of square ‘multiple sets of data. For instance, here is tuple
brackets. For example: ‘called NPC (Non Playable Characters) containing the character name
twonths=C*January”s “February”; “March; “Aprit®, dhe combat ating For an adventure game:
“way”, “June”) NPC=[C*Conan™, 100), (“Belit”, 80), (“Valeria”,
months 95)]
| eat ont gee oe wae oe
er ae eae er Sar ey os
PPE DD ust acwith ists, che items within anamed tuple can [PRIMM cach of these data items can be accessed asa
be indexed according to their position inthe data whole by entering NPCinto the Shell or they can be
range, te indexed according to ther postion NPC), You can also index the
months] indvual tuples within the NPC list:
mmonths[5] Neco} t1)
However, any attempt at deleting or adding tothe tuple will result willisplay 100.
inan errarin the Shel,isworhrcingttwbenfeereng mute ETERS Now srk tetera 0
SuePS tuples within a list, the indexing is slightly different. Sues corresponding variables:
from the norm. Yuwould expect te 95 combat rating ofthe
character Valeria to be NPC[4][5], but it’s not. It’s actually: Come pesca naDEHES
nectz101) You can now check the values by entering name and combat. rating,
Mes erep em Set Mae” o “mn fo sre tomato
FETISED Remember, as with sts, you can also index tuples
Using negative numbers which count backwards
From the end of the data list. For our example, using the tuple with
multiple data tems, you would reference the Valeria character with:
Nec2I[-0
Which a you can mapine,getsa ite confusing when you've gota
lotof tuple data to deal wth eee elise
BSTSE DD Terlesthough utilise a Feature called unpacking, BNR) You can use the max and min functonsto find the
where the data items stored withina tuple are highest and lowest values ofa tuple composed of
assigned variables. First create the tuple with two items(nameand numbers. For example:
combatting) runbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99)
NPC=C*"Conan”, 100) ‘The numbers can be integers and floats. To output the highest and
lowest, use:
print (max(nunbers))
print(minCnunbers))Terre eaten eu TE NAC a arlene Ay
of dealing with data items, They can be tricky to get to grips with at first but you'll soon
ITED eo MnO oll men aole a
KEY PAIRS.
alist but instead each data item comes as a pal
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.
FETE RED t's sev you want to create a phonebook in Python.
‘You would create the dctionary name and enter
the data in curly brackets, separating the key and value by 8 colon
Key:Value. For example:
phonebook={“Enma”: 1234, “Daniel”: 3456, “Hannah”:
6789}
Just as with most lists, tuples and so on, strings
Siar
need be enclosed in quotes single or double),
whilst integers can be left open. Remember thatthe value can be
either a string or an integer, you just need to enclose the relevant
‘one in quotes:
phonebook2=
David": “0987 654 321"}
Aswith sts and tuples, youcanchekthe contents
Sua? of a dictionary by giving the dictionary a name:
phanebook inthis example This ply the tatemsyouve
tetered na sina fshion toast whch youre no dove farsa
with by now,
Ree
‘The benefit of using a dictionary s that you
Bary
canenter the key to index the value. Using the
phonebook example from the previous steps, you can enter:
phonebook [“Enma”]
phonebook [*Hannah‘Adding toa dictionary esto. Youcan include
SuePS anew data item entry by adding the new key and
vale ems the
phonebook[“David"] = “0987 654 321”
phonebook
Nest, you need to defn the wsernputs and
Sues variables: one for the person's name, the other
for their phone number (let's keep it simple to avoid lengthy.
Python coe
ane=inputC“Enter name:
hunber=intCinputC“Enter phone nunber: “))
BETTS You can also remove items from a dictionary by
Issuing the del command Followed by the item's
key; the value willbe removed as wel since both work as a pair of
data items:
el phonebook[*David"]
STEI "Note we've kept the number as an integer instead
(ofa string, even though the value can be both
~aninteger ora string, Now you need to add the user's inputted
variables to the newly created blank dictionary. Using the same
process asin Step 5, you can enter:
phonebook{nane] = nunber
Taking this astep further, how about creating a
piece of code that will ask the user forthe dictionary
key and value items? Create a new Ecitor instance and start by
coding in a new, blank dictionary:
phonebook={}
fags.
Now when you save and execute the code, Python
willask For a name and a number. fe will then insert
those entriesinto the phonebook dictionary, which you can test by
entering nto the Shel
phonebook
phonebook[“David”]
IF the number needs to contain spaces you need to make ita string,
so remove the int part ofthe input.
ww pgubieatons com