14g Python 3 | C++|Working with Code (|
Pythons.
for Beginners
Learning to code for students, for
work, for fun, for everyone
p |
£999 fl | 33
ll
77 204%"990036Discover more of our complete
manuals on Readly today...
eS
ican The Complete The Complete
coo (Ubuntu | Linux Mint
Manual Manual Manual
Sy
See
WhatsApp
The Complete
Building Your
Own PC
Manual
Manual
‘Android | The Complete AG ia
lordPress
marot Google Manual
Mantal
Pe compite on ees
Outdoor Black & White Landscape
ait hy Photograph
Photography sa Wey Y
Manual‘| BD's Definitive Guide Series
Python:.C:
for Beginners
“Most good programmers do programming not
because they expect to get paid or get adulation
by the public, but because it is Fun to program.”
~Linus Torvalds (developer of the Linux kernel)
Having a basic knowledge of programming can open many different doors
for the newcomer to explore. You can understand how hardware and
software work together better, 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 andit’sall 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!
iy] @bdmpubs Gi BDM Publications ‘[Link]\
Contents
‘ontents_)
6 ) Say Hello to Python 60 Writing to Files
62 Exceptions
8 _WhyPython? 64 Python Graphics
10 Equipment You will Need
12 Getting to Know Python
14 Howto Set Up Python in windows.
16 How toSet Up Python on a Mac
18 How toSet Up Python in Linux
68 Calendar Module
70 OSModule
72 Random Module
CRG euch 74 _Tkinter Module
76 Pygame Module
22 _ Starting Python for the First Time 80 Create Your Own Modules
24 Your First Code
26 Saving and Executing Your Code 82) Say Hello to C++
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
84 WhyC+?
86 Equipment Needed
88 How to Set Up C+ in Windows
90 How to Set Up C++ on a Mac
92 How to Set Up C++ in Linux
94 Other C+ IDEs to Install
Cea CU
44) Working with Data
98 Your First C++ Program
46 Lists 100 Structure of a C++ Program
48 Tuples 102 Compile and Execute
50 Dictionaries 104 Using Comments
52 _ Splitting and Joining Strings 106 Variables
54 _ Formatting Strings 108 Data Types
56 Date and Time 110. Strings
58 Opening Files 112 C++ Maths
BE) 20sec sete veine3dQS c ons GURU kere
116 User interaction 138 Common Coding Mistakes
118 Character Literals 140 Python Beginner's Mistakes
120 Defining Constants 142 C++ Beginner's Mistakes
122. File Input/Output 144 Where Next?
> EEE
126 while Loop 148 Python File Manager
128 For Loop 150 Number Guessing Game
130 Do... While Loop 152 Polygon Circles
132 Statement 153 _ Random Number Generator
134 If... Else Statement 154 Random Password Generator
155 Keyboard Drawing Script
‘It’s OK to Figure out murder mysteries, 156 Pygame Text Examples
but you shouldn’t need to Figure out code. 157 Google Search Script
You should be able to read it.” 158 Text Adventure Script
~ Steve McConnell (Software Engineer and Author) 160 Hangman Game Scriptindex)
Say Hello
to Python
“How did you know so much
about computers?”
“| didn’t, it was the first one.”
~ Admiral Grace Hopper (pioneer programmer)
when interviewed by David Lettermanora bmpublcations com
Say Hello to Python
‘There are many different programming
languages available to learn and use. Some
are extremely complex and incredibly
powerful, while some are extremely
basicand used as minor utilities For the
‘operating system. Python sits somewhere
in the middle, combining ease of use with
generous helping of power, which allows
the user to not only create small projects
butalso 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; 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 Python, and from there
guides 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 aMac
18 How to Set Up Python in LinuxED) sriiioron
Why Python?
REET icns ae cuneate ee Cees eu kcout sin
Pee eee eh aisedticeicmscue ato lentes
are designed For scientific work, others for mobile platforms and such. So why choose
Python out of all the rest?
PYTHON POWER
Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee
hours, slaving over an overheating heap of circuitry to create something akin to magic.
‘These pioneers of programming carved their way into anew Regardless of whether you use an Android device, 10S device, PC,
Frontier, Forging small routines that enabled the letter '®'to scroll Mac, Linux, Smart TV, games console, MP3 player, GPS device builtin
across the screen. It may not sound terribly exiting to ageneration to aca, settop box ora thousand other connected and ‘sma
‘that's used to ultra high-definition graphics and open world, multi appliances, behind them alis programming,
player online gaming, However, forty-something years ago it was.
inaly brillant. All those aforementioned digital devices need instructions to tell,
‘hem what to do, and allow them tobe interacted with, These
"Naturally hese bedraom coders helped form the foundations for instructions Form the programming care of the device and that care
‘every piece of digital technology we use today. Some went onto can be built using a variety of programming languages.
‘become chief developers for top software companies, whereas
‘others pushed the available hardware to its imits 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 ts
certssontsenttonst
oid Arrayctrl::childLostrocus()
seraycerl::Paint(Orave ») (
urtaamet Paine):
1) =o)
)
Galor fe » Blend(scoloroieabled, ScolorPaper):
Stata)
siete earcamey
frbottom © Fekop + oateanecy(a):
Torddne 5
< [Link](); 344) ¢
int by Roeder GatracisdehO)
nt em = cotumni3] mara
Feces a
for Tay) ctrrain(s
ree ieeeenvironment or users. Operating systems, such as Windows, macOS
{and such are usually @ 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 soon,
‘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 nown as a High-Level Language, in that it ‘talks
to the hardware and operating system using a variety of arrays,
variables, objects, arithmetic, subroutines loops and countless
more interactions, Whilst t'snatas streamlined as a Low-Level
Language, which can deal directly with memory addresses, call
stacks and registers, its benefitis that it's universally accessible
and easy to learn.
import java. [Link].*;
‘lass. Tavoke
Public static void main( string [] args )
try
Gass ¢
Method’
Ut 3s
Object het = msinyokeC mul1, nuT1 95
Sybten-out princinc
STavoked seats method: " + args(1]
yofenass: * *args(o)
+" wich no-args\onesules: + ree >;
catch ¢ Classnotroundexception ¢ ) {
{7° Classcforname(.)- can't finds the-class
Caren C fosuchmethodexception 2) {
[fat method doesnt exioe
Gaceh ( TMlegataccesstxception 3
Fre don't Rave peraission eo favoke that
‘sss. fornane( args(0)
“Cigeiethodt atg2{), adn class
inethod
¥ catch ( tnvocationtargetexception e4 ) {
77-an exception ocurred while invoking that
inethod’
Syst
out _printin¢
‘Method thren an: " + e4.
getTargetexception( ")")}
Javaisa powerful
language that’s used in
‘web pages, settop boxes,
TWsand even cars.
ora publications com
Why Python? Cll
Python was created over twenty sik years 290 and has evolved to
become an ideal beginner's language for learning how to program a
‘computer. It’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 tse
Python is Free to download, install and use andis available For Linux,
‘Windows, macOS, MS-DOS, 05/2, BeOS, IBM iseries machines, nd
‘even RISC OS. thas been voted one of the top five programming
languages in the world ands continually evolving ahead ofthe
hardware and internet development curve.
So to answer the question: why python? Simply put, it's Free, easy to
team, exceptionally powerful, universally accepted, effective and a
superb learning and educational tool
BASIC was once the starter language that early
‘bit home computer users learned.
ae
B poperaete senate
Python isa more modern take on BASIC, i's easy to learn
‘and makes for an ideal beginner's programming language,z=» Say Hello to Python)
J
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
freely available.
WHAT WE'RE USING
‘Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linux, Raspberry Pi and more. If
you have one of those systems, then you can easily start using Python.
(| COMPUTER
Obviously youre going to needa computerin order to lear howto programin
Python and to test your code. You can use Widows (rom XP onward) on ethera 32
or 62 processor an Apple Mac or Lind insaled PC.
[_] AN IDE
AnIDE (Integrated Developer Environment) is used to enter and execute Python
code, Itenables you to inspect your program cade and the values within the code, as
‘wellas offering advanced Features. There are many different IDEs available, so Find
the one that works For you and gives the best results,
|_| PYTHON SOFTWARE
‘macOS and Linux already come with Python preinstalled as part of the operating
system, as does the Raspberry Pi However, ou 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 a text editor is an ideal environment to enter code into, i's not an absolute
necessity. Yu can enter and execute code directy From the IDLE buta text editor,
such as 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 a more
efficient language. Having access to the Internet will keep you up-to-date, help you
lout when you get stuck and alve 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
stuckattimes and other times the cade wil Flow ike water. Understand you're learning
something entirely new, and you will get there.
soso sen( Equipment You Will Need Cl
THE RASPBERRY PI
‘Why use a Raspberry Pi? The Raspberry Pisa 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.
Sal agd
The Raspberry P 3s the latest version, incorporating a more
powerful CPU, more memory, Wii and Bluetooth support
You can pick up a Pi for around £32 or asa part of kit for £50+,
E depending on the kit youre interested in
FUZE PROJECT
The FUZE isa learning environment built onthe latest model
of the Raspberry P. You can purchase the workstations that
come with an electronics kitand even a robot arm for you
to bulld and program. You can find mare information on the
FUZE at [Link]
BOOKS
iieciencoseal ERE
Raspberry titles
available via www.
bdmpublications.
‘com, Our Pi books
cover howto buy
your frst Raspberry
Pi, setitup and use
itthere are some
greatstep-by-step
project
examples
guides
toget
the most
From the
Raspberry
Pitoo.
RASPBIAN
The Raspberry P's main operating system isa Debianrbased
Linux distribution that comes with everything you need in
a simple to use package. It's streamiined for the Piandis an
ideal platform for hardware and software projects, Python
programming and even asa desktop computer.z=» Say Hello to Python)
Getting to
Know Python
MERI eeom ccm tere STEM ele kN merece od
Poa e ee Reo ME Mel tel Raa eete CIMT
OMe eal
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
3 Programs are lke recipes For computers. coer
} Aprogramming language recipe to bake a cake could go lke this: 2 ‘Red 100 grane of butter to the bon.
isallistof instructions that
a computer follows. These
instructions can be as simple
as displaying your name
or playing a music file, or
as complex s building 2
whole virtual world, Python
Put 100 grams of selfraisng flour in a bowl
‘Add 100 grams of butterto the bowl.
‘Add 100 miliitres of milk.
Bake for half an hour.
CODE
eee
concent ate 50 ae
Sess Jtties reps apogmeanissothanciow taryutoion | msi
at Centrum Wiskunde & in order. A program that describes a cake might run like this: iss joking caNe ses
irra Out te “ Le-ae
Mecdeuccs: | ~RSEITE a
i ascunuse {iraseos ig
i butter «5 BEE aeons
Guido van Rossum, the
father of Python.
‘bowl append four butter milk] 9
cake. cook(bonl)
PROGRAM COMMANDS
You might not understand some of the Python commands, lke bowl. append and cake. cook(bow),
The firsts alist, the second an object; we'll look at bath inthis 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,
EBD corr erintive cue series Volume( Getting to Know Python Cl
ZEN OF PYTHON
dare known as"hightevel’. Python lets you access all the power of a computer ina language
‘hiss because they fly high above the hardware (also referred to as that humans can understand. Behind all thisis an ethos called "The
“the metal’). Languages that “ly close to the metal ike Assembly, Zen of Python." This a collection of 20 software principles that
{are known as “low-level. Low-level languages commands read abit _influencesthe design of the language. Principles include "Beautiful
tke this msg db ,0xa Len equ $ = msg isbetter than ugly’ and "simpleis better than complex.” Type
import: this into Python and it wil csplay al the principles.
HIGH-LEVEL LANGUAGES.
Computer languages that are easy to
PYTHON 3 VS PYTHON 2
Ina typical computing scenario, Python is complicated somewhat by the existence of two active versions of the language:
Pe!
PTT ar futher s.7isthenewestrelease PMNSUERYM tn 2008 Python 3 arrived with several
eet nets
if you diga ite deepe’ Ged ee ae
ait Gos epee
an run Python 3 and Python 2alongside each other it's not compatible Tee iad
Sue rege ee mete
Su eau
Dytenar
so f Python 3s growing popular has mean that
Gates) Pe ae ES ue as Cue cd 0)
erences eer titi
eee s Cie 3 companies, such as SpaceX and N
40 to programming languages for beginners and experts to: Re edu ete
eesz=» Say Hello to Python)
How to Set Up
Python in Windows
Meets eten oan eee rns ara Tua aren}
PLO tet Ma Re eon Tel nea ool TITRA ELA
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.
FETED S2tby opening your web browser to [Link].
‘0rg/downloads/. Look for the button detailing
the download lnk for Python 3.x. The latest version atthe time of
‘writing is 3.7.0 but as Python s Frequently updated this may bea
different version for you.
Tees
eet
for Pyt
BRPIEPDD lckthe download button for version 3x, and
save the file to your Downloads folder. When the
file's downloaded, double-click the executable and the Python
installation wizard wil launch. Fram here you have twa choices:
Install Now and Customise installation, We recommend opting For
the Customise Installation link.
Install Python 3.7.0 (32-bit)
pyth
wind
toot ae Ses ed
(haan ee
FETTER) Choosing the customise option allows you to
specify certain parameters, and whist you may
stay withthe defaults, i's a good habit to adopt as sometimes (not
with Python, thankfully) installers can include unwanted additional
Features, On the first screen available, ensure all boxes are ticked
and click the Next button,
Bren tase
er rns ersten)
puthé ~~
wind tak Net Cone
BRTERE DD The next pave of options include some interesting
additions to Python. Ensure the Associate file with
Python, Create Shortcuts, Add Python to Environment Variables,
Precompile Standard Library and install for All Users options are
ticked, These make using Python later much easier, Click Install when
you'r ready to continue.
=
@
Optional Features
canes
20
ranean e
‘Advanced Options
(emer pe
arenes omemornt ree
[Shope ra casos ct
puthi
wind wa Oras | coeHow to Set Up Python in Windows Cl
onfirm the installation with the ESRB Clicking on the IDLE (Python 3.7 32-bit) ink wil
\Windows authentication notification Simply click launch the Python Shell, where you can begin
Yes and Python will bein to instal, Once the installation is complete
your Python programming jaurney, Don't worry if your version
Final Python wizard page wil allow you to view the latest asit'sPython 3.x our code works inside your
ome online Python 3 interface,
Setup was successful
ad ue
FRIYD ereyou dove tensa vz window FEI 1000 econ the windows start ton aan,
however it's bestto click on the link next to the and this time type: (MD, you'll be presented with the
shield detaled Disable Path Lenath Limit. Thiswillaliow Python Command Prompt link, Click to get to the Windows command line
o bypass the Windows 260 character limitation, enabling you to environment. To enter Python within the command line, you need
execute Python programs stored in deep folders arrangements ype: python and press Enter
‘Again, click Yes to authenticate the process; then you can Close the
installation window.
© visable path enat ii
Close
=
rand ln version of Pthon worksin
2 Inuchthe sare way asthe Shelyoucpenedin
ys 10 users can now i Step 8; note the three left-facing arrows (>>>). Whilst it’s a perfectly
Sawithinthestaeouton fia ine or now Enter: eXLEC) to leave and ae the Command
Recently Added section pyran Prompt wi
The first link, Python 3.7. “
G20) wil neh the oa
Python when clicked (more
mn that in a moment). To
pen the IDLE, type IDLE
inta Windows start
‘worabdmpublications comz=» Say Hello to Python _ )
How to Set Up
Python on a Mac
IF you're running an Apple Mac, then setting up Python is incredibly easy. In fact a
Neem a ee eC CeN A ecl lea OOO ACER Colt aro COM RUE OL AUT]
Laem Tee
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.
SpenarewTeriniwindonyccingcos ERE ice one teersiont thon 0
sue? Utilities, then double-click the Terminal icon. Now Ue) case this is the download button For Python 3.6.2.
center: pythonli==version. Youshouldsee"Python 25.1" and This will automatically download the latest version of Python and
‘even later, iF Apple has updated the OS and Python instalation, depending on how you've got your Mac configured, it automatically
Either way, it's best to check forthe latest version. starts the installation wizard
pessfcancteszowrtownnnarthonsr) — EERE wen theron maton vsrsnen kon
sh downloads. Just as with the Windows setup nas) the Continue button to begin the installation. It's
procedure onthe previouspages youcansee two yelow download worthtakng a momento read trough the portant information
buttons oneforython 3.62, andtheotherforPthon 27.13 section incase refrencessomething that apbes your version
Note, that version numbers may be different dueto the Frequent of macOS. When ready, click Continue again
releases of Python,
wane Se
PC ROC Coa Ea Ta odThe next section details the Software License
Agreement, and whlst not particularly interesting
tomost folks, it's probably worth a read. When you're ready, click on
the Continue button once again.
Finally you'te be presented with the amount of
space Python will take up on your system and an
Install button, which you need to click to start the actual installation
‘of Python [Link] to your Mac. You may need to enter your password
toauthentiate the installation process.
The instalation shouldnt take to ong the older
suai ‘Mac Mini we used in this section is a little slower
than more modern Mac machines anditony tok round iy
seconds forte sation Successful prompt tobe delay,
ora bmpublcations com
There's nothing mich le eto doin the Pyehon
Sar installation wizard so you can click the Close button.
Fyou now crop bckintos Terminal sesonandreente the
command: python. =-verston you can see the new versions
now sted, To enter the commanine version oFPyon, you need
tDenterpython3. Toes. = exitO)
Youneed to search nFnder for the Python IDLE
Sui) when you've Found it, click it to launch and it
shoud look similar to that of the Windows DLE version shown on
the previous page. The only difference beng the Mac detected
hardware platform sunning on
Pen 60 Set
PeeC2.23 Capte in bla S06) (it 39) on doris
yee eapyraht,“erotta™ er slteamseC> fr save taforatin,
nih" wren FUT (89) too yt eea
(Older Mac versions mayhave trouble withthe
ery ‘newer versions of Python, in which case you will
need torevertto a previous Python 3 bul along ar youre wing
Python 34 te code mihi book wil work or you
Python 3.1.2 (r312:79360K, Mar 24 2010, [Link])
(cc 4.0:1" (apple Inc. build 5493)) on’ darwin
‘Type “copyright”,
EEincormation.
"credits" oF "license()" for mo
How to Set Up Python on a Mac E maSay 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,
PEPER Fistyounced to ascertain which version of Python RINBM some Linux distros will automaticaly update
is currently installed in your Linux system as we the installation of Python tothe latest versions
mentioned, we're going tobe using Linux Mint 18.1 forthissection. whenever the systemis updated. To check, frst do a system update
‘As with macOS, drop into a Terminal by pressing CtrlrAtiT, and upgrade with
sudo apt-get update && sudo apt-get upgrade
Fle Edit View Search Terminal Help Enter your password and let the system do any updates
PEPER Next enter: python!==version into the Terminal JESEMBy Once the update and upgrade is complete, you
en. You should have the output relating to may need ta answer 'Y to authorise any upgrades,
version 2.x of Python inthe display. Our version as you can see center: python. =-version to see if Python [Link] undated or even
below, is Python 2.7.12 installed, In the case of Linux Mint, the version we have is Python
3.5.2, whichis Fine For our purposes
david@david-mint~ 1 or ew soon eee ep
Fle dit View Search Terminal Help
rrr)
aT
DMs Definitive Guide Series -Volome 33“ How to Set Up Python in Linux
Nowe Fyounantteitetaievesen cu ETA, wennee thon eer
ona? will need to build Python from source. Start by. S123
tering these commands into the Terminal a
ee a sudo make altinstall
sudo apt-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 coulda litle white depending on the speed of your computer
‘Once finished, enter: python3.6 ==version to check the
installed latest version
sudo apt-get install idte3
Pte
Gradeanat mint rwnienisPynanae
se six vw Sench Yeni Hee
Inthe Terminal go the Downloads older by FERED oi cterces 2 9 nsats recog tin ss
suai entering: ed DownLoads/. Then unzip the er dd tool to help you install more modules and extras.
‘contents of the downloaded Python source code with: tar =xvf_ Enter: sudo apt-get install python3-pip
ython-[Link];tanerz Now erterthenewlyureppedtoler pp, hen stale check fr the test updte wth
vip3 install ~-upgrade pip
‘When complete, close the Terminal and Python 3x willbe available
via the Programming ection in your dstro's menu.
ora bmpublcations com Python & C++ For GeginersIndex. )ora bmpublcations com
( Getting Started with Python
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
and learn how to get a result and how to
get what you want from the code.
In this section, we cover the core
concepts: saving and executing your code,
22 Starting Python for the First Time
24 Your First Code
28 Executing Code from the Command Line
30 Numbers and Expressions
‘
variables, numbers and expressions, user
input, conditions and loops. ‘
26 Saving and Executing Your Code
32. Using Comments
34 Working with Variables
36 User Input
38 Creating Functions
40 Conditions and Loops
Python Modules
—Pamela Zave (Developer, scientist and telecommunications expert)
Python & C++ For Geginersz= Getting Started with Python
Starting Python For
the First Time
Pete u an Seo uae a en Cte CI
platform. The latest version of Raspbian comes preinstalled with Python 3 (version
ere rea te Nenur rie el cicero
STARTING PYTHON
‘We won't 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 or coding,
FETTER With the Raspbian desktop loaded, click on the FETTER for cxample, inthe Shell enter: 242
‘Menu button followed by Programming > Python 3 After pressing Enter, the next line wil display the
(IOLE). This will open the Pyehon 3 Shell, Windows and Mac users can_answer: 4 Basically, 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.
(ie Es Sh Dg Gi nn Ue
et reas or asc or are itr,
PEPTIPD) The shellis where you can enter code andsee the EAB the python shell acts very much ke a calculator,
responses and output of code you've programmed since code is basically a series of mathematical
into Python. This is 3kind of sandbox, where you're able to try out interactions with the system. Integers, which are the infinite
some simple code and processes sequence of whole numbers can easily be added, subtracted,
multiplied and soon.Starting Python for the First Time E Hm
EAR While that's very interesting it's not particularly
exciting, Instead, try this
print¢*Hello everyone!”
Just enter itinto the IDLE as you did in the previous steps.
ESTED Thisise little more tke it, since you've just produced
your First bit oF code. The Print commands Fairly
self-explanatory t prints things. Python 3 requires the brackets as
well as quote marks in order to output content to the screen, inthis
case the Hello everyone! bit
>>> print("Hello everyone
ay everyone!
>>>
BeTeeEAD 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
‘Orange~ Commands
Blue— User Functions
Dark Red —Comments
Light Red - Error Messages
IDLE Colour Coding
[-eateur [use tor] examples |
atte | Erar meson
ora bmpublcations com
BEPAETR The Pithon IDLEisa power interface, and one
that's actually been written in Python using one
of the avaliable GUI toolkits. Fyou want to know the many ins and
‘outs forthe Shell, we recommend you take afew moments to view
[Link]/3/library/[Link], which detaits many oF
the IDLE’ Features
clicking on the Highlighting tab, However, we dor't recommend that
‘as you won't be seeing the same as our screenshots.
ESTED st ke most programs available, regardless ofthe
‘operating system, there are numerous shortcut
keys avallable. We dont have room for them all here but within the
‘Options > Configure IDLE and under the Keys tab, you can see alist
(of the current bindings.
Python a cesforsesinness QE]ED) cans saneh tion
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
SOR ter UCR ium e neces
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 kno\
1g these words, so you need to learn them.
FATED you've closed Python 3 IDLE, reopen itin
whichever operating system version you prefer. In
the Shell, enter the Familiar following:
printC*Hetlo”)
BTTERED st 2s predicted, the word Helio appears in the
Shellas blue tex, incicating output from a string
It's Fairly straightforward and doesn't require too much explanation.
Now try:
primt(*22")
PEPER Youcan 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
to the IDLE Shel: to print the total of 242 you need to remove
the quotes:
print(2+2)
BRPEPM You can continue as such, printing 2+2, 46442343
and soon to the Shell. An easier way sto use a
variable, which s something we will cover in more depth later. For
‘now, enter:
a\hatyouhave done here isassign the ters
Eu?S and b two values: 2 and 2. These are now variables,
‘which can be called upon by Python to output, add, subtract, divide
‘and [Link] Fors long as their numbers stay the same, Try this:
printca)
print(b),
Ee ESB Spine nse
Courrecode (CH
C Your First Code
PEPER Nowlet'sadda surname:
surname="Hayward”
print(surname)
‘You now have two variables containing a frst name and a surname
€and you can print them independently
be kao) og one rn te
FETTER) The output ofthe last step displays the current
values of both a and b individually, as you've asked
them to be printed separately Ifyou want to add them up, you can
usethe following:
print (arb)
This code simply takes the values of a and b, adds them together
and outputs the result
oe Ges Dean mat
a
FETS You can play around with different kinds of variables
and the Print Function. For example, you could
{assign variables for someone's name:
ame="David”
primtCname)
wera publications com
IF we were to apply the same routine as before,
Using the + symbol the name wouldn't appear
STEP 9
correctly in the output inthe Shell. Try it:
print (name+surnane)
You need a space between the two, defining them astwo separate
values and not something you mathematically play around with
iz ane
i
Hat
i
3
In Python 3 you can separate the two variables
iocmecntom
print(name, surname)
Alternatively, you can add the space ourselves:
print(name+” “+surname)
‘The use ofthe comma is much neater, as you can see.
Congratulations, you've just taken your First steps into the wide
world of Python,
Python & C++ For Geginersz= Getting Started with Python
Saving and Executing
Your Code
While working in the IDLE Shell is perfectly fine for small code snippets, it's not
designed for entering longer program listings. In this section you're going to be
introduced to the IDLE Editor, where you will be working from now on.
EDITING CODE
You will eventually reach a point where you have to move on From inputting single lines of code into the Shell. Instead, the
IDLE Editor will allow you to save and execute your Python code.
ESTeERED Fist open the Python IDLE Shell and when's up, JESESJEMM You can see thatthe same colour coding isin place
dlckon File > New File. This will open a new window In the IDLE Editor as tis in the Shel, enabling you
‘with Untitled as its name. Thisis the Python IDLE Editor and within it to better understand what's going on with your code. However, to
you can enter the code needed to create your Future programs. ‘execute the code youneed to first save it Press FS and you get a
Save...check box open,
ieee
cep es
Treois esters forivensmnanspenss TREMP cic onthe btn te Sve boxandseets
eure simple text editor with Python features, colour cued) destination where you'll save all your Python code.
coding and so on; much inthe same vein as Sublime. You enter ‘The destination can be a dedicated folder called Python or you
code as you would within the Shell so taking an example from the _canjust dump it wherever you lke, Remember to keep atidy drive
previous tutorial, enter though, to help you out inthe Future
print(*Hello everyone!") senate
ET) 2 cece veeEnter a name for your code, ‘print hello’ for
‘example, and clickon the Save button. Once the
Python code is saved it's executed and the output will be detailed in
the IDLE Shell. n this case, the words ‘Hello everyone!
BTID Thisishow the vast majority of your Python code
will be conducted. Enter it into the Editor, hit F5,
save the code and look atthe output in the Shell. Sometimes things
will differ, depending on whether you've requested a separate
window, but essentially that’s the process. I’ the process we will
se throughout this book, unless otherwise stated
eed teeg re yds eH
ee Soya rei
Tubueratitainnne ayes seared
Python resource sites will be .py. Just ensure that the code is written
for Python 3,
wera publications com
Saving and Executing Your Code Cl
nz
be2
ane="David”
‘surname="Hayward”
printCname, surname)
print Carb)
IF you press FS now youll be asked to save the file, again, asit'sbeen
modified from before.
Let's extend the code and enter afew examples
From the previous tutorial
IFyou click the OK button, the file willbe
‘overwritten with the new code entries, and
STEP 9
‘executed, with the output inthe Shell's not a problem with ust,
‘hese Few lines but iFyou were to edita larger fil, overwriting can
become an issue. Instead, use File > Save As from within the Editor
to create a backup.
[ie £6 fort Bin tote Yann He
PePET BD Now create a new file. close the Editor, and open,
anew instance (File > New File From the Shel)
Enter the following and save itashellopy:
‘a="Python”
beris”
ce"cool!”
print(a, b, ¢)
‘You will use this code in the next tutorial,
Telapy: anapioaasrena/Pyan areas BA)
(ie G8 Fama Bn Eins Hinson ep
Python & C++ For GeginersGetting 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 [Link], let's see how you can run code that was made
inthe GUI at the command line level.
ys0 E=p Now you're atthe command line we can
thon. For Python 3 you need to enter
mand python3 and press Enter. Ths wil put you into th
smmand line Familiar three right
executing
on 2, whilst the other uses the Pytho
pinto the command line or Terminal on
You can see that it works exactly the same,
Command Line returned search -
‘and macOS users can get access
their command line by clicking
Utilities > Terminal
DMs Definitive Guide Series -Volome 33Executing Code from the Command Line Cl
FETTER) ow enter: exit()to eave the commandline Python JEM The result of running Python 3 code From the
session and return you back ta the command Python 2 command ine is quite obvious. Whilst
mp. Enter the | reyou saved the sn tin any way, due s between the
previous tutorial and list the available files within; hopefully you Python 3 handles the Print thon 2, the result
should see the [Link] file isn’t as we expected. Using Sublime for the moment, open the
hellopy file
E=D From within the same Folder asthe code youre E=D Since Sublime Text isn't available forthe Raspberry
‘going to run, enter the Following into the ;, you're going to temporarily leave the Pi for the
need to use the Python IDLE. With the [Link] file open, alterit to
FEAETEELIENED inclu the Following —
This wil execute the code we created, which to remind yous: eT
‘e"Python” print(‘Hello,”, nane)
bets?
c="cool!” a
print(a, bs <)
PEPER aturally, since this Python 3 code, using the
syntax and layout that’s unique to Python 3, t only
rks when you use the python3 command. iFyou like, try the same
fh Python 2 by entering:
python [Link]
ave the [Link] file and di
ktothe
‘command line, Now execute the newly saved
python3 [Link]
‘The result wil be the original Python is cool statement, together
ith the added input command asking you For your name, and
splaying itn the command windowzk Getting Started with Python
Numbers and Expressions
MeN aeons Selec srl i ae ave Cet el EU Tar
like. Let's expand on that now and see just how powerful Python is as a calculator. You
Ce R LAT ea aN eat-8 PM Bn Colm Mea eel Col N Nm Olen Lo
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.
ESTER Ocen upthe culversion of Python 3, as mentioned PRIMM vou can use all the usual mathematical operations:
you can use either the Shell or the Editor For the divide, multiply, brackets and so on, Practise with a
time being, you'e going to use the Shelljust to warm our maths Few, For example:
‘muscle, which we beleve sa small land located atthe backoFthe 42
brain (or no =
24283
a2")
BEPEED 0 the shall enterthe following: EEPEPR Youve no doubt noticed, division produces a
= decimal number. In Python these are called Floats,
orton pon rete Hone younedan ger ae
Stasor4s5n265
—— Sppead ts deci aoe heyoucin ie Gade sa
Yovcansethtrencanindesomecutelasenimben, — MB
{And soon,
ies rede” ae “Leaneey” far mre tara,
ET) 22sec seveYoucanalso ue an operation tose the reminder
Sua?5 left over From division. For example:
wa
Will display 3333333333, whichis of course 3.3-ecurting, Ifyou
now enter:
10%3
‘This will display 1, whichis the remainder left over From dividing 10
into 3
( Numbers and Expressions Cl
FFD wie inne tr concn
format(3, ‘b’)
BETETD ext uo we have the power operator, or
exponentiation iFyou want tobe technical To work
cut the power of something you can use a double multiplication
symbol or double-staron the keyboad
203
10"10
Essential its 2x2x2 but we're sure you already know the basis,
behind maths operators. Thisis how you would work tout Python,
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-twisters. For
‘example, to corwert a number to binary, use:
ings)
wera publications com
ESTEE G00lean Expression isa logical statement that will,
either be true or false. We can use these to compare
data and test to see if i's equal to, less than or greater than. Try this
in aNew File
a=6
od
print(1, a == 6)
print(2, a == 7)
print(3, a == 6 and b == 7)
print(4, a == 7 and b = 7)
print(S, not a == 7 and b == 7)
print(6, a == 7 or b == 7)
print(7, a == 7 or b == 6)
print(B, not Ca = 7 and b = 6))
print(9, not a == 7 and )
Execute the code 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. I's an extension oF
‘what you've looked at, and an important part of programming.
Python & C++ For Geginerszk Getting Started with Python
Using Comments
MANU Retin Mi MNS N CU sce com Ita
Miler neue tae hte eum nice cha citar
or MM eon mec Ul cas ae dsl n
#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. It's just good practise.
STEER Sir by creating anew instance ofthe DLE Editor
(Fle > New Fie and create a simple variable and
print command
0-10
printC*The value of A is,”, a)
Save the file and execute the code.
Sas
att mo tens rts te
BEER fnning the code will return the line: The value of A
is, 1Dinto the IDLE Shell window, which is what we
‘expected. Now, add some ofthe types of comments you'd normally
see within code:
# Set the start value of A to 10
o=10
# Print the current value of A
print(*The value of A is,”, a)
Ee cesees vee
BRPIRED Resave the code and execute it. You can see thatthe
‘utputin the IDLE Shel stil the same as before,
despite the extra lines being added, imply put, the hash symbol (#)
denotes line of text the programmer can insert to inform them,
‘and others, of what's going on without the user being aware,
Pymona42She
Let's assume thatthe variable A that we've created
isthe number of tvesin a game. Everytime the
player dies, the value is decreased by 1. The programmer could
Insert.a routine along the lines of
ona=1
print (“You've just lost a life!”)
printC*You now have”, a, “Lives teft!”)PEP whilst we know thatthe variable Ais lives, and
that the player has just lost one, 3 casual viewer or
‘someone checking the code may not know. Imagine for a mioment
that the code istwenty thousand nes long instead of just our
seven, You can see how handy comments ae.
(Using Comments Cl
Inline comments are comments that flow asection
S28 of code. Take our examples from above, instead of
inserting the code on a separate line, we could use:
010 # Set the start value of Ato 10
print(*The value of A is,”, a) # Print the current
value of A
o=a-1 # Player lost a life!
printC*You've just lost a life!”)
rintC*You now have”, a, “Lives left!”) # Inform
player, and display current value of A (lives)
Essentially, the new cade together with comments
Riad
could look tke:
# Set the start value of A to 10
0-10
# Print the current value of A
print(“The value of A is,”, a)
# Player lost a life!
na-1
# Inform player, and display current value of A
ives)
printC*You’ve just lost a life!”)
printC*You now have”, a, “Lives left!
Youcan use comments incferent was. For
Su ‘example, Block Comments are a large section of
textthat details what's going on inthe code suchas teling the code
reader what varibles youre panning on wing
4H This is the best game ever, and has been
developed by a crack squad of Python experts
4 who haven’t slept or washed in weeks. Despite
being very smelly, the code at Least
# works really well.
FERED The comment, the hash symbol, can 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 First print statement, you would use:
# print(“The value of A is,”, a)
[Ele ot Farmat Bun Options windows Help
i Set the start value of A to 10
S10
Frnt caren wun of
fe prinec'the value of A tas", a
fe Blayer lose'a Iatat
4
form player. and display current value of & (lives)
pranc(“vou've Just lost a.1ifel")
Prane(-You now have", a, “Lives left!)
You also use three single quotes to comment
‘out a Black Comment or multiline section of
‘comments. Place ther before and after the areas you want to
‘comment for them to work:
This is the best gane ever, ond 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.
wera publications comzk Getting Started with Python
Working with Variables
We've seen some examples of variables in our Python code already but it’s always
Cee nec eu Mar kee rue entry
Nel oR] e
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 previ
IDLE Shell to clear up any old code.
In some programming languages you're required
tose dollar sign to denote astrng, whichis a
variable made up of multiple characters, such asa name ofa person.
in Python this ft necessary. For example, inthe Shell enter:
‘name="David Hayward?” (or use your own name, unless youre
also called David Hayward).
oie one ers
You've seen previously that variables canbe
ous?) 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 colon anda spac, svasibes te connected tout spaces,
so we needto ad them manual,
"ie GSB Ene ee
Be aie ohana" for mice ito.
BPP You can check the type of variable in use by
issuing the type () command, placing the name of
the variable inside the brackets. n our example, this would be:
‘type Chane). Add a new string variable: ti'tLen"Descended
from Vikings”.
IE) 200 ce sees vee
ster 4 al
combine vrbles
within another variable For
trample, to combine bath name
and ttle 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 are integers, as we know,ESTER oweves you can't combine both strings and
integer type variables inthe same command, 5 you
would a set of similar variables. Youneed to either turn one into the
‘other or vice versa. When you do try to combine both, you get an
error message!
print Cname + age)
C Working with Variables Cl
Thispresent io problem whenyu wane to
S28 work with a number that's been inputted by the
user, as age + 10 won't work due to being a string variable and an
integer. Instead, you need to enter:
‘intCage) + 10
‘This will TypeCast the age string into an integer that can be
worked with,
yet cer it nc a py
Thisisa process known as TypeCasting. The Python
codes:
Riad
print (character +“ is “+ strCage) +“ years
old.")
oryoucan use
print (character, “is, age, “years old.”)
Notice again that inthe last example, you don't need the spaces
between the wordsin quotes as the commas treat each argument
to print separately
>>> print (mane + age)
Traceback (most recent call Last):
File s
", Line 1, in
print’ (name sage)
‘Typetrror: can't convert “int* object to str implicitly
S3BSprine (eharacter +! is"" 4 str(age) += years 91d")
Davia Hayward: Desesnded from Vikings is “4 years old.
D3> prane (character, "is", age, “Years old.)
David Hayward: Deseended fron Vikings is 44 years old.
2B
age= input (“How old are you? “)
‘le Eat shel Debuy aptont wndows lp
Another example of TypeCasting s when you ask For
input from the user, such as a name. for example,
wera publications com
pe
FETED) The use of Typecasting is also important when
dealing with loating point arithmetic; remember:
‘numbers that have a decimal pointin them. For example, enter:
shirt=19.99
Now enter typeCshiint) and youl see that Python has allocated
the number a let, because the value contain a decimal pont.
When combining integers and floats Python
usually converts the integer to afloat, but should
the reverse ever be applied it’s worth remembering that Python
doesn't return the exact value. When converting a float to an
integer, Python will always round down to the nearestinteger,
called truncating; in our case instead of 19.99 it becomes 19.
see =
‘le Eat Shab Debug Grtens wndows Heb
een 32am OF 1 04, TTY
“License()* for wore information,CJ Getting Started with Python
User Input
ARSC ol a Mey Len ecir- Lae ORY Keele MONE eM RC od
Pn er relacletc cant Chan euue on)
Teese ureteral
USER FRIENDLY
‘The type of input you want from the user
depend greatly on the type of program you're coding. For example, a game may
‘ask for a character's name, whereas a database can ask For personal details.
ETE its not already, open the Python 3|DLE Shell,
and start @ New File in the Editor Let's begin with
something really simple, enter:
printC*Hello”)
firstname=inputC“What is your first name? “)
print (*Thanks.")
‘surname=input(“And what is your surname? “)
Save and execute the cade, and as you already no
doubt suspected, in the IDLE Shel the program will
‘ask for your first name, storing its the variable firstname, followed
bby your surname; also stored ints own variable (surname).
BE) 2c cesses vee
FRPP) Now that we have the user's name stored ina
couple of variables we can call them up whenever
we want:
printC*Welcone”, firstname, surname, “. I hope
youre well. today.”)
BE TERE DD ur the code and you can see astight isu, the
fullstop after the surname follows a blank space.
To eliminate that we can add plus sign instead of the comma in,
the code:
printC*Nelcone”, firstname, surnames. I hope
you"re well today.”)You don't always have to include quoted text within
the input command. For example, you can ask the
user their name, and have the input inthe line below:
printC*Hello. What”s your name?”)
hname=inputC)
userinput py -/home/pi/Documents/Python Code/us\
[Ble Edt Farmst Bun Options Windows Help
iprant(Helle, what's your nase?)
hane=input()
(User input Cl
what youve created here isa condtion, whch we
SES) will cover soon. In short, we're using the input From
the user and measingRagasta condo, So the ser enters
Dads ther name, te guard wil alow them to pss unhindered
Ete, they enter a name other than Dai, the qurdchalenges
them toafiht
FETTER) The code from the previous step is often regarded
asbeing alittle neater than having a lengthy
‘amount of text in the input command, butit’s not arule that’s set in
stone, so do as you like in these situations. Expanding on the code,
uythis
print(*Halt! Who goes there?’
nameinputC)
‘Be E Farat Bin Stans YnSon Hep
BITEEE ADs 2 900d start to a text adventure game, perhaps?
Now you can expand on t and use the raw input
from the user to flesh out the game alittle:
‘if name=="David”:
printC*Welcome, good sir. You may pass.”)
else:
printC*I know you not. Prepare for battle!
ie 588 Fart in Stes roe te
wera publications com
ust as you learned previously, ary input from a
User is automatically string, so you need to apply a
STEP 9
‘TypeCast in order to turn it into something else. This creates some
interesting additions to the input command. For example
# Code to calculate rate and distance
print(“Input a rate and a distance”)
rate = floatCinput¢“Rate: “))
fe Et Format Bin otons nds Ue
Raat 8
BRTTSETBD 1 finalise the rate and distance code, we can add:
distance = floatCinput(“Distance: “))
print(*Time:”, (distance / rate))
Save and execute the code and enter some numbers. Using the
float{input element, we've told Python that anything enteredis a
Fioating point number rather than a string
Python a cerforsesinness @Yyz= Getting Started with Python
Creating Functions
NOMEN aUrecrs te kia curcumin Tele cy
Geechee rca eet ars untclmene tase
Crack une cimatu
FUNKY FUNCTIONS
A funct
‘works on it and then returns the result.
.a command that you enter into Python to do something. Its a little piece of self-contained code that takes data,
{enath or type of items. Basically, a function is a short word that's
Followed by brackets. For example, len(), list) or type)
A function takes data, usually variable, works on
It depending on what the Function is programmed
todo and returns the end value. The data being worked on goes
Inside the brackets, soifyou wanted to know how many letters
are in the word antidisestablishmentarianism, then you'd enter:
‘Len¢“antidisestablishmentarianism”) and the number 28
would return,
3
BETERERD You con pass variables through functionsin much
the sare manner. Let's assume you want the
‘numberof letters in a person's surname, you could use the following
code (enter the text editor for this example):
ane=input (“Enter your surname: “)
‘count=LenCname)
print (“Your surnane has“, count, “Letters in
im
Press FS and save the code to execute it.
Python has tens of functions bul inti, Far too
‘many to get into inthe limited space available here.
However, to view the list of builtin Functions avaiable to Python 3
navigate to www-does [Link]/3/library/functionshtml. These
are the predefined functions, but since users have created many
‘more, they'e not the oly ones avaliable.PEPID *ccitional functions can be added to Python
through madules. Python has a vast range of
modules available that can cover numeraus programming duties
They add Functions and can be impor
example, to use advanced mat
import math
ed as and when requited. Fr
‘tics Functions enter:
Once entered, you have access to all the Math module Functions.
FORGING FUNCTIONS
‘There are many different Functions you can import create
Tose funcon{rom amodul eter the ne of
SUz6 the module followed by a full stop, then the name
ofthe Function Forinstance, sng he Math module nce youve
just imported it into Python, you can utilise the square root Function,
Todoso, enter:
math. sqrt(16)
‘You can see thatthe code is presented as madule function(data.
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.
eee eerns
tion called Hello
eee
ert eee
PPD 11s now expand the functionto accept a
variable, the user's name For example. Edit your
parser
ina
Sanna
peers teats
‘worabdmpublications com
Cece ats
ee aed
the Editor and file (File> Ne
EID what you've just do
Pee
Pea net,
ease
eee:
i b)
result — a + by
creating rincions CRIz= Getting Started with Python
Conditions and Loops
eo See eae Msn R neces
Pea ata uh cic Reset ec isaat| cy
ELenTay
hey 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
sees
word=input(*Please enter a four-letter word:
ERPS Now we can create anew variable, chen use the len
Function and pass the word variable thraughit to
‘get the total numberof letters the user has just entered:
word~input(“Please enter a four-letter word: “)
word_Length=LenCword)
IT) 220 eevee
ERTERERD ow you can use aniFstatement to checkif the
word_length variable is equal to Four and print a
friendly conformation fit applies tothe rule:
word=input(“Please enter a four-letter word:
word_length=LenCword)
‘if word_length == 4:
print (nord, “is a four-Letter word. Well done.”)
‘The double equal sign (==) means check if something is equal to
something else.
‘The colon atthe end of IF tells Python that I this
statements true do everything after the colon
that's indented, Next, move the cursor back tothe beginning of
the Editor:
word=input(“Please enter a four-letter word:
word_Length=LenCword)
if word length == 4:
print (nord, “is a four-letter word. Well
done.”)
else:
print (word, “is not a four-letter word.”)
ten rst 9 teCondonsanitoons ORE
PRIM Press 5 and save the code to execute't. Enter
a Fourdetter word in the Shel to begin with, you
should have the reture hat it's the word is Four
Now pressF5 again and rerun the program but ths time en
five-letter word. T
hell wil display that it's not a Fouretter word,
LOOPS
ESTEE "Yow expand the code to include another conditions
Eventually t could become quite complex We've
‘added a condition for three-letter wor
word=input(“Please enter a four-letter word: “)
word_Length=LenCword:
if word_length == 4:
print (word, “is a four-letter word. Well
done”)
elif word_length = 3:
print (nord, “is a three-letter word. Try again.”)
else:
print (word, “is not a four-letter word.”)
‘loop looks quite similar to a condition but they are somewhat different in their operation. A loop will run through the same
block of code a number of times, usually with the support of a condition.
STEP 1 QeeerisCr Emme icencucrat as
rire tint
Sree
b= 1
fehile x < 10:)
print OO]
The difference between if and while
Cena
eg
Meena
asec re nner
re
praia
ose
etter et
‘worabdmpublications com
rere
cae! geet
pee ors
‘or x in range Ci, 10):)
print Oo)
Senet
Cee
ing the range Function:
Ces
Cee ee eee)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.
the builtin Fune ‘The results an errorin the IDLE Shell asthe
Althousha
a? are limited. The use of nised or installed in
tomate more sophisticated programs. Asyouare aware, modules” Python Toistallam CP istals Packages).
Bre Python spt that are ported, suchas mport math Close downthe DLE Shelland opin command prompt o
Terminal session, At an elevated admin command prompt, enter
pip install pygame
ime [Link], other odes aren awa avlable 4 suse can serch or CMD vite Stat ton an
‘example on non-Pi platforms isthe Pygame madule, which contains click the result then click Run as Administrator. Linux and Mac users
‘many functions to help create games. Ty import pygame, can use the Sudo command, with sudo pip inst
al package.
DMs Definitive Guide Series -Volome 33Python Modules E Hm
clesteconmardsemetcteraand —— EERERI) tte ocean be imparidwatinarce
SUED esnch che OLE shel when you now enter: SEED 5 oendour example use
‘mportpygane the ode wlbemprtedinathe coe
‘tout ay problems Yu'lfind hat most code dowicadedorSMPOTENtandon
copied From the Internet will contain a module, mainstream oF _
‘unique, these are usually the source of errors in execution due to for I in range(S):
them Belg ising Drint Crandon. randint2, 2599
Bean prinkcoath. pi
FETTER The modules contain the extra code needed to PEED The result isa string of indo numbers Followed
achieve a certain result within your own code, 2s by the value of Pas pulled from the Math module
‘we've previously experimented with. For example: Using the print(math.p function. You canals pullin certain
: fanaons froma medley ung the fom and pat commands,
‘import: random funaio
brings inthe cade fromthe Random Number Generator module . .
You can then use this module to create something like: ‘firominendomEapoeRnonaLre
os for i in range(5):
for i in range(10): =
print([Link](1, 25)) aaeneeniemmemn!
Dive Sasa
PRPIIEDD This code, when saved and executed, will displayten MBI this helos create amore streamlined approach to
random numbers from to 25. You can play around
programming. You can also use import module*,
withthe code to display more orless, and from agreat orlesser which wll mport everything defined within the named module.
range. For example:
However, t's often regarded as a waste of resources but it works
ED nonetheless Finally, modules can be imported as aliases:
for i in range(25): ‘import math as m
[Link](1, 100)) print¢m-pi)
(Of course, adding comments helps to tll others what's going on.
Dt Cevtibeaneanienati BF =e x
pmo
senses PrensaWorking
Wie. =
“The most important
single aspect of software
development is to be
clear about what you are
trying to build.”
~ Bjarne Stroustrup (Developer and
creator of C++)
ora bmpublcations com
( working with Data Cl
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, multi-dimensional lists; also
how you can use them to forge exciting
and useful programs.
Then, you can learn how you to use the
date and time Functions, write to files in
your system and even create graphical
user interfaces that take your coding skills
tonew levels and into new projectideas.
46 Lists
48 Tuples
50 Dictionaries
52 _ Splitting and Joining Strings
54 Formatting Strings
56 DateandTime
58 Opening Files
60 Writing to Files
62 Exceptions
Python GraphicsLists are one of the most common types of data structures you will comes across in
Python. A list is simply a collection of items, or data if you prefer, 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 v
and lists within lists.
les. You can even include functions in lists,
Alistisa sequence of data values called items. You
create the name of your list followed by an equals
sign, then square brackets and the items separated by commas,
‘note that strings use quotes
numbers = [1, 4, 7, 21, 98, 156]
mythical_creatures - [“Unicorn”, “Balrog”,
“Vampire”, “Dragon”, “Minotaur”)
BRPISPR Once you've defined your list you can call each
by referencing its name, followed by a number. Lists
start the first item entry s 0, followed by 1,2, 3 and soon,
For example:
punbers
Tocallup the entire contents ofthe lst.
punbers[3]
To callthe third From zero item inthe lst (21 in this case).
ET) 2s ec seve
You can also access or index, the lat item ina list by
Using the minus sign before the item number 1},
for the second to last item with [2] and so on. Trying to reference an
item thatisntin the st, such as 10] will return an error
punbers[=1]
mythical_creatures[~4]
ESPEPD Sicingissimiartoindexing but you can etrieve
‘multiple tems in alist by separating tern numbers
witha colon. For example:
unbers[1:3]
\ill output the 4 and 7, being item numbers 1 and 2. Note thatthe
returned values don't include the second index position (as you
‘would numbers[t:3] to retuin 4,7 and 21).You can update items within an existing list, remove
items and even jon sts together. For example, to
Join two lists you can use:
everything = nunbers + mythical creatures
‘Then view the combined list with:
everything
Css CE
Youcanvew what canbe done wth ists by entering
S28 dir(list) Into the Shell. The output is the available
functions, for example, insert and pop are used to add and remove
itersat certain positions To insert the number 62 at item index 4
nunbers-insert(4, 62)
Toremove it:
numbers .popC4)
PTT ers can be added toast by entering
nunbers=nunbers+[201]
Or or strings:
mythical_creatres=mythical_creatures+[“Griffin”]
‘Or by using the append function:
mythical_creatures..append(“Nessie”)
‘numbers .append(278)
Removal of tems can be done in two ways. The first
del nunbers(7]
Alternatively, by item name:
mythical_creatures. renoveC“Nessie”)
wera publications com
You also use the lst Function to break a string down
into its components. For example
STEP 9
Listc*Davia”)
Breaks the name David into'D, 2,
toa new lis:
nave=1ist“Dovid Hayward”)
name
ge [44]
user = none + age
user
id. Thiscan then be passed
FEET) 82520 on that, you can create a program to store
someone's name and age as alist:
pane=inputCWhat”s your name? “)
TnameslistCnane)
‘age=intCinput "How old are you: “))
Lage=[oge]
user = Inane + lage
‘The combined name and age lists called user, which can be called
by entering user into the Shel, Experiment and see what you can do.
Python a cerforsesinness QiTuples are very much identical to lists. However, where lists can be updated, deleted or
Cee elu se ne chute cea ica
perfect for storing fixed data items.
THE IMMUTABLE TUPLE
Reasons for having tuples vary depending on what the prograr
special but they're also used for example, in an adventure gam
is intended to do. Normally, a tuple is reserved for something
‘where non-playing character names are stored.
BITE *turle is created the same way [Link] but in this [EREESEEMM 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
«called NPC (Nor-Playable Characters} containing the character name
brackets. For example:
tronths=C*January"si"February”sesMarchsesaprinms _2ndthelr combat rating For an adventure game
“May”, “June”) NPC={C*Conan”, 100), (*Belit”, 80), (“Valeria”,
months 95)]
EETeEED estas with tists, the tems withina named tuple can [RRESSWAM Each of these data items can be accessed as a
be indexed according to their position inthe data whole by entering NPC into the Shell or they can be
Indexed according to their postion NPC(O). You can also index the
range, ie:
months[0] Individual tuples within the NPC lst:
rmonths[S] NPCtO] CLI
However, ay atternpt at deleting or adding to the tuple willresult wil display 100,
Jinan errorin the Shel,
ED coms vetntive cide seris- volume 33,Tes woth noting tat when referencing mile
Eu?S tuples within a list, the indexing is slightly different
from the norm. You would expect the 95 combat rating ofthe
character Valeria to be NPCIA][S], but’s not. t's actualy:
NPCC2I01]
oe Ea pty os nt ube
FETT This means of course that the indexing Follows thus:
o mm
a0 2
a1 20
1 2a
10
Which as you can imagine, gets ate confusing when you've got a
lot of tuple data to deal with,
PEPER tuples though utilise a feature called unpacking,
where the data ters stored within atuple are
assigned variables First create the tuple with two items (name and
‘combat rating):
NPG=C*Conan”, 100)
wera publications com
Now unpack the tuple into two
S28 corresponding variables:
(Chane, conbat_rating)=NPC
‘You can now check the values by entering name and combat_rating
FETED emember, as with lists, you can aso index tuples
Using negative numbers which count backwards
from the end of the data list. For our example, using the tuple with
multiple data items, you would reference the Valeria character with
NPctz][-0]
You can use the max and min anctionstofnd the
Sup highest and lowest values of a tuple composed of
numbers, For example
numbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99)
The numbers canbe integers anc oats To output the highest and
lowest se
print (maxCnunbers))
print (minCnunbers))Dictionaries
Lists are extremely useful but dictionaries in Python are by Far the more technical way
of dealing with data items. They can be tricky to get to grips with at first but you'll soon
Ite CLeoL PURO N ol mon Keele a
KEY PAIRS.
‘A dictionary is ike 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.
ERTESERD 2:5sav you want to create a phonebook in Python,
You would create the dictionary 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,
6789}
“Hannah”:
Just. as with most lists, tuples and so on, strings
need be enclosed in quotes (sinole or double),
whilst integers can be left open. Remember thatthe value can be
either a string or an integer, youjust need to enclose the relevant.
fone in quotes:
phonebook2={"David”: “0987 654 321”}
ET) secs veee
‘swith ists and tuples, you can check the contents
ofa dictionary by giving the dictionary @ name:
‘phonebook inthis example. This wil display the data items you've
entered ina similar Fashion toa lst, which you're no doubt familar
with by now,
BEPEPM the benefit of using a dictionary is that you
can enter the key to index the value. Using the
‘phonebook example from the previous steps, you can enter:
phonebook “Enna”
phonebookf"Hannah”]value items ike:
phonebook[“David”] =
phonebook
‘Adding to a dictionary easy too. You can include
‘a new data item entry by adding the new key and
You can also remove items from a dictionary by
Issuing the del command Followed by the tem's
key, the value wil be removed as well, since both work asa pair of
data items:
Riad
del. phonebook[“David”]
Tang thisasep ther how bout ceting
usd piece of code that will ask the user for the dictionary
key and value ters? Create a new Editor instance and start by
coding in anew, blank dictionary:
phonebook={}
wera publications com
‘Opn Cll
Dictionaries
Next you needto defn the userinputs and
S28 variables: one for the person’s name, the other
for their phone number (let's keep it simple to avoid lengthy
Python code):
ane=inputC*Enter nam
unber=intCinputC“Enter phone nun
»
aT
STEP 9
Note we've kept the number as an integer instead
(fa 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{name]) = number
pret)» mater
Now when yousave and execute the code, Python
Sup will ask fora name and a number. It will then insert.
‘those entries into the phonebook dictionary, which you can test by
entringinc the Shel
phonebook
phonebook[“David")
IF the number needs to contain spaces you need to makeitastring,
‘so remove the nt part ofthe input.Splitting and
Joining Strings
ANA aKel tare ROUiea Ke eM Aenea e911 WCE TUS TaN Lele OLR UT AU Te Colel oc Te)
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.
ESTED te main tootin the string function arsenals spt.
With ityou'e able to split apart string of data,
based on the argument within the brackets. For example, here's
string with three ters, each separated by a space:
‘text="Daniel Hannah Enna”
BRTISPRD Now let's turn the string ntoa list and split the
content accordingly:
names=text-splitC* *)
Then enter the name of the new ist; names, tosee the three items,
Es ec seve
BTSED ote that the text spit part has the brackets,
uotes, then a space followed by closing quotes
‘and brackets. The space isthe separator, indicating that each lst
‘tem entry is separated by a space. Likewise, CSV (Comma Separated
Value) content has a comma, so you'd use:
texts” January, February,March, April May, June”
months=[Link](*,")
months
EEPEPR Youve previously seen how you can split a string
into individual letters asa list, using a name:
name=ListC“David”)
name
The returned value is'D,'a, Whilstit may seem a little
useless under ordinary circumstances, it could be handy For creating
aspeling game for exampleBSED The opposite of the split function is join, where
you will have separate items na string and can join
them all together to form a word or ust a combination of items,
depending on the program you're writing. For instance:
‘alphabet="". join([“a","b","c","4","e"1)
‘alphabet.
‘This will display ‘abcde’ the Shell.
You can therefore apply join to the separated name
you made in Step 4, combining the letters again to
Riad
form the name:
‘name="". joinCnane)
‘name
C Splitting and Joining Strings Cl
stop, a hyphen or whatever you ike:
colours=[*Red”, “Green”, “Blue”]
Join(colours)
STEP 9
‘titLe="conan the cimmerian”
[Link]()
[Link]
‘swith the spit function, the separator doesn’t
have tobe a space, itcan also be acomma, 2 full
‘There's some interesting Functions you apply toa
string, such [Link] and itl, For example
‘We've joined the string back together, and retained the lst called
fname, passing itthrough the join Function.
You can alot osc operators on tring,
Sup ‘with the ‘in’ and ‘not in’ Functions. These enable
‘Agood example of using the join Function is when
you have a ist of words you want to combine into a
sentence: you to check iFastring contains (or does not contain) a sequence
ListeL“Conan”, “raised”, “his”, “mighty”, “snora”, characters
“and”, “struck”, “the”, “denon”] inessage="Have a nice day”
texte”
text
Note the space between the quotes before the join Function (where
there were no quotes in Step 6's oi).
*.joinclist) “nice” in message
"bad? not in message
“day” not in message
“night” in message
Se ae —
rsam coe |
wera publications com Python & C++ For Geginerszk Working with Data
Formatting Strings
When you work with data, creating lists, dictionaries and objects you may often want
rune ee Ure Mane rere faeces
PR eIoa anak keoulel ures
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.
BRPEE RD the basic formatting in Python is to call each ESTISEDD You can of course aso include integers into the mix:
variable into the string using the curly brackets =
nunber=
‘name="Conan” printC“{} of {} was a skilled mercenary,
printC*The barbarian hero of the Hyborian Age is: and thief too. He once stole {} gold from a
”. format name) merchant..”.format(name, place, nunber))
Remember to close the print Function with twa sets ‘There are many different ways to apply string
af brackets, as youve encased the variable none, formatting some are quite simple, as weve shown
and he pint function n another. Youcan nude multiple cases of youhere; others canbe significantly more complex. all depends
String Formatting na singe prin Function Using Modules )
Calendar Module
WORKING WITH DATES
The Calendar module is bul
calendar as a Windows administrator or sudo pi
into Python 3. However, if For some reason it's not installed you can add it using pip install
install calendar For Linux and macOS.
Launch Python 3 and enter: import calendar to
callup the module and its inherent Functions, Once
it’s loaded into memory start by entering
sep=[Link] [Link])
[Link](2019, 9)
[ee 3.0 2017
fe) on aga
‘ype Soy igh Sredts? or Scene) for sore inforation.
S33 sepsealendar:Toxtcalondar (calendar SUNOAY)
533 stp: prnonth( zou, 8)
FRPIPB You can see thatthe days of September 2019 are
displayed in a wal calendar fashion. Naturally you
can change the 2019, 9 part ofthe second line to any year and
month you want, a birthday For example (1973, 6). The first ine
configures TextCalendar to starts weeks on a Sunday; you can opt
for Monday ifyou prefer.
oe git Sot pug ten rdw te
Se 32 SS S$ —2
ter
ED) 22sec seve
There ae numerous Functions wthin the Calendar
Su? ‘module that may be of interest to you when
forming your own code. For example, you can cisplay the number of
leap years between two specific years
‘Leaps=[Link](1900, 2019)
printCleaps)
‘The result is 29, starting from 1904 onward
(ytion 35-3 (dofutt, sep 27 2018, 1775)
sta" Or "License()" for mre safornation
import. calendar
print(>>>>55>>>>Leap Year Calculator