<
The Complete
Python
Peli c ly
Pk
Sols ArtyDiscover more of our complete
manuals on Readly today...
Pre Complete The Complete y ai Wee
untu fh Es maliits FR efeye ate}
Manual an WWeleivell
ie atsAp f staprar
ats, Instagram
Ne, Hh M 4
The Complete
Linux
IV Eraterel
The Complete
WordPress
ELM eT ee The Complete The Complete
ais =5 ‘Google | | Android
Mandal Manual
The: orp ~) m -
ite |
Photo: phy
Photography | [Photography 1)
Manual yManu PyBau a iu soleus Cer ede cola
eT ona i) a clear eye a Pea id
Our modern digital world is made up of code. The Internet, our
phones, TVs, games consoles, banking and virtually anything else
you can think of, that’s connected in some way to the wider world,
ESE Aco Remco MMe R AR NASM Ue Rose)
Dre acolo
That code can come in different forms, called programming
languages. Some offer better stability, speed and complex
Elfen Olan ee Me ese la Teoma St)
Frerro Tee lee ea TM 010s CCOM oD emE-T aT Lt Co)
Eleectse-ure heer Deak Tale e-Lec¥- Dale bl cell Keele eM
ite Wenn Ro me cole eM AM ole RSMMC Teh
HiTal(AU TONY IAeU Ee) WANN ol-leetol elt Cm
Vleet clea Maa cod cca MCR Sole mesa TOE)
few simple lines of code can create something amazing and can
cite ARLE ue h oll meee lV ane ake aod
of the most popular and powerful languages to learn and with
the help of this book plus a little imagination, you will soon be
eter T ecole a
Now, turn the page and let’s start learning how to code.
—— @bdmpubs |] som pubi )ape ets
C]
9 £
4] ¥
t i
Ey ry
4 :
The Complete Python Manual
8
ct
re
cr
eee ea
Dena
lee eae
Where Next?
(16) PS Vae kena Zen on)
oy
20
Fry
Fy
26
30
Er
34
Ed
38
rr
rr
44
ery
48
Ey
Pt
56
a
Renny
Equipment You will Need
ere
Ce Ua
Coes unread
Sena Mom aaa
See ne ry
ET ea ete orig
Executing Code from the Command Line
Pee
Using Comments
on orn er
east
cere
Conditions and Loops
Python Modules
Lists
a
Cee eee
Ee eee
Cees Renee)
CMe
Cea Ra
66 Opening Files
68 Writing toFiles
eres on
Ee ed
76 Calendar Module
LCs
Cacao cs
Caer
Cee
Cocca tan
90 Create Your Own Modules
PPM ent)
Pen)
ce ees
Teal teeteae nT
102 Howto Set Up C++ in Linux
104 Other C++ IDEsto Install
CMM etees trict)
Crete etc
pee uc Econcdie
@
w
Z
[
a
9
rT MOS eouurcy
STM rnc
CMT?
POs
cre eee iy
) (ovaries
eer
pro ecm ncn
Ei Tees
PM ei
rae ery
Pe Mage
cy eee er)
comes
Trae
Sy MRecn ME boty
Cee ead
(1s0) Code Repository
See Ea
154 Number Guessing Game
re ees
157 Random Password Generator
Cece enc
mua keg
“Good code is short, simple, and
ene Rene ate a
Figuring out how to get there.”
~ Sean Parent (Developer and author)
eee)Working
with CodeIt’s always worth looking at the common
pitfalls of coding before you start hitting
away at the keyboard; after all, bad
habits are often formed at the start
of a process. IF you're aware of how to
structure your code before you begin,
then you will learn to avoid most of the
mistakes that usually accompany poorly
developed code.
This section starts your coding journey
by examining those common mistakes,
as well as investigating where your
coding skills can take you as your
experience grows.
“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)mmon Coding Mistakes
Co
UN tReeeMehea MMe NR ME Aue come neIy Tag
CMe ee edie ne ore at een aad
Seo aeM oat Relea Oa Sa MUN Cod CCUM MSEC Cole]
X=MISTAKE, PRINT Y
There are many pitfalls For the programmer to be aware of, Far too many to be listed here. Being
able to recognise a mistake and fix it is when you start to move into more advanced territory, and
become a better coder. Everyone makes mistakes, even coders with over thirty years’ experience.
Learning from these basic, common mistakes help build a better coding Foundation. e
EASY VARIABLES
"Meaningful naming for variables is @ must to eliminate
common coding mistakes. Having letters ofthe alphabet
isfine but what happens when the code states there's.
a problem with x variable. I's not too dificult to name
variables tives, money, playert and soon.
would be wonderful to be able to
‘work lke Neo from The Matrix movies
Simply ask, your operator loads it into
your memory and you instantly know
everything about the subject. Sadly
though, we can't do that. The First
‘major pitfallis someone trying to learn
too much, too quickly. So take coding in
small pieces and take your time.
points = 1023;
lives = 3;
tovaltime = 457
write("Points: "spoints);
write("Lives: "s1ives);
write("Total Tine: "+totalTine
write(
//COMMENTS write("Your total Score is: "+totalscore) ;
Use comments.’ simple concept but commenting on
jour code saves so many problems when you next come to
took overt Inserting comment Uneshelps you auch sift PLAN AHEAD
through the sections of code that are causing problems;
also useful if you need to review an older piece of code. Ce a ee ee
a classic text adventure, it's not always practical without a
‘900d plan. Small snippets of code can be written without
too much thought and planning but longer and more in
depth cade requires a good working plan to stickto and
help iron out the bugsUSER ERROR
BACKUPS
Sa ECR a ama}
SECURE DATAz= Working with Code )
Python Beginner's Mistakes
SCC eon Meee ence Meer schisms
Ree Le Coe Me Rae er)
language, it can be easy to make common mistakes that'll stop your code from running.
DEF BEGINNER(MISTAKES=10)
Here are ten common Python programming mistakes most beginners Find themselves making. Being able to identify these
‘akes will save you headaches in the Future.
VERSIONS
Todd to the confusion that most beginners already face when
coming into programming, Python has two live versions of its
language available to download and use. There is Python version
2.T.xand Python 3.6.x. The 3.6.x version isthe most recent, and
the one we'd recommend stating. But, version 2.7 xcode doesn't
always work with 3.6.x code and vice versa,
python
THE INTERNET
Every programmer has and does at sme point goon the Internet
{and copy some code to insert nto their own routines. There's
‘nothing wrong with using others’ code, but you need to know how
the code works and what it does before you go blindly running ton,
your own computer.
Creatldelete xt fle na pynon program
EDD ows eFintive Gude series-Volume 4
INDENTS, TABS AND SPACES
Python uses precise indentations when displaying ts code. The
indents mean that the code in that section s apart ofthe previous
statement, nd not something linked with another part ofthe code.
Use four spaces to create an indent, not the Tab key.
COMMENTING
‘Again we mention commenting. t's a hugely important factor in
programming, even if you're the only one wito is ever going to view
the code, you need to add comments as to what's going on. Is this
Function where you lose aife? Write a comment and help you, or
anyone else, see what's going on,COUNTING LOOPS
Remember thatn Python 3 loop doesn't count the last number you
specify ina range. Soif you wanted the loop to count from 1 to 10,
then you will need to use:
n = List(range(1, 11))
Which will return 1 to 10.
TW reeatine =e x
CASE SENSITIVE
Python is acase sensitive programming language, so you will need
to.check any variables you assign For example, Lives=10 isa
different variable to lives=10, calling the wrong variable in your code
can have unexpected results
Fle Edit Shell Debug Options
Python 3.6.2 (¥3.6.2:5¢a33b5, Jul
fon wins?
Type "copyright",
DSS Lavess10
>>> Lavesss
>>> prins (Lives, lives)
® 2017, 04
3
Noxedite" or "1icense()" for mor
BRACKETS
Everyone forgets ta include that extra bracket they should have
‘added to the end ofthe statement. Python relies onthe routine
having an equal amount of closed brackets ta open brackets, so any
errors in your code could be due to you forgetting to count your
brackets including square brackets.
def print_game_status(seif):
print (board[len(self.missed_letters)])
Print ("Word: ' + self-hide word())
print (‘Letcers Missed: ',)
for letter in self.missed letter:
print (letcer,)
print 0
print ("Letters Guessed: *,)
for letter in self.guessed letters:
print (letcer,)
print ()
(_ Python Beginner's Mistakes
COLONS
It’s common for beginners to Forget to add a colon tothe end of a
structural statement, such as
class Hangman:
def quess(self, letter):
‘And so on. The colonis what separates the code, and creates the
indents to which the Following code belongs to.
OPERATORS
Using the wrong operators also common mistake to make. When
youre performing a comparison between two values, for example,
you need to use the equality operator (a double equals, ==). Using
{single equal =) san assignment operator that places a value to 3
variable (such as, Ives=10).
OPERATING SYSTEMS
\writing code For multiple platforms is dificult, especially when you
start to utilise the external commands ofthe operating system, For
‘example, iF your code calls For the screen to be cleared, then For
Windows you would use és. Whereas, for Linux you need to use
‘Lear. You need to solve this by capturing the error and issuing it
with an alternative command,
+ coae to aes:
‘ce-ayotem(‘ciess")
————z= Working with Code )
C++ Beginner's Mistakes
There are many pitfalls the C++ developer can encounter, especially as this is a more
Cou eieunnrn lente esc me chee cere rc)
pene eh ars al Coil Kora TaeToay
VOID(C++, MISTAKES)
Admittedly
's not just C++ beginners that make the kinds of errors we outline on these pages, even hardened coders are
prone to the odd mishap here and there. Here are some common issues to try and avoid.
UNDECLARED IDENTIFIERS
‘Acommon C++ mistake, andto be honest a common mistake with
‘most programming languages, s when youtry and output a variable
that doesnt exist. Displaying the value of x onscreen isfine but not
ifyouhaver't told the compiler what the value of xis to begin with
File Edit View Search Tools Documents Help
AoH&in»e~|xaOH|iag
(Citestt.cpp x
#include
GCC OR G++
IF you're compiling in Linux then you willno doubt come across
‘gccand g++. Inshort, gcc the Gnu Compiler Collection (or Gnu
C Compiler as it used to be called) and ge isthe Gnu ++ (the Cr+
version) of the compiler. you're compiling C++ then you need to,
use g++, asthe incorrect compiler drivers willbe used.
davidermint mate “Documents
Fle Edt view Search Termin HelpCOMMENTS (AGAIN)
Indeed the mistake of never making any comments on code is back
‘once more. As we've previously bemoaned, the lack of readable
identifies throughout the cade makesit very difficult to look backat
hhowit worked, for both you and someone else, Use more comments.
QUOTES
‘Missing quotes is a common mistake to make, for every level oF user.
Remember that quotes need to encase strings and anything that's
going to be outputted to the screen or into a file, For example, Most
compilers errors are due to missing quotes in the code,
EXTRA SEMICOLONS
‘while it’s necessary to have a semicolon at the end of every C++ line,
thereare some exceptions to the rule. Semicolons need to be at
the end of every complete statement but some lines of code aren't
complete statements. Such as:
include
if lines
switch Lines
\Fitsounds confusing don’t worry, the compiler lets you know where:
you went wrong,
(_ C++ Beginner's Mistakes Cl
TOO MANY BRACES
‘The braces, or curly brackets, are beginning and ending markers
~around blocks of code. So for every {you must have a}. Often is
‘easy to include or miss out one or the other Facing brace when
‘writing code; usually when writing in a text editor, as an IDE adds
them For you.
#include > x;
cout << x;
{
cout << "\n\n
cout << mystring
+
INITIALISE VARIABLES
In C++ variables arent initialised to zero by default. This means if
Yyou create a variable called x then, potentially, itis given arandom
number fram 0 to 18,446,744,073, 709,551,616, which can be
using namespace std;
dint maint)
c
int x:
cout << x;
»
A.OUT
‘A common mistake when compiling in Linux is Forgetting to name
your C++ code post compiling. When you compile Fram the Terminal,
you enter:
t+ code.cpp
‘This compiles the code in the File code.cpp and create an aut file
that can be executed with /a.out. However, iFyou already have code
in acoutthenit's overwritten, Use:
‘gt code.cpp =o nameofprogram
Fle Ede Vow search Temi! tpz= Working with Code )
Where Next?
Coding, like most subjects, is a continual learning experience. You may not class yourself
Creve stele TaN et Mole otal Male colc molt mele MCL eee eco}
Rae Meee A agree re RCD Ue enol t= 1are CCE olen im cere CANT ed Ue Ue
#INCLUDE
What can you do to further your skills, learn new coding practises, experiment and present your code and even begin to help
‘thers using what you've experienced so far?
OPEN PROJECTS
Look for open source projects that you tke the sound of and offer
TWITTER
‘Twitter isrtall trolls and antagonists, among the well publicised
vitriol are some genuine people who are more than wing to spread
their coding knowledge. We recommend you find a few who you can
‘late to and follow them. Often they post area tips, hacks and fixes
fForcommon cading problems.
a
=
—
eo
KEEP CODING
\f you've mastered Python fairly wel then turn your attention to
Cetoreven GH. Sill keep your Python skis going butlearing anew
cading language keeps the old bran ticking over nicely and give youa
view into another community, and how they do things differently.
sos ten ie Sets ome t
to.contribute tothe code to keep it alive and up to date. There are
millons of projects to choose From, so contact a few and see where
they need help. It may only be a minor code update butit’s a noble
‘occupation for codersto getinto
SHARE SKILLS
Become more active on coding and development knowledge sites,
such as StackExchange, If you have the skilto start and help others
‘out, not only will you feel really good for doing so but you can also,
learn alot yourself by interacting with other members.GOING MOBILE
The mobile market sa great place to test your coding skills and
present any games or apps you've created. IF your app is good, then
‘who knows, it could be the next great thing to appear on the app
stores. t's a good learning experience nevertheless, and something
worth considering
Dcoonhoy =
i
ar
ONLINE LEARNING
Online courses are good examples of where to take your coding
skills next, even iF you start from the beginner level again. Often,
an online course follows a strict coding convention, soif you're se
taught then it might be worth seeing how other developers lay out
their code, and what's considered acceptable.
Learn to code interactively, for free.
SHARE CODE
Get sharing, even if you think your code isnt very good. The
iitcism, advice and comments you receive back help you iron out
~any’ssues with your code, and you add them alto your checklist
Alternatively your code might be utterly amazing but you won't
know unless you share t
( Where Next? Cl
PORTFOLIOS
IF you've learned how to code with an eye Fora developer jab in
the Future, then k's worth starting to build up an online portfolio
‘of code. Look at job postings and see what skills they require,
then learn and code something with those skills and add itto the
portfolio. when it comes to applying, include alinkto the portfolio,
My Work
TEACH CODE
Can you teach? IF your coding sil are spot on, consider
approaching a college or university to see iFthey have need fora
programming language teacher, pethaps.a part-time or evening
‘course. not teaching, then consider creating your own YouTube
how to code channel
HARDWARE PROJECTS
Contributing to hardware projects isa great resource For proving your
‘ode with others and learning from ther contributors. Mary of the
‘developer boards have postings for coders to apply to For hardware
projects, using unique code to get the most from the hardware that's
being designed,Say Hello
to Python
“The best programs are written so that computing
machines can perform them quickly, and so that
human beings can understand them clearly.”
= Donald E. Knuth (Computer scientist, mathematician and author)
sos ten ie Sets ome tSay Hello to Python
‘There are many different programming
languages available to learn and use. Some
are terrifically 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 &
a generous helping of power, allowing
the user to create projects ranging from
minor utilities through to great games and
performance-heavy computational tasks.
However, there's more to Python than
simply being another programming
language. It has 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, so now it's your turn to
take the plunge and learn how to program
in Python.
This section will get you started with
Python and introduce you to this.
remarkable programming language.
Before long, you will be able to code
your own helpful systems tools, text
adventures and even control a character as
they move around the screen.
18 WhyPython?
20 Equipment You Will Need
22 Getting to Know Python
24 How to Set Up Python in Windows
How to Set Up Python in Linux
ora bdmpublications comWhy Python?
DOSE Miccn a ae cua cute ICM Cm murine etcis
Pues eR cece hanitetic cect aaarc dents
Ere Kel core Cece lee The AOC Ceol CP Cece eR Ue mc R WA Renee)
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 al
‘These pioneers of programming carved their way into a new
Frontier, Forging small routines that enabled the letter ‘to scroll
‘across the screen It may not sound terribly exiting to a generation
that's used to ultra high-defintion graphics and open world, multi
player online gaming, However, forty-something years ago it was
blindingly brillant.
‘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.
Regardless of whether you use an Android device, 10S device, PC,
‘Mac, Linux, Smart TY, games console, MP3 player, GPS device builtin
to. car, settop box ora thousand other connected and ‘smart
appliances, behind them allis programming.
tomagi
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 on the situation, the
platform, the device's use and how the device wil interact wth ts
‘environment or users. Operating systems, such as Windows, macOS
‘and such are usually a combination of C+, CH, assembly and some
form of visual-based language. Games generally use C++ whilst web
pages can use a plethora of available languages such as HTML, Java,
Python and so on.
More general-purpose programming is used to create programs,
_apps, software or whatever else you want to cal them. They're
widely used across all hardware platforms and suit virtually every
‘conceivable application. Some operate Faster than others and some
* visenaeecs)@ 9/8 [mee ¥/>/5@
one Giro a
el | enema? F
oe = void Arrayctrl::childLostrocus()
- ae if (cursor >= 0)
wo Ret reshRow(cursor);
pacman carton tontrocue (hE
econ exec a) >
[Saris | Bntens |
Shaman
Sree
Shoe Sree ese eSeShaets
oer et
ae ‘bottom = 0;
ou ‘ taarocusonep();
ee, ee
$5, estserotls
ee ip < column. cartoon; jae)
Sonos Ya cx header ti sbaaath (jel
Stones FECT ag er ertgrad s Lye'm colum.cetcount() = 20) = 0)
Bicone sauce i
Seance Soman
Sources rc »
JSewrce rman || Gator fe = Slndtscolortisbled, scolerbane
Sascan” (Graces eal
Banc Srna TENELE. etcount()
eames rec leet) ah
Steestwcp|pnae” =] {bottom = rap t oetLinecy i:
BED conserve aude Series-Volume 24Why Python?
{are easier to lear 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 avarety of arrays,
variables, objects, arithmetic, subroutines, loopsand countless
‘more interactions. Whilst it's not as streamlined as a Low-Level
Language, which can deal directly with memory addresses, cal
stacks and registers, ts benefits that i's universally accessible
{and easy to lear.
Python was created over twenty sixyears ago and has evolved to
become an ideal beginners language fr learning how to programa
computer.’ perfect for the hobbyist, enthusiast, student, teacher
and those who simply need to create their own unique interaction
between either themselves or a piece of extemal hardware and the
computer itself
Python i Free to download, install and use ands available For Linux,
\windows, macOS, MS-DOS, 05/2, BeOS, IBM iseries machines, and
‘even RISC OS. Ithas been voted one of the top five programming
languages in the world and fs continually evolving ahead
(of the hardware and internet development curve.
‘Soto answerthe question: why python? Simply
pt, it's Free, easy to learn, exceptionally
powerful, universally accepted, effective
{and a superb learning and educational tol
[/7FiTe: invoke. java.
Fimport java. lang.reflect.*;
class tnvoke
Dublie_ static void main( string [) args ) £
try,
Crass ¢ = Class. forname( args[0] );
Method m = c-getMethod( argsii], new class
03 5
object ret = _m.invoke( null, null);
systen.out.printinc
“Tnvoked. static method: " + args{1)
+ of class: © + args[o]
Tn with no args\nResults: " + ret);
} catch ( Classnocroundexception e ) {
77 Class. fornane(”) can't find the class
} Gatch C Nosuchethodexception e2') {
JnaisapovertllamungetiptSuseainwed — ll
8
eee 8
#
8
3
2
HB
if
Ho
Z
: iS
i
Python is a more modern take on BASIC, it’s easy to learn BASIC was once the starter language that early
sp Ut esiecbabieabeaey
na bempublcatonszx Say Hello to Python)
Equipment You Will Need
ole TaN aM R YB (Lee CURT Ke LUZ 1k MeL OTL U MRT 1aCe= Ma een ol)
clea een arse lao Ui Cee UU ANU ear early
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.
01 tn ct Ses
volume 24
COMPUTER
Obviously you're going to need a computer in order to learn how to
program in Python and to test your code. You can use Windows from
XP onward) on elther a 32 or 64-bit processor, an Apple Mac or Linux
Installed PC.
[_] AN IDE
AniDE (Integrated Developer Ervironment) is used to enter and
execute Python code. It enables you to inspect your program code and
the values within the code, as well as offering advanced Features. There
are many different IDEs avaliable, so find the one that works For you
and gives the best results
PYTHON SOFTWARE
1macOS and Linux already come with Python preinstalled as part of the
‘operating system, as does the Raspberry P. However, you need to
ensure that you'r running the latest version of Python, Windows users
need to download and install Python, which well cover shorty
TEXT EDITOR
\Whilst a text editors an ideal environment to enter code into, it's not
an absolute necessity. You can enter and execute code directy From the
IDLEbuta text editor, such as Subime Text or Notepad++, offers more
advanced features and colour coding when entering code.
INTERNET ACCESS
Python isan ever evolving environment and as such new versions
‘often introduce new concepts or change existing commands and code
structure to make tt a more efficient language. Having accessto the
Internet will keep you upsto-date, help you out when you get stuck and
give access to Python's immense number of modules.
TIME AND PATIENCE
Despite what other books may lead you to believe, you won't become
a programmerin 24-hours. Leaming to code in Python takes time, and
patience. You may become stuckat times and other times the code wll
Flow tke water. Understand you're learning something entiely new, and
‘you wil get there.(aipnentvouvainees CE
THE RASPBERRY PI
Why use a Raspberry Pi? The Raspberry Pisa tiny computer that’s very cheap to purchase but offers the user a fantasticlearning
platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many modules and extras.
Saag)
The Raspberry Pi3 isthe latest version, incorporating a more
powerful CPU, more memory, Wii and Bluetooth suppor.
You can pick up a Pi for around €32 or as apart of kit For £50+,
depending on the kit you're interested in.
FUZE PROJECT
The FUZE isa learning environment built on the latest model ofthe
Raspberry i. You can purchase the workstations that come with an
‘electronics kit and even a robot arm for you to build and program.
‘You can find more information on the FUZE at www.Fuze.co.uk
Tele) <3 Codine io
Raspberry Pitts available in
«cam, Our Pibooks cover how “et
Py set tup and use i; there
7S
The Rasbery Ps man operating systems Debian based
Ur dstrbuton that comes ith everyingyou nee
dimple to ue paclage ls stesmined forthe Mandan fet ecrien
‘deal platform for hardware and software projects, Python = ie
J programming and even asa desktop computer meetene’ Raspberry Pi
» she Beginners’ Guide
az= Say Hello to Python)
Getting to
Know Python
Mae iccecceei lca tected eater Raver cite a tatoos
you to fully harness the power of a computer, in a language that’s clean and easy
eon eC IT
WHAT IS PROGRAMMING?
It helps to understand what a programming language is before you try to learn one, and Python is no different. Let's take 3
look at how Python came about and how it relates to other languages.
‘A programming language
isa listof instructions that
‘a computer follows. These
instructions can be as simple
‘as displaying your name
or playing a music file, or
ascomplexas building a
‘whole virtual world. Python
isa programming language
conceivedin the late 1980s
Eby Guido van Rossum
Eat Centrum Wiskunde &
Informatica (OW) in the
Netherlands asa successor to
PROGRAMMING RECIPES
Programsare ke recipes for computers.
recipe to bake a cake could go like this: 2
Put 100 grams of selfaising flourin a bow
‘Add 100 grams of butter tothe bowl,
‘Add 100 mlliitres of milk.
Bake for half an hour,
CODE
Just lke a recipe, @ program consists of instructions that you follow
in order. A program that describes acake might run like ths:
bowl =
the ABC language Heese Bete
milk = 100 SEES Bacnae meant)
Guido van Rossum, the
Father of Python.
bon .append( flour, butter mic]
Il cake. cookCbon)
PROGRAM COMMANDS
You might not understand some of the Python commands, lke bowL append and cake.cook(bowl)
The firsts 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 easy to
Figure out how a program works,
ov tn ise volun 4HIGH-LEVEL LANGUAGES
Computer languages that are easyto read are known as high evel
Thisis because they fly high above the hardware (also referred to as
‘the metal’) Languages that fly close to the metal lke Assembly,
are known as “low-level”. Low-level languages commands read abit
likethis msg db ,@xa len equ $ - msg,
PYTHON 3 VS PYTHON 2
Cettngtoknow exten CE
ZEN OF PYTHON
Python lets you access all the power of a computer in language
that humans can understand, Behind all this isan ethos called "The
Zen of Python." Ths isa colection of 20 software principles thet
influences the design ofthe language. Principles include “Beautiful
isbetter than ualy" and "simple i better than complex." Type
import: this into Python and it wil dsplay al the principles.
Ina typical computing scenario, Python is complicated somewhat by the existence of two active versions of the language:
Pee Lene!
er oes
Roe ates
digalittle deeper into the Python site, and investigate
PYTHON 2.
eer iy Cite
prea aioe
Plone tee ara ee tons
able resource.
rome ea
Ceres
Br
at
Senet
PYTHON 3.X gpusdsiuene eames Rae rearing
Pen terre
pond Se ea
eerste cet ee garnet at
poco ripts, modules and tutorial
not popular at frst, Python 3 has since become the cutting edge of
Coo
ER ACER Python 3's arowing popularity h
oases
ee ea
Many development companies, uch as SpaceX and NASA use
Python For snippets oF mportank code,z= Say Hello to Python )
How to Set Up
Python in Windows
Windows users can easily install the latest version of Python via the main Python
Downloads page. While 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.
san easy process to follow.
ESTs ERED S2"tby opening your web browser to www.python.
‘ra/downloads/. Look for the button detailing
the download link for Python 3.x. The latest version atthe time of
\weting fs 3.7.0 but as Python is frequently updated this may bea
different version for you.
Thankfully,
tan Ceensey
Python for
to help test developmen
ae Pee
Click the Download button for version 3x, and
save the file to your Downloads folder. When the
fle is dawnloaded, double-click the executable and the Python
installation wizard wil launch, From here you have two choices
Install Now and Customise Installation, We recommend opting for
the Customise installation link.
_
Siar
Install Python 3.7.0 (32-bit)
wind Chae Pyne 379 EH
ET 220 re cite sees vole 4
BITEAED Choosing the Customise option allows you to
specify certain parameters, and whilst you may
stay with the defaults, i’ 2 good habit to adopt as sometimes (not
‘with Python, thankfully) installers can include unwanted additional
Features. On the fist screen available, ensure all boxes are ticked
and click the Next button,
Optional Features
Comes
Pear moet nae
Spm Beant
mw
Fi sepmen
wind
Pal
The nest page of optionsinclude some interesting
ue additions to Python. Ensure the Associate file with
Python, Create Shortcuts, Add Python to Environment Variables,
recom Standard brary and talfor Aller option are
ticked. These make using Python ater much easier, ick nsalwhen
yeue ready to contrue
‘Advanced Options
‘acme tn fi gy ee)
mw
a [eager RSE
windYou may need to confirm the installation with the
Windows authentication natifcation Simply lick
Yes and Python wil begin to instal, Once the installation is complete
the final Python wizard page wil allow you to view the latest release
notes, and Fllow some online tutorials,
Setup was successful
_/ rm
windows.
Before you close the install wizard window,
Sy
however, it's bestto click on the link next to the
shield detalled Disable Path Length
20 bypass the Windows 260 charac
‘execute Python programs stored in de
‘Again, click Yes to authenticate the process
installation window.
rit, This will alow Python
limitation, enabling you to
olders arrangements.
en you can Close the
© cisabie pathlength iit
‘close
ndows 10 users can now =
find the installed Python o
3.xwithin the Start button
Recently Added section
The First ink, Python 3.7
(32-bit will aunch the
command line version of
Python when clicked (mk
fon that in a moment). To
‘open the IDLE, type IDLE
sur wyona7 280
How to Set Up Python in Windows Cl
BED licking on the IDLE (Python 3.7 32-bit) link wll
launch the Python Shell where you can begin
your Python programming journey. Don't worryf your version is
newer as long at's Python 3.x our code works inside your
Python 3 interface,
{ ster 9 ) IF you now click on the Windows Start button again
{and this time type: €MD, you'lbe presented with the
Command Prompt ink. Click it to get to the Windows command ine
environment. To enter Python within the command line, you need
totype: python and press Enter.
BED The command line version of Python works in
much the sare way asthe Shell you opened in
Step 8; note the three leftfacing arrows (>>>). whilst i's a perf
Fine environment, it's not tao user-friendly, so leave the command
line For now. Enter: exit to leave and close the Command
Prompt windoSay 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, but for this particular tutorial, we will stick to Linux Mint.
PEPER Fistyounced to ascertain which version of Pyth
iscurrently installed in your Linux system. To begin
‘with, drop into a Terminal session from your distro's menu, or hitthe
Ctrlsalte keys
dovide david tine -
SPD Nex enter python =version nto te Terminal
Siape screen. You should have the output relating to
version 2x Python ithe splay By deta, mos Linu dios
‘come with both Python 2 and 3, as there's plenty of code out there
stil available For Python 2. Now enter: python3. =-versicn.
avidodavid nine: ~
Inour case wehave both Python 2 and installed
SUP ‘As long as Python 3.x.xis installed, then the code in
cur tutorials ork les aways worth checking to see the dito
has been updated withthe latest versions, enter: sudo apt=get
update && sudo apt-get upgrade to update the system,
vison nine —
‘BOM Definitive Guide Series- Volume 24
‘Once the update and upgrade is complete, enter:
SUED pythons --version saintoseeifPytion 3x
isupdated or even installed. Aslong as you have Python 3x, you're
running the most recent major version, The numbers after the 3.
indicate patches and Further updates. Often they/re unnecessary,
but can contain vital new elements.
‘onever Fyouwantthe atest, cating edge
Sug? version, you'll need to build Python from source.
Start by entering these commands into the Terminal:
sudo opt-get install build-essential checkinstall
sudo apt-get install libreadline-gplv2-dev
Libncursesn5-dev libssl-dev libsqlite3-dev tk-dev
Libgdom-dev Libc6-dev Libbz2-devHow to Set Up Python in Linux
pen upyour Linux web browser and go to the
BALD eon downoad page: https wwwpython.ora/
downloads. Click onthe Doiloads flowed by the button under
the Python Source window. This opens a download dialogue box
choose location and tart the download process,
In the Terminal, goto the Downloads Folder
byentering: ed Downloads/. Then unzip the
Contents of the downloaded Python source code using: tar’ =xvF
Python-3.Y.Y.tar.xz. (replace the Y's with the version numbers
you've downloaded), To access the newly unzipped Folder, enter: ed
Python-3..¥/.
FEED Within the Python folder, enter:
-/configure
sudo make altinstall
This could take a while, depending on the speed of your computer.
(Once finished, enter: python3.7 -=version to check the
latest installed version. You should now have Python 3,7 installed,
‘alongside older Python 3.xx and Python 2.
Forth GUIIDLE,you'need to ener the Following
SH) command into the Terminal:
sudo opt-get install iale3
TheIOLE can then be started with the command: tl e3. Note that
DDLErunsa diferent verson fromthe one you instaled from source
“voc in. -/oomnloda/tyhon 372
Youll ato need iP (ip sal Pacages) hich
SHEP tool to help you install more modules and extras.
Enter: sudo apt-get install python3-pip
IPs then installed, check forthe latest update with
pip3 install --upgrade pip
‘When complete, close the Terminal and Python 3 willbe available
via the Programming section in your distro's menu.
evident -/Domiotrython 72 -
Installation of Python on mac0S can be done in much the
same way as the Windows instalation, Simply go tothe Python
webpage, hover your mouse pointer over the Downloads link
and select Mac 0S X from the options. You willthen be guided
tothe Python releases for Mac versions and the necessary
installers for macOS 64-bit, For 05 X 10.9 and later.
vemrimuteatorscom“| have always wished for my computer to be as
easy to use as my telephone; my wish has come
true, because | can no longer figure out how to
use my telephone.”
— Bjarne Stroustrup (Developer and creator of C++)
IE) 20s eve crests voteGetting Started with Python cl
Learning how to code may seem a
little daunting at First. Thankfully, the
Python language has been designed
with simplicity in mind. Like most things,
you need to start slow, learn how to get
a result and how to get what you want
from the code.
Inthis section, we will cover the core
concepts: saving and executing your code,
variables, numbers and expressions, user
input, conditions and loops.
30 Starting Python for the First Time
32 Your First Code
34 Saving and Executing Your Code
36 Executing Code from the Command Line
38 _ Numbers and Expressions
40 Using Comments
42 Working with Variables,
44 User Input
46 Creating Functions
48 Conditions and Loops.
50 Python Modules@) Getting Started with Python )
Starting Python For
the First Time
The Raspberry Pi offers one of the best all-round solutions For learning and coding on,
in particular, Python. Raspbian, the Pi’s recommended OS, come pre-installed with the
latest stable version of Python 3, which makes it a superb coding platform.
STARTING PYTHON
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 for coding.
FETTSEDD With the Raspbian desktop loaded, click onthe EATERED £0" example, in the Shell enter: 242
"Menu button followed by Programming > Python 3 ‘After pressing Enter, the next line will display the
(OLE. This will open the Python 3 Shel. 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.
‘meni and via Finder.
PEPIIP DD The shellis where youcan enter cade andseethe ESB the Python shall acts very much ike a calculator,
responses and output of code you've pragrammed since code fs basically a series of mathematical
into Python. Thissakind of sandbox, where you're abet try out interactions with the system. Integers, which ae the infinite
some simple code and processes. sequence of whole numbers can easily be added, subtracted,
multiplied and so on.
ise Stee rasa o eas
ET 220i sees volunStarting Python for the First Time cl
ESTED) While thats very interesting it's not particularly
exciting, Instead, try this
print(*Hello everyone!”)
Just enter it nto the IDLE as you did in the previous steps.
licking on the Highlighting tab, However, we don't recommend that
_asyou won't be seeing the same as our screenshots,
ESSER Thisise litle more tke it, since you've just produced
your first bit of code. The Print commands Fairty
self-explanatory, 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!™)
Hello everyone!
>>> |
FTTED lust lke most programs available, regardless of the
‘operating system, there are numerous shortcut
keys avallable. We don’t 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.
Bare AD You may have noticed the colour coding within
the Python IDLE. The colours represent different
elements of Python code. They ae:
Black -Data and Variables
Green Strings
Purple—Functions
(Orange - Commands
Blue— User Functions
Dark Red Comments
Light Red ~ Error Messages,
IDLE Colour Coding
[-eeteur [use tor_[exampies
antes [Ererrosuote | syntanteror
FEPSETR The Pithon IDLEis a power interface, and one
that’s actually been written in Pythan using ane
(of the available GU! toolkts. F'you want to know the many ins and
cuts forthe Shell, we recommend you take afew moments to view
‘www.docs.python.org/3/library/idle.html, wich details many oF
the IDLE's FeaturesEA) ceintnatnnenn
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
wi
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.
STEERED you've closed Python 3 IDLE, reopen itin PEPER You can see that instead ofthe number 4, the
whichever operating system version you prefer. In outputs the 2+2 you asked to be printed tothe
the Shell enter the Familiar Following: 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)
print(*Hetlo”)
rs ye a a “cfr me att
ESTeeE RD vst as predicted, the word Hello appearsin the BITeEE MD You can continue as such, printing 242, 46442343
Shellas blue text, indicating output from a string and s0.on ta the Shell. An easier way is touse a
's airy straightforward and doesnt require too much explanation. variable, which is something we wil cover in mare depth later. For
Now try now, enter:
print(*2+2") on?
ETD 200s velarys
( Your First Cod
(Your First Code Cl
\What you have done here assign the letters
and b two values: 2 and 2. These are now variables,
\which can be called upon by Python to output, add, subtract, divide
{and soon for as long a their numbers stay the same. Try ths:
printCa)
print(b)
1s Es Sh One ew
Ly
BETTE The output ofthe last step displays the current
values of both a and b individually, as you've asked
them tobe printed separately. Ifyou want to add them up, you can
Use the following
print(a+b)
‘This cade simply takes the values of a and b, adds them together
and outputs the result
You cn ply around with afeent kinds of variables
SUP and the Print function. For example, you could
‘assign variables for someone's name:
nane="David”
print(nane)
PEED Now let's add surname:
surnane="Hayward”
print(surnane)
‘You now have two variables containing a frst name and a surname
‘and you can print them independently
1 Ea sh Dt oom nts en
TELE ve were to apply the same routine as before,
Using the + symbol, the name wouldn't appear
correctly in the output inthe Shell. Ty it
print (name+surname)
You need a space between the two, defining them as two separate
values and not something you mathematically play around with,
printCname, surname)
In Python 3 you can separate the two variables
with aspace using a comma:
‘Alternatively, you can add the space ourselves
printCnane+” “+surnane)
‘The use of the comma is much neater, as you can see,
Congratulations, you've ust taken your First steps into the wide
‘world of Python.
ora vmpublcatonscom@) Getting Started with Python
Saving and Executing
Your Code
VCR tea ests trot cee cece Ke Ea em eto
Penal cae ca accieul ea ce Mice cca n otha h else
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.
STEERED Fi'st.open the Python IDLE shell and when i's up, JESTESIEMM You can see that the same colour coding isin place
dlickon File > New Fie. This will open a new window the IDLE Editor asit is inthe Shell, enabling you
‘with Untitied as its name. Thisis the Python IDLE Editor and within it vo better understand what's going on with your code. However, to
you can enter the code needed to create your Future programs. _ execute the code you need to first save It. Press FS and you get a
‘save...Check box open,
Thelte eer oratinertssedouosis EERE) clekonthe Ocbuton inte Sve boxandseets
Suara simple text editor with Python features, colour cue? destination where you'll save all your Python code.
cading and so on; much in the same vein as Sublime. You enter ‘The destination can be a dedicated Folder called Python or you
code as you would within the Shell so taking an example from the canst dump it wherever you lke, Remember to keep atidy drive
previous tutorial, enter: though, to help you out the Future.
print(*Hello everyone!”
ET 220i seesEnter a name for your code, ‘print hello’ for
‘example, and clickon the Save button. Once the
Python code is savedit's executed and the output will be detalledin
the IDLE Shell n this case, the words Hello everyone!
FETTER Thisishow the vast majorty of your Python code
willbe conducted. Enter it into the Editor, hit F5,
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
Use throughout this book, unless otherwise stated
(_ Saving and Executing Your Code Cl
Let's extend the code and enter afew examples
From the previous tutoriat
0-2
be2
rnane="David”
surnane="Haynard”
printCname, surname)
print Casb}
IF you press FS now youll be asked to save the file, again, s t's been
modified from before.
IF you click the OK button, the File willbe
‘overwritten with the new code entries, and
Sia
‘executed, withthe output in the Shell. I’s not a problem with just
these Few tines butf you weretto edit a larger file, overwriting can
become an issue. Instead, use File > Save As from within the Editor
tocreatea backup,
Ifyou open the file Location ofthe saved Python
code, youcan see that it endsin apy extension.
Thisis the default Python file name. Any code you create will be
whatever py and any code downloaded from the many Internet
Python resource sites will be py. Just ensure that the code is written
for Python 3
[ie ES Fame fin tom We
Now create new fle. Close the Eloy, and open
Suid anew instance (File > New File from the Shell).
Enter the following and save tas hello:
‘a="Python”
be"is”
c="cool!”
print(a, b, ¢)
‘You will use this code in the next tutorial
= we
———Getting 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.
Ez Python, in Linux, comes with two possible ways ol BED Now you'e atthe command ine we can stat
‘executing code via the command line. One of the Python, For Python 3 you need to enter the
th Python 2, whilst the other uses the Python 3 libraries ‘and python3 and press Enter. This will put you into the
‘on. First though, drop into the command line or Terminal on ll, with the familar three right
Your operating system,
Fae EED sm here you're able to enter the code you've
7 looked at previously, suchas:
Windows users will
so an2
printCa)
You can see that it works exactly the same.
macOS users can get access
0 their command line by licking
Go> Utities > Terminal
‘BOM Definitive Guide Series- Volume 24Executing Code from the Command Line Cl
Now ener: ext to eave the commandtine Pon
Suz session and return you back to the command
prompt: Enter the Folder where you saved the code from the
previous tutorial and list the available Files within; hopefully you
should see the hello.py ile,
Sy
From within the same Folder asthe code you're
‘ong to run, enter the Following into the
python3 hello. py
This wll execute the code we created, which to remind yous:
‘as"Python”
i
ca"cool!”
print(a, b, ¢)
Naturally since this s Python 3 code, usin
ED ia: ac ayoutthars unique to Python 3, only
works when you use the python3 command. IF you ike, try the same
with Python 2 by entering:
python hello.py
EED The result of running Python 3 code from the
Python 2 command lin s quite obvious. Whitt
esn't error out in any way, due to the differences between the
way Python 3 handles the Pri command over Python 2, the result
Using Sublime For the moment, open the
isn't as we expecte
hellopy file,
{ ster 9 ) Since Sublime Text isnt available For the Raspberry
Pi, you're going to temporarily leave the Pi For the
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:
nane=input¢“What is your name? “)
printC‘Hello,”, name)
Save the heliopy file and drop back tothe
commandline. Now execute the newiy saved
code with
python3 hello. py
‘The result willbe the original Python is cool! statement, togethe
with the added input command asking you For your name, and
displaying tin the command window.eo Getting Started with Python
Numbers and Expressions
VA SECTa Colao orton Laat: o(e=1 Roce (OAT ACOA Tn) cae-LeLel Leo AACE
like. Let's expand on that now and see just how powerful Python is as a calculator. You
can work within the IDLE Shell or in the Editor, whichever you like.
IT'S ALL MATHS, MAN
You can get some really impressive results with the mathematical powers of Python; as with most, if not all, programming
languages, maths isthe driving Force behind the code.
FETTER oven up the Gul version of Python3,asmentioned IM You can use all the usual mathematical operations
‘you can use either the Shell or the Ector. For the divide, multiply, brackets and so on, Practise with a
time being, you're going to use the Shelljust towarm our maths ew, For example:
‘muscle, which we believe sa small gland located atthe backoFthe 4
brain or not). a
24283
G24")
a er met Serine
FETED |" the Shell enter the Following: BEEP Youve no doubt noticed, division produces a
decimal number. In Python these are called fits,
& ‘or floating point arithmetic. However, fyou need an integer as
'54356+34553245
‘99867344°27344484221 ‘opposed to a decimal answer, then you can use a double slash:
You can see that Python can handle some quite large numbers =
ET 220.C Numbers and Expressions Cl
‘You can also use an operation to see the remainder
leftover From dhision, For example:
10/3
‘ill display 3,333333333, which i of course 3.3-ecurting you
nowenter:
103,
‘This will display 1, whichis the remainder let over From dividing 10
into 3,
FETED Nex up we have the power operator, or
‘exponentiation if you wantto be technical. To work
‘outthe power of something you can use a double multiplication
‘symbol or double-star on the keyboard:
23,
10*10
Essentially is 2x2x2 but we're sure you already know the basics
bbehind maths operators. This is how you would workit out in Python.
Numbers and expressions done stop ther. Python
Surf has numerous built-in Functions to work out sets
of numbers, absolute values, complex numbers and a host of
‘mathematical expressions and Pythagorean tongue-tuisters. For
‘example, to convert a number to binary, use:
bing)
This be dpayed 051, converting the
SIEaS) integer into binary and adding the prefix Ob to the
Front Fyou want to remove the 0b prefix, then you can use:
format(3, *b’)
‘The Format command converts value, the number3,toa
Formatted representation as controlled by the Format specification,
the part.
‘ABoolean Expression isa logical statement that will
either be true or false. We can use these to compare
data and test to see ifit’s equal to, less than or greater than. Try this
inaNew File
a=6
be?
print,
print(2,
print,
a == 6)
a== 7)
a == 6 ond b == 7)
print(4, a == 7 and b == 7)
print(5, not a == 7 and b == 7)
print(6, a
print(?,
print(s,
print,
Execute the code from Step 9, and you can see a
series of True ar False statements, depending on
the resut of the two defining values: 6 and 7. t's an extension of
‘hat you've looked at, and an important part of programming.
setrobetiaconeo Getting Started with Python
Using Comments
UMass Ae OMAN IE cn UEC come Cicer cial
PU ey arle erate oN EL Ese Aol MN Clee Ce hcel UT
code line by line but over time, it can become difficult to read.
#COMMENTS!
Programmers use a method of keeping their cade readable by commenting on certain sections. fa variabl
‘programmer comments on what it’s supposed to do, for example. I's just good practise.
is used, the
BR sat cresting a new stance ofthe OLE Edtor
Sug? (File > New File) and create a simple variable and
pane command
on10
print(“The value of A is,”, a)
Save the file and execute the code.
Se
(oe tat ram Stan doe
BEER Running the code will return the line: The value of A
is, 10intothe 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)
220 tie cies voles
PSTISEDD Resave the code and execute it. You can see that the
‘outputin the IDLE Shells stil the same as before,
‘despite the extra lines being added, Simply put, the hash symbol (t)
denotes line of text the programmer can insert to inform them,
{and others, oF what's going on without the user being aware.
i yon 342
fe 0 en tne rn
ey Soa ow eT)
BREE Let's assume that the variable A that we've created
Is the number of lvesina game. Every time the
player dies, the value is decreased by 1. The programmer could
insert aroutine along the lines of
ona-1
printC*You’ve just lost a life!”)
printC*You now have”, a, “Lives left!”)( Using Comments Cl
Whit ve now tha th variable Ais ves and
Suse that the player has just lost one, a casual viewer or
someone chectng the ce may 8 ko age For amoment
thatthe code twenty thousand Ineslong, sted of st ur
seven, Youcan se hwvhandy comments ar
Inline comments are comments that follow section
SARE rode tse ow cxarplestrom dove instead oF
inserting the code ona separate line, we could use:
0-10 # Set the start value of A to 10
printCThe value of Ais,”, a) # Print the current
value of A
a=a-1 # Player lost a life!
printC*You’ve just lost a life!”
printC*You now have”, a, “Lives left!") # Inform
player, and display current value of A (lives)
ESTEE Essentially, the new code together with comments
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!
ona
# Inform player, and display current value of A
lives)
print(*You’ve just lost a life!”)
printC*You now have”, a, “Lives teft!”)
Fe sore connos maroon fo
# 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.
ATER the comment, the hash symbol, can also be used to
comment out sections of code you don't want tobe
‘executed in your program. For instance f you wanted to remove
the First print statement, you would use:
# print(“The value of A is,”, a)
ee
[eset the start value of Ate 10
10
[F Peine the current value of A
Antc*The value of A tes", a]
layer lost’ a lif
fF Inform player, and display current value of A (Lives)
Prant(-You've just lost lifel">
Print(-You non have". a, “lives left!*)
‘Youalso use three single quotesto comment
Suid ‘out a Block Comment or multiline section of
comments Place them before and after the areas you wet to
Comment for them to 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.
———@) Getting Started with Python
Working with Variables
SVE ol ga aoc) ole 1) Mele Lm Varela aele|F-]K—2-[eN Pt eel S
ronnie Re ernie ener e ues eucecaeia)
NUTONE oC
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 Shelt to clear up any old code.
BBs some prosraming languages youre required
Suz? to.use a dollar sign to denote a string, which is a
variable made up of multiple characters, such asa name of a person.
In Python this isnt necessary. For example, inthe Shell enter:
nane="David Hayward” (or use your own name, unless you're
also called David Hayward).
BETES You can check the type of variable in use by
issuing the type (command, placing the name of
the variable inside the brackets. In our example, tis would be:
type name). Adda new string variable: title="Descended
from Vikings".
TD 220i sees volun
You've seen previously that arabes canbe
Buss) 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, variables are connected wut space,
owe needto ada them manvaly,
(ie ES) oy Ets om
EE You can also
combine variables
within another variable. For
‘example, to combine both name
and tile variables into anew
variable we use:
be ba out ts Bis ee
charactersnane +“: +
title
Then output the content of the
new variable as:
print character)
Numbers are stored as different
variables:
oge=44
Type Cage)
Which are integers, as we know.0
ESTED However, you can't combine both strings and
integer type variables inthe same command, a5 You
‘would a set of similar variables. You need to either turn one into the
‘other or vice versa. When you do try to combine both, you get an
error message:
print Cname + age)
‘Thisis a process known as TypeCasting, The Python
codes:
Bia
print (character + “ is “+ str(age) +“ years
old.")
oryou can use:
print (character,
s*, age, “years old.")
Notice again thatin the last example, you don't need the spaces
between the words in quotesas the commastreat each argument
toprint separately
>>> print (nane + age)
Traceback (most recent call last):
File “". line 1, in
rane (nave * age)
Typetrror: Can't convert “int object to str implicitly
SBSprane (enaracter + ss") + str(age) #" years old."
David Hayward: bescended fron Vikings is 14 years old.
D>> prane (character. "is", age, "Years old.)
David! Hayward: bescended fram Vikings is 44 years olé.
>
enter
‘age= input “How old are you? *)
All data stored from the Input commands stored asa string variable.
fle Gat shel Debug Options wndows eb
ion 8 Get. 8k we TTT
ee cops raites or cema "for are Satara,
elas ste
=
“Another example of TypeCasting is when you ask for
input from the user, such as a name. for example,
Thispresets bit ofa problem whenyou want to
Sus) work with a number that's been inputted by the
use as age +10 wont work dve to beng asting arabe endan
integer Instead, you reed enter:
intCage) + 10
‘This will TypeCast the age string into an integer that can be
‘worked with.
typettrer: Can't cowert “unt abject to ste implicitly
ed
TERED The use of typecasting is also important when
dealing with floating point arithmetic; remember:
rnumbers that have a decimal point in them. For example, enter:
shirt=19.99
Now enter type(shint) and you'llse that Python has allocated
the number as a float’, because the value contains a decimal point.
Python =
(eens.
type Scepyaghe "ereiter or "Licansey* for wore inforation
33 Gpetahiee)
clas "tio
Z (aetaulk, Oct 18 2014, THRTTD
‘online
When combining integers and eats Python
Suid usually converts the integer to a float, but should
the reverse ever be applied ’s worth remembering tha Python
does return the exat value, When converting = lato an
integer, Python lava round own to he nearest integer,
Caled resting in urease instead oF 19.9 became 9,
thea Sone op
Pa Saya OB TTT
pe Sepyighes resis” or “License for mare infomation.
————
(Working with Variables Cleo Getting Started with Python
User Input
WATER o ua erie Sa ee: Ce nea Mea eeole ieee Aloe a kelly
earlier, so now would be a good time to Focus solely on how you would get information
Pee iecene att ccna
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.
FETED is notalready open the Python 31DLE Shell
and start a New File inthe Editor. Let's begin with
something really simple, enter:
printc*Hetto”)
firstnane=input ‘What is your first name? “)
print¢“Thanks.")
surnane=input(“And what is your surname? )
Save and execute the code, and as you already no
doubt suspected, in the IDLE Shell the program will
ask for your firstname, storing itas the variable firstname, followed
bby your surname; also store in its own variable (curname).
Siar
Fee yw sr mt
IT 220 cite sees vole
"Now that we have the user'sname stored ina
couple of variables we can call ther up whenever
Siar)
we want:
printC*Welcone”, firstname, surname, “. T hope
you're well today.”)
FID rec yen cance ssh oe
ERD i ere
Toe vedas den
Sen
printC‘Welcone”, firstname, surnames. I hope
you're well. today.")(User input Cl
iG P|
‘ou dort ays haveto nude quoted tex thin
Suse the input command. For example, you can ask the
userther name, and have the nputinthe tne below
print(*Hello. What’s your name?”)
‘nane=inputC)
seringut py - home/pi/Documents/Pythan Code/us
[Ele Edt Format fun Options windows Hep
‘prant(iello, What's your name)
P anesinput()
hat youve created hres condition, which we
Sus) will cover soon. In short, we're using the input From
theuser and measuring against a condtion So, the vsr enters
Davis thet name, the guard willow them topes unhindered
Else, if they enter aname other than David, the guard challenges
them toa fight.
ESTEE The code from the previous step is often regarded
asbeing alittle neater than having a lenathy
‘amount of text in the input command, butt’s not arule that's setin
stone, so do a you lke in these situations. Expanding on the code,
tuythis
print(“Halt! Who goes there?")
‘names input©
eat Farmat Bin Stans woe ep
PEPTIED) |: 2 g00d star to atext adventure game, perhaps?
Now you can expand on it and use the raw input
from the user to flesh out the game litte:
‘if name=="David”:
printC*Welcome, good sir. You may pass.”)
else:
printC*I know you not. Prepare for battle!’
ie Set Fat Bin Stes nde ep
ESTEE utes you learned previously, any input from a
Users automatically a string, o you need to applya
‘TypeCast in order to turn it into something else. This creates some
Interesting additions to the input command. For example:
# Code to calculate rate ond distance
rint(*Input a rate and a distance”)
rate = float CinputC*Rate: “))
BRTTSET DD 1 finalise the rate and distance code, we can ade
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
Floating point number rather than a string,
cemineatscon@) Getting Started with Python
Creating Functions
Now that you've mastered the use of variables and user input, the next step is to tackle
CiMten Coa AULT eM ee eee A en eco Te Dold eaTelA)
enables you to define your own functions.
FUNKY FUNCTIONS
A function
‘a command that you enter into Python to do something. Its a little piece of self-contained code that takes data,
Fe sata rtannsscn en
ERD ses eseschesrresi te
followed by brackets, For example, len(), list() or type().
FETED A function takes data, usually a variable, works on
Tedepending on what the Function is programmed
todo and,eturnsthe end value. The data being worked an 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 nunber 28,
would return,
GIT 220 rie cites vole 4
BATeRE DD You can pass variables through Functions in much
number of letters in person's surname, you could use the following
ode (enter the text editor for tis example):
ame=input (“Enter your surname: “)
count=Len(name)
print C*Your surname has“, count, “Letters in
a
Press FS and save the code to execute it.
Python has tens of functions buil into it, far too
‘many to get into in the limited space available here.
However, to view thelist of builtin Functions available to Python 3,
navigate to wwv.docs.python.org/3ibrary/Functions.html, These
are the predefined functions, but since users have created many’
more, they/re not the only ones available.Creating Functions
FER sratnncinc canoe oieiobon
They add Functions and can be imported as and when required, For
example, to use advanced mathematics Functions enter
import math
‘Once entered, you have access tll the Math module Functions.
Tousefuncon roma module ete the name of
Sur the module Followed by a Full stop, then the name
of he function, For instance sing the Math module sce you've
Istimportd tint Python youcan us the square ret Function,
Todos ete
math. sqrtC16)
‘You can see thatthe code is presented as module function(data.
FORGING FUNCTIONS
Mea see Re Cee re aoc gd
‘across some excellent examples in the Future; you can also create your own with the def command.
Cremeans
eerie
es
fcr
PPE BD cs now expand the function to accept a
ee eens ag
rere
ee eae a
ene ore enact
ees
the
Peace eat
Het loC*David")
Ce etree
Bee What you've just done is import the Hello Function
from the saved Hello.py program and then used it
Pe ere an
ete ee eae@) Getting Started with Python
Conditions and Loops
Conditions and loops are what makes a program interesting; they can be simple or
rather complex. How you use them depends greatly on what the program is trying to
achieve; they could be the number of lives left in a game or just displaying a countdown.
TRUE CONDITIONS
Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let's start then by checking
if something is TRUE, then doing something else if it isn't.
BB ces createa new thon prosram tha wilask
Suz? the user to input a word, then check it to see iFit's:
afoureterwordor not Start wthFe> New Fle, ndbegh wth
theinptvaribe
wordzinput(“Please enter a four-letter word: “)
BEER Yow we can create a new variable, then use the len
Function and pass the word variable through it to
‘get the total numberof letters the user has just entered:
wordsinput(“Please enter a four-letter word: “)
word_Length=LenCword)
220s volun
BREED Xow you can use anf statement to checkif the
word length variable is equal to Four and print a
Friendly conformation if it applies to the rule
word=input("Please enter o four-letter word: “)
word_Length=LenCword)
if word length == 4:
print (word, “is a four-letter word. Well done.”)
‘The double equal sign (==) means check f something is equal to
something else.
BETEEE The colon at the end oF IF tells Python thatif this
statements true do everything after the colon
thats indented. Next, move the cursor back to the beginning of
the Editor:
word=input(Please enter a four-letter word: “)
word_Length=LenCword)
if word_length == 4:
print (word, “is a four-letter word. Well
done.)
else:
print (word, “is not @ four-letter word.”)condtonsandtoors CE
bressFS and save the code to excite. nter
Suz a four-letter word in the Shell to begin with, you
should hve theretured message that tthe word our eters
Now press agin andrerun the program buts time enter a
fvetetter word The Shel ply that snot Furteter word
LOOPS
Now expand the code to include another conditions.
Eventually it could become quite complex. We've
‘added a condition for three letter words:
wordsinputC“Please enter @ four-letter word: “)
word_Length=lencword)
if word_tength == 4:
print (word, “is @ four-letter word. Well
done.”)
elif word_tength
print (word, “is a three-letter word. Try again.”)
else:
print (nord, “is not a four-letter word.)
ere ena eee ae ee ve un eed
block oF code a number of times, usually with the support of a condition,
ae
hing is TRUE, then run
Lee!
corn
rie
etry
Ete eee
Je current value of x, then adds one to
Deas
rp
arenes
penton ete
5p over a range
ees
for_word in words:
[print (word)
Bee tee
Cou ee na
[for x in range (1, 10):)
)
eri
Pelee
Certo
last numbers used.Getting Started with Python
Python Modules
MASTERING MODULES
Think of modules as an extension that's imported into your Python code to enhance and extend its capabilities. There are
countless modules available and as we've seen, you can even make your own,
BED Mosher ebuteniincinswtninrien REED rhe estsanevornthete shel asthe
make mote sophisticated programs. Asyou ste aware, modules Python Tolstals module we ean use PIP (ip sal Packages)
are thon sis tht are inprte, sch Inport math Close down the LE shel end drop nto a command prompt or
Terminal session, at an elevated admin command prompt, enter:
pip install pygame
| step2 ) Some modules, especially on the Raspberry Pi BED The PI installation requires an elevated status
are included by default, the Math module being a due it installing components at different locations.
prime example. Sadly, other madules aren't always available. A good Windows users can search for CMD via the Start button and right
example on non-Pi platforms isthe Pygame module, which contains clic the result then click Run as Administrator. Linux and Mac users
many functions to help create games. Try: mport pygame. 3 use the Sudo command, with sudo pip install package.
‘BOM Definitive Guide Series- Volume 24(Crtonmeaies RE
(Python Modules
Close the command prompt or Terminal and
relaunch the IDLE Shell when you now enter:
‘import pygame, the module will be imported into the code
without any problems, Youll ind that most code downloaded or
copied from the Internet will contain a module, mainstream of
nique, these are usually the source of errors in execution due to
them being missing
a
‘Multiple modules can be imported within your code.
BARD ecerd our exanole, se
import random
‘import math
for I in range(s):
printCrandom.randint(1, 25))
print¢nath. pi)
b
‘The madules contain the extra code needed to
Sats
achieve a certain result within your own code, as
we've previously experimented with. For example:
‘import random
Brings in the code from the Random Number Generator module.
You can then use this module to create something like:
for i in range(10)
printCrandom.randint(1, 25))
o
PRPTEM) This code, when saved and executed, will display ten
random numbers fram 1 to 25. You can play around
with the code ta display more or less, and fram a great or lesser
range. For example:
‘import: randon
for i in range¢2s):
rintCrandom.randint(1, 100))
ERTEEED the resultisa string of random numbers Followed
by the 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):
print(randint(l, 25))
&
BETSET DD This helos create a more streamlined approach to
programming. You an also use import module
‘which wilimport 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.pid
‘Of course, adding comments helps to tell others what's going on.
ey Ctenistoameient ney 7 - 3 x
cemineatscon“It's OK to figure
out murder
mysteries, but you
shouldn’t need to
Figure out code.
You should be able
to read it.”
~ Steve McConnell (Software
Engineer and Author)
Datais everything. with it, you can
display, control, add, remove, create
and manipulate Python to your every
demand. Over these coming pages we
look at how you can create lists, tuples,
dictionaries and multi-dimensional lists
then how you can use them to forge
exciting and useful programs. It's little
wonder that data is now valued more
than gold or oil.
You will also learn how you can use
the date and time Functions, write to
Files in your system and even create
graphical user interfaces that will take
your coding skills to new levels and into
new projectideas.
Lists
Tuples
4
56
58 Dictionaries
60 Splitting and Joining Strings
62 Formatting Strings
64 Date and Time
66 Opening Files
Writing to Files
70 Exceptions
Python Graphics
wetirosicioncn CEeee eons eRe Retest Ceo erect}
Python. A list is simply a collection of items, or data if you prefer, that can be accessed
as a whole, or individually if wanted.
WORKING WITH LISTS
Lists are extremely handy in Python. A list can be strings, integers and also variables. You can even include Functions in lists,
and lists within lists.
EDD 2 istise sequence of data values caled items You
BAD cate name of your ist flowed by an ecuss
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”)
Beg ge an meee
FETE (nce you've defined your list you can call each
by referencing ts name, followed by anumber. Lists
start the first item entry as 0, Followed by 1,2, 3 and oon.
For example:
unbers
Tocallup the entire contents ofthe lst
unbers[3]
To call the third From zero item in the lst (21 in this case),
GET 200i
FER vr asoscon roses onnonnci
‘or the second to last item with [-2] and so on, Trying to reference an
unbers[=1
imythical_creatures[~4]
Slicing is similar to indexing but you can retrieve
Oia
‘multiple ternsin alist by separating item numbers
with a colon. For example:
unbers[1:3]
vill output the 4 and 7, bing item numbers 1 and 2. Note thatthe
returned values don't include the second index positon (as you
‘would numbers[1:3] to return 4,7 and 21).ETSI You can update items within an existing ist, remove [ESSEBM You can view what can be done with lists by entering
join two lists you can use: Functions, For example, insert and pop are used to add and remove
—— items at certain postions. To insert the number 62 at item index 4
‘Then view the combined list with: umbeerstinSAECASEE2)
To remove it
‘nunbers .pop(4)
everything
ESTEE terns canbe added toast by entering ESTED You ats0 use the lst Function to breaka string down
rie into its components. For example:
Orfor strings a
: griffin] 2° eaksthename David nto’D, a, V, This can then be passed
aythical_creatresenythical_creatures+[“Griffinn] revs the
(by using the append Function paweatiseCcoavtalnayartE)
aythical_creatures.append(“Nessie”) rane
runbers.append(278) ‘age=(44]
user = none + age
ner ate i user
PEPE D) Removal oftems.can be done intwoways. The fist [EUSIANB faced on that, you can create a program to stare
isby the tem number: someone's name and age as alist:
del nunbers{7] namesinputC“What’s your name? “)
Alternatively, by item name: Tie TCE)
i ‘age=intCinput (“How old are you: “))
mythical_creatures. renove(“Nessie”) ‘age=Lage]
ues = min mes mpeg tat 1 user = Inane + lage
‘The combined name and age lists called user, which canbe called
____byetering user into the Shell, Experiment and see what you can do,
aTuples are very much identical to lists. However, where lists can be updated, deleted or
changed in some way, a tuple remains a constant. This is called immutable and they're
perfect for storing Fixed data items.
THE IMMUTABLE TUPLE
Reasons for having tuples vary deper
19 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.
Auplescenedtbenmeweyescitbutntss — EEREEB voucn cee gondii thantan
ou" instance you use curved brackets instead of square Buss ‘multiple sets of data. For instance, here is a tuple
brackets. For example: ‘called NPC (Non-Playable Characters) containing the character name
tmonths=C*Jonuary”s “February®) “March”; “Aprit”, andthe combat rating For an adventure game:
“May”, “June”) NPC=[C"Conan”, 100), (“Belit”, 80), (“Valeria”,
months 95)]
Pn
ae
BEE noc, we ee wn
FETED st as with ists, the tems within named tuple can [ESSWPM Each of these data items can be accessed asa
be indexed according to their position inthe data \whole by entering NPCinto the Shell or they canbe
range, indexed according to thelr postion NPC), You canals index the
ronths [0] indvdual tuples within the NPC Ist
name Necro [2]
However, any attempt at deleting or adding tothe tuple wil result will display 100.
inan errorin the Shel.
ET 220sIesworth noting that when referencing mle
Suse tuples within a list, the indexing is slightly different
from the norm. Youweuld expect the 95 combat rating ofthe
character Valeria to be NPC[4][5], but it's not, It's actually:
NPC(2] (1)
FETS) Thismeans of course that the indexing Follows thus:
@ ma
ao 2
a2 20
1 aA
1,0
\which as you canimagine, getsa ite confusing when you've got a
lotof tuple data to deal with.
Tuples though iia feature called unpacking,
SUP where the data items stored within a tuple are
assigned variables. First create the tuple with two items (name and
combat rating)
NPC=C*Conan”, 100)
eee Mow unpack the tuple into two
corresponding variables
name, conbat_rating)=NPC
‘You can now check the values by entering name and combat. rating,
ERTERERD Remember, as with lists, you can also index tuples
Using negative numbers which count backwards
From the end of the data lis. For our example, using the tuple with
multiple data items, you would reference the Valeria character with
NecrzI£-0]
‘oucanuse the ma and min functionsto find the
Suid 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 an oats To output the highest and
lowest use:
primtCmaxCnunbers))
print(minCnunbers))
————Dictionaries
Merten eee ete Tne NAc arate mie ACY
of dealing with data items, They can be tricky to get to grips with at first but you'll soon
tel Reon oll meals oa
KEY PAIRS.
jonary is like a list but instead each data item comes as a pair, these are known as Key and Value. The Key part must be
‘unique and can either be a number or string whereas the Value can be any data item you like.
Let's say you want to create a phonebook in Python,
SALE ovis create the dctonary name and enter
the data in curly brackets, separating the key and value by a colon
Key:Value. For example:
phonebook={“Enma”: 1234, “Daniel”: 3456, “Hannah”:
6789}
BETS EDD estas with most ists, tuples and so on, strings
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.
fone in quotes:
phonebook2={“David”: “0987 654 321”}
GET 220i
ED ss wertsinnnesyv cme teens
Dork niece hoon catereyae
with by now.
Eee a TTT
EATER 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]
phonebook “Hannah"™)‘Adding toa dictionary is easy too. You can include
a new data tem entry by adding the new key and
value items ike:
phonebook{“David"] = “0987 654 321”
phonebook
Next youneedtodefne the user inputs nd
Sus) variables: one for the person's name, the other
forthelephone number let’ keep spe avid lengthy
Python code):
ane=inputC“Enter name: “)
hunber=intCinputC“Enter phone nunber: *))
FETTER You can also remove items from a dictionary by
Issuing the del command followed by the tems
key; the value will be removed as wel since both work as a pai of
data items:
del. phonebook[“David"]
Tsing thease rer Now aout»
STEP 7 piece of code that will ask the user for the dictionary
key and value items? Create a new Editar instance and start by
coding in a new, blank dictionary:
phonebook={}
ere "Note we've kept the number as an integer instead
(of astring, even though the value can be both
~aninteger ora string, Now you need to add the users inputted
variables to the newly created blank dictionary. Using the same
process as in Step 5, you can enter:
phonebook{nane] = nunber
fens = mer
Now henyousave and execute the code, Peon
Suid will ask for a name and a number. it will then insert
those entries into 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 makeita string,
so remove the int part of the input.
cemineatsconSplitting and
Joining Strings
MaKe lias R enna M a eae Ler] AKO TULL R LMU aCeloLel ole eLN]
come across long sets of strings. A useful skill to learn in Python programming is being
able to split those long strings For better readability.
STRING THEORIES.
You've already looked at some list functions, using insert, .remove, and .pop but there are also Functions that can be applied
tostrings.
‘The main too in the string Function arsenals spit). Note that the text.split part has the brackets,
With you're able to spit apart string of data, uotes, then a space followed by closing quotes
bbased on the argument within the brackets. For example, here's __and brackets. The space isthe separator, indicating that each lst
string with three items, each separated by aspace: item entry s separated by a space. Likewise, CSV (Comma Separated
Value) content has a comma, so you'd use:
‘text="January, February,March,April May, June”
monthsstext.split(",”)
rnonths
‘text="Daniel Hannah Emma”
FER cscrnnesninostxausgne ‘eine ena ee
nanesstext.split(* “) namesList(“David”)
name
Then enter the name of the new list; names, to see the three items
‘The retumed value is‘D ‘d Whilst it may seem alittle
useless under ordinary ccumstances, it could be handy for creating
aspeling game for example.
220i sees volunC Splitting and Joining Strings Cl
Theopostesttespthncionjon tee ERT swine stfncon sheep rn
illite you will have separate items in a string and can join Sus) have to bea space, it can also be a comma, a full
them all together to form a word or just 8 combination of items, ‘stop, a hyphen or whatever you like:
depending on the program you're writing. For instance:
‘alphabet="". join([“a","b”,"c”,"d","e"])
‘alphabet.
This will display ‘abcde’ the Shel.
-[*Red”, “Green”, “Blue”]
1” joinCcolours)
ESTISED) You can therefore apply jon to the separated name EINEM there's some interesting Functions you apply toa
‘you made in Step 4, combining the letters again to string, such as. capitalize and title, For example:
formthe name: ‘title="conan the cinmerian”
nane="". joinCname) title.copitalizeO
‘name title. title
We've joined the string back together, and retained thelist called
‘name, passing it through the join Function,
Aspdeampic wnt sintncin ston EEEEAB Youcato etn opetosonctigs
STEP 7 you have a list of words you want to combine into a Suid ‘with the ‘in’ and ‘not in’ functions. These enable
sentence: youto check string contains (or does not contain) a sequence
Liste[*Conan”, “raised”, “his”, “mighty”, “sora”, fcharectes
and”, “struck”, “the”, “denon™] mnessage="Have a nice day”
texte" «.joinclist) “nice” in message
= "ead" not in message
Note the space between the quotes before the join function (where “day” not in message
there were no quotes in Step 6's join. “ight” in message
Te EOS) BG Es aH
cemineatscon@) Working with Data
Formatting Strings
When you work with data, creating lists, dictionaries and objects you may often want
Pormmset dred crane cna eis o neo a arene Cd
earlier versions of Python tended to complicate matters.
STRING FORMATTING
Since Python 3, string Formatting has become a much neater process, using the format Function combined with curly brackets.
It’s a more logical and better formed approach than previous versions.
Trebaicfomstinginronstocaeach RETIRE oucanofcuse aoc teens thei
SIE variable into the string using the curly brackets: Buss)
nunber=10000
‘nane="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
4”. formatCnane)) merchant..”.format(nane, place, nunber))
se
is Fatt tT emeinmen
ESTEGERD Remember to close the print function with two sets [ESNSSWAM There are many different ways to apply string
of brackets, as you've encased the variable in one, formatting, some are quite simple, as we've shown
{and the print function in another. You can include multiple cases of youhere; others canbe significantly more complex. Itall depends
string formatting ina single print Function: ‘on what you want from your program. A good place to reference
Frequently regarding string Formatting is the Python Docs webpage,
Found at www.docs.python.org/3.1/ibrary/string.html. Here, you
will Find tons oF help.
‘nane="Conan”
place="Cimmeria”
printC*{} hailed from the North, in a cold land
known as {}”.format(name, place))
TD 220i cine sees volunE
Formatting Strings Cl
\
Interestinly you can reference alist using the string HEED You can also print aut the content of a user's input
SUPE Formatting Function. You need to place an asterisk in plEtg inthe same Fashion:
front ofthe stare ce
numbers=1, 3, 45, 567546, 3425346345. print(“Hello {}.”.format(name)
printCSone numbers: 0,0, 0, 0, OP.
Format Cnunbers))
ESTEE With indexing nists, the same appliesto calling — EEEM Youcan extend this simple code example to display
list using string formatting. You can index each item the irstletter in a person's entered name:
‘according to its position (from 0 to however many are present} Fome=tnputCovbatsivourInane?s®)
funbers=1, 4, 7, 9 printC‘Hello {}.”. format(name))
print¢‘More numbers: {3}, {0}, {2h, Iname=1ist(nane)
{1}.”. Format C¢nunbers)) print(“The first Letter of your name is a {0}".
format *1name))
FE vc scpciyscnctgovanaaiies EBB ox nascar casera
characters=[“Conan”, “Belit”, “Valeria”, 19, 27, names=[“Conan”, “Belit”, “Valeria”]
20) ‘ages=[25, 21, 22]
Prim CU{0} is {3} years old. Whereas {13 18 {4 Creating twolists. Now you can cll each ist, and individual items:
years old.”. format(*characters))
printC*{0[0}} is {1(0]} years old. Whereas {0[1]}
is {21} years old.”.formatCnames, ages))
cemineatsconDate and Time
PMO RR en eet amen reel a CCRT
Uo en eure rac ae enter cinel arse ur
For how long. Luckily acquiring the date and time is easy, thanks to the Time module.
TIME LORDS
‘The Time module contains Functions that help you retrieve the current system time, reads the date From strings, Formats the
time and date and much more.
Feayouneedtingoterinemodie sone TREE Youcensee este thow ine speed
ou" that’s built-in to Python 3 so you shouldn't need to Buss) byentering:
dropintoa command prompt and pista. OneleSIMPOES, sane ageat time)
you can athe current time and date with simpe commands
ee The outputs displayed as such: time. struct time tm
ee yeor=2017, tmnon-9, tnnday=7, tm-hour=9,
: ‘tmmina6, ‘tmsecei3, tmnday=3, tm_yday=250, tm
‘isdst=0)’; obviously dependent on your current time as opposed
tothe time ths book was witen
Eee Sa tt ome rin
ESTEE Thetime Function sspit into nine tuples, these are EWA There are numerous functions built into the Time
divided up into indexed items, a with any other ‘module. One of the most common of these is
tuple, and shown in the screen shot below. strftime0. With t, you'e able to present a wide range of arguments
‘as it converts the time tuple into a string For example, to display the
‘current day of the week you can use:
oT ar ‘time. strftimec*%A’)
a =
oo ves Pee ne ome
oes ee
eee =
GT) 220i volun7
(. Date and Ti
(Date and Time Cl
Thisratraly mane youcan heoporate various
Suse functions into your own code, such as:
time. strFtimeC*%a")
time. strFtimeC“%B")
time. strFtimeC“%b")
time. strftimeC“%H")
time. strFtimeC“HAN")
FETTER Note thelast two entries, with 6H and %H9%M, as
{you can see these are the hours and minutes and as
the last entry indicates, entering them as %H¥6M doesn't display the
Lume correctly in the Shell. You can easily rectify this wth:
time. strFtimeC*xH:90")
FED tres sve guste sts
ED oie catia eae
import time
nanesinputC“Enter Login name: “)
printc‘Melcome”, nane, “\d”)
print(“User:”, name, “logged in at”, time.
strftime *#H:36"))
‘Try to extendit Further to include day, month, year and so on
‘You saw at the end of the previous section, inthe
BALD coc to calcite Pito however many decal laces
the users wanted, you can time a particular event in Python. Take
the code from above and alter it slightly by including
start_time=time.timeC)
‘Then there's
endtime=time. timeC)-start_time
[Ss gre ae eres ws gy _}
EATEEED the output wil ook similar to the screenshot below.
‘The timer Function needs tobe either side ofthe
input statement, as that’s when the variable name is being created,
‘depending on how long the user took to login. The length of time is
then displayed on the last tine ofthe code asthe endtime variable.
‘There's a lot that can be done with the Time
module; some of itis quite complex too, such as
displaying the number of seconds since January 1st 1970. IF you
‘want to drill down Further into the Time module, then in the Shell
enter: help(time) to display the current Python version help file
forthe Time module.
cemineatsconIn Python you can read text and binary files in your programs. You can also write to file,
Miia neuen RR cel eastern iene feohfl eters)
output and store data from your programs.
OPEN, READ AND WRITE
In Python you create a file object, similar to creating a variable, only pass
‘categorised as text or binary.
FETED s2rtbyentering sometextintoyoursystem'stext EIB sr younow enter poem into the Shell, you will get
editor. The text editoris best, not a word processor, some information regarding the text file you've just
‘8s word processors include background formating and other ‘asked to be opened. You can now use the poem variable to read the
elements, In our example, we have the poem The Cimmerian, by contents of the file:
Robert E Howard. You need to save the file as poem.bxt,
poem. readC)
Note than a in entry inthe text represents a new tine, as you
used previously.
FETED You use the opend functionto passtherileintoa EAM Fyou enter poem ead) a second time you will
variable as an object. You can name the file object ‘notice thatthe text has been removed from the fle.
anything you like, butyou will need to tell Python the name and —-—_-Youwill need to enter: poem=open(“/home/pi/Documents/
location of the text file you're opening: Poem. txt”) again to recreate the fil. This time, however, enter:
oemsopen("/home/pi/Documents/Poem.txt”) printpoem.read())
This time, the n entries are removed in Favour of new lines and
readable text.
220i sees volunPata etdmaaeeeaa
poem.read(S)
Displays the First five characters, whilst again entering:
poem.read(5)
‘will display the next Five. Entering (1) wil display one character at
atime.
Extending tis Further, you can use readtines() to
SALAD grate ines ofthe tex ond store themes
multiple lists. These can then be stored as a variable:
poen=open("/home/pi/Documents/Poem. txt”)
‘Tines=poem.readlines()
Lines[0]
Lines {1]
Lines [2]
Similarly, you can display one line of text at atime by
Using the readline() Function. For example:
Bia
poem=open(“/home/pi/Documents/Poem.txt”)
poem. readlineC)
wil display the first tine ofthe text with
poen. readline)
Displaying the next line of text once more.
You may have quested that you can pas the
SUP readline() Function into a variable, thus allowing you
to.allitagain when needed:
oenopen("/home/pi/Docunents/Poem.txt”)
Line=poem. readline)
line
em ome ao
You can also use the For statement to read the lines
of text backto us:
for Lines in Lines:
printClines)
‘Since this 's Python, there are other ways to produce the same output:
Oia
poem=open(“/home/pi/Documents/Poem. txt”)
for Lines in poem:
print(Lines)
FET i csneinayrovon opiate
import time
oem=open("/hone/pi/Documents/Poen. txt”)
‘Tines=poem.read()
for Lines in lines:
printClines, end="")
time. sleepC.15)
‘The outputis un to view, and easly incorporated into your own code.
wurubémpubicatonscomAeron eer Ca na eee MMe aN rene) OPCs
eee Mec AMO mietr rok ster tect eter Medicus!
afile, that you can then read() back into Python.
WRITE AND CLOSE
The write() Function is slightly more complex than read(). Along with the filename you must als
determines whether the file in question isin read or write mode.
Start by opening IDLE and enter the Following
‘teopen(*/hone/pi/Documents/text.
STEP 1
txt?)
Change the destination From /home/pi/Documents to your own
system. This code will create a text file called text.txt.in write mode
Using the variable there's no file ofthat name inthe location, it
will create one. Fone already exits, it will overwrite it, so be careful
BETS You can now write tothe textile sing the write
function. This works opposite to read, writing lines
Instead of reading them. Try this:
‘t.write(“You awake in a small, square room. A
single table stands to one side, there is a locked
door in front of you.")
[Note the 109. t's the number of characters you've entered.
rersccene
| se st nr
ET 220i sees vole
However. the acl ext lest blank youcan
Buss) ‘check by opening it up). This is because you've |
wen thetn of texto te le objec bt not commitedittothe
Me sel Pat oF te wre uncon stat you need to commit the
changesto the le; you can dots by entering
t.closeQ)
|f you now open the text file with a text editor,
you can see thatthe line you created has been
‘written tothe file. This ives us the foundation for some interesting
possiblities: perhaps the creation of your awn logfile or even the
beginning of an adventure game.‘To expand this code, you can reopen the file using HEED YYoucan pass variables toa file that you've created
Suse ‘a’, For access or append mode. This will add any text Sus) jin Python, Perhaps you want the value of Pito be
atthe endof the rg inelnstead oF wiing thee and creating _wktento ale You can cl fom the Math module, reste ew
‘anewone, For example: file and pass the output of Pinto the new file:
‘teopen(/home/pi/Documents/text .txt”,"a") import math
tenmitteC*\n") printC*Value of Pi is: “,math.pi)
t.write( You stand and survey your surroundings. print(“\nliriting to a file now..")
On top of the table is sone meat, and a cup of
water.\n”)
FETTER You can keep extending the text ine by line, STE! Now lets create a variable called piand assign tthe
tending each with anew line \n), When you're value of Pi
done, finish the code with tclose() and open the file intext =
editor to see the results: pasate
tawritec“The door is made of solid oak with iron’ Yous need tocreate anew fein which towne Pt:
strips. It’s bolted from the outside, Locking you t=open(“\/home/pi/Documents/pi.txt”,"w")
in. You are @ prisoner!.\n")
ticloseO Remember to change your file location to your awn particular
system setup,
Tarexevarouoperoisacesstoconiee | ESRI roth yucanuse sig emattogto ci
SUP using the open() Function. Each depends on how the Suid variable and write it to the file, then commit the
fleisacessdandeventhe postion ofthe cursor ror empl, r+ changes and dose the le:
cous feinedandwiteadpiesthecerat testo weeacnatue of PLB! (7 FOrHkCODD
erie t.closeQ)
You can see from the results that you're able to pass any variable to
afile,
woratémpubicatonscom GyMieaneore emote Roepe re SMe Rel cree
Meet sts etek Matte una eke cop cc
will create an error and break your code.
EXCEPTIONAL OBJECTS
Rather than stop the Flow of your cot
, Python includes exception objects which handle unexpected errors in the code. You
‘ean combat errors by creating conditions where exceptions may occur.
PEPER You can create an exception error by simplytrying EIB Youcanuse the functions raise exception to create
to divide a number by zero. This will report back ‘our own error handling code within Python. Le’s
with the ZerobivisionError Division by zero message, as seen in the assume your code has you warping around the cosmos, too much
scteenshot. The ZeroDivisionError parts the exception class,of however results in 8 warp core breach. To stop the game from
Which there are many. ‘exiting due tothe warp core going supernova, you can create 3
‘custom exception:
raise Exception(“warp core breach”)
ee ‘Scop oyonarnnclsoem eae
anonaaynon douecmeleantccertiacesnon venice
ee arousing tesa ce
inherently wrong with the cade.
ee eee
senate oe
atte wapoatie
see
ET 220i cite sees volunFor example, use the divde by zero errr. You can
Suse create an exception where the code can handle the
errr without Python uiting due tothe problem:
try:
a=intCinputC“Enter the first number:
baintCinputC*Enter the second nunber
print(a/b)
except ZereDivisionError:
rint¢*You have tried to divide by zero!”)
else:
print(*You didn’t divide by zero, Well done!)
p>)
“I
‘Naturally, you can quickly fix the issue by changing
Sus) the “r” read only instance with a “w* for write. This,
asyouabeady now, wl ceae the fle andunte the content then
‘commit the changes tothe file, The end result wil report a different
set of circumstances, inthis case, a successful execution ofthe code,
PTSD) You can use exceptions to handle a variety of useful
tasks. Using an example from our previous tutorials,
let's assume you want to open a file and write toi
try:
‘txt = opent“/home/pi/Document's/textfile.txt”, “r”)
txt.nriteC“This is a test. Normal service will
shortly resume!”)
except I0Erro
print (“Error: unable to write the file. Check
permissions”)
else:
print (“Content written to file successfully. Have
a nice day.”)
‘txt-closeQ)
FETED viously this won't work due tothe file textile txt
being opened as read only the “” part). Soin this,
case rather than Python telling you that you're doing something
wrong, you've created an exception using the |OEzrar class
informing the user that the permissions are incorrect.
ESTED You canalso use a finally: block, which worksina
similar Fashion but you cant use else with it. To use
‘our example from Step 6:
tr
‘txt = open(“/home/pi/Documents/textfile.txt”, “n”)
te
txt.writeC“This is @ test. Normal service will
shortly resume!”)
finally:
print (“Content written to file successfully.
Have a nice day.”)
‘txt.closeQ,
except I0Error:
print C*Error: unable to write the file. Check
permissions”)
PEPTET DD 2 before an ecror will occuras you've used the
read-only permission. Fyou change Itto aw",
then the cade will execute without the error being displayed inthe
IDLE Shell. Neecless to say, it can be a tricky getting the exception
code right the first time, Practise though, and you will get the hang
oft.
vtec
(
(Exceptions ClMERCH Manette er eae Ueda y cel ene eae
MUN nae egelesiies ictccscnleounl tee eee oo)
Pee MMe ie mecnlavetacirla cat lcs
GOING GRAPHICAL
You can draw simple graphics, lines, squares and so on, or you can use one of the many Python modules available, to bring out
some spectacular effects
‘One of the best graphical modules to begin learning
ll Python graphics is Turtle, The Turtle module is, as
tre ae suggests based onthe treet used nay seo,
Sateen be pograried to dow sorting oo age
oF paeronthe or The Tutlemedl canbe mp
Saport tort.
Let's begin by drawing a simple circle, Start a New
Siar
File, then enter the following cade:
‘import turtle
turtle. circle(sa)
turtle. getscreen(). root .mainLoop()
‘As usual press 5 to save the code and execute it. A new window will,
‘now open up and the Turtle’ will draw a circle
[80M Definitive Guide Seris-Volume 24
Thecommand turtle. crcle(50) shat cravsthe
Buss) circle on the screen, with 50 being the size. You
can play around with the sizes if you like, going up to 100, 150 and
beyond; you can draw an arc by entering: turtLe.circle(s®,
180), where the size is 50, but you're telling Python to only draw
400" othe crc
BITEEE MD "he last part ofthe circle code tells Python to keep
the window where the drawing staking place to
remain open, sothe user can clckto close it. Now, let's make a square:
import turtle
printC“Drawing a square.”)
for t in rangeCa):
‘turtle. forward(100)
turtle. leFt(90)
turtle. getscreen()._root.mainloop()
‘You can see that we've inserted a loop to draw the sides of the square,© Python Graphics cl
PEPTSD You can add anew line tothe square code to add
some colour:
turtle.colorc*Red”)
‘Then you can even change the character to an actual turtle by entering:
turtle.shopeC“turtle”)
You can also use the command turtle, begin ALLO, and
turtLe.end_fl1Q tofll inthe square withthe chosen colours;
‘ed outline, yellow filin this case,
BETTS You canssee thatthe Turtle module can draw out
some pretty good shapes and become a ite
‘more complex as you begin to master the way itwork. Enter this
example
from turtle import *
color(‘red’, ‘yellow’)
begin fL1C)
while True:
Forward(200)
leFtc170)
if abs(pos()) < 1:
break
end_AlLO
done)
Isa different method,
butvery effective
FETE EEA nother way in which you can display graphicsis
by using the Pygame module. There are numerous
‘ways in which pygame can help you output graphics to the screen
but for nowlet’s lookat displaying a predefined image. Start by
‘opening a brawser and finding an image, then saveit to the Folder
Where you save your Python code.
as
Ei s&
Nowlet' get the code by importing the ygame module
‘import pygane
ygane.init()
‘img = pygane. image. load“RPi.png”)
white = (255, 255, 255)
w= 900
h= 450
screen = pygane.display.
set_mode((n, h))
screen. fill((white))
screen. fill((wite))
screen. blitCing, (0,0)
pygane.display.fiipQ
while True:
for event in pygane.event.get():
‘if event.type = pygane QUIT:
Pygane.quit()
ESTEE 2 the previous step you imported pygame, initiated
the pygame engine and asked to import our saved
Raspberry P logo image, saved as RPi.png. Next you defined the
background colour of the window to display the image and the
‘window size as per the actual image dimensions. Finally youhavea
loop to clase the window.
w = 900
h = 450
screen = pygame.display.set_mode((w, h))
screen. fill((white))
screen. fill((white))
screen. blit(img,(0,0))
pygame. display. flip()
while True:
for event in pygame.event.get():
if event. type == pygane. QUIT:
pygane.quit()
PRET Press F5 to save and execute the code and your
image willbe displayed in a new window. Havea
play around with the colours, sizes and so on and take time to look
tp the many functions within the Pygame module too.>)
Index }
“First, solve the problem.
Then, write the code.”
— John Johnson (Developer and author)
FA) cows detnkive Guide Series: Volume 34Using Modules
‘Python module is simply a Python-
created source File which contains the
necessary and unique code for custom
classes, Functions and global variables.
You can bind and reference modules to
extend functionality and create even
more spectacular Python programs.
Want to see how to better use these
modules to add a little something
extra to your code? Then read on and
learn how they can be used to Fashion
Fantastic code. There's even some basic
animations in this section, to help you
get more from the Python modules.
76
78
80
82
88
90
Calendar Module
(OS Module
Random Module
Tkinter Module
Pygame Module
Basic Animation
Create Your Own Modules
vwonabdmpubcatonscom — (8@) Using Modules )
Calendar Module
‘WORKING WITH DATES
The Calendar module is bul
into Python 3. However, if
For some reason it’s not installed, you can add it using pip install
calendar asa Windows administrator, or sudo pip install calendar for Linux and macOs.
Launch Python 3 and enter: import calendar to
call up the module and its inherent Functions, Once
Itisloaded into memory stat by entering:
‘sep=calendar. TextCalendar(calendar.. SUNDAY)
sep.prmonth(2019, 9)
fle Eat Shel Debug gptons wow Help
Cues
recorder
SS tc catenin ar
Seema
Lcense()" for more snfornation.
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 tine to any year and
‘month you want, a birthday for example (1973, 6).The first-line
configures TextCalendar to start its weeks an a Sunday, you can opt
for Monday if you prefer.
ie tat Oh tg soto done
§ ta be ase
WIFE) 201 ote cite sees ean
Leaps=calendar.Leapdays(1900, 2019)
printCleaps)
The results 29, starting from 1904 onward.
‘le Eat Shel Debug Ortons now Hp
PEPER
Hee ee mt iti
Soe aSaPY calendar
eee,
import calendar
print(S>>>>>>>>>Leap Year
Calculator< Using Modules )
OS Module
INTO THE SYSTEM
(One of the primary Features of the OS module is the ability to list, move, create, delete and otherwise interact with files
stored on the system, making it the perfect module for backup code.
FETED You can startthe 0S module with some simple ESTEED The windows output is different as that’s the
Functions to see howit interacts withthe operating current working directory of Python, as determined
system environment that Python is running on. Fyou're using Linux by the system; as you might suspect, the os getcwd Function is
or the Raspberry Pi, try this: ‘asking Python to retrieve the Current Working Directory, Linux users
an wise something along the sae nes the Raspes
hone=os.getcwdC)
print (home)
PEPTIPD) The returned result From printing the variable home BEVFB yer ancther interesting element to the OS module,
isthe current user's home folder on the system. 'sits ability to launch programs that are installed
Inour example thats /home/pi:it willbe different depending on _inthe host system. For instance, iFyou wanted to launch the
the username you og in as and the operating system you use. Chromium browser From within a Python program you can use
For example, Windows 10 will output: C\Program Files (x86)\ the command
Python36-32 iment
rT bronsersos. system(“/usr/bin/chromiun-bronser”)
WUD) 2ov. ote cite seis elaESTED the ossystem0 function is what allows interaction
with external programs; you can even call up
previous Python programs using thismethod. You wil obviously
‘need to know the Full path and program Fle name foritto work
successfully. However, you can use the following
‘import os
os. system(‘start chrome “https://nwa. youtube. com/
feed/music””)
The ably to manipulate decors or Folders
Sas you prefer, is one of the OS module's best Features.
Fovevampletocete anew rectory you cane
import os
(0s .mkdirC*NEW")
‘This creates a new directory within the Current Working Directory,
named according to the object the mkdir Function,
FETTER For Step 5's example we used Windows, to show
that the OS module works roughly the same across
all platforms. n that case, we opened YouTube's music Feed page, so
itis therefore possible to open specific pages:
‘import os
os.system(‘chromium-browser “http://
bdnpublLications..con/”*)
REDD ots inthe previousstep' example the use of
single and double quotes. The single quotes encase
the entire command and launching Chromium, whereasthe double
quotes open the specified page You can even use variables to call
‘multiple absinthe same browser:
inport 0s
a=(‘chromium-browser “http: //bdmpublications.
con/"")
b=C'chromium-bronser “het
os.system(a + b)
‘Jun. google co.uk”?
BSED scr storsronesny drecoresyuve ress
import os
os.renameC*NEW", “OLD”)
Todelete ther:
import os
os.rmdirC“OLD")
Another module that goes together wth OSis
SusPild shutil. You can use the Shutil module together
vith OS ndtne to create a timestemped bacup rectory and
copy lesitot
import os, shutil, time
root_src_dir = r’/hone/pi/Documents?
root dst_dir = ‘/home/pi/backup/? + time.asctimeC)
for srcdir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_sre_dir, root_
dst_dir, D
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for file_ in files:
sre_file = os.path.join(sre_dir, file_)
dst_file = 0s.path. join(dst_dir, file_)
if os.path.exists(dst file):
0s. renoveCdst_file)
shutil.copy(sre file, dst_dir)
print(sssssss>>>Backup completeccccceceee”)
wnentinoticoncn CS
\ OS Module Cll@) Using Modules )
Random Module
RANDOM NUMBERS
There are numerous Functions:
Python programs.
in the Random module, which when applied can create some interesting and very useful
FRE swans moatsyeuceiorwon
we're going to look at in this tutorial, Let’s begin by simply printing a
‘import random
printCrandomint(0,5))
Inour example
Suave the number Four
was returned, However enter
the pn ncn afew more
times nd pay erent
imager values romthe st oF
numbers given, eo ve The
Overalefect though eeudo:
fandom s adequate forthe
average programmer to ulise in
ther code
Fora bigger set of numbers, including floating
point values, you can extend the range by using the
‘multiplication sign
import random
printCrandom.random() *100)
Will display a Floating point number between 0 and 100, tothe tune
(of around Fifteen decimal points.
DD) 20ers olan
However. the Random module aitused exclusely
Bue for numbers. You can use it to select an entry From a
lst From random, and thelist can contain anything:
import random
random. choiceC{*Conan”, “Valeria”, “Belit”])
This will display one of the names of our adventurers at random,
which fsa great addition toa text adventure game.
You can extend the previous example somewhat by
hhaving random. choice) select froma list of mixed
variables. For instance:
import random
Lst=[“David”, 44, “BOM Publications”, 3245.23,
“pi”, True, 3.14, “Python”]
rnd=random. choiceCIst)
print(rnd)Interesting, youcan ao ea function whine
Suze Random module to shuffle the items in the list, thus
‘adding alittle more randomness into the equation:
random. shuffleClst)
print(ist)
‘This way, you can keep shuffling the list before displaying a random
item from it.
Using shuffle, you can create an entirely random lst
‘of numbers. For example, within a given range:
Sis
‘import_random
Ast=[[i] for I in range(20)]
random. shuffleClst)
print(1st)
Keep shuffling the list and you can havea different selection of
items from 0to 20 every ime.
PEPTID) You can also select.a random number framagiven
range in steps, using the start, stop step loop:
‘import random
for i in range(10):
printCrandom.randrange(®, 200, 7))
Results will vary but you get the general idea as to howit works.
(Random Module Cll
Levsuse an example pec of code wich ipsa
EUSP) virtual coin ten thousand times and counts how
many times itwil land on heads or tails:
import random
‘output={*Heads”:0, “Tails”:0}
coin-listCoutput.keys())
for i in rangec10000):
‘output[random. choi ceCcoin)]+=1
print(‘Heads:”, output[“Heads”])
print(“Tails:”, output[“Tails”])
Here's an interesting piece of code. Using atext
File containing 466 thousand words, you can pluck
‘user generated number of words from the file (text file Found at:
‘www. github.com/dwyl/english-words):
import random
print(>ss>>ss>59Random Word Finderc>>>25>5>>Your adventure rolecceceece=600 or pos[t] <0:
ya = -ya
if pos[2] >=800 or pos[0] <0:
gui -updateC)
time.sleep(.025)
Remove the codeyouenteredin Step 2andinsr.
Size the code from Step 5 in its place; again, between the
ball = canvas. create_oval(S,5,60,60, fill=’red’)
and the gui .mainL.oop() tines. Save the code and Run it as normal
you've entered the code correctly, then you wil see the red ball
‘bounce off the edges of the window until you close the program.
The bouncing animation
takes place within the
While True loop. First, we have the values
(of xa and xy before the oop, bath of $ and
10. The pos=canvas..coords(bal11) line
takes the value of the balls location in the
window. When it reaches the limits oF the
window, 800 or 600, will make the values
‘negative; moving the ball around the screen
PRD eons nowrsisrmasete poate
ue sti = 250
def init_stars(screen):
“© Create the starfield “”
global stars
stars =
for i in rangeCMAX_STARS):
# A star is represented as a list with this
Format: [X,Y
star = [randrange(®, screen.get_width©) - 1),
randrange(@, screen.getheight©) - 1)]
stars.append(star}
def move_and_draw_stars(screen):
“© Move and dran the stars “”*
global stars
for star in stars:
star[1] += STAR_SPEED
if star[1] >= screen.get_height©:
star[i] = 0
star[0] = randrange(@,639)
screen. set_at(star, (255,255,255))
FETED ow add the Following:
def main():
pygane. init©
screen = pygane.display. set_mode((640,480))
pygane. display. set_captionC*Starfield
Simulation”)
‘clock = pygame. time.Clock()
init_stars(screen)
while True:
# Lock the framerate at 50 FPS
clock. tick(S0)
# Handle events
for event in pygane.event.get():
if event.type == pygame. QUIT:
return
screen. fl1((0,0,0))
move_and_draw_stars(screen)
pygame.display. flip)
if _name__ ==
main)
“_main_
det main)
yaame: nse)
Pyoane-dsbplay.Set-eaption( "=
EXeek = pyoane-eine-cioek()
(640, 0)
Mfct8'Staabatson)
| snst_stara(screen)
‘hock: eiek(S0) °
handle events
event. get)
yoame: rt
screen. F511((0,9,9))
ee eee
Prasee.sisplay- F300),
PEPPER) Seve and Run the code. You will agree that the
simulated starfield code looks quite impressive.
Imagine this s the beginning of some game code, or even the start
toa presentation? Using a combination of Pygame and Tkinter, your
Python animations wil look fantastic.@) Using Modules
Create Your Own Modules
BUILDING MODULES
‘Modules are Python files, containing code, that you save using a py extension. These are then i
now Fa
ported into Python using the
import command
Lette by creating aset of bast matheratis
SIE Functions. Multiply @ number by two, three and
square or raise a number to an exponent (power). Create a New File
Inthe IDLE and enter
def timestwoCx):
return x * 2
def timesthree(x):
return x * 3
def square(x):
return x * x
def power(x,y):
return x ** y
print Ctimestwo(2))
print Ctimesthree(3))
print Csquare(4))
print Cpower(5,3))
Save the program as basic math.py and execute itto get the results.
Under the above code, enter Functions to call the
code:
rane Ptentenso) =
DBD) 201 ote cite sees olan
BATEREDD Now you're going to take the Function definitions
‘out of the program and into a separate file
Highlight the Function definitions and choose Edit > Cut. Choose File
> New File and use Edit > Paste in the new window. You now have
two separate files, one with the Function definitions, the other with
the Function calls
IF you now try and execute the basic_math,py code
‘again, the error’ NameError: name timestwo' is
not defined! willbe displayed, This is due to the code no longer
having access to the Function definitions
ED Returnto
thenewly
created window containing
the Function definitions, and
Click ile > Save As. Name this
minimath.py and save it in the
same location as the original
basic_math.py program. Now
close the minimath.py window,
so the basic_math.py window fs
left openPEPTID G2ck to the basic_math.py window: at the top ofthe
code enter:
from minimath import *
‘Thiswillmport the Function definitions asa module, Press F5 to
save and execute the program to see itn action,
FEPTIED You can now use the code Further to make the
program alittle more advanced, utilising the newly
created module to its Full Include some user interaction. Start by
eating a basic menu the user can choose from:
print(“select operation.\n")
print(“1.Times by two”)
print(“2.Times by Three”)
print(“3.Square”)
print(“4.Power of”)
choice = input¢“\nénter choice (1/2/3/4):”)
‘nun = intCinput(“\nénter number: “))
This illsave the user-entered number asthe variable num?
Now we can add the user input to get the number
the code will work on:
Tron minimath Inport *
print("Select operation.\n")
Hee 1.Times by two
irint("2.Tames
irint("3.Square")
print(~4:Poner of")
choice = input("\nénter choice (1/2/3/4):")
punt = int¢input("\nenter number: "))
-
( Create Your Own Modules
finaly youcan now create a range off statements
EUSP) to determine what to do with the number and
utilise the newly created function definitions:
if choice == ‘1’:
printCtimestwoCnumt))
elif choice == 2
print(timesthreeCnunt))
elif choice == ‘3’:
print(squareCnum))
elif choice == <4":
‘und = intCinput(“Enter second nunber:
print(poner(numl, nun2))
else:
printC*Invalid input”)
le Est Fmt Ban opera swe tp
»)
gman
Note that forthe ast avalable options, the Power
Surly of choice, we've added a second variable, num2.
This pases asecond number trough the function defniton cle
power. Sve and execute the program o seein action,
wnentinotictoncn GT“The most
important
property of
a program
is whether it
accomplishes
the intention
of its user.”
syictooc CRE
C++ is an excellent, high-level
Programming language that’s used in a
multitude of technologies. Everything
from your favourite mobile app, console
and PC game to entire operating systems
are developed with C++ as the core,
together with a collection of software
development kits and custom libraries.
C++ is the driving force behind most
of what you use on a daily basis, which .
makes it a complex and extraordinarily ee
powerful language to get to grips with.
In this section, we look at how to install a
C++ IDE and compiler on your computer.
94 Why Cos?
96 Equipment You Will Need
98 Howto Set Up C++ in Windows
100 How to Set Up Cr+ ona Mac i
102 How to Set Up C++ in Linux
Other C++ IDEs to Installz= Say Hello to C++ )
Why C++?
eee gas Ce cc eateries et ACH
called C with Classes, the language was renamed C++ in 1983. t's an extension of the
original C language and is a general purpose object-oriented (OOP) environment.
C EVERYTHING
Due to how complex the language can be, and its power and performance, C++ is often used to develop games, programs,
device drivers and even entire operating systems.
G &conemeraterduntstrrton
Dating backto 1979, the start ofthe golden era of home ‘computing labs and by regular people who didn't have access tothe
Computing, C++, or rather C with Classes, was the brainchild of mainframes and large computing data centres.
Danish computer scientist Blame Stroustrup while working on his
PhO thesis. Stroustrup's plan was to further the original language, Cts impactin the digital word is immense. Many of the programs,
which was widely used since the early seventies. applications, games and even operating systems are coded using
Cr+. For example, all of Adobe's major applications, such as
C++ proved to be popular among the developers ofthe 80s, Photoshop, InDesign and so on, are developed in C++. You will find
since it was a much easier environment to get to grips with and that the browser you surf the internet with i written in C++, as
‘more importantly, it was 99% compatible with the original C ‘well as Windows 10, Micrasoft Office and the backbone to Google's
language. This meant that it could be used beyond the mainstream search engine. Apple's macOS is writen largely in C++ (with samme
PET 220 cite sees vole(why c+4? Cl
\
ven summary
Microsoft's Visual Studio is a great,
Free environment to learn C++ in.
‘other languages mixed in depending on the function) andthe likes begin with Python and spend some time getting to grips with
‘of NASA, SpaceX and even CERN use C++-For various applications, _programming structure and the many ways and means in which
‘programs, controls and umpteen other computing tasks. you Find a solution to a problem through programming, Once
Yyou can happily power up your computer and whip
‘outa Python program with one hand tied behind
your back, then move on to C++. OF course,
there's nothing stopping you from jumping
straight into C+ if you Feel up tothe task,
go fort.
C++ salso extremely efficient and performs
well across the board as well as being an
easier addition tothe core C language.
This higher level of performance over
other languages, such as Python, BASIC
and such, makes it an ideal development
environment For moder computing,
hence the aforementioned companies
Using itso widely
Getting to use C+ is as easy as Python, all
you need isthe right set of tools in which
to-communicate with the computer in
C++ and you can start your journey. A C++
IDEs Free of charge, even the immensely
powerful Visual Studio from Microsoft
's freely avalable to download and use.
You can get into C++ from any operating
system, be it macOS, Linux, Windows or even
mobile platforms.
While Python is great programming
language to learn, C++ putsthe developer
Ina much wider world of coding. By
‘mastering C++, you can find yourselt
developing code forthe likes of Microsoft, Apple
and so.0n. Generally, C++ developers enjoy a higher
salary than programmers of some other languages and
due toitsversatliy, the C++ programmer can move between Justlke Python, to answer the question of Why C++ isthe
Jobs and companies without the need to relearn anything specific. answer is because it's fast, efficient and developed by most ofthe
However, Python is an easier language to begin with. you're ‘applications you regularly use l's cutting edge and a fantastic
completely new to programming then we would recommend you language to master.
using is written in Ces.
= & © @
“_ Mac — debian ubuntu
———
GS Indeed, the operating system you're\
Say Helloto C++ )
Equipment You Will Need
Sor Meee eee eM MR ol Keen NT
don’t need an entire computing lab at your disposal either. Providing you have a fairly
modern computer, everything else is Freely available.
C++ SETUPS
‘Most, if not all, operating systems have C++ in their code, so it stands to reason that you can learn to program in C++ no matter
what OS you're currently using.
COMPUTER
Unless you Fancy writing out your C++ code by hand on a sheet of
paper (which is something many older coders used to do), 2 computer
isan absolute must have component, PC users can have any recent
Linux distro or Windows OS, Mac users the latest macOS.
[_] AN IDE
_ code. Many IDEs come with extensions and plugins that help make
provides enhancements depending on the core OS being used, such as
— being enhanced for Windows 10.
COMPILER
————<
‘compiler isa program that converts the C++ language into binary,
so that the computer can understand, While some IDEs come with 3
compiler builtin, others don't. Code: Blocks s our Favourite IDE that
comes ith a C++ compiler as part ofthe package. More on ths later.
|_| TEXT EDITOR
Sete en eat arena es
Cee code before running ttirough a compiler Essentaly you can
Use any text editor to wre code just save with a.cpp extension
eee tee
|_| INTERNET ACCESS
While it’s entirely possible to learn how to code on a computer that’
not attached tothe Internet, it's extraordinarily difficult. Youneed
to install relevant software, keep it up to date install any extras or
extensions and look for help when coding, All of these require access
to the internet.
L] TIME AND PATIENCE
Yes, as with Python, you're going to need to set aside significant time
tospend on learning how to cade in C++. Sadly, unless you're a genius,
isnot going to happen overnight, or even a week. A good C++ coder
has spent many years honing their craft, so be patient, start small and
keep learning
BET 200 cies eure(Equipment You will Need Cl
OS SPECIFIC NEEDS
‘C++ will work in any operating system but getting all the necessary pieces together can be confusing to a newcomer. Here are
some OS specifics For C+.
ay
We have mentioned previously that a good IDE is Microsoft's
Visual Studio. However, a better IDE and compiler is
Code:Blocks, which is regularly kept up to date with a new
release twice a year. Otherwise Windows users can enter
their code in Notepads-, then compile it with MinGW as used
by Code:Bi
Linux users ae lucky thatthey already have a compiler and
text editor butt into their operating system. Any text editor
allows you to type out your C++ cade, when i's saved with a
cpp extension, use gr+ to compile
RASPBERRY PI MAC
} The Raspberry P's operating
system's Raspbian, which
isLinux based, Therefore,
you're able to write your code
‘out using a text editor, then
compile twith g++ as you
would in any other Linux distro.
Mac owners willneed to
download and install Xcode
tobe able to compile their
C++ code natively, Other
‘options For the macoS
include Netbeans, Eclipse or
Code:Blocks. Note: the
latest CodesBlocks srt
available For Mac due to a lack
‘of Mac developers..
Say Helloto C++ )
How to Set Up
C++ in Windows
AU YinNeCo RUE VER IMl eRolm eae AU aM eon nA Co Dols CTU aN Cae eK E
are plenty of IDEs and compilers available, including Visual Studio from Microsoft.
However, in our opinion, the best C++ IDE to begin with is Code::Blocks.
CODE::BLOCKS
Code:Blocks is a free C++, C and Fortran IDE that’s Feature rich and easily extendible with plug-ins. It's easy to use, comes with
a compiler and has a vibrant community behind it.
FETED S2tby visting the Code:Blocks downloadsite, at EEEEM when you've located the file, click on the
worw.codeblocks.org/downtoads, From there, click Sourceforge.net link atthe end ofthe line and a
‘on the ‘Download the binary releases’ ink tobe taken to the latest download notification window appears; click on Save File to start
downloadable version fr Windows. the download and save the executable to your PC. Locate the
TS ‘downloaded CodeBlocks installer and double-click to start. Follow
oo the on-screen instructions to begin the installation
Welcome to CodeBlocks Setup
Sup ge you tru eaten Cs
Rereomnendet lyases ote eet
‘fuer Sun ere pe aoe
‘Seeder teers wre rs
PEPIPD You cansee that there are several Windows versions [EFM once you've agreed to the licencing terms, thereisa
available. The one you want to download has choice of installation options avalable. You can opt
‘mingw-setup.exe' atthe end of the current version number. At fora smaller install, missing out on some of the components but we
the time of writing this: codeblocs-17.12mingwesetup.exe. The would recommend you opt forthe Ful option as default
differences that the mingw-setup version includes a C++ compiler
td debuage rom TDMECe (acompir suite ®
a
ao cee
| Peon -
cnc nme rma soe: =
aes a a
ET 220 cite sees ene(_ Howto Set Up C++ in Windows Cl
Next choose an instal ocation fr the Codes Blocks
Suse files. It's your choice, but the default will generally
suc, ules ofcourse you hoe any pede equements When
you click Next, the install begins; when it's inished a notification
ops up asking you iF you want to start Code:Blocks now, so click Yes
rae rte Cs atta oaneg Mew rcs at Mar os)
ere le Cis ber ea.
aye j
=<
=<
rant a oe |
aeRO
FETTER The Fisttime Code:Blocks loadsitruns an
auto-detect for any C++ compilers you may already
have installed on you system. you don’t have any, click on the
first detected option, GNU GCC Compiler, and clckthe Default
button to set it as the system's C++ compiler. Clik OK when you're
ready to continve.
iebitieeeeeesatcc!
BERT) When the program starts another message appears,
informing you that Code:Blacks is currently not the
default application For C++ files. You a couple of options: to leave
everything ast sor alow Code: Blocks to associate all C++ fle
types. Again, we would recommend you opt forthe last choice to
‘associate CodeBlocks with every supported file typ.
Before youstart using Code:Blos t's worth
Sua ‘explaining exactly why you need the added
complet rst, acomplerise seperate program tht reads
throughyour Cvs code and cheds agaist the atest acceptable
programing standards why youneed te mest rece
Evatble comple Te caren Cor wth C20 undery
FETED Essentially, computers work and understand only
binary, ones and zeros, or Machine Language
Programming in binary isnt effective For human beings. For
‘example, to outputthe words "Hello World!” tothe screen in C++
‘would appear in binary as:
1100011 01101111 01110101 21110100 e0100000
00111100 0111100 90100000 90100010 01001000
01100101 01101100 01101100 @1101111 @0100000
1010111 01101111 01110010 @1101100 01100100
00100001 00100010 o0111011
Select
FETS eR ED the compiler therefore takes what you've
entered as C++ code and translates that to
Machine Language. To execute C++ code the IDE builds the code,
‘checking for errors, then pass it through the compiler to check
standardisation and convert i to ones and zeros For the computer
toact upon. It's rather clever stuff, when you stop to think about ft
ora bdmpublications com.
@) Say Helloto C++ )
How to Set Up
C++ ona Mac
To begin C++ coding on a Mac you first need to install Apple’s Xcode. This is a Free, Full
featured IDE that’s designed to create native Apple apps. However, you can also use it
to create C++ code relatively easily.
XCODE
Apple's Xcode is primarily designed for users to develop apps For macOS, iOS, tvOS and watchOS applications in Swift or
‘Objective-C but you can use it for C++ too.
Start by opening the App Store on your Mac, Apple ‘when you're ready, clickon the Get button which
"Menu > App Store. Inthe Search box enter Xcode’ then tumnsinto install App Enter your Apple ID
and press Return, There are many suggestions filing the App Store and Xcode begins to download and install It may take some time
‘window butts the first option, Xcode, that youneed tocickon. depending on the speed of your Internet connection
PEPTPD Take amoment to browse through the app's EEPPD when the installation is complete, click on the
information, including the compatibility, to ensure ‘Open button to launch Xcode, Click Agree to the
you have the correct version of macOS. xcode requires macOS licence terms and enter your password to allow Xcode to make
10.126 or later to install and work. ‘changes tothe system. When that is done, Xcode begins to install,
‘additional components,
FEED sorts Detnive cide seris- volume 34With everything now installed, including the
additional components, xcode launches, displaying
the version number along with three choices and any recent projects
that you've worked on; with afresh install though, this is blank
you're developing code For. Click the macOS tab, then click the
Command Line Tool option. Click Next to continue.
Start by clicking on Create New Xcode Project; this
‘opens a template window to choose which platform
SET erey Del
Fillin the various fields but ensure that the
Language option atthe bottom i set to C++; simply
choose it from the drop-down list. When you've iled inthe field,
‘and made sure that C++ isthe chosen language, click an the Next
button to continue,
Te next step asks hereto create aGitRepostory
plEtg for all your Future code. Choose a location on your
Mac oranetwor action, and ickthe Create buton when
You've done althat you can start to code. Thelethand pane
deta the ies used Inthe C+ program youre codhng, Conte
maine le inthe
You can see that Xcode has automatically
completed a basic Hello World program for you
STEP 9
‘hile it may not make much sense at present, you wil discover
more as you progress, the content is just Xcade utlising what's
‘available on the Mac.
corr Tr
‘when ouwantto run the code, ikon Product»
Suid Run. You may be asked to enable Developer Mode
nthe Mac tisistosuthorse Xcode to perform uncions without
needing your password every seson Whenthe rogram execs,
the output is dsplyed atthe bottom ofthe Xcode window
Pron a
wmvinociccoson CT
(How to Set Up C++ on a Mac ClBE) sito.
How to Set Up
C++ in Linux
aed endo tC ne eee ee cect
Coon oN ee el re ene Reon | MN Ae el Cole E eK anna
entering code into, including colour coding. There’s also tons of extra software available
oh helt helt a
LINUX++
IFyou're not familiar with Linux, then we recommend taking a look at one of our Linux titles From the BOM Publications range.
IF you have a Raspberry Pi
The fist step isto ensure Linux is ready For your C++
code, so check the system and software are up to
date. Open a Terminal and enter- sudo apt-get update && sudo apt-
‘get upgrade. Then press Return and enter your password. These
‘commands update the entice system and any installed software.
le Edk_Vew Sear Terminal Hp
PEPER ost Linux distros come preinstalled with all
the necessary components to start coding in
C+s;however, i's always worth checking to see if everything
's present, Stil within the Terminal, enter:sudo apt-get
Install build-essential and press Return. you have the right
components nothing is installed; iF you're missing some then they
are installed by the command,
EEE cores etntive Guide Seris-votume 24
he commands used below work just Fine and for this example we're using Linux Mint
FETED srazinaly thats. everthing is already for you
tostart coding. Here's how to get your First C++
program up and running, In Linux Mint the main text editors Xe,
‘hich you can launch by clicking on the Menu and typing Xed into,
the search bar. Clickon the Text Editor button inthe right-hand pane
toopen it.
FPP M 10 Xed, or any other text editor you may be using,
enter the lines of code that make up your C++ Hello
‘World program. t'sa little efferent to what the Mac produced:
#include
int main
i
7iMy first C++ program
std::cout << “Hello World!\n”;
¥
pealns
xen aavowtostvcrninx CR
FTIR) When youve entered yourcode,cickFile>Saveas ERIM sefore you can execute the C++ file you need to
and choose a folder in which to save your program. compile In Linux t's common to use g++, an open
Name the Fle ashelloworld.cpp (it can be any name aslong as ithas source C++ compiler; as you're now inthe same folder as the C++
pas the extension), Click Save to continue. file, enter: g++ helloworld.cpp in the Terminal and press Return,
Fe tt Vow tach Terie
FETTER The Fist thing to notice is that Xed has FETTER takes short time while the code is compiled by
automatically recognised this asa C++ file, since the {g++ but providing there are no mistakes o errors in
file extension is now set to cpp. The colour coding is present in the the code you are returned to the command prompt. The compiling
code and iF you open up the file manager you can also.see thatfil’s of the cade has created a new file. If you enter into the Terminal
icon has C++ stamped onit, you can see that alongside your C++ files aout.
BEPTSER) With your code now saved, drap into the Terminal SIIB the aout files the compiled C++ code. Torun
again. You need to navigate to the location of the code enter: fa.out and press Return. The
the C++fileyou'veust saved. Qur examples inthe Documents words ‘Hello World appear on the screen. However, a.out ist
Folder, so we can navigate to it by entering: ed Documents, very friendly. To name it something else postcompiling, you can
Remember, the Linux Terminals case sensitive, so any capitals recompile with: g++ helloworld.cpp-0 helloworld, This creates an
‘must be entered correctly ‘output file called helloworld which can be run with: /helloworl.
tlt Vow Seach Teri tp Fit Yon tech Tb ele@) Say Helloto C++)
Other C++ IDEs to Install
Tana SECT ech N geet Meee
plenty of options available to you. Windows is the most prolific platform for C++ IDEs
but there are plenty for Mac and Linux users too.
DEVELOPING C++
Here are ten great C++ IDEs that are worth looking into. You can install one or all of them if you like, but Find the one that
works best For you.
ren Ste Eclnseis a hugely popular C++ IDE that offers FREE TE Codelite isa free and open source IDE that's
the programmer a wealth of Features, has a regularly updated and available for Windows,
‘reat, clean interface, is easy to use and available For Windows, Linux and macOS. t's lightweight, uncomplicated and extremely
Linux and Mac. Head over to www.ecipse.org/downloads/ to powerful. You can find out more information as well as how to
download the latest version. If you're stuck, click the Need Help link download and instalit at www.codelite.ora/.
for more information,
FAD The GNAT Programming Studio (GPS) isapowerful — INPEMSSNNER Another popular choice is NetBeans. This
‘and intuitive IDE that supports testing, debugging [s another excellent IDE that's packed with
and code analysis. The Community Edition is Free, whereas the Features and a pleasure to use. NetBeans IDE includes project based
ro version costs; however, the Community Editionis available for templates for C++ that give you the ability to build applications with
\windows, Mac, Linux and even the Raspberry Pi You canfinditat dynamic and static libraries. Find aut more at www.netbeans.org/
wwrw.adacore.com/downtoad. Features/cpp/index.html.
ov tn ise volun 4(
XX
Other C++ IDEs to Install Cl
Microsoft's Visual Studio is 2
mammoth C++ IDE that allows you
VISUAL STUDIO
to create applications for Windows, Android, iOS and the web. The
Community version s Free to download and install but the other
versions allow 2 ree tral period, Go to www.visualstudio.com/ to
see what itcan do For you.
ESRD Ths ross platform IDEs designed to
create C++ applications For desktop and
‘mobile environments. Itcomes with a code editor and integrated
tools For testing and debugging, as well as deploying to you chosen
platform, i's nat free but there sa tial period an offer before
The Anta Devstudi ia Uru ony DE that
AoHoE Features some of the more advanced features you
would nermaly dina pad software development tudo, There's
{GUI designer source edtor pp wierd, nteracve debugger and
Inch more Goto wnwanjuta.r/ for more formation
Ia eee Ts excellent IDE allows developers
towrite C++ code For desktop and
‘web applications across all the major platforms. There's an advanced
text editor, integrated debugger and a configurable workbench to
help you create your code. I's available for Windows, Mac and Linux
andis free to download and use: www.monodevelop.com/.
PYSYTSIEMD Bloodshed Dev C+, despite its colourful name,
isan older IDE that is for Windows systems only.
However, many users praise its clean interface and uncomplicated
\way of coding and compiling. Although there's nat been much
updating for some time, it's certainly one to consider if you want
something ifferent: www.bloodshed.net/devcpp.html
a
=e 4
Ultimate +s cross-platform C++ IDE that boasts a
rapid development of code through the smart and
‘aggressive use of C++. For the novice, it's beast of an IDE but behind
its complexity s a beauty that would make a developer's knees go
‘wobbly. Find out more at www.ultimatepp.org/index.html
wmvinociccoson CI(C+ Fundamentals
\
Within this section, you will begin to
understand the structure of C++ code and
how you can compile and execute that
code. These are the core Fundamentals
of C++, which teach you the basics such
as using comments, variables, data types,
strings and how to use C++ mathematics.
These are the building blocks of a C++
program. With them, you will be able to
Form your own code, produce an output
tothe screen, store and retrieve data and
be well on your way to creating your own
custom code.
108 Your First C++ Program
110 Structure of a C++ Program
112 Compile and Execute
114 Using Comments
116 Variables £
118 Data Types i
120 Strings
C++ Maths:
SCRE
(Pioneer programmer)
when interviewed by
pec
ora vmpublcatonscom=
Zz 2 ) C++ Fundamentals )
Your First C++ Program
SME CMe ee Rech ace gM aCe STs [ Cs
Marre Ueh AIA Ia acu Keeton: ee enema Ma
your First C++ program and taking the First small step into a larger coding world.
HELLO, WORLD!
nal in programming for the first code to be entered to output the words ‘Hello, Wor
stra
0 the screen. Interestingly,
this dates back to 1968 using a language called BCPL.
ESTEE 5 mentioned, we're using Windows 10 and the FETED A:the momentit doesnt look tke much, and
latest version of Code:Blocks forthe rest ofthe C++ itrakes even less sense, but we'llget to that
ode in this book. Begin by launching Code:Blocks, When open, click in due course. Now click on File > Save File As. Create or find @
(on File> New > Empty File or press Ctri#Shift#N on the keyboard. suitable location on your hard drive and inthe File Name box, call
ithelloworld.cpp. Click the Save as type box and select C/C++ Files.
‘lick the Save button.
ESTEE ow you can see a blank screen, withthe tab Bea You can see that Code:Blocks has now changed
labelied *Untitiedt, and the number one inthe top the colour coding, recognising thatthe file's now
left of the main Code:Blocks window. Begin by clicking in the main C++ cade. This means that code can be auto-selected from the
window, so the cursors next to the number ane, and entering Codes.Blocks repository, Delete the tinclude line and
re-enter it. You can see the autoselect boxes appearing,
#include
[80M Definitive Guide Seris-Volume 24C Your First C++ Program Cl
BERTSED) 2utoselection of commands is extremely handy and
cuts out potential mistyping, Press Returnto get to
line 3,then enter:
int main
"Note: there's no space between the brackets.
PeimveisaliSias hie SEErrr es
x
ESTEE) onthe next line below int maind, enter a curly bracket:
{
‘This can be done by pressing Shift and the key tothe right of Pon an
English UK keyboard layout.
asim S
eae
veeeaitgdoborb ade scasee
oe
My first C+ program
[esis wiSiae mie.
[Note again the colour coding change. Press Return at
the end of the previous steps ine, and then enter:
std:
‘cout << “Hello, world!\n";
es reel SRE
ele eee sexu sl emligee
Bes tam
Just. as before, Coder:Blocks auto-completes the
Code you're entering, including placing a closing
Sia
speech mark as soon as you enter the first. Dont forget the
semicolon atthe end of the line; this sone of the most important
‘elements to a C++ program and wel tell you why in the next
section. For naw, move the cursor down to the closing curly bracket
and press Return.
(eealaeiors: ecusieaig
ig ere Sit she Be sa= is
ee
Tact pended moms ta
wmvinectccoson CE=
zk C++ Fundamentals )
Structure of a ;
C++ Program
ae eM ine eaten eu Me Ram OTe a een fata
Pee eeu hac neem cil tema cris isctetck
NEE ecu ae ene alco eetastice
#INCLUDE
Learning the basics of programming, you begin to understand the structure of a program. The commands may be different
from one language to the next, but you will start to see how the code works.
on #INCLUDE Stxthere | “helloworldcyp |
‘#include includes the
while making ta more iostream header to support
User friendly environment inputjoutput operations.
through anew structure
Blame Stroustruy
INT MAIN() [Serthee %| *helloword.epp x |
Intmaind inotes the
dectartion oF function, which
isa group of code statements
under the name main ll
C++ code beginsat the main
Function, regardless of where it
actualy lies within the code
Finclude
int main)
BRACES Starthere | *helloworkd.cpp
The open brace (curly brackets) is something
that youmay not have come across before,
‘especially if you're used to Python, The
‘open brace indicates the beginning of the
main function and contains allthe code that
belongs to that Function
ETD 2s recuse sets net
#include
int main()
feCOMMENTS
Lines that begin with a double slash ace comments.This means they
won't be executed in the code and are ignored by the compiler.
Comments are designed to help you, or another programmer
(ooking at your code, expainwhats going on. There ae two types
of comment: /* covers multiple ine comments, single ln, Lines
that sin with a double slash are comments.This means they won't
be executedinthe code and
are ignored bythe comptr.
Commentsare designed |
tohelp you, or another
programmer looking at
yourcodeexplainwhat’s |
going on. There eto
types of comment: /* covers |
‘multiple ine comments, //2_||
single line,
C Structure of a C++ Program Cl
<<
‘The two chevrons used here are insertion operators, Thismeans
that whatever Follows the chevrons isto be inserted into the
std:cout statement, In this case they're the words Hello, world,
‘hich are to be displayed on the screen when you compile and
execute the code,
STD
\while std stands for something quite different, in C++ it means
‘Standard. I's part ofthe Standard Namespace in C+, which covers.
‘a number of ciffecent statements and cormmands. You can leave the
stds part out of the code but it must be declared atthe start with:
using namespace std; not both. For example:
#include
using namespace std;
4
COUT
Inthis example we're using cout, which isa part of the Standard
"Namespace, hence why t's there, as you're asking C++ to use irom
that particular namespace. Cout means Character OUTput, which
displays, or prints, something to the screen. If we leave std: out we
have to declare it atthe start of the code, as mentioned previously.
[Sathee —%<) *hellowordepp =
1 | finclude
2 | using namespace sta;
3
4 | ant main)
5 lac
6
7 cont,
°
°
20
OUTPUTS
Leading on, the “Hello, world” partis what we want to appear on
the screen when the code is executed. You can enter whatever you
lke, as long asits inside the quotation marks. The brackets aren't
needed but some compiles insist on them, The \n partindicates a
new line is tobe inserted
//My first C++ program
cout << “Hello, world!\n”
; AND}
Finally you can see that lines within a Function cade block (except
‘comments) end with a semicolon. This marks the end ofthe
statement and all statements in C++ musthave one at the end or
the compiler Fails to build the code. The very last ine has the closing
brace to indicate the end of the main Function.
[Satiee DN] “retoworae x
Vinciude
ing namempace att
int main()
cout << *Hello, world! \n";
EB weveuaune|
az= C++ Fundamentals )
Compile and Execute
You've created your First C++ program and you now understand the basics behind the
Rte omer eee ea au aku eke mrtg
you prefer, the program and see how it looks.
GREETINGS FROM C++
Compiling and executing C++ code from Code::Blocks is extraordi
result. Here's how it's done.
(Open Code:Blocks,f you haven't already, and
load up the previously saved Hello World code you
created. Ensure that there are no visible errors, such as missing
semicolons at the end of the std:cout lin,
IF your code is looking similar tothe one in our
screenshot, then look to the menu bar along the top
of the screen. Under the Fortran entry in the topmost menu you can
see a group of cons: a yellow cog, green play button and a cog/play
button together. These are Build Run, Build and Run functions.
ly easy; just a matter of clicking an icon and seeing the
ESTED t2rtby clicking onthe Build icon, the yellow cog
the CodeBlocks compiler and checked For any errors. You can see
the results of the Build by looking to the bottom window pane. Any
messages regarding the quality ofthe code ae displayed here.
fo Aeseaoe se
SI Res =] Seattg x1 faim At
[Now click on the Run icon, the green play button.
‘command line box appears on your screen
displaying the words: Hello, world, followed by the time it’s taken.
toexecute the code, and asking you press akey to continue. Well
done, you ust compiled and executed your First C++ program.
EEE corset Gude Seris-votume 24Conpieandeeate OR
12a deliberate errarin the code. Remove the
semicolon from the cout line, soit reads:
cout << “Hello, world! \n"
Presingayyinibeconmendinetoccet, SD
NSPE returning you to Code::Blocks. Let's alter the code Sua
slighty Under the sinclude ine, enter
using nanespace std;
‘Then, delete the std: part of the Cout ine; like so:
Starthere x
cout << “Hello, world\n”;
using namespace std;
int masn(
Finclude
using namespace std; cout << a3
: cout << "\n"s
me cout << bs Sing ames mae
7 ‘The cout <<" par ee man
simply places new line
between the output of
tands, wees
Fined:
int main()
;
FEED Se2ttsimple by creating two variables, aandb, with [ESSE Naturally you can declare anew variable, call it
‘one having a value of 10 and the other S. You can result and output some simple arithmetic:
use the data type int to declare these variables. Within the curly :
brackets, enter: TESS
result «a +b;
= Goes] wren % cout << result;
= § = Insert the above into the cade as per the screenshot
b=5;
soot ieee oieveiates CE
Youcenssignavaietoneralessconasyas TREAD) Teepeussten ets evar ates,
Suz declare it. The code you've typed in could look like: Sua which is a global variable. in a game, for example,
ths stead 2 plye sve oup or down depending on how wel how bad
int a = 20; recs tots defo sates Hereweve asrgned 3s thet
int b= 55 :
ees subtracted 1, leaving 2 lives left
cout << result
FETED The modern C++ compiler is far more intelligent.
than most programmers give it credit. While there
are numerous data types you can declare for variables, you can in
d fact use the auto Feature:
include
using namespace std;
‘auto pi = 3.141593;
BETTER Soeciictoci+.youcanalsousethefollowing int main)
toassign values to a variable as soon as you :
declare them: double area, radius = 1.5;
int @ 10); = pi * radius * radius;
— area = pi * rad dius;
‘Then, from the C++ 2011 standard, using curly Brac EEN
int result {orb}; ‘
FSTeER AD You can create global variables, which are variables
that are declared outside any Function and used in
any Function within the entire code, What you've used so far are
local variables: variable used inside the Function. Far example:
‘Acouple of new elements here: ist, auto won't
work unless you go to Settings > Compiler and
tick the box labelled ‘Have G++ Follow the C++11 150 C++ Language
#include Standard [std=c++1J. Then, the new data type, double, which
using namespace std; means double-precision floating point value. Enable C++, then,
int StartLives = 3; build and run the code, The result should be 7.06858,
int main © at
{
startLives = StartLives = 1;
cout << Startlives; _
}
vwonatdmpublcatonscom QRS=
zk C++ Fundamentals )
Data Types
Variables, as we've seen, store information that the programmer can then later call up,
ETM Clem Cee LeU e ETE Ate Rena Cele Le Cot
Tenet cee Me Teme ue Ke lea tree
THE VALUE OF DATA
There are many different datatypes avaliable forthe programmer
in C+, suchas an integer, floating point, Boolean, character and so
on. I's widely accepted that there are seven basic datatypes, often
called Primitive Bultin Types; however, you can create your Own,
data types should the need ever arise within your code.
‘The seven basic data types are:
TYPE
COMMAND
Integer
Gone
Dealers | ems]
‘These basic types can also be extended using the Following modifiers:
Long, Shot, Signed and Unsigned. Basically this means the modifiers
can expand the minimum and maximum range values for each data
{ype. For example, the int datatype has a default value range of
2147483648 to 2147483647, fair value, you would agree.
‘Now, if you were to use one of the modifiers, the range alters:
Unsigned int = 0to 4294967295
Signed int =-2147483648 to 2147483647
Short int =-32768 to 32767
Unsigned Short
Signed Short int =-32768 to 32767
Long int =-2147483647 to 2147483647
Signed Long int =-2147483647 to 2147483647
Unsigned Long int = 0 to 4284967295
"Naturally you can get away with using the basic type without the
‘modifier, as there's plenty of range provided with each datatype.
However, its considered good C++ programming practise to use the
‘modifiers when possible.
‘There are issues when using the modifiers though. Double
represents a double-floating point value, which you can use For
BEEP sorts etnive cide seris- volume 34
incredibly accurate numbers but those numbers are only accurate
upto the fifteenth decimal place. There's also the problem when
clsplaying such numbers in C++ using the cout Function in that cout
by default only outputs the First five decimal places. You can combat
that by adding a cout precision () Function and adding a valve inside
the brackets, but even then you're stil limited by the accuracy of the
double data type. For example, try this code:
#include
using namespace std;
double PI = 3.141592653589793238463;
int mainQ)
{
¥
cout <«< PI;
Stathere %| Datatypescpp >
using namespace st
| doubie pr = 3-1sisszessseoros2se<63;
© Urea Document\Co\DatTypen
Build and run the code and as you can see the outputs only
3.14158, representing cout’ limitations inthis example
You can alter the code including the aforementioned cout:precision
Function, For greater accuracy. Take precision allthe way up to 22
decimal places, with the following code:
#include
using namespace std;
double PI = 3.141592653589793238463;
int mainQ)
{cout precision(22);
cout << PI;
3
Sarthee | DataTypescop
2 using namespace std:
3 double PY ~ 3.141592653589753230463/
4
6
® cout << PI?
n |
‘Again, build and run the code; as you can see from the command
ine window, the number represented by the variable Plis diferent,
to the number you've told C++ to use in the variable. The output
reads the value of Pas 3.141592653589793115998, with the
numbers going awry from the fifteenth decimal place
Calculator
= Scientific D
15.142857142857142857142857142857
DEG HYP FE
Me ms
2 sin cos tan
10* log Exp Mod
= cE c
ae
co
oN WO
recsion standard occ
oF data, of which 52-bits ae dedicated to the significant (the
ant digits in a floating-point number) and roughly 3.5-bits
are taken holding the values 0 to 9. I you divide 53 by 35, then you
‘attive at 15.142857 recurring, which is 15-digts oF precision
fe that needs to be accurate to
ou wouldn't be using Cr+,
ould use some scientific specific language with C++-as the
To be honest, if you're creating
more than fifteen decimal places, then y
nective tissue between the two languages,
You can create your own data types, using an allas-ke system called
typedef. For example:
include
using namespace std;
int main © #include
= using namespace std;
} int main ©
Xea|Qaforson as {
we [reel 2 Vid + bLO char greet{] = “Welcome”;
1 Oo cout << greet << “\n”;
i tenes coer, a
PEPPER is casyto confusea string with an array. Here'san RSPB in c++ there's also a string function, which works in
array, which can be terminated with anull character: ‘much the same way. Using the greeting code again,
#include Solfcanentert
using namespace std; #include
ae using namespace std;
int main ©
char greet(8] = {"W", ‘e’, ‘1, tc’, to", tm,
fe, N07}; string greet = “Welcome”;
cout << greet << “\n"; cout << greet << “\n";
3 3
BED 2s rece sets winesERED Tere are also many diferent operations that you
can apply wth the string Function. For instance, to
getthe length ofa string you can use
#include
using namespace std;
int main ©
{
string greet = “Welcome”;
cout << “The length of the string is: “;
cout << greet.size() << “\n";
You cansee thet we ved oe set output the
SUPE length, the number of characters there are, of the
contents the sting. Natural, fyoucllyourstng something
other than geet, then ou needt change the commando refi
ths I's alayssingname operator Bud andrunthe code tosee
Just. as you might expect, you can mix in an integer
{and store something to do with the string, n this
example, we created int length, which stores the result oF string
sizeQ and outputs itto the user:
#include
using namespace std;
int main ©
{
‘int Length;
string greet = “Hello”;
string greet2 = “, world!;
string greet3 =
Length = greet3.sizeQ;
cout << “The Length of the combined strings
is: “<< length << “\n";
greet + greet2;
BPD sins avataie operation that come withthe
Sra?) ‘string Function, you can manipulate the contents of a
string. For example, to remave characters From string you could use:
#include
using namespace std;
int main ©
1
string strg (“Here is a long sentence ina
string.”);
cout << strg << ‘\n’;
stra.
cout,
stra.
cout.
You can of course add strings together, or rather
combine them to Form longer strings:
#include }
using namespace std;
stra.
cout,
int main ©
inthe string,
right, so practice makes perfect. Take a look at the screenshot to see
the result of the code.
string greet = “Hello”;
string greet2 = “, world!”;
string greet3 = greet + greet2;
cout << greet3 << “\n";
erase (10,5);
<< strg << ‘\n"s
erase (strg.begin()+8);
<< strg << S\N;
erase (strg.begin()+9, strg.end()-9);
<< strg << ‘\n5
les worth spending some time playing around with
the numbers, which are the character positions
jonally, it can be hit and miss whether you get it
121
ora bdmpublications com