Expert
Precis
to improve
NTs Ay
4TH EDITION
100% INDEPENDENTDiscover more of our
Complete Manuals today...
{WhatsApp
Manual
The Cor te
Python
Aa
Wve Complete
Nikon
Lee Tt Manual
Manual( BDM's Definitive Guide Series
Maya uoia eter ees ame e ia 1)
development is to be clear about what you are
trying to build.” giame stroustrup (Developer and creator of C+)
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,
has some Form of code behind it, driving it and telling it how to
rT RU cok elon
Biel Meee Me cra el ee) |e cele LTA}
languages. Some offer better stability, speed and complex
algorithms. Others are designed for use with minimal system
resources, in places that are impossible for an engineer to
Elece cele ea Ese eee Ear 1PM ele
industry runs off clever coding. In short, code surrounds and
LAULUT Net) Neto laetel mele
What a brilliant time then, to learn how to code; to see how a
few simple lines of code can create something amazing and can
interact with you and your technology. Python and C++ are two
Oma aureia eee RoE ete aol EU RV 7iel)
the help of this book plus a little imagination, you will soon be
Ee leaped T cole
Now, turn the page and let's start learning how to code.
y F zBe eo ae
ery are
O.
6 SW Tau RUT k eer
STS as Chena uy
(74) Using Modules
92) Say Hello to C++
Cc aCe)
52) Working with Datai
i
Fa
9Working
wien Code
|
Wi
ie:It’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
NUR eee hae NR Mu Aue cme ey Tag
Cel nae Ue ies Mee Net lace n eget
even experts make the occasional mishap. Thing is, to learn from them as best you car
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. It’s not too dificult to name
variables tives, money, playert and soon.
Ie would be wonderful to be able to
‘work lke Neo from The Matrix movies.
Simply ask, your operator toads it into
your memory and you instantly know
everything about the subject. Sadly
though, we cant 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
points);
write("Lives: "s1ives);
write + "totaltimes" secs’
write( Y
‘totalscore
//[COMMENTS write("Your total Score is: “+totalscore);
Use comments t's simple concept but commenting on
jour code saves so many problems when you next come to
took overt Inserting comment nes helps you auch sift PLAN AHEAD
through the sections of code that are causing problems;
also useful fyou need to review an older piece of code
While it’s great to wake up one morning and decide to code
a classic text adventure, it's not always practical without a
‘good 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 bugs.USER ERROR
BACKUPS
SS ECR a an}
SECURE DATA@) Working with Code )
Python Beginner's Mistakes
Python isa relatively easy language to get started in where there's plenty of room for
Reel ee cuca Me eka ae ear)
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
‘mistakes will save you headaches in the Future.
VERSIONS INDENTS, TABS AND SPACES
Toadé to the confusion that most beginners already face when Python uses precise indentations when displaying its code. The
coming into programming, Python has two live versions oF its indents mean that the code in that sectionis apart ofthe previous
language available to download and use. ThereiisPython version _statement, and not something linked with another part ofthe code.
2.7.x and Python 3.6.x. The 3.6.x version isthe most recent, and Use four spaces to create an indent, not the Tab key.
the one we'd recommend starting. But, version 2.7xcode doesn't
always work with 3.6.x code and vice versa, =a
python
THE INTERNET COMMENTING
Every programmer has and does at sme point goon the Internet Again we mention commenting. l’s a hugely important factorin
{and copy some code to insertinta their own routines. There's programming, even if you're the only one wito sever going to view
‘nothing wrong with using others’ code, but you need to knowhow the cade, you need to add comments as to what's ging on. Is this
the code works and what it does before you go blindly runningiton function where you lose a life? Write a comment and help you, or
your own computer. anyone else, see what's going on,
Creatldelete a. fle na python program sss prea
EID ow eFintive Gude Series VolumesCOUNTING 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 user
n= ListCrange(1, 119)
(hich will return 1 to 10.
TB reeatie Sealand
CASE SENSITIVE
Python is a case sensitive programming language, so you will need
to check any variables you assign For example, Lives=10 is 2
different variable to lives=10, calling the wrong variable in your code
canhave unexpected results.
Britton
Fle_ft_Shell_Debug Options Window _Help
Python 3.6.2 (¥3.6.2:5¢a33b5, dul @ 2017, 04
fon wins?
Type "copyright",
53> Laves=10
>>> Lavesss
>>> print (Lives, lives)
3
Nozedite" or "License()" for mor
BRACKETS
Everyone forgets ta include that extra bracket they should have
added to the end ofthe statement. Python relies on the 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(self):
print (board[len(self.missed_letters)])
Print ‘Word: ' + self-hide word())
print (‘Letcers Missed: *,)
for letter in self.missed letter:
print (letcer,)
print ()
print ("Letters Guessed: *,)
for letter in self.guessed letters:
print (letcer,)
print ()
Ee
C Python Beginner's Mistakes
COLONS
It’s common for beginners to forget to add a colon tothe end of 8
structural statement, such as
lass Hangman:
def quess(self, letter):
‘And oon. The colonis what separates the code, and creates the
indents to which the Following code belongs to.
OPERATORS
Using the wrong operator is 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
23 single equal =) ian 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 eS. Whereas, for Linux you need to use
‘lear. You need to solve this by capturing the error and issuing it
with an alternative command,
4 code to detect exror for using a aitterent 05
‘e-ayotem(tcieas")
—————z= Working with Code_)
C++ Beginner's Mistakes
There are many pitfalls the C++ developer can encounter, especially as this is a more
CoM Ceu eur Tene anes men cechel cere rc)
Pen ee neh sates al Coal orate afer
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
aoa eojag
mel y
(Citestt.cpp x
#include
GCC OR G++
IF you're compiling in Linux then you will no 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 C++
version) of the compiler. f you're compiling C++ then you need to,
use g++, asthe incorrect compiler drivers willbe used.
. davidermint mate Documents
Fle Edt view Search Terminal 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
identifiers 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 ser.
‘Remember that quotes need to encase strings and anything that's
‘going tobe outputted to the screen or into a ile, 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++ tine,
there are some exceptions to the rule. Semicolons need to be at
the end of every complete statement but some lines of cade aren't
complete statements. Such as
#include
if lines
switch Lines
fit sounds confusing don’t worry, the compiler lets you know where
you went wrong,
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
difficult to include in an equation. When creating a variable, give it
the value of zero to begin with: X=.
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?
TWITTER
‘Twitter srtall trols 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 afew who you can
‘late to and follow them. Often they post great tips, hacks and fixes
fForcommon cading problems.
=
a
oe
KEEP CODING
\f you've mastered Python fairly wel then turn your attention to
Cet oreven GH. Sillkeep your Python skills 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.
01 tn ite Ses olan
OPEN PROJECTS
Look fr open source projects that you lke the sound of and offer
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 skills to 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 isa great place to test your coding skis 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. I's a good learning experience nevertheless, and something
worth considering
D coger =
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, sof you're sel
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
( Where Next? ‘C
PORTFOLIOS
IF you've learned how to code with an eye for a 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 a link to 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, perhaps a part-time or evening
‘course. not teaching, then consider creating your own YouTube
how to code channel
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
~anyssues 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
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,STA male)
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)
ae
01 tn ite Ses olanSay 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. t'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 bpublications comWhy Python?
DeSean sae uur cue eC Camu ureon tis
PI Ree eric nciemac cru m aides lca etal ences
Ere Kel sre eho TAN OM Com Cell CP Cece eRe mc M WN 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, sta
‘These pioneers of programming carved their way into anew
Frontier, Forging small routines that enabled the letter ‘to scroll
{across the screen It may not sound terribly exciting to 8 generation
that's used to ultra high-definition 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 alls programming.
over an overheating heap of circuitry to create somet
akin to magi
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
‘ane 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 wl 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
eee
00 tn ites vole 4
verdgrid * {js'e= colum.cetcount()
a) 0)
fe 6 Hao Rokr Bas Gy fat Se
Py cr o|sncnacess) O/B Hee #2 5@
sxtcureor(p-y)s
cerl:schitseatrocusiS
vod arraycert::chitdLostroct
‘leursor >= 0)
efresinoetcursor);
— cxrtehstatastfocue()}
om
Gremetvonce |) void _srraycert::Paine(Orawe ) (
rem ‘inintCsine 2
Shoe Ceeshsets
$oawmacas
Stance
oor
oa
see
ss uf « column cata) fre) €
Crocker rs eviaowidth( jel;
Stones Ua ter
$ Stace i
Stace” »
Gren Eater fc = eland(scoloroisabled, sclorPaper):
Sreane eal
Street TENELE cetcount())
wc ‘top SERtLiner) « ab
Seco Sites etsy) breeds
Sate re bottom =
Sop t optuanecy (a)Why Python?
{are easier to lear and use than others. Python sone such general-
purpose language.
Python is what's known as a High-Level Language in that it 'talks!
to the hardware and operating system using avarety of arrays,
variables, objects, arithmetic, subroutines, loops and countless
‘more interactions. Whilst it's not as streamlined asa Low-Level
Language, which can deal directly with memory addresses, cal
stacks and registers, ts benefitis that it's universally accessible
{and easy to lear.
Python was created over twenty sixyears ago and has evolved to
become an ideal beginners language for learning howto 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 external hardware and the
computer itself
Python i Free to download, install and use andi 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 word and fs continually evolving ahead
Of the hardware and internet development curve
‘oto answerthe question: why python? Simply
put, it's Free, easy to learn, exceptionally
powerful, universally accepted, effective
and a superb learning and educational tool.
[/7FiTe: invoke. java.
Fimport java. lang.reflect.*;
class rnvoke
DUbIHE static void main( string [) args ) {
try
Gass ¢ = Class. forname( args[o] );
Method m = c-getMethod( argsi1], new class
0) 5
object ret = _m.invoke( null, null);
systen.out.printinc
“Tnvoked. static method: " + args{4]
+ of clase: © + args[o)
with no args\neesules: * + ret;
} catch ( Classnocroundexception e ) {
77 Class. fornane(.). can't find the class
} Catch C Nosuchwiethodexception e2') {
Se |
pages stop boxes Tsun evens
Bais. oe
2
THEN LET py
Python is a more modern take on BASIG, it's easy to learn BASIC was once the starter language that early
3nd makes for an ideal beginner's programming language. B-bit home computer users learned.
ona bdmpublcatonsz= Say Hello to Python
Equipment You Will Need
ole TaN TMs enon (Lee CURT Ke LU 1k Aol ONIN 0 aT 1aCe Ma en ol)
don’t need an incredibly powerful computer and any software that’s required is
freely available.
WHAT WE'RE USING
Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linux, Raspberry Pi and more. If
you have one of those systems, then you can easily start using Python.
00 tn ies oun 4
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 Environment) is used to enter and
execute Python code. It enables you to inspect your program code and
the values within the code, as well as offering advanced Features. There
are many different IDEs availabe, so find the one that works For you
and gives the best results
PYTHON SOFTWARE
‘macOS and Linux already come with Python preinstalled as part of the
‘operating system, as does the Raspberry Pi, However, you need to
ensure that you're 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 Sublime Text or Notepad++, offers more
advanced features and colour cading 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 i 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
Flows ke water, Understand you're learning something entirely new, and
‘you wil get there.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.
Sa aaa)
The Raspberry Pi3 isthe latest version, incorporating a more
powerful CPU, more memory, Wii and Bluetooth suppor.
You can pick up aPi for around €32 or as apart of kit For £50+,
depending on the kit you're interested in.
The Raspberry P's main operating system isa Debian-based
Linux distribution that comes with everything you need in
simple to use package. t's streamlined forthe Piand s an
ideal platform for hardware and software projects, Python
programming and even asa desktop computer.
FUZE PROJECT
Cequpmentvouwilveed CR
The FUZE isa learning environment built on the latest model ofthe
Raspberry i. You can purchase the workstations that come with an
electronics kitand even a robot arm for you to build and program.
‘You can find more information on the FUZE at www.Fuze.co.uk
Coding for
Linux
We have several great
E Raspberry Pititles available
via wwwbdmpublications.
‘com, Our Pi books cover how
tobuy your First Raspberry
Pi, seit up and use it; there
are some great step-by-step
project examples
and guides to get
the most from the
Raspberry Ptoo,
Raspberry Pi
Bertani 2
A, heatopanttemngtaryhz= Say Hello to Python)
Getting to
Know Python
eMac ee eter tunlited eater kumar eiccteM a tar(ccd
SoCo AURAL Men oe mee Reon Lec lale(Uerel enlace]
to understand.
WHAT IS PROGRAMMING?
Ithelps to understand what a programming language is before you try to learn one, and Python is no different. Let's take a
look at how Python came about and how it relates to other languages.
‘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
by Guido van Rossum
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
at Centrum Wiskunde & inorder. A program that describes acake might run tke this
Informatica (CW inthe ae
Netherlands aa sucessorto bout = OL fe
the ABClanguose ES ees
patel BE mnmner
Guido van Rossum, the
Father of Python.
‘bo .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 bath inthis book. The main thing to know is
that it’s easy to read commands in Python. Once you learn what the commands do, i's easy to
Figure out how a program works,
00 tn ites one 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
like this:msg db ,@xa len equ $ = msg,
2
PYTHON 3 VS PYTHON 2
Peon u i ent ieee aT es
ee Lene!
WORLD OF PYTHON
erates
Cae!
at
eee
ete
perintothe Python ste
eretscen
PYTHON 2.
erie
nt
is
deed eee es
Se de eee
able resource.
(cetinstornowxion 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 sa collection of 20 software principles that
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.
ee eg Td
PYTHON 3.X UPauguenE eae Rae einige
Pen te et
Fe stable, effective and efficient p
eerste ces gs
Poco ripts, modules and tutorial
eet eee ee eng
thon programming
3.X WINS elueueeemain
Petre
Sue
ththe rants
eee eee ei hited
Python 3 For snippets of important 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.
Thankfully,
5 an easy process to follow.
FETSERD 2"tby opening your web browser to www.python.
‘0ra/downloads/. Look fr the button detailing
the download link for Python 3.x. The latest version atthe time of
\weting i 3.7.0 but as Python is frequently updated this may bea
different version for you.
Papeete! ee
Pe ee ee eee cata
ane
eo aa es
Click the Download button for version 3x, and
save the file to your Downloads folder. When the
fle is downloaded, double-click the executable and the Python
installation wizard wil launch, From here you have two choices
Install Now and Customise Installation, We recommend apting for
the Customise instalation link.
Gis
Install Python 3.7.0 (32-bit)
wind (Chae Pyne 372 PH
EZ) co's verre uid Series- volume 34
BRTERE RD Choosing the Customise option allows you to
specify certain parameters, and whilst you may
stay with the defaults, i's 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 ae ticked
and click the Next button,
Optional Features
seamen
ml
Be
amet
mene
yan ra a es tn)
pythi
wind
D
The nest page of optiosinclude some interesting
ue additions to Python. Ensure the Associate file with
Python, Create Shortcuts, Add Python to Environment Variables,
recompile Standard brary and talfrAllser option are
ticked. These make using Python ater much easier, ick nsalwhen
youre ready to contrue
‘Advanced Options
(acme fn fie py ae)
hacen oemcen rane
ml
i [eager RoE —
wind me Ora earHow to Set Up Python in Windows Cl
732i) ink wl
EED icking on the IDLE (Python
ication, Simply click launch the Python Shell, where you can begin
the installation is complete _ your Python programming journey. Don't worry if your version is
the Final Python wizard page will alow you to view the latest release aslong as it's Python 3.x our code works inside your
notes, and Fllow some online tutorial Python 3 interface,
Setup was successful m
a -
° .
pythén
*
windows oe
Before you cose the install wizard window, you now click on the Windows Start button again
SUS however, it's best to click on the link next to the SHEP) and this time type: CMD, you'll be presented with the
shield detaled Dale ath Length Limit. This wil allow Python Command Prompt nk, Cck eto get tothe Windows comnmand tne
to bypass the Windows 260 character limitation, enablingyou to environment. Toenter Python within the commandline, you ned
execute Python programs stored indeepfeldersarangements. _totype: python and press Enter
‘Again, click Yes to authenticate the process; then you can Close the
installation window. Wen
© Disable path lenath limit
Close
Saas =o EE The command tine version of Python works in
much the same way asthe Shell you opened in
Windows 10 users can now Step 8; note the three leftfacing arcows (>>>). whilst t's a perfect
find the installed Python exer) fine environment, i's not tao user-friendly, so leave the command
3.xwithin the Start button = line For now. Enter: exit to leave and close the Command
cently Added section
The First ink, Python 3.7
(32-bit will aunch the
‘command line version of
Python when clicked (more
‘on that in a moment), To
‘open the IDLE, type IDLESay 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
dovidedavid tine ~
Next enter python =-version into the Terminal
STEP 2 screen. You should have the output relating to
version 2x oF Python ithe splay By deta, mos nue dstios
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
SUPE) As long as Python 3.x.xis installed, then the code in
cur tutorials york es aways worth checking to see the cto
has been updated withthe latest versions, enter; sudo apt=get
update && sudo apt-get upgrade to update the system,
vidi ine —
‘80M Definitive Guide Series- Volume 24
‘Once the update and upgrade is complete, enter:
SUED ytnona version santo see if Pytion 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 latest, cating edge
SHaP5 version, you'll need to build Python from source.
Stare by entering these commancs into te Terminal
sudo opt-get install build-essential. checkinstalt
Sudo opt-get install Libreadline-aplv2-dev
Tibncursesw5-dev libssl-dev LibsqliteS-dev tk-dev
ibgdon-dev Libe6-dev Tibbz2-devHow to Set Up Python in Linux (¢
(Open up your Linux web browser and go to the EE For the GUIIDLE, you'll need to enter the Following
BED eon cowrioadpage:hetps//www.pythonora/ — Maal command nc the Terminal
thePythonSourcewnaowTisepensecowriosadlosce to, swdoant-get: instal led
choose location and tart the download process, ‘The DLE can then be started with the command: fde3.Note that
IDLE runs different version from the one you installed from source.
—— “dvoid in. -/oownlona/Pyhon 372
you've downloaded), To access the newly unzipped Folder, enter: cd“ ssssnnnsesnnses eassseneonestearess ssarsenene
Python-3.Y.¥/. FEET) Youllalso need Pip (Pip installs Packages), whichis
a tool to help you install more modules and extras.
Enter: sudo apt-get install python3-pip
IPs then installed, check For the 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 -Domiot Python 72
FEED Withinthe 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 3xx and Python 2.
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 will then be guided
tothe Python releases For Mac versions and the necessary
installers for macOS 64-bit, For 05 X 10. and later.
wonabdmpubicatonscom“| 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) 50s evecare ve 4Getting 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 Modulesz= Getting Started with Python ) :
Starting Python for Ay
the First Time a
The Raspberry Pi offers one of the best all-round solutions For learning and coding on,
Meneame ols enatieracn uci ekenecutticencel ce hit
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.
FETTER) With the Raspbian desktop loaded, click onthe BETERED or example, in the Shell enter: 242
"Menu button followed by Programming > Python 3 After pressing Enter, the next line wll 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 fram within the Windows Start button relevant output.
‘meni and via Finder.
=
PEPTPD) The shellis where you can enter cade andseethe — SSWB the python shall acts very much ike a calculator,
responses and output of code you've programmed since code i basically a series of mathematical
into Python. Thissakind of sandbox, where you're ableto 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.
ye Scare’ Screute™ or “Licaaat)* for sare snfomaton
ET 220iStarting Python for the First Time Cl
ESTER Wile thats very interesting i's not particularly
exciting, Instead, try this
print(*Hello everyone!”)
Just enter it nto the IDLE as you id in the previous steps.
case the Hello everyone! bit.
>>> print("Hello everyone
Hello everyone!
>>> |
licking on the Highlighting tab, However, we don't recommend that
_asyou won't be seeing the same as our screenshots.
pe caro uae aso 4
FETED ust lke most programs avaliable, regardless of the
‘operating system, there are numerous shortcut
keys avallable. We don’t have room for them all ere but within the
Options > Configure IDLE and under the Keys tab, you can see alist
(of the current bindings.
Fare 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
urple—Functions
‘Orenge-Commands
Blue — User Functions
Dark Red Comments
Light Red ~ Error Messages
IDLE Colour Coding
[-eoteur [use tor [examples
Daekred | Comments | ianeaber VAR
FETETR Te Pithon IDLE is a power interface, and one
that's actually been written in Python using ane
(of the available GU! toolkits. Fyou want to know the many ins and
‘outs forthe Shell, we recommend you take afew moments to view
‘www.docs.python.org/3/library/idte.html, which details many of
the IDLE’ FeaturesE) ceinstneawtnenn
Your First Code
Essentially, you've already written your First piece of code with the ‘print(“Hello
ONT Mit ae efor M aS KN UN et] ColtT1 a ON A ee Lear Le Lirel ole 1a
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.
ESTED you've closed Python 3 IDLE, reopen itin PEPER vou 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 (“Hello”)
a wma fr on
ESTeE RD vst as predicted, the word Hello appearsin the BITE You can continue as such, printing 242, 46442343
Shellas blue text, indicating output from a string {and soon ta the Shell. An easier way is to.use 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")
E220.7
(. Your First Cod
(Your First Code Cl
\hatyou have done here assign the tesa
Susp and b two values: 2 and 2. These are now variables,
which can be called upon by Python to output, add, subtract, divide
dando anor slong ther numbers stay these, Try ths
printCa)
print(b)
ei
‘The outputof the last step displays the current
Bia
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(arb)
‘This cade simply takes the values of a and b, adds them together
and outputs the result
oe ba Se) oeue es en
You cn ply around ith aferent kinds of variables
Suze and the Print function. For example, you could
assign variables for someone's name:
nane="David”
print(name)
PEPEED 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 ns en
TERED we were to apply the same routine as before,
Using the + symbol, the name wouldn't appear
Correctly in the output inthe Shell. Try it
print (name+surname)
You need a space between the two, defining them as two separate
values and not something you mathematically play around with,
print(name, surname)
In Python 3 you can separate the two variables,
with aspace using a comma:
‘Alternatively, you can add the space ourselves
printCname+” “+surnane)
‘The use ofthe comma is much neater, as you can see.
Congratulations, you've ust taken your First steps into the wide
‘world of Python
ora vmpublcatnscomz= Getting Started with Python)
Saving and Executing
Your Code
While working in the IDLE Shell is perfectly Fine For small code snippets, it’s not
designed for entering longer program listings. In this section you're going to be
introduced to the IDLE Editor, where you will
eel chee u mee
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.
First, open the Python IDLE Shell and when it’s up,
dlickon File > New Fie. This will open a new window
with Untitied as its name. Thisis the Python IDLE Editor and within it
you can enter the code needed to create your Future programs.
coamudsoon atria one toate
iterate aati tingencone ene
sca
print(*Hello everyone!”)
ET 200 re cate sees vole
BSTESEDD You can see that the same colour coding isin place
Inthe IDLE Editor asitisin the Shel, enabling you
tobetter understand what's going on with your code. However, to
‘execute the code you need to first save it. Press FS and you get a
‘ave...Check box open,PE
(_ Saving and Executing Your Code Cl
Enter 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 In this case, the words Hello everyone!
FETTER Thisishow the vast majority of your Python code
willbe conducted. Enter it into the Editor, hit FS,
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
Ifyou open the file Location ofthe saved Python
code, youcan see that it ends in 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 oy. Just ensure that the code is written
for Python 3
Lets extend the code and enter afew examples
MAD cm the previous tutor
0-2
be2
rnane="David”
surnane="Haynard”
print(nane, surname)
print Casb)
IF you press FS now youll be asked to save the file, again, as t's been
modified from before.
EATEEEDD vou click the Ok button, the Fle willbe
‘overwritten wit the new code entries, and
‘executed, withthe output in the Shell I’s not a problem with just
these Few tines butf you weretto edt a larger file, overwriting can
become an issue. Instead, use File > Save As from within the Editor
tocreate a backup,
ie EB Fame in ito Wn
Now create new fle. Close the Eto, and open
Suid anew instance (File > New File from the Shell).
Enter the following and save tas hello.py:
‘a="Python”
be"is”
c="cool!”
print(a, b, ¢)
‘You will use this code in the next tutorial
ie Se Fart in Entre ars bee
= we
webineatisconGetting 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 o EED Now you'e atthe command tine we can stat
‘executing code via the command line, One of the Python, For Python 3 you need to enter the
h Python 2, whilst the other uses the Python 3 libraries and python3 and press Enter. This wll put you into the
‘on. First though, drop into the command line or Terminal on ll, with the familar three right.
Your operating system,
mens EED sm here you're able to enter the code you've
: looked at previously, suchas:
Windows users will
. an2
printCa)
You can see that it works exactly the same.
rmacOS users can get access
9 their command line by licking
Go > Utities » Terminal
‘80M Definitive Guide Series- Volume 24Executing Code from the Command Line cl
Now enter: 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 file,
Sy
From within the same Folder asthe code you're
‘ing to run, enter the Following into the
python3 hello. py
This wll execute the code we created, which to remind yous:
‘as"Python”
i—
c="cool!”
print(a, b, ¢)
Naturally since this is Python 3 code, usin
ae
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 cade From the
Python 2 command lin is quite obvious, Whitt
esn't error out in any way, due to the differences between the
way Python 3 handles the Print command over Python 2, the result
Using Sublime For the moment, open the
isn'ta we expecte
hellopy file,
ED he 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:
Since Sublime Text isnt available For
name=input¢“What is your name? “)
print(*Hello,”, name)
Save the helio.py file and drop back tothe
commandline. Now execute the newly 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.C7} Getting Started with Python
Numbers and Expressions
Met eeu oe Sara ure or con Ave ru RTT Cette ns
MR ee ore Re aaa VEU CN es aoa ea ea en ETE es] at] lcm (oll)
UN aU n eat MPAA Coma eo en UB COUN Cm
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.
BETTE open upthe Gul version of Python3,asmentioned IM You can use all the usual mathematical operations:
‘you can use either the Shell or the Editor. For the divide, multiply, brackets and so on, Practise with a
time being, you're going to use the Shelljust to warm our maths ew, For example:
‘muscle, which we believe isa small gland located atthe backoFthe 4
brain (or not).
62
24283
Gs2)+"4)
FETED |" the Shell enter the Following: BRTEEE MD Youve no doubt noticed, division produces a
decimal number. In Python these are called fats,
= ‘or floating point arithmetic. However, you need an integer as
SSseesssz05 Shports decal ner tenn oe adoue sak
vr
You can see that Python can handle some quite large numbers.
ET 220. cine sees vole‘You can also use an operation to see the remainder
leftover From dhision, For example:
10/3
‘ill display 3,333333333, which is of course 3.3-ecurting. you
nowenter:
1083,
‘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
‘ut the power of something you can use a double mutiplcation
symbol or double-star onthe keyboard
203
3010
Essentially, i's 22x2 but we're sure you already know the basics
bind maths operators. This show you would workt ou in Python.
bing)
C Numbers and Expressions Cl
This wl be displayed as'0b11 converting the
piEtg integer into binary and adding the prefix Ob to the
Fron. Fyouwantt remove the Ob pref 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.
‘Boolean 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(1,
print(2,
print,
a == 6)
a== 7)
a == 6 and b == 7)
print(4, a == 7 and b == 7)
print(5, not a == 7 and b == 7)
print(6, a
print(?,
print (8,
print,
Execute the code from Step 9, and you can see a
series of True or False statements, depending on
the result of the two defining values: 6 and 7. t's an extension of
‘what you've looked at, and an important part of programming.
webineatisconC7} Getting Started with Python
Using Comments
Ue A OMAN IE cn URC come Ci inl
Oey acl e ate NNEC Aol mice Mle mn Tet Coico Mey
code line by line but over time, it can become difficult to read.
#COMMENTS!
Programmers use a method of keeping their code readable by commenting on certain sections. Ia variable is used, the
‘programmer comments on what it’s supposed to do, for example. I's just good practise.
Stary cetng anew stance ofthe LE EBRor
Su (File > New File) and create a simple variable and
pane conman
10
print(“The value of A is,”, a)
Save the file and execute the code,
BEER Penning 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 wichin code:
# Set the start value of A to 10
o=10
# Print the current value of A
print(“The value of A is,”, a)
22st
Resave the code and execute. You cansee that the
Burs) ‘output in the IDLE Shell is still the same as before,
despite the extra lines being added. Simply put, the hash symbol (#)
denotes atin of text the programmer can inset ifort,
and others oF what's going on tout te user beng aware,
ff yen 42 sal
(ie Et Se Gets ene ren
BRTEEE MD ets 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
na-1
printC*You've just lost a life!”)
printC*You now have”, a, “Lives left!”)¢ Using Comments Cl
Whilst we know thatthe variable is lves, and
thatthe player has just lost one, a casual viewer or
‘someone checking the code may not know. Imagine for a moment
that the code i twenty thousand ines long instead of just our
seven, You can see how handy comments are
Essentially, the new code together with comments
Bisa
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-1
# Inform player, and display current value of A
lives)
print(*You’ve just lost a life!”)
printC*You now have”, a, “Lives teft!”)
You can use comments in different ways, For
example, Black Comments are a large section of
text that details what's going on in the code, such as telling the code
reader what variables you're planning on using!
4 This is the best game ever, and has been
developed by a crack squad of Python experts
# who haven’t slept or washed in weeks. Despite
being very smelly, the code at Least
# works really well.
Inline comment re comments that follow section
Sus of code. Take our examples from above, instead oF
inserting the code on a separate line, we could use:
=10 # Set the start value of A to 10
printC*The value of A is,”, 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)
FATED the comment, the hash symbol, can also be used to
comment out sections of code you don't want to be
‘executed in your program. For instance if you wanted to remove
the Fist print statement, you would use:
# print(“The value of A is,”, a)
I
[eset the start value of A to 10
10
[e Peine the current value of A
# printc"The value of A is)", ai]
layer lost’ a life!
fF Inform player, and display current value of A (Lives)
Prant("You've just lost life!"
Print(-You non have". a, “lives left!*)
‘Youalso use three single quotesto comment
Suid ‘out a Block Comment or multiline section of
comments, lace them before and afer the aresyou want to
comment for them to work
This is the best gane 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.
———C7} Getting Started with Python
Working with Variables
AWARE Toney) LLYN 1) CoM Role Mm eon Reele|F-]kr-[eh aot ele S
romantic cna ener ees iecieta)
NU TON CUT oe
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.
Insome programing languages ore required
Su" to.use a dollar sign to denote a string, which is a
vavble made up of motile characters suchas a name of person,
InPythonths bt necessry. For example inthe Shel enter
name="David Hayward” (or use your own name, unless you're:
eocaled Dad Hayuad,
Bere 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, this would be:
‘type name). Adda new string variable: title="Descended
from Vikings”.
ED sows vetnine cide Series- volume 34
Youve 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 spice, as varibles are conected wut space,
soweneedto ad them manvaly,
1s ES) oy Sts om
EE You can also
combine variables
within another variable. For
‘example, to combine both name
and tile variables into anew
variable we use:
bao es Bis a
charactersnane +“: +
title
‘Then output the content of the
new variable as:
print character)
Numbers are stored as different
variables:
oge=44
Type Cage)
Wich are integers as we know.0
ESTEE 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 oF vice versa, When you do try to combine both, you get an
error message:
print Cname + age)
Bisa
‘Thisis a process known as TypeCasting, The Python
codes:
print (character +“ is “+ str(age) +“ years
old.")
oryou can use:
print (character,
s*, age, “years old.")
Notice again thatin the last example, you don’tneed the spaces
between the wordsin 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 +! ar" + str(age) #" years old
David Hayward: Descended fran Vikings is 44 years old.
doo prant (character, "is", age, "years old.")
David Hayward: Descended trom Vikings is 44" years old.
‘nother example of ypCasting when you askfor
Suze input From the user, such as a name. for example,
enter
‘age= input (“How old are you? *)
All data stored from the Input commands stored asa string variable.
fle Eat Shel Debug Options wndows ee
Tule, 0ce 9 3078, THAT
ae
=
Thispesets bit ofa problem whenyou want to
Sus work with a number that's been inputted by the
use. a5 ge + 10 wont work dve to beng 2sting arabe endan
integer stead, you reed enter:
intCage) + 10
‘This will TypeCast the age string into an integer that can be
‘worked with.
typettrer: can't cnwert "int" abject to str implicitly
el
‘The use of TypeCasting is also important when
Siar)
dealing with floating point arithmetic; remember:
numbers 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.
le Eat shed Debug Options windows Help
Python =
(eens.
Hype Sepprighe™ "eresite- or “License for mare information
33 petaniee)
clas “fiat
Z (aetaulk, Oct 18 2014, THRTTD
‘online
nah auctor
le E6t shel sua Optons windows ep
ythan 3-43 (Seta, Bet 1 BONE, THRTTID
(ee2.5°4) op tina
ihe", Neredsts” or “License()” for more information.
55> Sypetantee)
claet feat’?
————
(Working with Variables ClC7} Getting Started with Python
User Input
WATE TE Co) uid erie a ee Cen eR pea Reels ice ACR a eel oy
earlier, so now would be a good time to Focus solely on how you would get information
Pema cere ate ccnals
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.
BETSEDD is notalreads open the Python 31DLE Shell
and start a New File inthe Editor. Let's begin with
something really simple, enter:
printc*Hetto”)
firstnane=inputC*What is your first name? “)
print¢*Thanks.")
surnane=input(“And what is your surname? )
PEPPER save and execute the code, and as you already no
doubt suspected, in the IDLE Shel the program will
ask for your first name, storing itas the variable irstname, followed
by your surname; also store in its own variable (curname).
Fee yw sr nt
T2204
"Now that we have the user'sname stored in a
couple of variables we can call ther up whenever
Siar)
we want:
printC*Welcone”, firstname, surname, “. T hope
you're well today.”)
FID rece yen cance shu oe
ED so sect
Toe tanec en
print(‘Welcone”, firstnane, surnames. I hope
you're well. today.")(User input Cl
iG iP
You don'tatways have to include quoted text within
SAME out comand: For exarole, youcanaskthe
user their name, and have the input inthe line below:
print(*Hello. What’s your name?”)
‘nane=inputC)
useringutpy - Jhome/pi/Documents/Python Code/us
[Ele Edt Format fun Options windows Help
‘prant( Hello. Whats your nane?™)
Panes input
What youve created hres condon, which we
Sus will cover soon. In short, we're using the input From
theuser and measuring gansta condtion So, te user enters
Davids the name, the guard willow them to pass unhindered
Else, iF they enter aname other than David, the guard challenges,
them toa fight.
ESTEE The code from the previous steps 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 as you lke in these situations. Expanding an the code,
tay this
print(“Halt! Who goes there?")
‘names input
est Farmat Bin Stans wrsone 6p
PEPIIED |: 2 g00d start to atext adventure game, perhaps?
Now you can expand on it and use the raw input
from the user to flesh out the game ite:
‘if name=="David”:
print(*Welcome, good sir. You may pass.”)
else:
printC*I know you not. Prepare for battle!’
ESTEE ustes you learned previously, any input from a
Users automatically a string, o you need to apply 2
‘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: “))
rere year e rience
Focus feaecimpereate:
PETTSET DD 1 finalise the rate and distance code, we can ad
distance = floatCinput(“Distance: “))
+ Cdistance / 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,
print “Time:
webineatisconC7} Getting Started with Python
Creating Functions
Now that you've mastered the use of variables and user input, the next step is to tackle
CMten toa UA LMU EMM edo eee A Sn eco Te ol aa esTe.A)
enables you to define your own Functions.
FUNKY FUNCTIONS
A function
works on it and then returns the result,
‘2 command that you enter into Python to do something. Its a little piece of self-contained code that takes data,
Iesnotjst tathat a funtion works on. They can
Su" do all manner of useful things in Python, such as
sot data change tems fom oneormattosnather and check the
length or type of tems. Basically, a function is a short word that's
Followed by brackets, For example, len0, list) or typed).
FETED A function takes data, usually a variable, works on
it depending on what the Function is programmed
todo and,eturns the end value. The data being worked an goes
Inside the brackets, so ifyou wanted to know how many letters
are in the word antidisestablishmentarianism, then you'd enter:
‘Len¢“antidisestablishmentarianisn’) and the number 28,
would return,
NT 220i sees vole
‘You can pass variables through Functions in much
BALE the came manner Letsassume you wantthe
number of letters ina 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 builnt it, Fartoo
‘mary to getintoin the limited space available here.
However, to view thelist of bultin functions available to Python 3,
navigate to wowv.docs.python.org/3ibrary/Functions.html. These
are the predefined functions, butsince users have created many
‘more, they're nat the only ones availabe.creatngrincions CEE
Additional Functions can be added to Python
through modules, Python has a vast range of
‘modules availabe that can cover numerous programming duties,
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 tall the Math module functions
Tose function from a mackie enter the name of
Sua the module Followed by a full stop, then the name
‘of the Function. For instance, using the Math module, since youve
just imported it into Python, you can utilise the square root Function
Todoso, enter
math. sqreCi6)
‘You can see thatthe code is presented as module function(data.
FORGING FUNCTIONS
‘There are many different Functions you can import created by other Python programmers and you will undoubtedly come
‘across some excellent examples in the Future; you can also create your own with the def command.
erica
eee et
eet
erect
Dae,
food
ee etree cens
variable, the user's name for example. Edit
roe
Thi Hello
Oe eae
oer
eee en)
eet
eee eee
ie een teteee
eer egress
HelloC*David")
eee
STEP 4 usa eee gre ont
Pe nee crate
to.say hello to David. This is how modules and functions work: you
ete Cee ee te
eetestsC7} 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 is't.
Lets ceate new Python program that wilask Now youcan wean fstaterent to check the
Su" the user to input a word, then check it to see iF it's Buss) word_length variable is equal to four and print
afourletter word or not. Start with File> New File, and begin with Friendly conformation iit applies to the rule
ee ero wordsinputC“Please enter a four-letter word: “)
word=input(“Please enter a four-letter word: “) word_Length=len(word:
‘if word_length
print (word, “is a Four-Letter word. Well done.”)
‘The double equal sign (-
something ele
means checkif something is equal to
PEPIIPD ow we can create anew variable, then use thelen [EBB the colon at the end off tells Python that if this
Function and pass the word variable through it to statements true do everything after the colon
get the total number of letters the user has just entered: that's indented, Next, move the cursor backto the beginning of
—— = the Editor
wordsinput(“Please enter a four-letter word: “)
word_lengthelen(word) wordsinput(“Please enter a four-letter word: “)
word_Length=LenCword)
if word_length == 4:
print (word, “is a four-letter word. Well
7 done.)
else:
print (word, “is not @ four-letter word.”)
220i cites voleConatonsandioos CORE
PEED Press 5 and save the code to executeit. Enter FETED 01 expand the code to include another conditions
a fourletter word in the Shellto begin with, you Eventually it could become quite complex. We've
should have the returned message that it's the words our eters. added a condition For three etter words:
Now press 5 again and erunthe program butthstime ente'2— orastnput*Please enter a Four-Letter word: “)
Fiveletter word, The Shell wil depaythatsnot fouretter word, fora” Mou Tene,
if word tength == 4:
print (nord, “is a four-letter word. Well
done.)
elif word length
print (Word, “is a three-letter word. Try again.”)
else:
print (word, “is not a four-letter word.)
LOOPS
eer eran eae ae ee Ne a eed
block of code a number of times, usually with the support of a condition
STEP 1 eseeoe statement. Like I, ESSER The For loop is another example. Foris used to
Ese: Sete eres ors
Sear ables inside square brackets. For exa
= i prords=f*Cat™, “Doa®, “Unicorn?
ee
print GD) 3
print Cord}
tt Fama fi Gore Yrs th
Ve Me LI Eodrrrk,egy }phh
SIeae 9 aS edad SreE CRE hucie ur
preteen a
Q
poate ints the cu Ea le
cet ee ees TKO)
Be ees cs
eee eee eee eteGetting 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 2'cishgetthebitintnenswhinrton SED orn
oak mote sophisticated programs. Asyou ste aware, modules Python Tolstals module we ean use Pp sal Packages)
are thon sci tht are inperte, such 2s Inport ath Close down the LE shel and drop to a command prompt or
Terminal session, At an elevated admin command prompt, enter:
pip install pygame
ED Sore reticsccnt ontario, REI nherenesoneurean cloned
example on non Pi platforms isthe Pygame module, which contains click the result then click Run as Administrator. Linux and Mac users
many functions to help create games. Try: mport pygame. 31 use the Sudo command, with sudo pip install package.
‘80M Definitive Guide Series- Volume 24(Pronmeaies
(Python Modules
‘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 errorsin execution due to
Close the command prompt or Terminal and
relaunch the IDLE Shell when you now enter:
them being missing.
a
‘The madules contain the extra code needed to
achieve a certain result within your own code, as
we've previously experimented with. For example:
‘import random
Bisa
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))
a
This code, when saved and executed, will display ten
Suze random numbers from 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 random
for i in range¢es):
rintCrandom.randint(1, 100))
‘Multiple modules can be imported within your code.
To extend our example, use
import random
import math
for I in range(s):
printCrandom.randint(1, 25))
print (math. pi)
a
ESTEE the cesultisa 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))
a
‘This helps create a more streamlined approach to
STEP 10
programming. You can also use import module
‘which willimport 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.
ttre Ctenistoameient ney 7
webineatiscon“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
34
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
esRee ou ole ue coo Le Re Leese cho ANT] Reo = E-Ceceo Ty
eva a Se Keel enone d eu me Mm OU me D LE lce te)
Ere Riel OMIT RCT
WORKING WITH LISTS
Lists are extremely handy in Python. list can be strings, integers and also variables. You can even include Functions in lists,
TEP 1
‘sign, then square brackets and the items separated by commas;
ae
numbers = [1, 4, 7, 21, 98, 156]
mythical_creatures - [“Unicorn”, “Balrog”,
“Vampire”, “Dragon”, “Minotaur”)
Bes ge an meen
FETEEERD (nce you've defined your list you can calleach
by referencing ts name, followed by anumber. Lists
start the first item entry as 0, Followed by 1,2, 3 and soon,
For example:
unbers
To call up the entire contents ofthe lst.
unbers[3]
To cll the third From zero item in the lst (21 in this case),
GET 200.4
Fe vo nasoncon roses annem
‘or the second to last item with [-2] and so on, Trying to reference an
punbers[~1]
imythical_creatures[~4]
EERE icing is similar toindexing but you can retrieve
‘multiple ternsin alist by separating tem numbers
with a colon. For example:
punbers[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).Se cnc tnatinencatota gro
snr Ener
everything
Youcanview what canbe done wth sts by entering
piEtg dir(list) into the Shell. The output is the available
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
numbers. insert(4, 62)
Toremovet:
rnunbers .pop(4)
ESTED ers can be added toa lst by entering
nunbers=nunbers+[201]
Or for strings:
mythical_creatres=mythical_creatures+[“Gri ffin”]
(Or by using the append Function:
mythical_creatures.append(“Nessie”)
‘nunbers .append(278)
Removal a tems can be done in two ways. The first
Suze is by the item number:
del nunbers{7]
Alternatively, by item name:
mythical_creatures. renove(“Nessie”)
You also use the list function to break string down
Into its components. For example:
List¢“Davia")
Breaks the name David into Da, V,7,'¢’. This can then be passed
Ora
toanewlist
nanesList(“David Hayward”)
‘name
age=[44]
user = nane + age
user
Based on that, you can create a program to store
someone'sname and age as alist:
namesinputC“What”s your name?)
‘name=ListCname)
‘age=intCinput (“How old are you: “))
‘lage=Lage]
user = Iname + lage
‘The combined name and age lists called user, which canbe called
by entering user into the Shel. Experiment and see what you can do,
STEP 10
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
Pred ONE TCe
THE IMMUTABLE TUPLE
Reasons for having tuples vary deper
1g on what the program
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.
‘tuple created the same wayasa st but inthis
Su" instance you use curved brackets instead of square
brackets. For example
months=C"January”, “February”, “March”, “April”,
“May”, “June”)
months
‘You can create grouped tuples into lists that contain
SAD ici setsof dota Forinstonce,hereisa tuple
‘called NPC (Non-Playable Characters) containing the character name
{and their combat rating For an adventure game:
NPC=[C"Conan”, 100), (“Belit”, 80), (“Valeria”,
95)]
BSTe EDD st as with sts, the tems within a named tuple can
be indexed according to their position inthe data
range, ie.
rmonths[0]
months[5]
However, any attempt at deleting or adding to the tuple wil result
inan errorin the Shel.
ET 220i
BATE 2h ofthese data items canbe accessed asa
\whole by entering NPCinto the Shell or they canbe
indexed according to their position NPC[0 You can also index the
individual tuples within the NPC lst:
ecco} 1)
will display 100.Rsworhrtngttwhenfeerengrutie ETRE now snake tne ovo
Susp tuples within a list, the indexing is slightly different Sus corresponding variables:
‘romthenar.Youweuldexpect re 95 combetratingoftNe eames conbotratingy Pe
character Valeria to be NPCiA][S], but t's not. t's actually:
wectzien ‘You can now check the values by entering name and combat. rating,
FETT) Thismeans of course that the indexing Follows thus: ESUAINEMB Remember, as with sts, you can also index tuples
in — Using negative numbers which count backwards
ao : From the end of the data lis. For our example, using the tuple with
— = multiple data items, you would reference the Valeria character with
1 om Necrz]£-0)
1,0
\which as you canimagine, getsa tle confusing when you've got a
lotof tuple data to dea with.
Tuples though utlse a Feature called unpacking, EE ‘You can use the max and min functions to find the
BMD etre dat tems stored within tule are SALMA rest and lowest vues cf a tuple composed of
assigned variables First create the tuple with two tems (name and numbers. For example:
combat rating): humbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99)
aheneiesrniaeninal ‘The numbers can be integers and Fits. To output the highest and
lowest, se:
printCnaxCnunbers))
Payee See TT printGminCnunbers))
————Dictionaries
PMP ear Us AUN me Ceol a Leek M VA Mo EA e ne] AN
OTe eRe Ke RM Kees a eoke ack Nea tea le a oth eCe)
ITED Reo] Uno ol men Kaos 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.
FE cs csincntocencsskaonn ion REE sissies ucoonaheconas
Decannenaie seme TANE Nee pemmannseuenee ahem ese
Key:Value. For example: entered ina similar Fashion toa list, whch you're no doubt Familiar
phonebook={“Enma”: 1234, “Daniel”: 3456, “Hannah: Whby now.
6789}
ESTEE st as with most ists, tuples and so on, strings EATER The benefit of using a dictionary is that you
reed be enclosed in quotes (single or double), can enter the key to index the value. Using the
whist integers cn beet open. Remember thatthe valve can be phonebook example from the previous steps you can enter
eiterastingoraniegeryeunstneedtoeresseTereE nook sean”)
8 phonebook“Hannah”]
phonebook2={“David”: “@987 654 321”}
ET 201i sees vole 4‘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 nputs and
Sus variables: one for the person's name, the other
Torther phone number let's eepitampleto avid nat
Python code):
ame=inputC“Enter name: “)
hunber=intCinputC“Enter phone nunber: *))
BETTIE 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 crating»
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={}
STE! "Note we've kept the number as an integer instead
(of a string, even though the value can be both
~aninteger ora string, Now you need to add the user inputted
variables to the newly created blank dictionary. Using the same
process as in Step 5, you can enter:
phonebook{nane] = nunber
aan
Now whenyousave and execute the code, Peon
Suid will ask for a name and a number. it will then insert
those enresinta the phonebook dctonay, hich you canest by
enternginta 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.
wurbémpubicatonscom Gyz= Working with Data )
Splitting and
Joining Strings
MMT Ke Uae Re eM AM eam el AME Mee at MRR NTT Uae ol Lee
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.
STEERED The main tool in the string function arsenalis spit. [ESTESEMD Note thatthe text spit parthas the brackets,
With you're able to split aparta 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 a space: item entry is 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(",”)
‘text="Daniel Hannah Emma”
Noniutswnbestigivoatandsitine — ETRESF Yove previous eennonyoucnslasirg
Suse content accordingly: ue into individual letters as a list, using a name:
names=text.split(* “) ‘name=List(“David")
rane
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 circumstances, t could be handy for creating
aspeling game for example,
IT) 220i sees voleC Splitting and Joining Strings Cl
Fe conc sontinans on no
‘alphabet="”. join([“a”,"b”,"c”,"d”,"e"])
‘alphabet.
‘This will display ‘abcde’ the Shel.
Aswiththe split funtion, the separator doesit
piEtg have to be a space, it can also be a comma, a full
‘stop, a hyphen or whatever you like:
“Red”, “Green”, “Blue"]
-JoinCcolours)
ETE You can therefore apply jinto the separated name
youmadein Step 4, combining the letters again to
form thename:
‘nane="".joinCnane)
‘We've joined the string back together, and retained the list called
‘name, passing it through the Join Function.
FR cc cortctcny oe nici en
—
list=[“Conan”, “raised”,
“and”, “struck”, “the”,
texts" “.join(list)
a
“his”, “mighty”, “sword”,
‘demon™]
"Note the space between the quotes before the join Function (where
there were no quotes in Step 6's join)
ERTESERD there's some interesting Functions you apply toa
string, suchas. capitalize and title. For example:
‘titLe="conan the cimmerian”
title.copitalize()
title. titled
‘oucan ao ute osc operators onstrngs,
Suid ‘with the ‘in’ and ‘not in’ functions. These enable
you to check if a string contains (or does not contain) a sequence
of harcters
message="Have a nice day”
“nice” in message
oad not in nessage
“day” not in message
“night” in message
az= Working with Data
Formatting Strings
When you work with data, creating lists, dictionaries and objects you may often want
Pormset treet ee ranch cei nectar ened
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.
Trebascfomstiginrtonitocaeach RETR) oucanocuae ao ince rte hemi
Su" variable into the string using the curly brackets: Buss)
nunber=10000
‘name="Conan” print(“{} of {} was a skilled mercenary,
printC*The barbarian hero of the Hyborian Age is: and thief too. He once stole {} gold from a
£0”. formatCnane)) merchant..”.format(nane, place, nunber))
ESTEE Remember to close the print function with two sets EESSWAM 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 you here; others canbe significantly more complex. Ital 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
‘name=""Conan”
place="Cinmeria”
printC*{} hailed from the North, in a cold land
known as {}".format(name, place))
TD coves oetnie uid Series- Volume 24e
Formatting Strings Cl
\
Interestingly you can reference alist sng the sting
Sua Formatting Function. You need to place an asterisk in
front ofthe list name:
nunbers=1, 3, 45, 567546, 3425346345
printC“Some numbers: {}, (, {t, fh, 0”.
format (*nunbers))
BEPPD wien indexing in tists, the same apples to calng a
lst using tring Formatting. You can index each tem
according to its poston (rom 0 to however many are present
runbers=1, 4, 7, 9
print(‘More nunbers: {3}, {0}, (2,
{1}.”. format *nunbers))
‘dt you probably suspect, you can mixstngs
Suze and integers in a single list to be called in the
Format function
characters=[“Conan”, “Belit”, “Valeria”, 19, 27,
20)
print C“{0} is {3} years old. Whereas {1} is {4}
years old.”. format(*characters))
Youcanals printout the content of user nput
Sus in the same Fashion:
hame=inputC“What"s your nane? “)
printC‘Hello {}.”.format (name)
STE! You can extend this simple code example to display
the firstletter in a person's entered name:
ame=inputC“What”s your name? “)
printC*Hello {}.”.format(name))
Iname=List(name)
printCThe first Letter of your nane is a {0}".
format¢*Lname))
FP onset nnasarr tac ncomc
hames=[“Conan”, “Belit”, “Valeria”]
ages=[25, 21, 22]
Creating two ists. Now you can cll each ist, and individual tems:
printC*{0[0}} is {1(0]} years old. Whereas {0[1]}
is {1[1]} years old.”.format(nanes, ages))
webineatisconDate and Time
PMO RR en eCoie numer reco a cB
Eo eure racers inna erscuiur
Iofm WACOM Rte melee ane R en Relea MaRS nea con ea MIT mere Com
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.
Feayouneedtoingatie rine modi kone TRAE Youcensee estucweothow ne speed
su" that’s built-in to Python 3 so you shouldn't need to Buss) byentering:
drepinto commons promot andpip sta Once SIMON, ene: tocat etme)
you can callthe current time and date wth a simple commane:
mens ‘The outputis dsplayedas such: "time, struct _timeCtm.
‘time. asctime() year=2017, tmmon=9, tmmday=7, tm_hour=9,
: ‘tmunine6, tmsec=13, tmnday=3, tmyday=250, tm
‘isdst=0)'; obviously dependent on your cutrenttime as opposed
to the time this book was writen
ESTEE Thetime function sspit into nine tuples, these are EEE 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're able to present a wide range of arguments
‘as it converts the time tuple into a string. For example, to display the
‘current day of the week you can use:
= a tine strftime( x4’)
© aor yar aoe
: ei = is Stra! Meco “mn fo re neti
5 second 0 to 6 (60 61 ae hap Seconds)
6 bay ot week 006 (0% Mendy)
7 Dayo ear 1 t 366 (tan dy)
© Dayton saungs 1,0, 1,1 means rary determines OST
I 220i7
(. Date and Ti
(Date and Time Cl
‘This naturally means you can incorporate various
SME Fncionsintoyour on code suchas
time. strFtimeC*%a")
time. strFtimeC“%B")
time. strFtimeC“%b")
time. strFtimeC“%H")
time. strFtimeC“HAN")
‘You saw at the end of the previous section, inthe
BALD coco clelct 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
stort_time=time.timeC)
‘Then there's:
endtime=time. timeC)-stort_time
ea
FETED (Note the last two entries, with 6H and HM, 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 with:
time. strFtimeC“xH:90")
FEED tres sve guste sts ay
‘import: time
nanesinputC“Enter Login name: “)
printC*Melcone”, name, “\d”)
print¢“User:”, name, “logged in at”, time.
strftime“#H:36"))
‘Try to extendit Further to include day, month, year and so on
ERTERER 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 iis quite complex too, such as
displaying the number of seconds since January 1st 1970. you
‘want to drill down Further into the Time module, then in the Shell
center:help(time) to cisplay the current Python version help file
forthe Time module.
aIn Python you can read text and binary files in your programs. You can also write to file,
een en lel enscaect Cen Matar l eller acca vetlc)
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 ryounow enter poem into the Shell, you will get
editor. The text editors best, not a word processor, some information regarding the text file you've just
{85 word processors include background formatting and other ‘asked to be opened. You can now use the poem variable to read the
elements. In our example, we have the poem The Cimmerisn, by contents of the file:
Robert E Howard. You need to save the file as poem.txt,
poem. read¢)
Note than a mn entry inthe text represents a new tine, as you
used previously.
BETES You use the opend functionto passtherleintoa EAM iF you enter poem read 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, but you 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”) againto 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.
I 220i sees vole 4Aantewihiesci dconisanton— EERERF) tennis hte yu cnet
STE ‘you're able to index individual characters of the Sus grab all the lines of the text and store them as
tert For example mull sts These con then be stredas avarble
oem. read(s) poen=openchone/pi/Docunents/Poem. txt”)
Displays thes five characters, whist again entering eR
poem. read(5) lines[1)
lines(2]
‘will display the next Five. Entering (1) will display one character at
atime.
ESTED Sirilary, youcan display onetine of textatatime by Ea You can also use the For statement toread the lines
Using the readline() Function. For example: of text backto us:
oem=open("/home/pi/Docunents/Poem.txt") for Lines in Lines:
poem. readline() print(Lines)
Will display the first line ofthe text with ‘Since this is Python, there are other ways to produce the same output:
poen.readlineC) oemsopen(“/home/pi/Documents/Poem. txt”)
for Lines in poem:
Displaying the next line of text once more. ——
| Peaster em
veumostneguedtiatyvcnpesiie — EEREREE etsnsonettyounartn rstat one
Suse readline() Function into a variable, thus allowing you STEALO character at a time, like an old dot matrix printer
to call tagain when needed: ‘would, You can use the Time module med with what you've looked
poemsopenC“/hone/pi/Docunent's/Poem. txt") fasmmeaal
‘Vine=poen.readlineQ) import tine
line oem=open(/home/pi/Document's/Poem. txt")
‘Tines=poemn.read()
for Lines in lines:
printClines, end=”")
‘time.sleepC.15),
‘The outputis un to view, and easly incorporated into your own code.
aMeron rn ie nna aM cecal M Maree OPCS
eee Mec AOC mitr rks tet eter iets)
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.
\lude an access mode which
ESTEERDD %2"tby opening IDLE and enter the Following TERED tHowever, the actual text file still blank (you can
check by opening it up). This is because youve
SARL ‘writen the line of text to the file object but not committeditto the
can file itself, Part ofthe write() Function i that you need to commit the
CChange the destination from /home/pi/Documents to your own changes to the ile; you can do this by entering:
system Thiscode wil crete text file clledtext2xtinwite mode. ergcecy
Using the variable‘ f there's no file ofthat namein the location, it *
will create one. Fone already exits, it wll overwrite it, so be careful
Sige Poel apc Yom. nee ron
FETED You can now wrtetothetext fle using the write) — EES ifyou now open the text file witha text editor,
Function. This works opposite to read, writing lines you can see that the line you created has been
Instead of reading them. Try this: ‘written tothe file. This gives us the foundation for some interesting
possiblities: perhaps the creation of your own log file or even the
beginning of an adventure game.
‘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.
——- -
ryten3.425re|
IT 220i cite sees vole 4‘To expand this code, you can reopen the file using HEED Youcan pass variables toa file that you've created
Susp ‘a’, For access or append mode. This will add any text Sus jin Python, Perhaps you want the value of Pito be
atthe end ofthe original line instead of wiping the file and creating written to file. You can call Pi from the Math module, create anew
‘anew one, 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 some meat, and a cup of
water.\n”)
FETTER You can keep extending the text ine by line, STE! Now let's create a variable called piand assign tthe
tending each with anew line \n). When you're value of Pi
done, finish the code with t.close() and open the file in atext ==
editor to see the results: pismath.pi
tawritec“The door is made of solid oak with iron’ YoUs#s need to create anew filein which towne Pt:
strips. It’s bolted from the outside, Locking you t=open(““/home/pi/Documents/pi.txt”,"w")
in. You are a prisoner!.\n")
ticloseO Remember to change your file location to your awn particular
system setup,
Tieewerainnonrtfie xaastocnice: TREE Toren yu conse svgtematingta che
Suze using the open() Function. Each depends on how the Susy variable and write it to the file, then commit the
fleisacessed and eventhe postion ofthe cursor ror example, r+ changes and cose te le:
coeafieinveandwrteadpnestheceera testo waeacnatue of PLA8! (7 fOrHtCODD
erie. ‘t.close()
You can see from the results that you're able to pass any variable to
afile,
wurmbémpubicatonscom GyMeare em Tot Ure Reo rare re Lea Reo cree
erties et mh eterna aia ce Rms
Milter cr ururnlc arenas
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.
FETE You can create an exception error by simplytrying EIB youcanuse the functions raise exception to create
to divide a number by zero. Tis 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 partis 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”)
arora non doyecmelenanecereiaesnon venice
ee erence oti esos c
Seton
eee
senate oe
cant atone
see
ne meetin hm 6 8 A
00 tn ites one 4(_ Exceptions Cl
For example, use the divide by zea err. Youcan
Susp create an exception where the code can handle the
error without Python quitting due to the problem:
try:
‘a=intCinputC“Enter the first nunber
beintCinputC*Enter the second nunber:
print (a/b)
except ZeroDivisionérror:
printC*You have tried to divide by zero!”)
else:
printC*You didn’t divide by zero, Well done!")
?
>)
‘Naturally, you can quickly fix the issue by changing
Sus the “r” read only instance with a “w* for write. This,
asyouabeady now, wl ceste the fle andunte the content then
Committe changes to thee, The end est wil eport ferent
setof crcumstances, nts cit, a sucessful execton othe code
FETTER You can use exceptions to handle a variety of useful
tasks. Using an example from our previous tutorials,
let’s assume you want to openafile and write to it
try:
‘txt = opent“/home/pi/Documents/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)
TEER AD Obviously 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 |OErrar class
informing the user that the permissions are incorrect
You can also use a finaly: block, which works ina
similar Fashion but you cant use else with it. To use
‘our example rom Step 6:
tr
‘txt = open(“/home/pi/Documents/textfile.txt”, “r”)
te
txtawriteC“This is @ test. Normal service will
shortly resume!)
finally:
print (“Content written to file successfully.
Have @ nice day.”)
‘txt.closeQ,
except I0Error:
print “Error: unable to write the file. Check
permissions”)
=—=—==——.
PEPTET DD 2 before anecror will occur as you've used the
read-only permission. Fyou change Itto a "w",
then the cade will execute without the errar being displayed inthe
IDLE Shell. Neeclessto say, it can be a tricky getting the exception
code right the First time, Practise though, and you will get the hang
oft.
smn eoscamMCR M Neen eer eel ue Rm ey cel cnet eae
will come a time when a bit of graphical representation wouldn't go amiss. Python 3
Pee Meee menace tena cattle
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
a Python graphics is Turtle, The Turtle module is, as
tre amesusgsts asd onthe ture bot wsed nay seo,
Gatean be rograrined to dow sorting ona age
oF paeronthe oor The Tutlemedl canbe mpd
Sport ture.
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 pressF5 to save the code and execute it. A new window will,
‘now open up and the Turtle’ will raw a circle
FED 200s vetnine uid Series- volume 34
The command turtle cee) hat ras the
Buss) circle on the screen, with 50 being the size. You
can play acound with theses you te, golng upto 10, 150 and
beyond: you can draw an arc by entering: tuntLeseincLeCsey
180), where the sizes 50, but you'e telling Python to only draw
180" ofthe cle.
BRED the last part of the circle code tells Python to keep
the window where the drawing istaking place to
remain open, sothe user can cckto closet. Now let's make a square:
import turtle
print (“Drawing @ 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
PTSD) You can add anew line to the 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_fl1© tofillin the square withthe chosen colours;
ed outline, yellow filin this case,
from turtle import *
color(‘red’, ‘yellow’)
begin fL1C)
while True:
Forward(200)
leFtC170)
if abs(pos()) < 1:
break
end_Al1O
done
Isa different method,
butvery effective
FETED 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 loka displaying a predefined image. Start by
‘opening a browser and Finding an image, then save itt the Folder
Where you save your Python code.
oc
si Ss
Now let’ get the code by importing the Pygame 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(Cwhite))
screen. blitCing, (0,0)
pygane.display.fiipO
while True:
for event in pygane.event.get():
if event.type = pygane.QUIT:
ygane.quit()
Inthe 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.
Sar)
w = 900
h = 450
screen = pygame display.set_mode((w, h))
screen. fill((white))
screen. fill((white))
screen.blit(img,(0,0))
pygame. display. #lip()
while True:
for event in pygame.event.get():
if event. type == pygame. QUIT:
pygane.quit()
PPT Press FS to save and execute the code and your
image willbe displayedin 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.
RaspberryPiIndex )
“First, solve the problem.
Then, write the code.”
— John Johnson (Developer and author)
FA) coves Detnkive Guide Series: Volume 24Using Modules
‘Python modules 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
wonabdmpubcatonscom — (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 as a Windows administrator, or sudo pip install calendar for Linux and macOs.
Itisloaded into memory stat by entering
‘sep=calendar. TextCalendar(calendar.. SUNDAY)
call up the module and its inherent Functions, Once
ssep.prmonth(2019, 9)
fle Eat Sheh_pebug aptons widow Help
aT 25538)
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 or example (1973, 6).The first-line
configures TextCalendar to starts weeks an a Sunday, you can opt
for Monday if you prefer.
ie tat Sh tn soto done
eee TEL oa OT
DFE) 201. ote cite sees olan
Launch Python 3 and enter: import calendar to
‘There are numerous functions within the Calendar
Buss) ‘module that may be of interest to you when
Forming your own code, For example, you can display the number of
leap years between two specific years
Leops-calendar. Leapdays(1900, 2019)
printCleaps)
The results 29, starting from 1904 onward.
le Edt Shel Rebus Options Yndow He
Python 3-5-3 (defo, Sep 27 208, 17525538)
ype “copyright, ereaite" or “License()* for sore information
Se aiaet cllndar
325 1SipescSlendar-Leapdeys(2900, 2019)
255 Rite)
You could even fashion that particular example into
apiece of working, user interactive Python code:
import calendar
print(“s>>>>>>>>>Leap Year
Calculator<>>Backup completecccececeee”)
°° /nome/pi/Documents*
“/nome/pi/backup/? + time.asctimeC)
\ OS Module CH@) 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
“ust as ith other modules ounces toimport
Su" random before you can use any of the functions
we're going to look at n this tutorial. Let's begin by simply printing @
random number from 1to 5:
‘import random
printCrandomint(0,5))
Inour example
Suse the number Four ie Bi Shek cea ere dow
was retuned However enter
ther function afew more
tines rdw pay erent
integer values fromthe sear
numbers given, eo fe The
overal effect athough pseudo
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) 201 ote cite sees one
However. the Random module aitused exclusely
Bu for numbers. You can use it to select an entry From a
lst From random, and thelist can contain anything:
import random
random. choi ce¢ Conan’ “Belit”))
This will display one of the names of our adventurers at random,
which isa great addition toa text adventure game.
, “Valeria”
You can extend the previous example somewhat by
having random. choice select from a list of mixed
variables. For instance:
import random
Lst=[“David”, 44, “BOM Publications”, 3245.23,
“pi”, True, 3.14, “Python”]
nd=random. choiceCIst)
print(rnd)Interesting, you can ao wea funtion whine
Suz Random module to shuffle the items in the list, thus
adding te more randomness into the equation:
random. shuffleClst)
print(ist)
‘This way, you can keep shuffling the list before displaying a random
item from it
PER Using shure, you can create an entirely random list
cof numbers, For example, within a given range:
‘import randon
Lst=[[i] for I in range(20))
random. shuffle(Lst)
print(lst)
Keep shuffling the list and you can havea different selection of
items from 0to 20 every time.
PEPTID) You can also select.a random number framagiven
range in steps, using the start, stop step loop:
‘import random
for i in rangeC10):
printCrandom.randrange(®, 200, 7))
Results will vary but you get the general idea as to how it works
(Random Module CH
Levsuse an example pec of code whch ipsa
Sus) virtual coin ten thousand times and counts how
many times iwil land on heads o 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>>5s>>>Random Word Findercccceceece")
printC*\nUsing a 466K English word text file I con
ick any words at random.\n”)
wds=intCinputC*\nHow many words shall I choose?
»
with openC“/home/pi/Downloads/words.txt”, “rt™) as
‘words = F.readlinesC)
words = [w.rstrip() for w in words]
printc* =)
for w in random.sample(words, wds):
printw)
printc*
wventinosictoncn GIz= Using Modules)
Tkinter Module
GETTING GUI
=
Tkinter i usualy built into Python 3, However, iFit's
available when you enter: import tkinter, then
youneedtopip install tkinter fromthe command prompt,
‘We can start to import modules differently than before, to save on
typing and by importing all their contents:
‘import tkinter as tk
from tkinter import *
PEPER is not cecommended to import everything From a
‘module using the asterisk but it won't do any harm
‘normally Let's begin by creating a basic GUI window, enter:
windsTkO
This createsa small, basic window. There's nat much else ta doat
this point but click the Xin the corner to close the window.
WED) 201 ore cite seis olan
er is easy to use but there's a lot more you can do with it. Let's start by seeing how it works and getting some code into it.
Before long you will discover just how powerful this module reall
FSTEEE DD The ideal approach i to add mainioop() nto the
code to control the Tkinter event oop, but well,
‘get to that soon, You've just created a Tkiter widget and there are
several more we can play around with:
ben=Button()
ben. pack()
ben{“text”]="Hello everyone!”
‘The first line Focuses on the newly created window. Click back nto
the Shell and continue the other lines.
‘You can combine the above into a New File
‘import tkinter as tk
from tkinter import *
btn=Button()
ben.pack()
ben['*text”]="Hello everyone!”
‘Then add some button interactions:
def clickO:
print(*You just clicked me!”)
ben{“conmand™}=click(Tkinter Module cl
EPTSIDD Seve and execute the code from Step S anda
window appears with ‘Hello everyone! inside. IF you
click the Hello everyone! button, the Shell will output the text You
justclicked met. I's simple but shows you what can be achieved
with 2 few lines of code.
FEPID) You can also display both text and images within
a Tkinter window. However, nly GIF, PGM or PPM
Formats are supported. So find an image and convertit before using
the code. Here's an example using the BDM Publishing logo:
from tkinter import *
root = Tk
‘logo = Photolnage(file="/hone/pi/Dowloads/BOM_Logo..
aif")
WL = Label(root, root. titleC“BOM Publications”),
‘image=1ogo).pack(side="right”)
content = “”” From its hunble beginnings in 2004,
‘the BOM brand quickly grew from a single publication
produced by a team of just tno to one of the biggest
‘names in global bookazine publishing, for two simple
reasons. Our passion and conmitnent to deliver the
very best product each and every volume. While
‘the company has groan with a portfolio of over 250
publications delivered by our international staff,
‘the foundation that it has been built upon renains
‘the sane, which is why we believe BOM isn’t just
tthe first ‘choice it’s the only choice for the snart
consumer.”
W2 = Label(root,,
justi fysLEFT,
padx = 10,
‘textacontent).pack(siden" Left”)
root .nainloop©
The previous code is
uite weighty, mostly
due tothe content
variable holding apart
(oF BOM's About page
From the company
website. You can
obviously change the
content, the root title
and the image to suit
your needs.
ETP You con create radio buttons too. Tr
from tkinter import *
root = TkO
v = IntvarQ)
Label (root, root.titleC“Options”), tex
a preferred language:”*”,
justify = LEFT, padx
RadiobuttonCroot,
text="Python”,
padx = 20,
varioble=v,
value=1).packCanchor=WW)
RadiobuttonCroot,
texte",
padx = 20,
variable=v,
value=2).packCanchor=")
rmaintoop()
from tkinter import *
root = Tk)
def var_states()
printC‘Warrior: %d,\nMage: Xd” % (varl.get(,
var2.getQ))
Label root, root.titleC“Adventure Gane”),
texte”>>>>s>>59>Your adventure rolecceceece=800 or pos(0) while True:
xa = -xa # Lock the franerate at 50 FPS
gui -updateC)
time.sleep(.025)
balla
Remove the code you entered in Step 2 and insert
the code From Step 5 ints place; again, between the
canvas .create_oval(5,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 se the red ball
bbounce off the edges of the window until you close the program.
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 —_nane__ == “_nain
BSA The bouncing animation moh —
takes place within the : det main
While True loop. First, we have the values
(of xa and xy before the op, 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
FED icc honsiarncroeue rene
‘New File and entering
import pygame
from random import randrange
MAX_STARS = 250
‘STAR_SPEED = 2
def init_stars(screen):
“" Create the starfield “™"
global stars
stars =
for i in range(MAX_STARS)
# A star is represented as a List with this
format: [X,Y] ie
star = [randrangeC0, screen.get_width() - 1),
randrangeC®, screen.get_height© - 13]
stars.append(star)
def move_and_draw_stars(screen):
“Move and draw the stars 4”
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))
Imagine this as 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.
pyoame:dnse()
Pyoame.dsbplay.Set-eaption( "5
EXeek = pyoane-tine-ciock()
do (640, 20)
Sete Staadatsonr)
snit_stars(sereen)
‘hock: eiek(S0) °
= handie events
sy event. get)
yoane:
screen. £511((0,9,9))
re ect Neer)
Pras. sisplay- #00),
Save and Run the code. You will agree that the
simulated starfield code looks quite impressive.Zz 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
impor command
Lette by creating aset of bask matheratis
Su" 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 timestnoCx):
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 cade, enter Functions to call the
code:
NBD) 201. te cite sees ele
FETS RD 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,
I 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 etunto
thenewly
‘created window containing
the Function definitions, and
lick File > 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 openCreate Your Own Modules cl
PEPTID) (b2ck to the basic_math.py window: at the top ofthe
code enter:
fron minimath import *
‘This ill mport the Function definitions as a module, Press F5 to
save and execute the program to see tin 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
creating 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):”)
unl =
Now we can add the user input to get the number
the code will work on:
intCinput(“\nEnter number: “))
This willsave the user-entered number asthe variable numt
Ble Edit Format Bun Options Windows Help
Tron minimath Inport *
print("Select operation.\n")
int("1-Tines by to"
| Freezes by The
irint("3.Square")
print(~4:Poner of”)
choice = input("\nEnter choice (1/2/3/4:
punt = int(input("\nenter number:
»
l
finaly youcan now create a range off statements
Sra) to determine what to do with the number and
utilise the newly created function definitions:
if choice = ‘1’:
printCtimestwoCnumt))
elif choice = °2
printCtimesthreeCnuni))
elif choice == ‘3’:
print(squareCnum))
elif choice = <4":
und = intCinput(“Enter second nunber
print(poner(numl, nun2))
else:
printC*Invalid input”)
‘he Est Frat Ban crore sone tp
SDD,
Peanet-tinwar eb)
Note hat forthe ast vlable options the Power
Buss of choice, we've added a second variable, num2.
This pases asecond number trough the function definition cle
power. Sve and execute the program o seein action,“The most
important
property of
a program
is whether it
accomplishes
the intention
of its user.”
syietcoc CEE
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
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 C+?
96 Equipment You Will Need
98 Howto Set Up C++ in Windows
100 How to Set Up C++ on a Mac
102 How to Set Up C++ in Linux
Other C++ IDEs to Install
igSay Helloto C++ )
ee Tuas Ce cc caterer ACH Y
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 ~onemeraterduntattrton
Dating backto 1979, the start ofthe golden era of home ‘computing labs and by regular people who didn't have access tothe
computing, C++, oF rather C with Classes, was the brainchild of mainframes and large computing data centres.
Danish computer scientist Bjame Stroustrup while working on his
PhO thesis. Stroustrup's plan was to further the original language, _C+1simpactin the digital world 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 Adabe'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 is written in C++, as
‘more importantly, it was 99% compatible with the original C ‘well as Windaws 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
BET 200 cate sees voleFree environment to learn C++ in.
S
‘other languages mixed in depending on the Function) and the likes
(of NASA, SpaceX and even CERN use C++For various applications,
‘programs, controls and umpteen other computing task.
C++ isalso extremely efficent and performs
well across the board as wells 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 modern computing,
hence the aforementioned companies
Using itso widely
While Python isa great programming
language to learn, C++ puts the developer
Ina much wider world of coding. By
‘mastering Ces, you can find yourself
(why c+4? Cl
\
summary
TT na pang ~ Delo development wt
Microsoft's Visual Studio is a great,
bbegin with Python and spend some time getting to grip with
‘programming structure and the many ways and means in which
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 ted 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.
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
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 toits versatility, the C++ programmer can move between
jobs and companies without the need to relearn anything specific.
However, Python is an easier language to begin with. you're
completely new to programming then we would recommend you
S
mobile platforms.
Justke Python, to answer the question of Why C+ isthe
answer is because i's fast, efficient and developed by mast of the
applications you regularly use e's cutting edge and a fantastic
language to master.
C @
debian ubuntu
aaa
Indeed, the operating system you're
using is written in C+.
Mac
Windows 10z= Say Hello to C++ )
Equipment You Will Need
You don’t need to invest a huge amount of money in order to learn C++ and you
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 al, 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 (whichis something many older coders used to do), 2 computer
isan absolute must have component, PC users can have any recent
Linux distro or Windows 05, Macusers the latest macOS.
[_] AN IDE
Just as with Python, an IDE is used to enter and execute your C++
cade. Many IDEs come with extensions and plugins that help make
it work better, oradd an extra level of functionality. Often, an DE
Sz _
_— provides enhancements depending on the core OS being used, such as
being enhanced for Windows 10.
a)
COMPILER
—<
‘compiler isa program that converts the C++ language into binary,
so thatthe computer can understand, While some IDEs come with 3
compiler builtin, others don't. Code: Blockss our Favourite IDE that
comes ith a C++ compiler as part ofthe package. More on this later.
[_] TEXT EDITOR
Some programmers much prefer to use atext editor to assemble thelr
C++ code before runningit through a compiler Essentially you can
Use any text editor to write code, just save it with a.cpp extension.
However, Notepad++ is one ofthe best code text editors available.
|_| INTERNET ACCESS
While it’s entirely possible to learn how to code ana computer that's
not attached tothe Internet, i'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,
ies not 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 cine sees vee( 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+.
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 Notepadt+, then compile it with MinGW as used
by Code:Blocks.
Linux users ae lucky in that they 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
Ia Lag MAC
} The Raspberry P's operating
systems 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 will need to
download and install Xcode
tobe able tocompile their
C++ code natively, Other
‘options For the macoS
include Netbeans, Eclipse or
CoderBlocks. Note: the
latest CodesBlocks isn’t
available For Mac due toa lack
‘of Mac developers..
Say Helloto C++ )
How to Set Up
C++ in Windows
Ute MR ere R Ur ake Re nee AO AN eo CoM Tee TL eT Gree 1K
are plenty of IDEs and compilers available, including Visual Studio from Microsoft.
However, in our opinion, the best C++ IDE to begin with is Cod
Iola
CODE::BLOCKS
Code:sBlocks 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 e2tby visting the Code:Blocks download site, at
ww codeblocks.org/downloads. From there, click
(on the ‘Download the binary releases' nk tobe taken to the latest
downloadable version for Windows.
a
PEPTSPR) You can see that there are several Windows versions
available. The one you want to download has
‘mingw-setup.exe' atthe end of the current version number. At
the time of writing thsi: codeblocks-17.12mingw-setup.exe, The
differences that the mingw-setup version includes a C++ compiler
and debugger from TDM-GCC (a compiler suite).
ED coms oetntive cui Series: Volume 34
‘when youve located the file, click on the
Sourceforge.net ink atthe end of the line and a
‘download notification window appears; click on Save File to start
the download and save the executable to your PC. Locate the
downloaded Code:Blocks installer and double-click ta start. Follow
the on-screen instructions to begin the installation
Welcome to CodeBlocks Setup
Seng nl ge you trough ean of Coste
Rereomneded lyase ste ete
fuer Sune sre pom uote
‘Sevoc yon detente wre
(Once you've agreed tothe licencing terms, there isa
Siar)
choice of installation options avalable. You can opt
fora smaller install, missing out on some ofthe components but we
‘would recommend you opt for the Full option as default.
@
(sone Compares
tet econ
ek
Screed 251488(_ How to Set Up C++ in Windows ‘Cc
Next choos an instal oation forthe Codes Blocks
Sua files. t's your choice, but the default will generally
suc, ules ofcourse you hove any ped requirements When
you click Next, the install begins; when's inished a notification
ops up asking you iF you want to start CodeBlocks now, so click Yes.
eae rt Cs ta osneg Mw ros at ar os)
es hl Cis ber ea.
a gi a
Saeco?
Sec 7
Crete = E
ua toe : bur
Cee port Caer ease acoA rear MU |
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 click the Default
button to set it as the systems C++ compiler. Clik OK when you're
ready to continve.
Sheeran
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 allow Code:Blacks to associate all C+ file
types. Again, we would recommend you opt forthe last choice to
‘associate CodeBlocks with every supported file typ.
Before youstart using Code: Blas t's worth
SSIES) ‘explaining exactly why you need the added
complet rst, acompleris seperate program tht reads
throughyour Cvs code and cheds agaist te atest acceptable
programing standards why youneed the mest rece
Evatable comple Ts caren Grr wth C20 under
BETSSEEDD 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 91101111 @1110101 21110100 e0100000
00111100 0111100 00100000 90100010 01001000
1100101 01101100 01101100 @1101111 @0100000
1010111 01101111 01110010 @1101100 01100100
00100001 0100010 e0111011,
Select
Bers eR ER 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 it to ones and zeros For the computer
toact upon It's rather clever stuff, when you stop to think about ft.
ora bpublications 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.
FETTER S2tbyopening the App Store on your Mac, Apple. ERMINE when you're ready, click on the Get button which
"Menu > App Store. inthe Search box enter Xcode’ then turns into install Ap. 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 but it's the Fist option, Xcode, that youneed toclickon. depending on the speed af your internet connection.
PEPE DD) Take amoment to browse through the app's EPID 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 syste. When that is done, Xcode begins to install,
as con ncnaeng additional components.
EEE cores etn Gude Seris-votume 24