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 [Link] letter:
print (letcer,)
print ()
print ("Letters Guessed: *,)
for letter in [Link] 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
([Link] 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
[Link] 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= [Link]()
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. [Link].*;
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);
[Link]
“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 [Link]
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 [Link](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 [Link].
‘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
[Link] 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 [Link] 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//[Link]/ — 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: [Link] 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
‘[Link]/3/library/[Link], 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 [Link] 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 [Link]:
‘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 [Link], 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 [Link] 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 [Link]
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 [Link] 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" [Link] 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 [Link]/3ibrary/[Link]. 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
[Link] 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 vole