Ta ae tae ULL ed iE
The Complete
eA olee
£
Coding Manual.
ere) ng felge
to imp y
Por tee s Papercut PeasThe Complete
Manual Series
Available on Readly
ray pincBncke ve yarn coresate
iPad
BB &iPados@
User Manual
Mac
vy
meen
The Complete
‘Chromebook ‘WhatsApp
Manual!
as a
Raspberry
+ Coding
(| Manual
i Fun |
cst
The Complete
Instagram
User Manual Networking § Computing
9 Manual Manual
£3) Papercut
For a full list of titles available please visit:
www.pclpublications.comThe Complete
Python
Coding Manual
Unlock your imagination with Python...
There are few coding languages that have enjoyed the success of
Python, Thanks to Python's unique development, everyone can learn
the code that is: helping to drive such technological projects as the
Large Hadron Collider, collating the petabytes of data that made up
the first image of a Black Hole and creating the next generation of
Artificial intelligence. it doesn't take long to get to grips with Python,
but you need to start small
This guide will help you form the foundation of your Python coding
future, from installing the language on to your computer, through to
forming user interaction and complex variables. There's so much you
can do with Python and within these pages you'll find everything you
need to know to become a Python programmer, ready for the
next level of advanced coding
Whether you're looking to learn Python for future career prospects, or
just have some fun and discover something new, our step-by-step
tutorials and guides will give you that much-needed foothold to help
you on your way.
So let's dive in and start coding with Python.
£3) Papercut
www.pclpublications.comContents }
Contents
(3) Getting Started
eu
Cen ener
sO enn prc
Genin se
Working with Data
Cac
Cas
68 Dictionaries
renee nnn Sante
en ct
Peerhn
Pron Coding & Programing
16
Why Python?
Lela u neal
ern een
eee
Opening Files
inion
Exceptions
Cramer
Combining What You Know So Far
Python in Focus: Gamingcr
od
ord
cry
Ham cr
cred
or)
CMa eu ce
Number Guessing Game
on eh Macca
eit ence
‘Text to Binary Convertor
Basic GUI File Browser
Mouse Controlled Turtle
Python Alarm Clock
red
cry
EC
132
SES}
cer
({ Contents
Rie eee ons
Cue ietscsg
OD ee rN)
foe q
Soran
Cee ica
Simple Python Calculator
Coe We cls
muplplication comance
Started 2%
Set ake
ph as
a
ne ae)
i Siena
a a
Sie ei(Getting started Cll
Python isa high-level, general-purpose
programming language that was
developed by Guido van Rossum in the
late eighties and is based upon a number
of other languages, while being the
successor to the popular ABC language.
Ithas been devised to work ona human
level, so it’s readable and understandable
without needing to delve into obscure
volumes of machine code, hexadecimal
characters, or even ones and zeros. It’s
dear, logical, comprehensive, powerful
and functional, yet also easy to Follow
and learn.
You will find Python at the heart of some
of the most interesting and cutting-edge
technologies in the world. It’s the code
that binds supercomputer algorithms
together; it's used in the space industry,
and in science and engineering. Al, and
the likes of Alexa and Siri, Cortana and
the Google Assistant all utilise Python For
their powerful voice recognition
technology. It’s simply an amazing,
versatile and incredible language to learn.
So let's get started and explore what you
need to become a Python programmer.
Being a Programmer
ABrief History of Coding
What can You Do with Python?
Python in Numbers
Why Python?
Python on the Pi
Using Virtual Machines
Creating a Coding Platform
———— 7Being a Programmer
Programmer, developer, coder, they're all titles for the same occupation, someone who
creates code. What they're creating the code For can be anything from a video game
to a critical element on-board the International Space Station. How do you become a
programmer though?‘Times have changed since programming inthe 80s,
butthe core valves still remain.
“It's up to you
how far to take
your coding
adventure!”
— © sectestor(tusce)
. —_—
=
ie
si,
Being able to follow a logical pattern and
"see an end result sone ofthe most valued
skills oF a programmer.
MORE THAN CODE
For those of you old enough to remember the ‘80s, the golden era of home
‘computing, the world of computing was a very different scene to how its,
today. 8-bit computers that you could purchase as a whole, as opposed to
beeing in kit Form and you having to solder the parts together, were the stuff
‘of dreams; and getting your hands on one was sheer bliss contained within
2 large plastic box. However, it wasnt so much the new technology that
‘computers then offered, moreover it was the fact that For the frst time
‘ever, you could control what was being viewed on the ‘television.
Instead of simply playing one of the thousands of games available atthe
time, many users decided they wanted to create their own content, their
‘own games; or simply something that could help them with their homework
‘or home finances. The simplicity ofthe &-bit home computer meant that
‘creating something from a Few lines oF BASIC code was achievable and so
the first generation of home-bred programmer was born,
From that point on, programming expanded exponentially. t wasn't long
before the bedroom coder was a thing ofthe past and huge teams of
designers, coders, artists and musicians were involved in making a single
‘game. This of course led to the programmer becoming more than simply
‘someone who could Fashion a sprite on the screen and make it move at the
press ofa key.
Naturally, time has moved on and with itthe technology that we use.
However, the Fundamentals of programming remain the same; but what
‘exactly doesit taketo be a programmer?
‘The single most common traitof any programmer, regardless of what
they/re doing, is the ability to see a logical pattern. By this we mean
‘someone who can logically Follow something from start to Finish and
‘envisage the intended outcome. While youmay not Feel you're such a
person, itis possible to train your brain into this way of thinking. Yes, It
takes time but once you start to thinkin this particular way you willbe able
to.construct and follow code.
‘Second to logicis an understanding of mathematics. You don't have to be
‘at a genius level but you do need to understand the rudiments of maths.
Maths is all about being able to solve a problem and code mostly Falls under
the umbrella of mathematics
Being able to see the big pictures certainly beneficial For the modern
programmer. Undoubtedly, asa programmer, you will be part ofa team
‘of other programmers, and more than likely part of an even bigger team
(of designers, al of whom are creating a final product. While you may only
be exnected to create a small element of that final product, being able to
Understand what everyone else is doing will help you create something
that’s ultimately better than simply being locked in your own coding cubicle.
Finally, there's also level of creativity needed to be a good programmer.
‘Again though, you don't need to be a creative genius, just have the
imagination to be able to see the end product and how the user willinteract
with it.
‘There is of course a lot more involved in being a programmer, including
learning the actual code itself: However, with time, patience and the
{determination to lear, anyone can become a programmer. Whether
you want to be part ofa triple-A video game team or simply create an
‘automated routine to make your computing life easier, t's up to you how
Farto take your coding adventure!
en
Being a Programmer CllD cainasare
A Brief History of Coding
It’s easy to think that programming a machine to automate a process, or calculate a value,
is amodern concept that’s only really happened in the last Fifty years or so. However, that
assumption is quite wrong, coding has actually been around for quite some time.
Tel M CMM MMM OR MLM ROMO week
Essentially all forms of coding are made up of ones and zeros - on or off states. This works
For both a modern computer and even the oldest known computational device.
Ce eae
‘programmable loom, which used cards with
Bice teint oe
emer
Ce ei eee ea
escent ae
eee ee
Eee ireuetd salts
ee \ pea ies
Seat ate eaine
et eet s
ees
Dee ude
Cre oe a a
eestee
Pe ened
aad
Dead
Cee at
Ree mene’
eed
eee oe
Cea’
Pre eer
Sree ees
cee etee
1951-1958 1960-1970
From the 1970s, the development ofthe lkes of SQL, C with
Classes (C+4), MATLAB, Common Lisp and more, came tothe
Fore. The 80s was undoubtedly the golden age of the home
‘computer, time when silicon processors were cheap enough for
‘ordinary Folk to buy. This le to a boomin home/bedroom coders
with the rise oF &-bit machines,
1970-1985
1990s-Present Day
‘Computer programming
‘was mainly utilised by
universities, the military and
big corporations during the ‘60s
‘or home user, language wi
the development of BASIC
(Beginners All-purpose
‘Symbolic Instruction Code) in
the mid-sixtes.
Rete Rea
‘Assembly Language (ASM) or
‘The Internet age brought a wealth of new
Emu error)
Pence see ae
Pee nome
Not only could auser learn how to code,
Pe ee aes
source other code to improve their own,
eee
Rees
Cen
Ce a
renee eis
ete eee
such as IPL, FORTRAN and ALGOL,
eee
‘Admiral Grace Hopper was part oF
the team that developed the UNIVAC
‘computer and she eventually
developed a compiler frit. n time,
the compiler she developed became
COBOL (Common Business-oriented
Language), computer language thal
stilin use today
ea)What can You
Do with Python?
Python is an open-source, object-oriented programming language that's simple
rot el RSTO RON AB lets] Con To tt Eee tu Cr]0) (oo a
Cayelreraa ci a(ed unr ad MU Coen TaM nn) edd e-Ta a Clive] CeCe] cod (i
Python's ability to create highly readable code within a small set
‘oF instructions has a considerable impact on our moder digital
ee Mie ee et ea
Cote a ci
Cerca tilt
Sree eee erred eens eas
cece eee a ea sey
Pythonis the imagination ofthe person coding init.
Pecan errors
ue eens
‘coding world, that require more efficent code, stil se Python.
eee enue ee ets
‘andasa bridge between other programming languages. This way,
Doo es nee ere cee eet ecg Prodalpodere
Fe eee ea eee ihe
fills the gaps and provides the means to get the job dane. You'll bees
BIG DATA
Big data is a buzzword you're tkely to have come across inthe last couple of years.
ee eee ee ee ce
Pe a ee eed
ees es ae eee ee ac ee eal
industries, from social media to health and welfare, engineering to space exploration
See
eee ea eC ne eee ere ered
Deere eens ee eee ace ey
eeu iu ea we eG)
Uae cee
inamongst the numbers, that counts and presenting it in Fashion that’s readable and
Reese Maat
De eee a
‘mare importanty, accurate processing of datafrom the likes of supercomputing clusters, ——
antes eer tee ae eee ed
He frecienseenl ie eapiiriniesrrer spin fey Martina
Serer erent eee ee em eee
can gett the content they want without the needto lar afar more complex
Soe ets
oesARTIFICIAL INTELLIGENCE
Astificial intelligence and Machine Learning are two ofthe
‘most groundbreaking aspects of modern computing. Alis the.
umbrella term used For any computing process wherein the
‘machine is doing something intelligent, working and reacting
in simitar ways to humans. Machine Learning isa subset of Al
Se eae ay
euistoinces
eres ecco Teed
intent on wiping out human civilisation. Indeed, Al can be
Found ina variety of day-to-day computing applications where
the ‘machine’, or more accurately the code, needs to learn
fcr acre cd
the inputis likely to require, or do, next.
See RO
Instagram and so on. Have you ever looked up a celebrity on
Instagram and then discovered that your searches within other
social media platforms are now specifically targeted toward
similar celebrities? Thisis a prime example of using Alin
targeted advertising and behind the code and algorithms that
eee ea on ee
Spotify, For example, uses Python based code, among
‘other things, to analyse your musical habits and [ an |
Coe ase ss
permanent hoes
ee er eed
orniateeninnet iy y
NTs 2o) AU held
\Web development has moved on considerably since the early
days of HTML scripting ina limited text editor The many
Frameworks and web management services available now
‘means that building @ page has become increasinaly complex.
With Python, t has the ability to create
dynamicand highly secure web apps, enabling interaction with
‘other web services and apps such as instagram and Pinterest.
Python also allows the collection of data from other we
and even apps built within other websites.
oo
*
Po //i)s milla
Pion}
Although you won'ind too many triple-A rated games coded using
Python, youmiay be surprised tolear that Python i used as an
‘extraon many ofthe high ranking modern games.
Alotof the
seacch for potential heating, load baa
ski matchmaking and to
clientside game matches te server's versions There's aoa
Python module that can beincluded ina Minecra-serve, enabling
Is, jd automate alot
‘Asyoucan see, Python is quite a versatile
Deena ae Mc a
yyouare creating a well-rounded skillset that's
‘able to take you into the next generation of
‘computing either professionally or simply as
elssies
Sane ee ete LN
coding journey, you will do well to have
Prien‘
saaaWnn
Getting Started D)
There's a
lot to like about
Python, but don’t just
take our word for it. Here are
some amazing Facts and Figures
surrounding one of the most popular
programming languages of recent years.
=> |
® ea
Alexa, Amazon's Virtual Data analysis and
Personal Assistant, uses ‘Machine Learning are the
Python to help with ‘two most used Python
speech recognition. ‘examples.
a
PYTHON AND
LINUX SKILLS
ARETHE THIRD
ene, See
eres MOST POPULAR | jniceerucincesoneere
discussed language on ~~ TT. SKILLS IN to operate between other
theimonee Suc: raph packages
5%) (we) (i
(OVER 75% OF 90% OF ALL IT'SESTIMATED
RECOMMENDED FACEBOOK POSTS. ‘THAT OVER 75% OF
CONTENT FROM NETFLIX ‘ARE FILTERED NASA'S WORKFLOW
1S GENERATED FROM ‘THROUGH PYTHON- ‘AUTOMATION
MACHINE LEARNING ~ ‘CODED MACHINE SYSTEMS ON-BOARD
CODED BY PYTHON. LEARNING. THE ISS. USE PYTHON.
Pron Coding & Programing( Python in Numbers Cll
16,000
ttititti 6th
Hitt Iw °
There are over 16,000 Python jobs
posted every six monthsin the UK. JOBS IN THE UK.
Python Data Science is Google isthe top Data Science, Blockchain New York and San
thought to become the ‘company for hiring Python ‘and Machine Learning Francisco are the top
‘most sought-after job in developers, closely are the Fastest growing Python developer cities
the coming years. Followed by Microsoft. Python coding skills. inthe world.
Python developers enjoy an average salary of
S35 £60,000
(95% ) (75%) (79% ) (49
N77 SN NS
195% OF ALL BEGINNER ‘75% OF ALL PYTHON 79% OF ALL 49% OF WINDOWS.
‘CODERS START WITH. DEVELOPERS USE PROGRAMMERS USE 10 DEVELOPERS.
‘AND STILLUSE, PYTHON 3, WHEREAS PYTHON ONA DAY-T0- USE PYTHON 3
PYTHON AS THEIR 25% STILL USE THE DAY BASIS, 21% USE AS THEIR MAIN
PRIMARY OR ‘OUTDATED PYTHON 2 ITAS A SECONDARY PROGRAMMING
SECONDARY LANGUAGE. ‘VERSION. LANGUAGE. LANGUAGE,
vow gcipublications.comWhy Python?
There are many different programming languages available For the modern computer,
and some still available For older 8 and 16-bit computers too. Some of these languages
are designed for scientific work, others for mobile platforms and such. So why choose
Meta tetascd
PYTHON POWER
Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee
hours, slaving over an overheating heap of circuitry to create something akin to magic.
‘These pioneers of programming carved their way into new Regardless of whether you use an Android device, iOS device, PC,
Frontier, Forging smal routines that enabled the letter toscroll_ Mac, Linux, Smart TV, games console, MP3 player, GPS device builtin
‘across the screen. Itrmay not sound terribly exciting to.ageneration to acar, settop box ora thousand other connected and ‘smart’
that's used to ultra high-definition graphics and open world, multi appliances, behind them all's programming.
player ontine gaming, However, fortysomething years ago it was
binding biliant. Allthose aforementioned digital devices need instructions to tell,
them what to-do, and allow them to be interacted with, These
Naturally these bedroom codershelped form the Foundations For instructions form the programming core of the device and that cove
‘every piece of digital technology we use today. Some went onto _canbe built using a variety of programming languages.
become chief developers for top software companies, whereas
‘others pushed the avallable hardware to its limits and founded the The languages in use today fer depending on the situation, the
billion pound gaming empire that continually amazes us. platform, the device's use and how the device wil interact with its
Pe G& tnoe Pom Bal Gea At Sete
XB on v [visto @|S Bee # > 0@
— or ‘etcursor(p.y) 3
es ceetssentaentacit? a
jcrncore pekoniore »
eS pte amc costtatrace
= pee if(cursor == 0)
tieeaetleuaor:
a MSE:
feemaas—\euemas a) >
Stara Gators
void srrayctrl: sPaint(Oravé w) (
rane Paine!
| REMEN hls:
betton
sje < columm.catcount(); ja+4)
header et staan }af2
vertgrad'* {js = colum.cetcount!) - 1)) =» 0)
lend(scotorcisabled, Scatorraper);
oy me
aC catcoue))
Liteteop > aizeccy! dreak:
febottom = Fop > etanecy();
°
jg elumontengt
jor Setvabissthia)
Unt em = columijsemargin:
Men's 0)
dos -Tab).thargint)s
=ooo
eoo-0
1
0
oo‘environment or users. Operating systems, such as Windows, macOS
‘and such are usually a combination of C++, Ci, 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,
_2pps, 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
{are easier to learn and use than others. Python is one such general-
purpose language.
Python is what's known asa High-Level Language, in that it ‘talks
to the hardware and operating system using a variety of arrays,
variables, objects, arithmetic, subroutines, loops and countless
‘more interactions, Whilst it’s not a streamlined as a Low-Level
Language, which can deal directly with memory addresses, cal
stacks and registers, its benefits that it's universally accessible
{and easy to learn,
[//Fi Te: Tavoke. java
Finport java. lang.reflect.*;
class tnvoke {
Public [Stacic void main¢ string {0 args )
Gass c = class.forwane( args{0) );
nethod'g = c.getmethod( args(i], néw class
Gbject ret = m-nvokeC null, mutT )s
systen.out.printinc
Tyvoked static method: " + args(1]
of class: © + args(0
with no args\nResults: "+ ret);
3 catch ¢ ClasshotFoundexception e ) {
77 Class.forname() can't find the class
} cavch C Nosuchtethodexception 2") {
7 that method doesn't exist
2 each The
ZZ ne gon
) Gatch ( snvocarionrargetexception ef ) {
97'sn exception curred woite invoking that
aechod
Systen.out princi
i Shethod threw an: " + e4.
getTargetexception( ")°);
galaccessexception 3 ) {
fave permission to invoke that
Javaisa powerful
language that's used in
‘web pages, set-top boxes,
‘TWsand even cars.
Why Python? Cll
Python was created over twenty sixyears ago and has evolved to
‘become an ideal beginner’s language for learning how to program a
computer. I's perfect forthe hobbyist, enthusiast, student, teacher
and those who simply need to create their own unique interaction
between either themselves or apiece of external hardware and the
computer itself
Python is free to download, install and use andis avaliable for Linux,
Windows, macOS, MS-DOS, 05/2, BeOS, IBM series machines, and
even RISCOS. Ithas been vated one ofthe top five programming
languages in the world and is continually evolving ahead of the
hardware and internet development curve.
So to answer the question: why Python? Simply put, its free, easy to
learn, exceptionally powerful, universally accepted, effective and a
superb learning and educational tool.
BASIC was once the starter language that early
S:bithome computer users learned.
remount)
Python is amore modern take on BASIC, it’s easy to learn
‘and makes for an ideal beginner's programming language.
snaPython on the Pi
IF you're considering on which platform to install and use Python, then give some
thought to one of the best coding bases available: the Raspberry Pi. The Pi has many
advantages for the coder: it’s cheap, easy to use, and extraordinarily Flexible.
THE POWER OF PI
While having a Far more powerful coding platform on which to write and test your code is deal, it's not often Feasible. Most of
us are unable to jump into several hundred-pound investment when we're starting off and this is where the Raspberry Pi can
help out.
‘While having a Far more powerful coding platform on which to
ee es eee ee Nee One a
eee eee eee
Rereeene ee et ee eee
Mao arenes oot ud
Peco es races nettle cry
‘about computers, how they work, how to code and Foundation
level electrons. Thanks to its unique mix of hardwareand custom
Pe ir aura cd
Pete te tes ras
‘hile you'e able, with ease, to use the Raspberry Pito learn to
ee ea oe eae ne a
ete eae ee et eet sey
Pere ener peut eared
Coen ces iece eet ri
Pe eee ee nee)
programming, as opposed toa fresh installation of Windows 1,
‘which has no Python-specific base. However, the Raspberry Pi
Foundation has gone the extra mile to include a vast range oF
Porat eee aa eee
So, essentially, all you need to do is buy @ Raspberry Pi, Follow the
instructions on how to set one up (by using one of our excellent
Raspberry Pi guides found at www.bdmpublications.com) and you
Een ie ne cere ont el
‘Significantly there's alot more to the Raspberry Pi, which makes
Peters eee ee es
See ee ent ey
Deen ete
toremotely connect to the Raspberry Pi from any other computer,
‘or device, on your home network. For example, once you've set up
Sears ei ue eS
Sn ee ge en eats
router. As long as the Piis connected, you wll be able to remotely
Pet tees
sitting in Front of the Pi with akeyboard and mouse.
Using this method saves a ot of money, as you don't need another
keyboard, mouse and monitor plus, you wont need to allocate
sufficient space to accommodate those extras either. If you're pushed
ether ar ot tenant
ees
eee geet eee ere an
latest Raspbian 05), acase, power socket and cables, thisis a good
idea as you could, with very tle effort, leave the Pi plugged into the
Pern ay Cees eee
Sg ee ge eee ay
Raspberry Pi Foundation has included out of the box. The reason
Pe oar ee eters
User, whether that's coding, electronics, or some other aspect of
computing, To achieve that goal the Pi Foundation includes diferent
IDEs forthe userto compile Python code on; aswell as both Python
2 and Python 3, there's even a Python library that allows you to
eet ines
There are other advantages, such as being able to combine Python
code with Scratch (an Object-Oriented programming language
developed by MIT, fr children to understand how coding works) and
Deer tls one cr eee
eer een a eet
a Sense HAT Emulator (@ HAT is ahardware attached piece of
Circuitry that offers different electronics robotics and motorisation
projects to the Pi), which can be accessed via Python code.
Consequently, the Raspberry Piisan excellent coding base, aswell
Peet oe ie
reasons we've used the Raspberry Pi as our main Python codebase
Cer tae ee a ae ceed
Pi, you're also able to use it in Windows, other versions of Linux and
‘macOS. Ifthe code requires a specific operating system, then, don't
Rees ast
J See ae Sad
included with the Os!neo
Peet
wa
Introduced on 24th June 2018, the Raspberry Pi4 Model was
significant leap in terms of Pi performance and hardware
specifications. tw:
orignal Pi, to sell out.
With anew 1.5GHz, 64-bit, quad-core ARM Corte
a choice of 1GB, 2G8, 04GB memory versions the Pi4is one-step
tobecoming atrue desktop computer. In adclition the Pi 4 we
launched with the startling decision to include dalmonitor support,
inthe form of a pair of two micro-HOMI ports. Youll also find a pair
Inaddition to releasing the Pi4, the Raspberry Piteam also complied
ane n ofthe Raspbian operating system, codenamed Buster.
Inconjunction with the new hardware the i 4 bo
Ss, Buster does
offera Few updates. Although on the whole t's very simian
‘appearance and operation to the previou ‘oF Raspbien. The
Updates are mainly indine with the 4k display and playback ging the
idan set of graphical drivers and performance enhancements
In short, what you ee inthis book will work with the Raspberry P
4 and Raspbian Buster!
Once set up, you can remotely connect to the P's desktop
Fromany device/PC.
‘OF USB 30 ports Bluetooth 50, and a GPU that'scapable ofhanding
4k resolutions and OpenGL ES 3.0 graphics.
In shor, the Pid isthe most pow Pi
models, However, the diferent memory’ increased
cost. The 168 ts £34, 2GBs £44, and the 4GB version wil
setyou back €54, Remember to also factor in one ortwo micro HOM!
cables with your order.
You can even test connected hardware with Python
ees
—|
Getting Started
Using Virtual Machines
PAE eee Oa enn kee hemi nee
on your desktop. This way, you're able to host multiple systems in a secure, safe and
Fo) leroR-a ikea tne Dae Y=] BV A Keele
‘Sounds good, but what exactly is a Virtual Machine (VM) and.
how does it work?
The official definition ofa virtual machine i ‘an efficient, isolated
duplicate of areal computer machine’. This basically means that a
virtual machine is an emulated computer system that can operate in
‘exactly the same way as a physical machine, but within the confines
(of a dedicated virtual machine operator, or Hypervisor.
The Hypervisor itself is an app that will allow you to installa
separate operating system, creating a virtual computer system
within itself, complete with access to the Internet, your home
network and soon
‘The Hypervisor willtake resources fromthe host system - your
physical computer, to create the virtual computer. This means that
part of your physical computer's: memory, CPU, hard drive space
{and other shared resources, willbe set aside for use inthe virtual,
‘machine and therefore won't be availabe to the physical computer
ntl the hypervisor has been closed down,
This resource overhead
canbe crippling for the
physical machine you
dont already have enough
‘memory or hard drive
space available, or your
computer has a particularly
slow processor. hile it's
entirely possible to run
Virtual machines on as litle
22GB of memory, it's not
advisable, Ideally, you wil
‘need a minimum of 868.
(of memory (you can get
‘away with 4GB, but again,
your physical computer
willegin to suffer with
the loss of memory to the
virtual machine}, at least 25
to 50GB of Free space on
your hard drive and a quad
core processor (again, you
can have a dualcore CPU,
but that can cause a bottleneck on your physical computer)
mK PEON A CDN
peu
Tae
Coding Manual
140
oF eo)
‘Seer
(ur Linux titles contain
steps on how to installa
hypervisorand OS.
The limit to how many different virtual machines you hest on your
physical computer is restricted, therefore, by the amount of physical
system resources you can allocate to each, while stl leaving enough
For your physical computer to operate on,
7 ae
You're able to install Linux, and code inside a virtual
machine ona Windows 10 host.
VIRTUAL OS
From within a hypervisor you're able to run a number of different
‘operating systems. The type of OS depends greatly on the
hypervisor you're running, as some are better at emulating a
particular system over others. Far example, VirtualBox, a free and
‘2a9) to use hypervisor from Oracle is great at running Windows
‘and Linux virtual machines, butsn’t so good at Android or macOS,
‘QEMU is good for emulating ARM processors, therefore ideal For
‘Android and such, but it can be difficult to master.
‘There are plenty of hypervisors avaliable to try for Free, with an
‘equal amount commercially availabe that are significantly more
powerful and offer better Features. However, For most users, both
beginner and professional, Virtualox does 2 goad enough job.
Within a Fypervisor, you're able to set up and install any of the
newer distributions of Linux, orif you Feel the need, you're also able
to install some of the more antiquated versions. You can install early
versions of Windows, even as Far back as Windows 3 complete with
DOS 6.22 ~although you may Find some Functionality of the VM lost
‘due to the older drivers (such as access tothe network).
With this in ind then, you're able to have an installation oF Linux
Mint, or the latest version of Ubuntu, running in an app on your
Windows 10 PC. This is the beauty of using a virtual machine.
Conversely, if your physical computer has Linux as its installed
‘operating system, then with a hypervisor you're able to create a
Windows 10 virtual machine although you will need to have a
licence code available to register and activate Windows 10.Using virtual machines remaves the need to dualboot. Dual booting
ishaving two, or moce, physical operating systems installed on
the same, or multiple, hard drives on a single computer. Asthe
‘computer powers up, you're given the option to choose which OS,
you want to boot into. While this sounds lke a more ideal scenario
itisn't always a stright Forward as it sounds, asall the operating
systems that ae booted into will have Full access to the computer's
entice system resources.
‘The problems with dual-booting come when one ofthe operating
systems is updated, Most updates cover security patching, or bug
Fixing, however, ome updates can alter the core -the kernel, of
the OS. when these changes are applied, the update may alter the
‘way in wich the OS starts up, meaning the initial boot choice you
made could be overwritten, leaving you without the ability to access
the other operating systems installed on the computer. To rectify
this, ull need to access the Master Boot Record and ater the
configuration to re-allow booting into the other systems. There's,
‘also the danger of possibly overwriting the first installed OS, or
‘overwriting data and more often than not, most operating systems
put 100
Programs are ike recipes for computers. A
recipe to bake a cake could go tke this:
rons of butter to the
ise miliiitres of milk
Put 100 grams of selfalsing flour in a bowl.
‘Add 100 grams of butter to the bowl
‘Add 100 millitres of ik
Bake Forhalfan hour.
CODE
Just ke a recipe, a program consists of instructions that you follow
in order. Aprogram that describes a cake might run tke this:
Jeu - 0 meen
flour = 100
butter = 50 Enis
[Eases Ee aeciurentananaieh
bowl . append (flour butter, milk }
‘cake . cook (bow!)
PROGRAM COMMANDS
You might not understand some of the Python commands, lke bowl append and cake.cook{(bowi)
‘The first isa list, the second an object; we'llook at both in this 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.HIGH-LEVEL LANGUAGES
Computer languages that are easy to read are known as ‘high-level
Thisis because they fly high above the hardware (also referred to as
the metal’) Languages that “ly close to the meta lke Assembly,
>>). Whilst it's a perfectly
version of Python when clicked (more on that ina moment). To open fine environment, it's not too userriendly, so leave the command
the IDLE, type IDLE into Windows st line for now. Enter: exit () to leave and close the Command
Prompt window.
opeHello, World.)
How to Set Up
Python in Linux
PYTHON PENGUIN
Linux is such a versatile operating system that it's often difficult to nail down just one-way of doing something, Different
distributions go about installing software in different ways, so for this particular tutorial we will stick to Linux Mint.
PEPER Ficstvouncedto ascertain which version of Python BEAM once the update and uparade completes, enter:
is currenty installed in your Linuxsystem. To begin yt!
chon}. ~-version again to see'f Python 3.xis
‘ith, drop intoa Terminal session from your distro'smenu, orhit the updated, or even installed. As long as you have Python 3.x you're
CertsaleeT keys running the most recent major version, the numbers after the 3.
indicate patches plus Further updates. Often they're unnecessary,
davidedavid-Mint:~ but they can contain vital ew elements,
File Edt View Search Terminal Help
Next enter pytinon ~-vereion inathe Terminal
Suse screen. You should have the output relating to
version 2x Python inthe pay. Mos Linux stro come wth
both Python 2 and 3 by default, as there's plenty of code out there
stil available For Python 2, Now enter: python
version.
davidedavid-mint
Terminal
File
dit View Search
eS TT)
aye tig SEED tiowevesiFyouwantthe atest, cutting edge
bi Cig Start by entering these commandsinto the Terminal:
gudo apt-get install build-essential checkinstall
sudo apt-get install libread]ine-gplv2-dev
Libneursesw5-dev libsel-dev Libeglites-dev tk-dev
PEPED | ourcase wehave both Python 2 and installed. Libgabm-dev libe6-dev 1ibbz2-dev
Aslong as Python 3.xx:sinstalled, then the code in
‘our tutorials will work. I's always worth checking to see ifthe distro
has been updated withthe latest versions, enter: sudo apt-get
update && sudo apt-get upgrade to update the system.
avidedavieatine ~
Pron Coding & ProgramingOpen upyour Lux webbrowser nde othe
SuaPG Python download page: https://www.python.org/
downloads Cit onthe Downloads flowed the button de
the thon Source wow Ts opersa download logue box,
choose lation then star the dovnoad proces
Inthe Terminal, go tothe Downloads Felder
SEPT byentering:cd Downloade/. Then unzip the
coneents ofthe dounloaded Python soure code with eae vt
bython-3.¥.¥ tar (epace the Ys wivthe version numbers
Youve downlcaded), Now enter the newly nzippe older wih
yehon-3.¥.¥/
FETED Within the Python folder, enter:
Jeonfigure
sudo make altinatall
‘This could take a while, depending on the speed of your computer.
Once finished, enter: python .7. --varaion to check the latest
installed version. You now have Python 37 installed, alongside older
Python 3xx and Python 2
“ How to Set Up Python in Linux
gudo apt-get inatall idlea
For the GUIIDLE, you'll need to enter the Following
‘command into the Terminal
The IDLE can then be started with the command: Sdie3, Note, that
IDLE uns different version tothe one you installed from source,
devide david int-roomloadltython 3.72
FEET BD Youllatsoneed Pip (Pip installs Packages), whichis
2a tool to help you install more modules and extras.
Enter: eudo apt-get install python3-pip
(Once PIP is installed, check For the latest update with:
pip3 install --upgrade pip
When complete, case the Terminal and Python 3.x willbe available
via the Programming section in your distro's menu:
vided ti -fDomloterynon 72
Installation of Python on macOS can be done in much the
same way as the Windows installation. Simply goto the Python
‘webpage, hover your mouse pointer over the Downloads
link and select Mac OS x from the options. You willthen be
‘Guided to the Python releases for Mac versions, along with the
necessary installers For macOS 64-bit for OSX 10.9 and later.
pps~
ZZ y Hello, World )
Starting Python for
the First Time
The Raspberry Pi offers one of the best all-round solutions on which to learn and code,
eM coca Ceara heme eaicen eke
LE Lecryate-lo) Ree es aOR UME ood Ee) oCcia Keele are) Laie
STARTING PYTHON
Everything you need to begin programming with Python is available from the Raspberry Pi desktop. However, if you want,
drop into the Terminal and update the system with: sudo apt-get update.
EEE With the Raspbian desktop loaded, click on the
Meni button Followed by Programming > Python
3 (DLE). This opens the Python 3 Shel. Windows and Mac users can
Find the Python 3 IDLE Shell From within the Windows Start button
menu and via Finder
For example, inthe Shell enter: 2+2
‘After pressing Enter, the next ine dsplays the
answer: 4. Basically, Python has taken the ‘code’ and produced the
relevant output
Say
ESTEE The Shellis where you can enter code and see the
responses and output of code you've programmed
into Python. This sakind of sandbox, where you're able to try out
some simple code and processes.
Pron Coding & Programing
FSPTSP DD The Python shell acts very much ke a calculator,
since code is basicaly a series of mathematical
interactions withthe system. Integers, which are the infinite
sequence of whole numbers can easly be added, subtracted,
‘multiplied and so on,FETED While that's very interesting it's not particularly
exciting, Instead, try this
Print (*Hello everyone!")
Just enter into the IDLE as you've done in the previous steps
PPD thisisa ttle more like it, since you've ust produced
‘your Fist bit of code. The Print command is fairly
self-explanatory, itprits things, Python 3 requires the brackets as
‘well as quote marks in order to output content tothe screen, in this
‘ase the Hello everyone!’ bit.
>>> print("Hello everyone
Hello everyone!
>>|
Youmay hve noticed te colour coding within
Su? the Python IDLE. The colours represent different
‘elements of Python code. They are:
Black ~ Data and Variables Blue User Functions
Green ~Strings Dark Red ~ Comments
Purple Functions Light Red ~Error Messages
Orange Commands
IDLE Colour Coding
[Feetoor ose tor Beene]
trea [Ener messoes | syneanteror
( Starting Python for the First Time € mm
BETIEED The Puthon 1DLEis a configurable environment. f
you dont like the way the colours are represented,
then you can always change them via Options > Configure IDLE and
clicking on the Highlighting tab. However, we dor't recommend
that, asyou won't be seeing the same as our screenshots,
PRPED) us: ke most programs available, regardless of the
‘operating system, there are numerous shortcut
keysavallable. We don't have room for them all here but within the
(Options > Configure IDLE and under the Keys tab, you can see a list
of the current bindings.
Varseaninoe etcwnc ween =
Seomren sl
BEET RD) The Python 1OLE is a power interface and one
that’s actually been written in Python using one
of the available GUI took. f you want to know the many ins and
outs of the Shel, we recommend you take a few moments to view
wurw.docs.python.org/3/library/idte.html, which details many oF
the IDLE's Features,
‘wen pipublicatons comED) sete oie)
Your First Code
LSS aler WANA E Loe eccun (ol Me (re Koleole AU Tiea en nL WC}
Ca ola Mit nee AKON aM Le -Uco UA eel col Lg Col aor CCleed oder LT] Ln elo) 1
entering your code and playing around with some other Python examples.
PLAYING WITH PYTHON
‘With most tanguages, 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.
FETE RED "you've closed Python 3 IDLE, reopen itin
whichever operating system version you prefer. In
the Shell enter the familar following:
Just as predicted, the word Hello appearsin the
Shell as blue text, indicating output From a string.
sr)
le’ fail straightforward and doesn't require too much explanation.
Now try
FSTeGE DD ou cansee that instead ofthe number 4, the
‘output is the 2+2 you asked to be printed tothe
‘screen, The quotation marks are defining what's being outputted
to the IDLE Shel to print the tata of 2+2 you need to remove
the quotes:
‘You can continue as such printing 2+2, 46442343
‘and so on tothe Shell An easier ways tose a
variable, which is something we will cover in more depth later. For
now, enter:What you have done here isassign the letters a
and b two values:2 and 2, These are now variables,
hich can be called upon by Python to output, add, subtract, divide
{and s0 on For as long as their numbers stay the same, Try this
print (a)
print (b)
‘a Est a Gay tem o_o
C
eeu First Code ¢ q Za
Now let's add a surname:
aurnene="Hayward’
print (surname)
‘Younow have two variables containing a First name and a surname
and you can print them independently
(oe Et te Ceuta revs wen
ESTER The output of the last step displays the current
values of both a and b individually, as you've asked
them to be printed separately. F you want to add them up, you can.
use the following
print (a+b)
‘This code simply takes the values ofa and b, adds them together
and outputs the result.
‘Ue tat Ont beg Swene wnat Oe
PRP vc were to apply the same routine as before,
using the + symbol, the name wouldn't appear
correctly in the output in the Shel, Try it:
print (nana+eurnama)
‘Youneed a space between the two, defining them as two separate
values and not something you mathematically pay around with,
et so) gen Gene etn te
Berea Youcen play around with different kinds of variables
and the Print Function. For example, you could
‘assign variables for someone's name:
ame-"Davia"
print (name)
BETS ERED | Python 3 you can separate the two variables,
‘with aspace using a comma:
print (name, surname)
‘Alternatively, you can add the space yourself:
Print (names" “+surname)
“The use of the comma is much neater, as you can see,
Congratulations, youve just taken your fist steps into the wide
‘world of Python.
he ao“ ome tein |
om pcpueationscam~
ZZ » Hello, World )
Saving and Executing
Your Code
While working in the IDLE Shell is perfectly Fine for small code snippets, it's not
Cen Meuustne Cn ca recta en eccuN cout
eee Mee [coer Maceo Ao UN ron cafe ee
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.
PEPIIPMD First, open the Python IDLE shell andwhen its up, ENPNBWB) You can see that the same colour coding isn place
dick on File > New File. This wil open a new window in the IDLE Editorasitisin the Shell, enabling you
‘with Untitled asitsname. This isthe Python IDLE Editor and withinit to better understand what's going on with your code. However, to
you can enter the code needed to create your Future programs. execute the code you need to first save it. Press FS and you get 2
mmm, $2NE.-CheCKDOX OPEN,
FEED the IDLE Editors, forall intents and purposes, a FTE EE lickonthe Ox button inthe Save box and select a
simple text editor with Python features, colour Save As From within the Editor
Use throughout this book, unless otherwise stated. to.create a backup.
be Bem Be te TTT
Mhovooentenetcatonarbesneceton ESET vow sete ane cnet tor adopen
Sua code, you can see that it ends ina .py extension. SuzPilo a new instance (File > New File From the Shell).
Tis sthe default ythonfiename. Ary code youereate willbe Enerthe allowing andsave shel oy
whateveepy and any code downloaded om the mary nent
Python resource sites willbe py. Just ensure thatthe codeis written 87 BYERON”
For Python 3 ie
print (a, bye)
‘You will use this code in the next tutorial
ie eo Fat tn ent Ye te
wwmpciputictonscan QJHello, World
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.
EE Python, in Linux, comes with two possible ways of BED Now you're at the command tine we can start
‘executing code vi the command line. One of the Python, For Python 3 you needto enter the
waysis with Python 2, whilst the other uses the Python 3 ibraries command python3 and press Enter. Tis will put you into the
and soon. First though, drop intothe command ine or Terminalon command line version ofthe Shell, with the Familiar three right
your operating system, Facing arrows asthe cursor (>>)
BED Justas before, 5 z BED From here you're able to enter the code you've
we're using a looked at previously, su
ry Pi: Windows users will
need to lick the Sart button and =
search for CMD, then clickthe —
Command Line returned search; ” You can see that it works exactly the same,
print (a)
and macOS users can get access
totheir commandline by licking
Go> utlities > Terminal
Pon Cig & PrExecuting Code from the Command Line
BED oreersestotstenetiecmaaineryten EEF) te enstcng thon sad emte
prompt. Enter the folder where you saved the code From the doesn't error out in any way, due tothe differences between the
previous tutorial and lst the available Files within; hopefully you way Python 3 handles the Print command over Python 2, the result
should see the hello.py File, isn’t as we expected, Using Sublime for the moment, open the
hellopy fie
a - a
BED oriintesetsratecoseve EARP sre sitine rexel rte sry
gong ton, eter te fllowing tothe Piya
re going to temporarily leave the Pi forthe
command line: ‘moment and use Sublime as an example that you don't necessarily
needto use the Python IDLE. With the hello.pyile open, alterit to
include the following
python? hello.py
Thiswill execute the code we created, which to remind you is
nanesinput ("What 4s your name? *)
Python print ("Hello,", nane)
ex"eool !* .
printia, B, ) -
w- ee]
BED tise tcentonscaccerathe ERED snc tetelooy cans conbactiote
with Python 2 by entering
python3 command. Fyou tke, trythesame cox
python hello.py
SEEELEW The result willbe the original Python is cool statement, together
with the added input command asking you For your name, and
isplaying it inthe command window.
rn ppuiations.cmZz a ) Hello, World
Numbers and Expressions
ARR CM EOD MY EAM Lear Ie Cel oot ees A LAM SACOM LCE Tele eC TaTe Ra Ty
like. Let's expand on that now and see just how powerful Python is as a calculator. You
ese e AOE Aen o PM oes\i 1 Cem en eel come e LU Com
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.
EEGRED 0Pen up the GU! version of Python 3, as mentioned
you can use either the Shell or the Ecitr. For the
time being, you're going to use the Shel just to warm our maths
muscle, which we believe isa small gland located at the back ofthe
PEPER You can useall the usual mathematical operations:
divide, multiply, brackets and so on. Practise with 2
Few, For example:
a/a
brain (or nat) ma
24283
(asa) +0380),
Inthe helene the Following You've no doubt tied von produces
eye =m Suze decimal number. In Python these are called Floats,
or losing pon arthmetc However you nedan integer es,
54356+34553245
SE an opposed to decimal nave, then you can se a double at
fou can see | jon can handle some quite large numbers. aa
YoucanseethatPythencanhandlesomeautelagenumber., M2
sodsoon
Toe ea ot oes eo as
Re es oe eon
trBETA Youcan also use an operation to see the remainder
left over From division, For example:
20/3
ill isplay 3333333333, which Isof course 3.3-ecuring. IFyou
ow enter:
aoe
‘This wll display 1, which isthe remainder left over From dividing 10
into 3
FETE Next up we have the power operator, or
exponentiation if you want to be technica. To work
‘out the power of something you can use a double multiplication
‘symbol or double-star on the keyboard!
23
ao**10
Essentially its 2x2x2 but we're sure you already know the basics
behind maths operators. This is how you would work tout Python,
(- Numbers and Expressions Cll
\
ESTEE DD Tiswillbe displayed as’0b11", converting the
integer into binary and adding the prefix Ob to the
Front. F you want to remove the 0b prefix, then you can use:
format (3, "b")
“The Format command converts a value, the number 3, toa
Formatted representation as controlled by the Format specification,
the part.
PEPID 4 B0clean Expression isa logical statement that will
either be true or false. We can use these to compare
data and test to see f it's equal to, less than or greater than, Try this.
ina New File:
ass
be7
print (1,
print (2,
print (3,
print (4,
print (5, not a
print (6, a == 7 or b == 7)
print (7, @ == 7 or b == 6)
print (8, not (a == 7 and b == 6))
print (9, not a == 7 and b == 6)
Numbers and expressions dnt stp thee. ython
Sua has numerous builtin Functions to work out sets
of numbers absohite values, complex numbers anda hstof
mathematical expressions and Pythagorean tongue-twisters, For
‘example, to convert a number to binary, use
ints)
PRET Execute the cade from Step 9, and you can see a
series of True or False statements, depending on
the result ofthe two defining values: 6 and 7. t's an extension of
‘what you've looked a, and an important part of programming,
eT
ie Ea sob tenn dens i
smnZz 7d ) Hello, World
Using Comments
When writing your code, the Flow, what each variable does, how the overall program
A oY ote-le-are RoR oD] MUNEI(« BOLUM CePNTO ANI KL CMU meee] Ke) CVA
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. IF a variable is used, the
programmer comments on what it’s supposed to do, for example. It's just good practise.
print command:
aio
Print (“The value of A i
‘save the fileand execute the code. i
Start by creating a new instance ofthe IDLE Editor
(File > New File) and create a simple variable and
Resave the code and execute it. You can see that the
thesameas before,
SIEES) ‘output in the IDLE Shell is:
despite the extra ines being added. Simply put, the hash symbol (#)
denotes ane of text the programmer can insert toinform them,
and others, of what's going on without the user being aware,
Ee al
‘nmap hrmipDoamen yon deanna yaa) = = De eats ew a TITTY
Let's assume that the variable A that we've created
funning the cde wil etn thee: The value ofA
pid is, 10 into the IDLE Shell window, which is what we
‘expected Now adasome ofthe pes of eomments oud nermaly
see wihincode
# Sot the start value of A to 10
ae10
4 Print the current value of A
Print ("The value of A is,”, a)
STEPS) is the number of lives ina game. Every time the
player dies, the value is decreased by 1. The programmer could
insert. a routine along the lines of
asad
print ("You've just lost a 1ife!*)
Print ("You now have", a, “Lives 1eft!*)Whilst we know that the variable As lives, and
that the player has ust lost one, a casual viewer or
‘someone checking the code may not know. Imagine For a moment
that the code is twenty thousand lines long, instead of just our
seven, You can see how handy comments are.
Essentially, the new code together with comments
couldlook tke:
uaa
4 Set the start value of Ato 10
a0
# Print the current value of A
Print ("The value of A is,”, a)
# Player lost a life!
ara-t
# Inform player, and display current value of A
(lives)
print ("You've just lost a 1ife!")
print (*You now have", a, “Lives left!*)
C
(Using Comments Cll
Inline comments are comments that follow a section
‘of code. Take our examples from above, instead of
inserting the code on a separate line, we could use:
ac10 # Set the start value of A to 10
print ("The value of A is,", a) # Print the current
value of A
aca-1 # Player lost a lite!
print ("You've just lost a Life!*)
print ("You now have", a, “Lives left!") # Inform
player, and display current value of A (lives)
FRPP the comment, the hash symbol, can also be used to
‘comment out sections of code you don't want to be
‘executed in your program. For instance, if you wanted to remove
the first print statement, you would use:
# print ("The value of A is," a)
Forine the current value of A
4 print "The value of A is,
Player lost’ life!
F Inform player. and display current value of A (Lives)
prantc-vou've just lost a, 1ifet").
rane(-You new have", &, "lives Left")
‘Youcan use comments in different ways. For
example, Block Comments area large section of
text that details what's going on inthe code such as telling the code
reader what variables you're planning on using:
¥ Thies 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.
PEPAET BD You also use three single quotesto comment
‘uta Black Comment or multi-line section oF
comments. Place them before and after the areas you want to
comment for them to work:
‘This is the best game ever, and has been developed
by a crack squad of Python experts who haven't
slept or washed in weeks. Despite being very
smelly, the code at least works really well.
om pcpuleationscamZz 7d ) Hello, World
Working with Variables
NCAR MEO CU RRL eR eae eore Lema eee LY
worth going through the way they operate and how Python creates and assigns certain
Neo WUC
VARIOUS VARIABLES
You'll be working with the Python 3 IDLE Shell in this tutorial. Fryou haven't already, open Python 3 or close down the previous
IDLE Shelt to clear up any old code.
FTE RED '950me programming languages you're required EINEM You've seen previously that variables can be
to.use a dollar sign to denote a string, whichis concatenated using the plus symbol between the
variable made up of multiple characters, such asa name of 8 person, variable names. In our example we can use:print (name + *:
In Python ths isnt necessary. For example, inthe Shell enter: * 4 tite). The middle part between the quotations allows us to
nane="David Hayward” (or useyour own name, unless you're _add.acolon and a space, as variables are connected without spaces,
also called David Hayward) ‘owe need to add them manually
|—---—_ ___|
| Con |
FEMI can cneckthe pe oaribein vse by oo: TN
issuing the type Q) command, placing the name of combine variables xe sn gig Gane rr
{ie ES Sh Dt aoe
soya
the variable inside the brackets. In our example, this would be: ‘within another variable. For Pr ee TT
type (name).Addanew string variable: tities"Descended _exammple, tocombine bath narne
‘from Vikings" and ttle variables into anew
variable we use:
character-name +":
title
‘Then output the content of the
ew varlable as:
print (character),
Numbers are stored as different
variables:
age=4
Type (age)
Which, as we know, are integers.
mrFEED However, you can't combine bath strings and
integer type variables in the same command, asyou
‘would a set of similar variables. You need to elther turn one intothe
‘other or vie versa, When you do try to combine both, you get an
‘error message’
print (name + age)
Working with Variables Cll
PEPIID This presents a it of aprablem when you want to
‘work with a number that's been inputted by the
User, as age + 10 won't work due to being a string variable and an,
integer, Instead, youneed to enter
Ant(age) + 10
“This wil TypeCast the age string into an integer that can be
‘worked with
gta sere in ec ar iy
‘hiss a process known as TypeCasting. The Python
code is:
uaa
print (character + * ie" + str(age) + * years
eld.)
‘or you can use:
print (character, "is", age, ‘years old.")
Notice again that inthe last example, you don't need the spaces
between the wordsin quotes as the commas treat each argument
toprint separately.
Fractback (most recent call last)
File “", line 1, 1n
print (nave * age)
Typetrror: can't convert ‘int’ object to str implicitly
S38"print (characters " i=" + str(age) +" years old")
David Hayward: Descended fron Vikings is 14 years old.
SSS'prant (character, "is", age, years old.)
David Hayward: Descended from Vikings is 48 years old.
‘Another example of TypeCasting is when you ask For
input from the user, such asa name. for example,
enter:
ages input
‘All data stored from the Input commands stored asa string variable.
(How 024 are you? *)
Ta
5" or "License" for ore information
1
BRP The use of TyneCastingis also important when
dealing with floating point arithmetic; remember:
‘numbers that have a decimal point in them For example, enter:
ahize=19.99
Now enter type (ahixt) and youll see that Python hasallocated
the number as a float, because the value contains a decimal point
[ele Eat sheb Debug Ontons windows Heb
Python 54.7 (Getoult, Oct 19 2014, 13ST
(ec 4.9.1) on may
Tyee Seep Meredita” or -1icense()* for nore information.
35 Sypetsmire)
clase “tina
hen combining rtegersané eats Python
Suzrilo usually converts the integer to a Float, but should
the reverse ever be applied i's worth remembering that Python
doesn't return the exact value. When carwerting a Fat to an
integer, Python wil always round down to the nearest integer,
called truncating; in our case instead of 19.99 it becomes 19,
Ce at 8 bos gs a
SoSenireeaeas
35> typetshire)
Saris
Ea
smnED) i
User Input
We've seen some basic user interaction with the code from a Few of the examples
earlier, so now would be a good time to Focus solely on how you would get information
from the user then store and presenti.
USER FRIENDLY
‘The type of input you want from the user will depend greatly on the type of program you're coding. For example, a game may
‘ask For a character's name, whereas database can ask for personal details.
ETE ERED fitsnot already, open the Python 3 IDLE Shell, FaTeG ERD Now thet we have the user's name stored in a
and starta New Filein the Editor. Let’s begin with couple of variables we can call them up whenever
something realy simple, enter: ‘we want:
FER Scand eects the code andasyoustedyno Run he code andyoucan see astgt sve he
doubt sapeced inthe OLE Srl re proton wl Tastop afer the some olows blokes.
astforyourtrsinone soungtesthevoblefsiname falowed —Toelminate Ut we on aap gnratend of commen
by your surname; also stored in its own variable (surname). the code:
ieee meee eet Nae cat cee rr ea) me>
a hsYou don't always have toinclude quoted text within
the input command. For example, you can ask the
User their name, and have the input in the line below:
print (*Hello. What's your name?")
hame=input ()
Ele Edt Famat Bun Options Windows Help
rant Welle. vhat’s your nawe?=)
anes input()
userinput py - homne/pi/Documents/Python Code/us,
User Input Cll
Be What you've created here is a condition, which we
will cover soon. In short, we're using the input from
the user and measuring it against a condition, So, i the user enters
David a their name, the guard wil allow them to pass unhindered.
Els, iFthey enter a name other than David, the guard challenges
them toafight.
‘The code from the previous step is often regarded
as being litte neater than having a lenathy
‘amount of textn the input command, but it’s not arule that’s set in
stone, so doas youl in these situations. Expanding on the code,
try this
Drint (Halt! Who goes there?")
name=input ()
PPI 15:25 you learned previously, any input froma
User is automatically a string, so you need to apply a
TypeCast in order to tum into something else. Thiscreatessome
Interesting additions to the input command. For example:
# Code to calculate rate and distance
print ("Input a rate and a distance")
rate = float (input ("Rati
lesa gcodstart toa text adventure game, perhaps
Su Now you can expand on it and use the raw input
from the user to flesh out the game alte:
Af name--"David’ :
Print (*Welcone, good air. You may pass.")
else:
print (*r know you not. Prepare for battie
(ie at Fame Bin sito nde tap
ica, ats. asm at")
FTEERED 7 finalise the rate and distance code, we can ade:
Gistance = float (input ("Distance:
”
print ("Time:*, (distance / rate))
Save and execute the code and enter some numbers. Using the
Float{input element, we've told Python that anything entered isa
floating point number rather than a string,
wmpciputictonscan QE]Zz a ) Hello, World
Creating Functions
NU VOR RCE eee Me ola 1o) ETaTe RUM a LUM en Moo ect OACoela
functions. You've already used a Few Functions, such as the print command but Python
enables you to define your own Functions.
FUNKY FUNCTIONS
‘Afunction is a command that you enter into Python to do something. It's a little piece of self-contained code that takes data,
‘works on itand then returns the result.
FE circusconsustocimecice tases SEE won sven moon tocos ious
length or type oF items. Basically, afunction is ashort word that's _code (enter the text editor for this example):
followed by brackets. For example, len), st() or type).
ESTED {function takes data, usualy avaiable, workson— EITEIE Psthon has tens of Functions buitnto it Far too
todo and returns the end value. The data being worked on goes However, to view the list of builtin Functions available ta Python 3,
Inside the brackets, so if you wanted to know how many letters avigate to www. docs.python.ora/3/library/Functions htm. These
are in the word antidisestablshmentarianism, then you'd enter: are the predefined Functions, but since users have created many
Jen ("antidisestablichnentarianien”) and the number28 more, theyrenot the only ones available
would return.‘Adltional functions can be added to Python
through modules. Python has avast range of
modbles available 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
Once entered, you have access to all the Math module Functions.
FORGING FUNCTIONS
(Creating Functions Cll
Of the Function. For instance, using the Math module, since you've
just imported it into Python, you can utilise the square root Function,
Todo so, enter
math. sqrt (16)
You can see thatthe code is presented as module, function{data).
D rerrrenrweers itz nl
na ns tu ae ee UR ety
across some excellent examples in the future; you can also create your own with the def command,
PIR ch052 File > new Fle to enter the editor lets
ee ieee i
fe Script. You can see Hello in the
urs the new Func
PER 60's now expand the function’
eeepc:
es
ees
namie)
jello ("David")
ie
ree
aan
< on,
Petes
eo ee
STEP 3
am eane
seni
meat
SC as
ied
ee aa
ferom Hello import Hello}
Hello "David
ress F5 to save and execute the code,
td
enema this one, and modify
Sel
fact aaaia, >)
‘wen pipublications com