100%(1)100% found this document useful (1 vote) 743 views197 pagesThe Complete Python Manual (5th Edition) - April 2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
rayialeleY, the Sens
Inte
& The: Complete
Linux
Manualement,65)}), !1}}( Ms ps recmeeel oo
Bare teeny ent (a) || ( Brice
Ce BCs OD east) (Ol Crm ere eres
ate Dar (a, function(c,d){b. find( =) iG
(terns »function(c,d){d=$(d);var £=d.prop("name"); ! (a,f)?d
a [etc as SAM aeas = ti 7
Iters_Form_ container Selector) find(”.filter Aa eins FS a
(b) - length; 0ri
L)
i
p oe History of Coding |
(eee etd eC eee ater
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.
Cee RRR RRR RRR CONC RR CORLL
ee eee eee ae
i ear ee eat or
1842-1843 1930-1950
We
stare of when humans
‘rogram’ adevice. How
cepted that the
Ce eee)
Pei eee r at
ene ard
Doane sn
‘design on 3 previous automated weaving
Ce tae
eet
scholars who worked in the House of
Cees
Ce eet
Eee ee
was. amechanical musica instrument:
eee re
ere ie te P anailable atthe timsoor
oe meeed
SC eauae uae
See
Ce ature)
Sera
rad
Rien
Cee
freer een aera eg
re ees
Geers
From the 1970s the development of thelikes oF SQL, Cwith
Classes (C+), MATLAB, Common isp and more, came to the
fore. The’80s was undoubtedly the golden age ofthe home
compute atime when slicon processors were cheap enaugh for
‘ordinary Folkto buy. This led toa boom in home/bedroom coders
with the rise of bit machines.
1951-1958
‘The first tre computer code was,
en aces
Cee eee
Seats
Cea
eras
eis
ed
eee er team
ees
Computer programming
‘was mainly used by
universities the military and
big corporations during the ‘60s
and the'70s. Anotable step
toward amore userriendly,
lorhome user, language wa
the development oF BASIC
(Beginners All-purpose
Symbolic instruction Code) n
the midsities.
Si Sere ote
‘programming languages and allowed
eee ua’
eet eon
Peete rey
Peer neingctid
Peer
‘Admiral Grace Hopper was part of
the team that developed the UNIVAC
computer and she eventually
‘developed a compiler For tn time,
the compiler she developed became
‘COBOL (Common Business oriented
Language), computer language that's
stillin use today.
b coos
nr
”Choosing a -Bper=ticn —
Programming pret ens
Language ¥
Tatnelenacciacer ica) ct _X = Fa
See ee eT ere Ly aan a ee
a single book ofthis size. New languages Ra Uren a Tr
and ways in which to ‘talk’ toacomputer ©perat ee 2 = Fg
or device and set it instructions are being aT
invented almost daily; and with the mod MIRRC
Pista Ten ttesn tnt ma nur Pes -Use_x = Fa
eau auetes sen etl tunes __mod.use ae
PPevieeatu ten Secu ay ut ee ee]
ReMi ents od -use_z = Tr
Pe) stmt
Tras
CTH
eoie ae
7 Eee aes nate eer tes
a peer ester eee eh cer)
> (American National Standards institute) standard, there are different versions of
Se ee ea ete eee as
ones Reet a Seine aan
eV c<:1 1) Reenter beter
oe coe ee
ee
Functions JavaScript runs onthe clint side ofthe web, that canbe used to desion
See eye etre ees
Beemer renee ine wr met eee}
ee Reiss
ea Cone ee eso
rr eee areca ret
based content, games and mobile apps. The two main componentsof the Java
Java platform are the Java Application Programming Interface (API) and the Java Virtual
Leite ett eters
Citisan elegant object-oriented languagetthat enables developersto,
bull variety of secure and rabust applications that run on the NET
Framework. You can use CH to create Windows client applications, XML Web
Peet ee ree ee tetas
ree etege tire mete racer es
one)
ay Python isa widely used high level programming language used
eee ten
ese ence)
philosophy that emphasises code readablity anda syntax thet allows programmers
eee te a een
Sora
cH CCr* (pronounced cee pus plus) isa general purpose programming
eee eee ete eee ee rea)
Features. was designed with a bias toward system programming and embedded,
resoutce-constrained and large systems, with performance, efficiency and flexibly
Eee ser ris
Perce ens
Peete een ae
Crt ei ns
er eet ee eee eee eee
essential parts of Ruby can be removed or redefined, at will Existing parts canbe
porate
2 Cee et ed
range of tasks including system administration, web development,
network programming, GUl development and more. Its major Features ae that
perro ier trees per ans
perce teen mnt er ene ieee
eens neers rte
ES eer ua maurice came
eee on eee eer
See eer eae
eee ere Ene ete cnr
Pee Cee cree aehe World of Code”)
Creating a
Coding Platform
HARDWARE
Thankful, coding atthe
Foundation level doesnt
require specast equipment
for atop of the range quid
hydrogen-ooled PC. IFyou
‘own a computer, no matte
how basi, you can begin to learn how to code, Naturally, iF
iF computer in question is a Commodore 64 then you mey
have some difficulty folowing a modern language tutorial, But
some ofthe best programmers around today started on an
bk machine, so there's hope yet
‘Access tothe Internets necessary to downoad install and
Update the coding development environment, alongside a
Computer with ether: Windows 10, macOs, oF Linux installed
You canuse ather operating systems, bu these are the big
three and you wil find that most code resources are writen
with ane, orall ofthese, ning,
es
ean erreurs
Penner
Pe iene eae ies
rena
eg tents
ce ent
ree
Been cee inc
Sent Sey
oe ree eet ees
co carrer
SOFTWARE
interms of softuare,
nostofthe development
environments-thetools
thatalowyoutocode,
comple the code and
executet-are freely valableto download and instal There
are some specalt ols aoisble that wil cost, but athis evel
theyre not necessary;sodonttbefooledintothinkinayouneedto
purchase any extra software inorder to tart earring howto code
(Overtime, youray Find yoursel changing fram the mainstream
development envionment and using collection of your ow
lscovered, ool to write your code in, Rs all personal preference
nthe end and as you become more experienced, you wil start
touse different tools to get thejob done. Some envecnments
will enhance sections of code, making teaser to read, others wl
allow quickcompiling and exection. e's alla matter of testing
and experienceCreating a Coding Platform Cl
‘windows 10isthe most
Used operating system in
OPERATING SYSTEMS
the wort, soit’s natural
that the vast majortyof
coding tools are writen for Microsoft's leading operating
system, However, dant eiscount macOS and especial Linux.
‘acOS users enjoy an equal number of coding tools to their
Windows counterparts. Infact, you wil probably find that a
lot of professional coders use a Mac over aPC, simply because
ofthe Fact that the Mac operating ystems built on top oF
Unix (the commandline OS that powers much ofthe word's
filesystems and servers). This Unix ayer lets you test programs.
in almost any language without using a specialised IDE.
Linux, however Isby far one of the most popular and
important, coding operating systems avaiable. Not only
sdoesit have aUnictke backbone, but als it's aso free to
‘download, install and use and comes with mast of the tools
necessary to start learning how to code, Linux powers most of
the servers that make upthe Internet. I's used on nearly all oF
the top supercomputers, aswell as specicaly in organisations
such as NAGA, CERN and the military and itForms the base of
Android-powered devices, smart TVs and in-car systems Linux,
asa coding platform, isan excellent idea andit can be installed
inside a virtual machine without ever affecting the installation
‘oF Windows ar macO8.
‘THE RASPBERRY PI
IFyouhavert already heard
ofthe Raspberry, then
we suggest you head over
to wwm.raspberrypi.org, and
checkitaut.inshor, the Raspberry
Piisasmlt fly Functional computer that comes with Rs own
customised Linuchased operating system, pre-installed with
everything you need to stat learning howto code in Python,
C+, Scratch anc more,
£lesincredibly cheap, costing around £35 andalowsyou to utlse|
ferent hardware, inthe Ferm of rbotis and electronics
projects, as wll as offering a complete desktop experience.
Atbough not the most powerful computing device inthe word
the Raspberry Pihasa lot going fri, especialy in termsof being
‘one ofthe best coding platforms avaiable.
YOUR OWN CODING PLATFORM
‘whichever method you choose, remember that your coding
platform wll probably change, 3s you gan experience and Favour
one language aver another. Dont be afraid ta experiment along
the way, as youwill eventually create your own unique platform
that can handle allthe code you enter intoit.
VIRTUAL MACHINES
| Avitual machine isa piece of software thetallowsyoutoinstalla
Fully wrkng, operating system within the confines ofthe software
Itself The nstaled OS wil alacate user-defined resources fromthe
host computer providing memory, hard rive space etc as wells
sharin the hos commuters inert connection.
The advantage of avitual
‘machines that youcan werk
with Linu, for example, without
Ieaffectingyourcsertly
inetaled hott OS. This means
that you can have Windows 10
running, aunch your vital machine dent, bot into Unuxand use
allthe Functional oF Linux hie being able to we Wind.
This ofcourse, makes it fantastic coding platform, as youcan
have different instalations of operating systemsrunning from
the host computer wile using different coding languages.
Yau can test your code without fear af breaking your hast OS
andit’s easy to retuin toa previous configuration without the
reed to reinstall everything again
Virtualisation isthe key to most big companies now. You will
probably Find, For example, rather than having a single server
ith an instalation of windows Server, the T team have
instead opted Fora virtualised environment whereby each
Windows Server instance ie a vitual machine running From
several powerful machines. This cuts down on the number
(of physical machines allows the team to better manage
Fecoutces and enabes them to deploy an entire server
decicated toa particular askin a fraction ofthetime.
MINIX NEO N42C-4
The NEONA2C4isan extraordinary
small computer from miniPC developer,
MIND Measuring just 139 13930mrn ths ntl N4200 CPU.
Powered, Windows 10 Propreinstalled computers one of the
best coding platforms we've come across.
‘The beauty, ofcourse lesinthe fac. that with inceasedstorage
and memory avlable you'eable to create acomputerthatcan
easly host mutiplevitwal machines. The vitualmachinescan
cover Linux. Android and other operating stems alowing you
towte and test oss platform code without far of damacing,
‘or causing problems, with other production or home compute.
‘The MINK NEO N42C-4 starts a around £250, with the base
32GB eMMIC and 4GB of memary.Yaul need to add another
hundeed and Fifty or so, to increase the specifications, but
consider that license for Windows 10 ro alone costs €219,
fromthe Microsoft Store and you can becin to see the benefits
CF opting For amore impressive hardware foundation ver the
likes oF the Raspberry P.
oe:ZZ 2 ) Print ("The World of Code’
Using Virtual Machines
A Virtual Machine allows you to run an entire operating system From within an app
on your desktop. This way, you're able to host multiple systems in a secure, safe and
isolated environment. In short, it’s an ideal way to code.
Sounds good, but what exactly is a Virtual Machine and how
does it work?
The offical dentin ofa vtual machine's ‘an efficent, isolated
duplicate ofa real computer machine’. This basically means that
virtual machine isan emulated computer system that can operatein
exacty the same way a a physical machine, but within the confines
oF a dedicated virtual machine operator, o Hypervisor.
‘The Hypervisor itself, is an app that wil allow youto installs
separate operating system, creating avitual computer sytem
vithinitselF complete with acess to the intemet, your home
network and a on
The Hypervsor wil take resources from the host system -your
physical computer, to create the virtual compute. This means that
part of your physical computers: memory, CPU, hard dive space
and other shared resources, wil be set asie fr use inthe virtual
‘machine and therefore wont be avaliable tothe physical computer
until the hypervsor has been closed down,
This resource overhead
can be crippling forthe
physical machine Fyou
‘ori already have enough
memory, or hard dive
space available, o¢ your
computer has a particularly
slow processor. while i's
entirely possible to run
virtual machines ona tle
35 2GB of memory snot
advisable. ideally, you wil
heed aminimum of 68.
‘of memory you can get
away with 468, but again,
your physical computer
willbegin to sufer with
theloss of memoryto the
virtual machine, at least 25,
to 50G8 oF Free space an
your hard drive and quad
core processor again you
can have adualcore CP,
but that can cause bottleneck on your physical computer
ur Linuctitles contain
steps on how to installa
Inypervisor and 05.
The limit tohow many different virtual machines you host on your
Pysical computers restricted, therefore, by the amount of physical
‘system tesources you cn allocate to each, while stil leaving enough
For your physical computer to operate on.
EE) -2erostvoncon
‘You're abe to install Linux, and code inside a virtual
machine on a Windows 10 host.
VIRTUAL OS
From within a hypervisor you're able to run a numberof diferent
‘operating systems The type of 05 depends greatly on the
hypervisor you'e running, as some are better at emulating
patticular sytem over others. For example, VirtualBox, afiee and
f23y to use hypervisor From Oracle is great at running Windows
and Linux vitwal machines, but ist s0 good at Android or macOS.
(QEMUs 900d for emulating ARM processors, therefore ideal for
‘Andsoid and such, bucitcan be dfficl to master.
There are plenty af hypervsorsavallableto try For free with an
equal amount commercally avaliable tat are significantly more
owesful and offer beter Features, However, for most users, both
beginner and professional, VirtualBox does a good enough ob.
\Within a hypervisor, you're able to setup and install any ofthe
newer distributions oF Linu, orif you feel the need you're also able
tonstall some ofthe more antiquated versions. You can install ary
versions of Windows, even a Far back as Windows 3 complete with
DOS 6.22 ~ although you may ind some Functionality ofthe VM lost
due tothe older drivers (such a access tothe network
‘With this in mindthen, you're able to have an instalation of Linux
Min, oF the atest version of Ubuntu, running in an app on your
Windows 10 PC. Ths isthe beauty of using a virtual machine.
Conversely, your physical computer has Linuxas ts installed
‘operating system, then with ahypervsor you're able to create
Windows 10 virtual machine although you wil need to have @
licence code available to resister and activate Windows 10Using itual machines removes the need to duatboct, Duat-booting
ishaving two, or more, physical operating systemsinstalled on
the same, or multiple, hard drves onasingle computer. As the
compute powers up, you're given the option to choose which OS
you want to boot into, wile this sounds ike @ more ideal scenario
iRisn always as straightforward a it sounds, asall the operating
systems that are booted into will have Ful acces tothe computer's
entire system resources.
‘The problems with dual booting come when one ofthe operating
systemsis updated, Most updates cover security patching or bug
Fixing, however, some updates can alter the core =the kernel, oF
the OS. when these changes are applied, the update may ater the
‘way n hich che OS starts up, meaning the inital baot choice you
‘made coud be overwritten, leaving you without the ability to access
the other operating systems installed onthe computer. To rectify
this, oul ned te access the Master Boot Record and alter the
configuration to re-allow booting into the other systems. There's
aso the danger of possibly verwriting the Fstinstalled OS, or
‘overwriting data and more often than not, most operating systems
‘ont play well when cunning side-byside, Indeed, while good, cal:
booting has more than its ar share of problems. In contrast, using a
virtual machine environment, while sil problematic at times, takes
jut some of the more nasty and disastrous aspects oF using multiple
‘operating systems ona single computer
Even old operating systems canbe run inside 3
virtual machine
ea cual mactine can be sine compen aryour
ADVANTAGES FOR CODERS
For the coder, having a virtual machine setup offers many
advantages, the most popular being cross-platform cade. Meaning it
you write code within Windows 10, then with an installation ofa
Linux astro in a hypervisor, youre able to quickly and effortlessty
power up the vital machine and test your code in acompletely
{ferent operating system, From thi, yout able to iron out ay
bugs, teak the code so it works better on afferent platform and
expand the reach of your code to non Windows users
‘The advantage of being able to configure a development
environment, n speiicways for specc projects, isqute
Invaluable. Using a vrtual machine setup greadly reduces the
‘uncertainties that are inherent to having multiple versions of
programming languages, ibraries, IDEs and modules installed, to
support the many cifferent projects you may become involved in as
acoder. Elements of code that talk directy to specifics ofan
‘operating system can easily be overcome, without the need to
clutter up your main, host system with cross-platform libraries,
“hich in turn may have an affect on other ibrares within the IDE.
Another element to consider is stability. I youre wilting code that
could potentially cause some instability to te core OS during its
‘evelopment phase, then executing and testing that code on a
virtual machine makes more sense than testing ton your main
computer; where having to repeatedly reboot, or eset something
cuetothecode’s ©
instabiltes, an =
become
inefficent and
justplain
annoying,
Coding in Python on the Raspberry
Pi Desktop OS inside a VM on
Windows 10:
The virtual
machine
be viewed aca
sandbox, where
you're able to test
unstable code
vathout it causing harm, or doing damage to your main, working
computer Vues and malware canbe isolated within the VM
vthout infecting the main computer, you're able to set up
anonymity Internet use within the VM and you're abe o instal
thir party software without slowing down your main computer,
GOING VIRTUAL
While youre atthe early stages oF coding, using a vitual machine
may seema lite excessive, However, ts worth looking into because
coding in Liuxcan often be easier than coding in Windows, as some.
vetsons oF Linux hve IDES preinstalled. Either way, vituaisation oF
an operating sytem show many ofthe professional and successful
coders and developers work, so geting used tot early on in your
skillset is advantageous,
Tostart, look tinstaling VirtualBox, Then consider taking a look
at ourLinux tes, https://odmpublications.com/?s=tinux&post_
typesproduet, o learn how toinstal Linux in virtual
and how best to utlise the operating system,ZZ Z ) Print ("The World of Code’
Equipment You
Will Need
Se nan Neng Cee com Gece
Coniaiss Funes a oncattan cue EI ecient ect
fears
WHAT WE'RE USING
“Thankfully, Python isa multiplatform programming language available for Windows, macOS, Linux, Raspberry Pi and more. IF
you have one of those systems, then you can easily start using Python,
COMPUTER
Obviously youre going to need a computer inorder to learn how to program in
Python and to test your code. You can use Windaws (rom XP onward) on either a32
or 64-bit processor an Apple Maco Linux installed PC.
AN IDE
‘AnIDE (integrated Developer Environment) is usedto 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 avalable so ind
the one that works For you and gives the best results
PYTHON SOFTWARE.
‘macOS and Linux already come with Python preinstalled as part ofthe operating
system, as does the Raspberry P. However, you need to ensure that youre running
the latest version of Python. Windows users need to download andinstall Python,
which wel cover shorty,
TEXT EDITOR
‘whilst tex edtorisan ideal enranment to enter code int, I's not an absolute
necessity, Youcan enter and execute code directy From the IDLE but atext eto,
‘suchas Sublime Texto Notepad++, offers more advanced features and colour coding
‘when entering code,
INTERNET ACCESS
Python i an ever evolving environment and as such newversion often introduce
new concepts or change existing commands and code structureto make a more
efficient language. Having acces tothe Internet wil keep you up-to-date, help you
out when you get stuck and give access to Pythor'simmense number of modules.
TIME AND PATIENCE
Despite what other books may lead youto believe, you won'tbecome a programmer
in 24hours. Learning to code in Python takes time, and patience. You maybecome
‘stuckat times and other times the code wl lw tke water, Understand youre learning
Something ently new, and you wil get there.Equipment You Will Need Cl
THE RASPBERRY PI
\Why use a Raspberry Pi? The Raspberry Pisa tiny computer that's very cheap to purchase, but offers the user a Fantastic learning
platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many modules and extras.
RASPBERRY PI
‘The Raspberty Pi 4 Model ie the latest version,
Incorporating a more powerful CPU, a choice of 168,
2G8 or 4G@ memory versions and Wi and Bluetooth
‘support You can pickup a Pt From around £33, increasing
Upto £54 forthe 4GE memory version, or asa pat of Kt
For £50, depending onthe kityou're interested in.
FUZE PROJECT
The FUZE is learning environment bul on the latest model
ofthe Raspberry Pi. You can purchase the workstations that
me with an electronics kt and even a abot arm For you
te bull and program. You an Find mere information on the
FUZE at wwwfuze.couk
BOOKS
We have several great Raspberry Ptiles avaiable via wow.
‘bdmpublications.com, Our Pibooks cover how to buy your
RASPBIAN Fist Raspberry
setitupand use
there are some great step
bystep projec examples
and guidesto get the most
From
Raspberry
‘The Raspberry P's main operating system is a Debian-based
Linuxalstribution that comes with everything you need in
simple touse package. t's streamlined forthe Pland isan
ideal platform for hardware and software projects, Python
programming and even asa desktop computerWelcomePython is a Fantastic programming
language. With it, you can create
everything from a simple program to
backup the pictures on your computer,
through to analysing petabytes of data.
Not only is Python the programming
language of choice for some of the
biggest companies in the world, it’s also
one of the easiest to learn.
This chapter will help you get Python set
upon your computer, and introduce you to
this remarkable and powerful language.
Python’
19 You Do with Python?
ting to Know Python
2Welcome to Python
Why Python?
Dee alias ie uM eae te ee sce aku
Eo Ree ene eeu Maem ce ms a uCtda deat
Preece ek cement e en Melee ARO) e Cece aT eg OR WA Reece id
Preartiase nics
PYTHON POWER
Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled avay until the wee
hours, slaving over an overheating heap of circuitry to create something akin to magic.
‘These pioneers of programming carved thelr way into 3 new
Frontier, forging small routines that enabled the letter to scroll
‘actossthe screen. may not sound terribly exciting to a generation
that's used to ultrahigh definition graphics and open werld, muli-
player online gaming However, Fortysomething years agoit was
binginaly bilan.
Naturally these bedroom coders helped form the Foundations For
‘every piece of digital technology we use today. Some went onto
became chief developers for top sofware companies, whereas
‘others pushed the available hardware tots limits and founded the
billion pound gaming empire that continually mazes s.
Regardless of whether you use an Android deve, iOS device, PC,
Mac, Lnux, Smart TV, ames console, MP3 layer, GPS device builtin
toa car, settop box or athousand other connected and ‘smart
appliances, behind them allis programming,
‘Allthose aforementioned digtal devices need instructions to tell,
them what todo, and alow them tobe interacted with These
instructions Form the programming core ofthe device and that core
can be butt 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 wilinteract with its
stleurger >= 0)
Pefresinortcursor):
certTachataoneracend)
‘einen Deine
SE eeetieet:
iC reste
eet
ftor fe
Steen
re
farina J
poi arog scstontrocua
wold scrayeerL:-paine(oras ¥) {
‘ibtats © catcount())
flee catnerl
fibviton = Fitop ? cetLanecy(ids
“header
3g <,colum.catcoune(): jst) €
ft ce = Beaders ye
seegnds Ge
colum.catcomti) « 19) == 0)
lend(scatartisabled, Scoloreaper):
if
< coluny cescoue) j1+) (
5 sxcraban deh
‘tumisl morse‘envronment or users. Operating systems such as windows, macOS
‘andsuch are usually a combination of C++, CH, assembly and some
Form of visuabased anguage. Games generally use C++ whist web
pages can use a plethora of avaliable lanquages such as HTML, Ja,
Python and soon,
"More generat purpose pragrammingls used to crete programs,
_apps software or whatever else you wantto cal them. They're
widely used across all hardware platforms and suit virtually every
‘conceivable application Some operat Faster than athers and some
‘are easier to lear and us than others. Pythonis one such general
purpose language.
Python's what’ known as a High-Level Language, in that ‘talks’
tothe hardware and operating system using a variety of aay,
varables, objects arithmetic, subroutines oops and countless
‘more interactions Whist t's not as streamlined as a LowLevel
Language, which can dea drety with memory addresses, call
stacks and registers is benefit isthat ls universally accessible
‘and easy to lean,
/7#iTe: Tavoke java
import java. lang.reflect.*;
elas invoke {
public static void min( string [] args ) {
a
2 nee rn a)
O63 5 pale
Be ye oe amet a, 03:
Systen.out printint
Stivoked eeatig wethod: * + argel3]
+7 of class: * + args(0] ie
Fe mainte args\feselia: © pet 35
2 eel Elassocfoundbxceefon «
HT Sage orhtme oS Mcan’e' Fond che class
1 Gach aesutinehodeseaption 625°C
» Goeiht Tilepnaceeosbxcepeion o3 > {
pe jen! Rave’ peratoston to ahd eat
} EgechC xnvocacontargetexception e4 ) {
Jian excapeion ocurred while invoking that
inethod
System. out,printIn¢
Sheehod thren an: " + e8
‘gotTargetexeaption( *)
y
P
Javaisa powerful
language that’s used in
web pages, set-top boxes,
‘Tvsandevencars.
C Why Python? Cl
Python was created over twenty si years ago and has evolved to
became an ideal beainnerslanguage for earning how to programa
computer's perfect forthe hobbyist enthusiast, student, teacher
and those who simply ned ta create thelr on uniqueinteraction
between either themselves ora piece of externat hardware and the
computer isel.
Python sree to downoad, install and use ands avalable for Linux,
\Windows, macOS, MS-DOS, 05/2, 0, IBM iseries machines, and
even RISC OS. thas been vated one ofthe top five programming
languages in the world and continually evolving ahead ofthe
hardware and Internet development curve.
So to answer the question: why Pythor? Simply put, i's ree, easy to
learn, exceptionally powerful, universaly accepted, effective and 2
superb learning and educational tool
BASIC was once the starter language that early
‘sbithome computer users learned.
Python sa more modem take on BASIC, i's easy to learn
_and makes for an ideal beginners programming language.
oe:Fy
What can You
Do with Python?
Preece ceca cere enter ctintsciccl
ee Ue MSR tod en Lee RNs ool Lea
eeeeo cae tu cect enue giscaeti iol cas
ee Ve
Ce ae Ve
i es
Cee ee eas wy "
ee ae ene eee ee mee ee
eee feelings
Tear re ones
Line eh
Cm te eee en
eu ee ees
Se te et arm
Cee ee ee
‘need without having to cross multiple anauage barvers Python
GO ee eed
TaD A
Eee eee eae seat pces
Basically, t means extremely large datasets that are availabe or analysis to reveal
pattems trends and interactions between humans, sodety and technology. OF course,
oes eee eee enc ean ec
ee ee ee ete
Sores
Python plays substantiate inthe word of big data. t's extensively used to
Bee ence ee er ee
ee et ee eee eee
Geer ee ers
inamongst the numbers that counts and presenting it ina fashion that's readable and
Peern tee
Ce ere ee ere eee
etary Teer a cee ee preety
pete rence tee meee en een eect
Pe poeoboceeeorresoee ve uments tty
evi uariree erie Siete Tear roe PTS
Psionriotainnee een Leia merc en ionPU ae) a nee (e
ebm cues
ee ee ee eee
term used foray computing process wherein the machine s
oing something inteligent working and reacting in similar woys
eee eer eects
pen he crag
ieee
ere ee esd
ete nr era acre m een
ete eee reise eters
the machin’, more accurately the code, need to learn
ae une Ed
Sa eee irs
eet ren RL
eee
Instagram and then discovered that your searches within other
ee co ert!
similar celebrities? Thisisaprime example of using Alin
ere ree eee acai
Botte oat aas
Seer)
Seianitrdol ostream poser CO |
Cees ts
reece eae)
ee naa
parece eer iat y
PVecy austen) m
\Web development has moved on considerably since the early
days of HTML scripting ina limited text ecitor, The many
frameworks and web management services available now
‘means that building a page has become increasingly complex.
\with Python the web developer has the ability to create
dynamic and highly secure web apps, enabling interaction with
‘other web services and aps suchas instagram and Pinterest.
Python als allows the collection of data from other websites.
and even apps built within other websites.
le &
EL
ith
o/s m lay
find too many triple rat
y be surprised to lean that Python suse
y ofthe ghar
hon in gaming
rea Python sot can 2c
he sever
cheating load balan
matchmaking
aches the
canbe induded
add
PYTHON EVERYWHERE
Coe en ree
programming language. By learning Python,
Pea le es
ne ee ea
Coe ete
Biss
Ce
eee emcee
Pi aneiie
wneubinbicicnscanz= Welcome to Python
There’sa
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.
—_
oe
Alexa, Amazon's Virtual
Personal Assistant, uses
Python tohelp with
speech recognition.
Oe
Ne
saaaWnNs
ame oe
DeceMnen
PYTHON AND
ety LINUX SKILLS
ARE THE THIRD
eeuaweene MOST POPULAR
discused languaga on LT. SKILLS IN
the Internet THE UK.
&
aaron
(759% )
‘OVER 75% OF 90% OF ALL
RECOMMENDED FACEBOOK POSTS.
‘CONTENT FROM NETFLIX ‘ARE FILTERED
IS GENERATED FROM ‘THROUGH PYTHON-
MACHINE LEARNING ~ CODED MACHINE
‘CODED BY PYTHON. LEARNING.
i
Data analysis and
Machine Learning are the
two most used Python
‘examples,
Disney Pixar uses Python
inits Renderman software
twoperate between other
sraphics packages.
an
(75% \
ITS ESTIMATED
‘THAT OVER 75% OF
NASA'S WORKFLOW
‘AUTOMATION
SYSTEMS ON-BOARD
‘THELSS. USE PYTHON.16,000 “ass
titttiti 6th:
tt
4eriit
0 eeccccceccccccceces MOST SOUGHT-AFTER
‘There are over 16,000 Python jobs
posted every six months in the UK. JOBS IN THE UK. %
Python Data Science is Goosleisthetop Data Science, Blockchain New York and San
thought to become the company for hiring Python and Machine Learning Francisco are the top
most soughtaer job in developers closely are the fastest growing Python developer cities
the coming years. followed by Microsoft. Python coding sil inthe wold
Python developers enjoy an average salary of
SS £60,000
%) (15%) (79%) (49%)
\7 VY NS
95% OF ALL BEGINNER 175% OF ALL PYTHON 79% OF ALL 49% OF WINDOWS
‘CODERS START WITH. DEVELOPERS USE PROGRAMMERS 10 DEVELOPERS.
[AND STILL USE, PYTHON 3, WHEREAS USE PYTHON USE PYTHON 3
PYTHON AS THEIR 25% STILL USE THE REGULARLY, 21% USE [AS THEIR MAIN
PRIMARY OR OUTDATED PYTHON 2 ITASA SECONDARY PROGRAMMING
‘SECONDARY LANGUAGE. VERSION. LANGUAGE, LANGUAGE.
oe:WHAT IS
AVAXHOME?Se
Pee Cen uLey
De
See Cac
Ree cea
Unlimited satisfaction one low price
Cheap constant access to piping hot media
Protect your downloadings from Big brother
Safer, than torrent-trackers
18 years of seamless operation and our users' satisfaction
All languages
Brand new content
One site
AvaxHome - Your End Place
We have everything for all of your needs. Just open https://avxlive.icuZz 2 ) Welcome to Python
How to Set Up
Python in Windows
Wn ete Ie ec aria MNT una Ly
Look Celd ore NN Moree choo ae 1) TUNEL
Pee meee Mom Cea imcore Meee CU cece ef elt aie
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
san easy process to follow.
‘tart by opening your web rows to wanton
Sued ‘org/downloads/. Look For the button detailing the
ounloadink for bython 3. Python reglaty updated, changing
telat dg fr each bugfix and update. Tertere doit wary
Yousee Python 373, ormare along sits thon 3thecadeln
th ook wore
PSTD lick the download button for version 3x, and
save the fle to your Download folder. When the
Fleis dovinloaded, daublecckthe executable and the Python
installation wizard wil launch, From here you have two choices
Install Now and Customise installation, We recommene opting for
the Customise instalation link,
Install Python 3.7.0 (32-bit)
@
fe Siarmncsrona a
ED wwrnsdnputiationscom
Chovsingthe Cite option alow you to
OG ‘specify certain parameters, and whilst you may.
sayoithte deat ts goadhab ta apt ometnes it
wath oyton anu states can ude unwanted addons
features Onthe it ceen aves, ese al ove are hed
dodclek the New beton
~~
eo =
a
ESTED Te next page of options include some interesting
additions to Python. Ensure the Associate fle with
Python, Create Shortcuts, Add Python to Enviconment Variables,
recompile Standard Library and instal for All Users options are
ticked, These make using Python later much easier, lickinstall when
you're ready to continue,
J Aavanced Options
Optional Features
£
| ees
| puth :You may need to confirm the installation withthe
Bea
indows authentication notification, Simply cick
Yes and Python will begin instal. Once the installation is complete
the final Python wizard page wl allow you to view he ates release
rotes,and follow some onine tutorials.
Setup was successful
python
windows =
FID) cefore you close the instal wizard window
however, it’s best to ik onthe link next tothe
shield detailed Disable Path Length Limi. Ths wil allow Python
ta bypass the Windows 260 character limitation, enabli
execute Python programs stored in deep folders arranger
‘Again, lk Yes to authenticate the process then you can Close the
installation window
ose
STEP 7 zoo
ndows 10 users can now —
Findthe installed Python 4 Diepmnars
‘sx wathin the Stare button
Recently Added section ———
he first link, Python 3.7 :
(62-bit wil aunen che
command ine version of
Python when clicked (more
cnthat ina moment). To
‘open the IDLE, type IDLE
into Windows tart
“4 1
How to Set Up Python in Windows
ESTEEM licking onthe OLE (Python 3.7 32-bit lnk wil
launch the Python Shel, where youcan besin
your Python programming journey, Datt wary your version is
ewer as long ast’ Python 3.x ou code works inside you
Python 3 interface.
If you now click onthe Windows Start button again
SUEPD and this time type: CMD, you'll be presented with the
Command Prompt lnk, Click t ta get tothe Windows commandline
environment. To enter Python within the command ine, you need
totype: python and press Enter
FREED the command ine version of Python works in
‘much the same way asthe Shell you opened in
ep 8 note the three leftfacing arrows (22>).Whist t's perfectly
Fine environment, ts not too user friendly, so leave the command
line fornaw. Enter: exit to leave and close the Command
Prompt windowWelcome to Python
How to Set Up
Python in Linux
PYTHON PENGUIN
Linuxis 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.
otsouredtaacetanubicnvesiont thon TRIAS) Orcs ne upnte andupode competes tt
Sued is currently installed in your Linux system. To begin Sue python3. ==version again to see if Python 3.xis
vith, drop nto Terminal sessonfiom yourdstre'smen orhtthe update, or even nstaled. slong asyouave Python 3x youre
Cutest keys. funnin the mes recent major version the numbers after he 3.
inate patches plus urthe updates. ORen theyre unnecessary,
SeiddBaNRES I) bac they can conainvtal new elements.
Fle Edt View Search Terminal Help
Next enter: python’ =-version inthe Terminal
Sue ‘screen, You should have the output relating to
version 2.x of Python inthe display. Most Linux distro come with
both Python 2 and 3 by default, as there's plenty of code out there
stil avalabe or Python 2. Now enter pythons ~=verssien.
davidedavie-mint: ~
Fle Ect View Search Terminal Help
. TA aE] However, ifyou want the latest, cutting edge
ee iy ED ern souttncestobuid Pith rom source
eae ”y Startby entering these commands into the Terminak
ma! ‘sudo apt-get install build-essential checkinstall
sudo apt-get install Libreadline-gplv2-dev
7 a 5 * Vibncursesn5-dev libssl-dev Libsqlite3-dev tk-dev
FEED | our case we have bath Python 2 and installed, ‘Libgdbm-dev libc6-dev Libbz2-dev
As long as Python 32xxisinstalled, then the cade in
cur tutorials wilwork k's always worth checking to see f the distro
has been updated with the lates versions, enter sudo apt-get
update && sudo apt-get upgrade to updatethe syster
rides tine ~‘pen up your Linux web browser and goto the
SEE Python download page: https://www.python.org/
downloads Click onthe Dounioacs,Followee bythe button under
the Python Saurce window. This opens a download dialogue box,
choose a location, then sart the download proces,
@ python
ie bouton
Inthe Termin got the Dowload older
Gey byentering: ed DownLoads/. Then unzip the
Contersof the domloneaythonsource code with at 2
python-37-¥-tarnz ence the swith the ves umes
Youve dovnload, now ener the nev upped ole i
tython 3.7
Within the Python Folder, enter:
-/confgure
Sudo nake altinstall
his could take awhile, depending on the speed of your computer.
Once finished, enter python3.7 -version to check the latest
installed version. You now have Python 3.7 installed, alongside older
Python 3xx and Python 2
Ae
( How to Set Up Python in Linux
For the GUIDLE,you'need to enter the fallowing
Suz) ‘command into the Terminal:
sudo opt-get install iale3
‘The IDLE can then be started with the command: ide Note ha
IDLE runs a diferent version to the one you installed From source.
“tnisedvitn-/DominasPyban 3.72
PERRET DD Youll asoneed PP Pp installs Packages), which is
atoolto help you install moe modules and extras,
Enter: sudo apt-get install python3-pip
(nce PiPis installed, check Fr the atest update with
pip3 install
when compete, close the Terminal and Python 3.xwillbe avalable
athe Programming section inyour disto's menu,
upgrade pip
Installation of Python on macOS can be dane in much the
‘same way a the Windows instalation. Simply go tothe Python
‘webpage, hover your mouse pointer over the Downloads
Uinkand el
Mac 05X From the options. You will hen be
‘uidecto the Python relesres For Mac versions long with the
‘necessary installers For macs 64-bit For OS X 10.9 and aterPr
Python on the Pi
Aue Cun uM ie cticmiane enero aNear nee
thought to one of the best coding bases available: the Raspberry Pi. The Pi has many
Teel els (a col teers) el een el ey cen Me Recto ge LACUNA odo) om
THE POWER OF PI
While having a Far more powerful coding platform on which to write and test your code is ideal, t's not often Feasible. Most of
usare unable to jump into a several hundred-pound investment when we're starting off and this is where the Raspberry Pi can
help out.
PT ogee en ees
Pere Seger te are eae eed
es oer eee tar eae
Re Cees
The Raspberry Pisa Fantasticpiece of mader hardware that
has created, or rather re-created, the Fascination we once allhad
pet eerie ete
eee ee eee ec
Bee ey
ete ce en enn
Se een)
ee ea eee rete
Firmly pushed tothe Forefront. The Raspberry Pi uses Raspbian
eee Pee ee
Une 05, orto be more accurate it's a Debiabased distribution
Se re re nes
CE ute eed
Pre ee ie aca eS
Raspberry Pi Foundation has gone the extra mile toinclude vast
range of Python madules, extensions and even examples, ut of
eee ee ese
Follow the instructions on how to et one up (oy wing one of cur
Pete ee eee eee ans ee
Ceres ean ees arenes
ee erect ecertir cs)
Rees ee ese een
ores ee eee eer ery
eee eae neers
ee enn
ee een eee were a
Pe ee eet
Seater
‘Power socket anywhere in your house within range of your wireless
router, Aslong asthe Piis connected, you willbe abe to remotely
Se ere ete
Pate cheats
Using thismethod saves lat of money, as you dorit need another
eu ue ea tee oe)
Bee et eee ea ete)
Cee eee ce)
Peer nate reese ees
Peete et ere)
erate heme es ot ee gens
wall under desk while stil being able to connect tot and code,
‘The main advantage i, of course the extra content that the
Raspberry Pi Foundation has included out ofthe box. The reason
For thisis that the Raspberry P's goalis to help educate the
ser, whether thats coding electronics, or some other aspectof
Pte See Cn Lerner crs
IDEsFor the user to complie Python code on; a well as both Python
cee ere care eT
Penna
‘There are other advantages, suchas being ableto combine Python
Pee ee eee ea ars
Configure IDLE, an
clicking onthe Highlighting tab, However, we dont recommend that
Just enteritinto the ILE as you've donein the previous steps. as you won't be seeing the same a our screenshots
print¢*Hello everyone!”)
Thesaltlemoetiondneyaieninchced EERE witht sogans ani epi e
elem your First bit of code. The Print command is Fairly ue! ‘operating system, there are numerous shortcut
seenpunatos tps hogs ton Sreqresthepuetiess Keys we dst have oor for th alr, bute the Ops
aswell ac quotes inorder to autput content to the screen inthis > Configure IDLE and under the Keystab, youll see alist ofthe
casethe Hello everyone bit current bindings.
>>> _print(“Hello everyone
a everyone!
BETTER You'thave noticed the colourcoding within the PERBTD The Pithon ILE ea power interface, nd one
Python IDLE. The colours represent ifferent thav’s actualy been written in Python using one
elements of Python code. They are: cf the avalable CUItookits. you want to know the many ins and
cuts For the Shel, we recommend you take a Few moments to view
eta Darel Vere eae eee butps:/docs.ython.org/3/library/ile.html, which deta many of
Green-Strings Dark Red Comments Pa eIeaRee
Purple Functions ght Red—Error Messages
Orange — Commands fame
IDLE Colour Coding
oreen | ares | meee wort
eo
Cone
wmtineaicconon QEYour First Code
Essentially, you've already written your First piece of code with the print(“Hello
everyone!") Function from the previous tutorial. However, let's expand that and look at
PR Mec Cen Cnr Mh eau acai cui cs
D
PLAYING WITH PYTHON
‘As with 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.
EATER |" s0u've closed Python 3 IDLE, re-open itas you ESTESEDD You'tnotice that instead ofthe number 4, the
‘din the previous page. nthe Shell enter the ‘outputs the 2+2 you asked to be printed tothe
Familiar Fllowing screen. The quotation marks ae defining what's being outoutted
enone tothe DLE Shell to print the total of 2+2 youl need to remove
2 the quotes:
PITRE %s predicted, the word Hello appearsin the Shetl FTES) You can continue as such, printing 2+2, 46442343
as blue text indicating output froma string, t's and so onto the Shell An easier way sto usea
straightforward, and doesnt requretoo much explanation. _ variable, which something we will cverin more depth later. For
Now ty row, enter
woubampabiacenscom(_ Your First Code (2 mz
PRPEED what youhave donehere's assign thelettersa
and b twovalues:2 and 2. These are now variables,
‘hich can be calles upon by Python to autbut, ada, subtract, divide
‘and so on for as long as their sumbers stay the same, Ty this
printca)
printcb),
FED Now lets adda sumame:
surnane="Hayward”
printCsurnane)
\We now have two variables containing both a first nameand 3
surname, andwe can print them independently.
Te output ofthe stop pate crent
Bee values of a and b individually, as essentially you've
‘ed them to be printed separately you want toad the
You canuse the folowing
print(a+b)
Tis code takes the value of both aand b, adds them together, and
outputs the result
ie were to appythe same routine as before,
Sie using the + symbol, the name wouldn't appear
coneay inthe outatin te Sel Ty
printnanersurnane)
‘We need a space between the two, defining them as two separate
values and not something you mathematically play around with.
BETTER) You can play around with different kinds of variables
together with the Print function. For example, we
‘could assign variables for someone's name:
rame="Dovid”™
primtcnane)
BETTE 2 Psthon 3 we can separate the two variables
vith aspace by using commer
print(nane, surname)
‘Alternatively, you can ad the space yourself
print(nane+* “+surname)
As you can ee, the se ofthe comma is much neater.
Congratulation, you've ust taken your fst stes into the wide
world of Python,
vemebinpiationZz » Steps into Python )
Saving and Executing
Your Code
NUON a a esis eke eee cer)
eleenleceN Cem cole TuN eel Maen een Oinleore ec coney-a DE
Leelee Res emt ere Ree Reel kel
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 Ecltor will allow you to save and execute your Python code,
Fatepethe ron Steen toupck PETER Asyou cance te sane courcdogisnpacen
Sued ‘on File > New File, this will open a new window with SIEE tthe IDLE Editor as its in the Shell, enabling you to
Unttledas tame, Ths the Pthon DLE Eto, and vita you beter understanduhat going on wth your coe. To exeae the
canenterthe cde you need to create your fate programs code, however, youreed to rst sveit PressS andyoullhave a
Save, ..check box open,
ESTEE Te ILE Ecitorisforallintents and purposes,a ERTS) lick on the OK button inthe Save box, and select 2
simple text edtor with Python features, colour destination where youl'save al your Python code.
coding and so on. You enter code as you would within the Shell,so The destination canbe a dedicated folder called Python, or you can
taking an example From the previous tutorial, enter just dumpit wherever you ke, Remember to keep atidy filesystem,
poorest though itl hep you out inthe Future.
ED wwrnsdnpuiationscomEGER [tera name for your code, ‘prin hello for
‘example, and click onthe Save button. As soon
asthe Python codes saved, i's executed and the output willbe
etal in the IDLE Shel inthis case, the words Hello everyone!
TWisishow the vat maortyof our Python code
Bee will be conducted. Enter it into the Editor, hit FS,
save the code and cok atthe output nthe Shel Sometimes things
wil fe depending on wheter youve requested a separate
indo, tessa a's the proces and nes obherwe
Sate, thsisthe method we wl se
BETTER | you open the file location ofthe saved Python
code, youll notice that it ends in apy extension,
‘This is the default Python Flename, any code youcreate willbe
\whateverpy, and any code downloaded From the many Internat
Python resource sites wile py. ust ensue that the code is written
Fr Python 3
BSTETD eisextend the code and enter few examales
From the previous tutorial:
nz
bez
rane="David”
surnanes"Hayward”
printCnane, surname)
print Ca+b)
you press now, youllbe asked to save the fle again, asie’s been
‘maxified From before
Hyuk the Ox button thee wl be verurten
Sie with the new code entries, and executed; with the
cxtput inthe Shel snot problem wth jt eee Ves, ut
iF you were toed a larger ie averting can become anise,
Instead, use ile > Save As From within the Editor to create a backup,
[a pein ceercopetns
BSTTSET BD Now create anew file. close the Ector, and open
anewrinstance Fle > New File from the Shel.
Enter the following, and saveit as hello.py
‘-"Python”
boris”
"cool !*
print(a, b, ¢)
‘We willuse this cade inthe nex tutorial.
ere o™
oe;
Saving and Executing Your Code ClFirst Steps into Python
Executing Code From
the Command Line
COMMAND THE CODE
Using the code we created in the previous tutorial, the one we named hello.py, let's see how we can run code that was made in
the Guat the command line level.
Sie" routine automatically included all the necessary OE Python using the command python and pressing
components to allow the execution of code outside ofthe GU the Enter key. Thiswil put you into the command ine version ofthe
IDLE: in other words, the command ine. To begin with cick onthe Shel, withthe familar, three sghtfacing arcows asthe cursor (>>>),
Windows Start Button and type: end,
—
= =
EMER fi oninertrmeresut rom these he ala rede orevousysucas
rand Prompt Aon, Tissiluncho new window, whoa — ep
background and white text. This isthe command ne, ao called 3 2
erminal in macOS, Linux, and Raspberry Pl operating systems —
Asyou can see, works exactly the same,Nowenter exit©) to leave the command tine
Bea
Python session, and return backto the command
romp. Enter the folder where you saved the code from the
previous tutorial, and lst the avaiable files within; you should see
the hellopy fi
Pian Masicy koma
IF youive previously used Python 3 on a Maco Linux, and
bsequenty the RaspbertyP, you maybe a ttle confused as
towhy the Windows version of Python wsesthe command ine:
python instead of python
The feason behind this that UND Ike systems such as macOS
and Linux, already have Pthan iraries preinstalled. These older
branes are present because some ofthe macOSand Linuxsystem
sities ely on Python 2, and therefore instaling a newer version
‘oF Python, and thus aerng the executable name, could have dire
consequencesta te system,
‘ca recut developers decided thatthe best aparoach For macOS
and Linux ystems would be to leave the commas line python’
asexcusive Python 2 use, and newer versions of usrinstlled
Python would be python3
Executing Code from the Command Line
ESTEE) From withinthe same folderas the code youre going
torun enter the followinginto the commandline
python hetlo.py
This wll execute the code we created, which to remind you is:
="Python”
boris”
"cool!"
printca, b, ©
Tiss an issue with Windows, a i dese use any Python
laries other than the ones installed by the user th
wen actully instaling Python. When a Windows user installs
Pythan, the installation wizard wil auto-ncude the commang line
Instance tothe core Windaws PATH variable, which you can view by
entering path into the command tine, This points to the python.
‘exe file required to execute Python code from the commandline,
‘We don't recommend yauinstall both Python 2 and Python 3
within windows 10; natural, you canif you want, but realistically,
although Python 2stilhasaFootholdin the coding world, Python
3is the newest version. He 149, hen you wil ned to
Fenarne one ofthe Python versione nas as they will be installed
in iferen Folders and both use python.exe asthe
executable.’ litle long-winded, so unless there'sadre needto
have both versions of Python installed it’s best stick to Python 3.=> First Steps into Python)
Numbers and Expressions
Meee nee Esurance REL ars
like. Now let's expand on that, and see just how powerful Python is as a calculator. You
can work within the IDLE Shel, or in the Editor, whichever you like.
IT'S ALL MATHS, MAN
‘You can get some really impressive results from the mathematical powers of Python, as maths isthe driving force behind the
code with most, if nt all, programming languages.
EER O2er uothe cutversionofPython3, as mentioned FEM voucanuseal -
you can se ether the Shel or the Ecitor. For the thecustomary Se ES ony Opie Wind
time being, we're goingtouse the Shell. Fyou've opted to use 9 Mathematical operations: divide, PSS
third-party text editor note that youneedtogettothelDLE Shell multiply, brackets andso.on, pe sernianet, teeta" ox 11
Forthisparto the tora Practisewith afew, forexample: > *
&
eee ee eee Garay
FETED the shellenterthe folowing: BED ‘ever
eee Givsion producesadeciml | iber 7-9 Gs. oTaESOR
a number nPython hese are 2 ‘a
Caled lots orFenting pont ns
Asyoucansee, Python canhandle some quitelage numbers. arithmetic however you assesses
eed aninteger as opposed toa 2¢o%e2
>> #988726
seb sash —
we SS ea
cae 2S seas
andsoon :
sestonYou can also use
an operation to
see the remainder left over From
vision. For example:
vill display 3333333333, which
is, ofcourse, 3 3recurting, you
nowenter:
‘THis will cspla 1, whichis the
remainder leftover fram dicing
r0by3.
Nextupwe
SiGe ‘have the power
operator a exponentiation
you nant be techni
“oworkout the power of
something youcan wea
double maton smo
or doubestar onthe keyboard
Essentially, e's 24232, but we're
suteyou already know the
basics behind maths operators
‘This show you would workit
‘cut in Python,
ESTER) Numbers and
expressions don't
‘stop there, Python has numerous
bulla Functions to work out
sets of numbers, absolute values,
‘complex numbers, anda host of
Matheratical expressions and
Pythogarian tongueswisters. For
‘example, to convert a number to
binary, use:
TB ria
This willbe Draenor OF
See, eee
bit comerthatrenteger Sas
it biryani re ret
tbo the Font you woes
remove the Ob then ou
one :
format(3, ‘b?) :
‘he Ferma command carvers
abe he nbertoe
fematedrepresenation
as controlled by the format: sCiabttanananas
Specfavon tesa
Boolean Exessonis lage statement that wi
Sie either be true or false. We can use these to compare
data, and test to see fits equalto, less than or greater than. Try
a:
PERETD cxccute the code from Step, andyoulsee a
sees of True or False statements depending on
the resut ofthe two defining values: 6 and 7. I's an extension oF
‘what we've looked at, and an important part af programming.
a
wonbampabiatenscom
(~ Numbers and Expressions Cl=> First Steps into Python)
Using Comments
TIER ane Rk Cae ea rein
Pierre ine ey Un raeure oary
eo eta ete ecu iat ea iene alc
difficult to read.
#COMMENTS!
‘A method used by most programmers For keeping their code readable, is by commenting on certain sections. For example, if
‘variable is used, the programmer comments on what it’s supposed to do, It's just good practise
PEPER Wicltstarthy creating snewinstance ofthe oie BRB) resavethe code and execute it. Youllsee thatthe
Eeitor File» New File and then reste asimole cutputin the IDLE Shell stilthe same as before,
variable and print commman despite the extra lines being add. Sly put, the hash symbol
notes ine of text the programmer ean inst, infor them
NE and athers of what's going on, without the user Being aware.
Savethe le, and execute the code Bree
Se [Bpagag hese rsa sa rane re
LS Petpet Ope meer es
FETED Running the code witreturn the tne: The value of — PRTESIRIM Lets assume thatthe variable A we've crested is
As, 10intothe IDLE Shel window— which is what the numberof ivesin a game. Everytime the player
we expected. Now let's acd some ofthe types of comments you'd cis, the value decreases by 1. The programmer could insert 3
normally see within code: routine along the ines of
sestonC
(Using Comments Cl
FB hieweiroutacthe arti Adeiesnber EERESA) nine corms corer lov
wats of lives and the player has just lost one, 3 casual SEG section of code. Take our examples from above,
viewer orsomeonechecing tecoce,may not non magineford_ineeadofseeng tect ona separate nm, ve cI a
moment hat the codes twenty towsndineston,Psend ft
tirseen Youcansee whan comments
Bao >a x
Essent the new codetogeterwith comments The comment, the hash symbol canal be wed to
SiGe could look like: up ‘comment out sections of code you don’t want to be
executed inyour progam. For tance you vantedtoremove
# Set the start value of A to 10 Se ene
a the frst print statement, you would
# Print the current volue of A # print(*The value of A is,", a)
print(*The value of A is,", a)
4 Player lost a life! (B -Conmen py = CPython Code'Commentspy 570)"
omo-2
Fle Edt Fort Ran Optons Window Help
+
F Franc che current value of &
4 print ne value of A ae,", a]
# Payer tose a uate!
WTntorm player, and ateplay current of & (Lives)
"You've just toa a ite!)
ryou now haves, ay "ives Lefe!™)
PRPTSEDD You can use comments in ifferent ays For PEPET BD You aio use three single quotes to comment
‘example, Block Comments are alae section of ‘outa Block Comment, muitvine setion oF
text that details whats going on inthe code, suchas teling the cade comments. For ther to work, place them before and after the areas
reader which variables you'r planning on using youwant to comment:=> First Steps into Python)
Working with Variables
eee ES sacar ey tee ecm ec
Peo ast eco eMia air en resis
fete TTR LU RL
VARIOUS VARIABLES
‘We'llbe working with the Python 3 IDLE Shell inthis tutorial f you haven't already, open Python 3 or close down the previous
IDLE Shell to clear up any old code.
Ba
In some programming languages, you're required
touse adolarsignto denotea string, whichisa
‘arable made up of muluple characters, such as aname ofa person.
In Python this sn necessary, so, for example, nthe Shell enter:
rane="David Hayward? (use your ownname, unless you're also
«alled David Hayward)
Brann =a
‘As we've seen previously, variables can be
concatenated using the plus symbol between the
variable names. in our example, we can use: print (name + "2
*& tittle). The middle part between the quotations, allows.
us to adda colon and a space. As variables are connected without
spaces, we need toadd them manually
You can checkthe type of variable in use by suing
the type © command, placing the name of the
variable inside the brackets. our example, this would be:
‘type (name). Adda new string variable: ti tle="Descended
From Celts”.
ED wewbanpsstzacenscam
Wecanaso
within another variable. For iene
example, to combine both name
and title variables into anew
vatable, we use:
‘hen output the content ofthe
ew variable as:
print character)
Numbers are stored ascifferent
ii
Which, as we know, ae integers(Working with Variables Cl
PST However you cant combine both strings and
integer type variables in the same command as you
‘woulda set of simiar variables You need to tun one into the
‘ther, o vice versa. When you do tyte combine bth, youl get an
‘error message:
‘Alternatively, you can use:
print Character, “is*, age, “years old.")
Notice again thatin the last example, you dont need the spaces
between the words in quotes, as the commas treat each argument
toprint separately.
This presents abit ofa problem when you want
towork with a number that’s been inputted by
the user, for example, as age + 10isboth a string variable and an
integer, it won't work. Instead, you need to enter:
‘Thiswill Typecast the age string into an integer that can be
worked wth,
a
The wef ypeCsting ao imporant when
Sie dealing with Floating point arithmetic; remember:
umberstathaveadecnalpointinthem For rama, ent
Now enter type(shint) and youl se that Python has allocated
the number as float’, because the value contains a decimal pint.
a
BETTER) eather example of Typecastng is when you ask
Forinput from the user, such asa number. for
‘example, enter:
‘age input (“How old are you? “)
‘Alldata stored fom the Input command s stored asa string vaiable
BEET BD wen combining integers and oats Python
Usually converts the integer toa flat, but should
the reverse ever be applied, i's worth remembering that Python
doesnt return the enact value, When converting afloat to an
Integer, Python wil always round down tothe nearest integer,
talled truncating; in ourcase instead of 19.93, it becomes 18
a
os:=> t Steps into Python
User Input
MCR EC Ue olu Moreen ere MOR Reel MME Re Cue
earlier, so now would be a good time to Focus solely on how you get information from
the user, then store and present it,
USER FRIENDLY
‘The type of input you want from the user will depend greatly on the type of program you're coding. A game, for example, may
ask fora character's name, whereas a database can ask for personal details.
PEPID irs not already, open the Python 3 1OLE shell,
and stata New File nthe Edltor. Let's begin with
something really simple, enter:
Seer Cae saver ae)
BSED Nove that we have the user's name stored ina
couple of variables, we cn call them up whenever
we want
ay cnr ar =e
PTE Seve and execute the code, and, as you no doubt
suspected, nthe IDLE Shel the program il ask
for your fist name storing it asthe variable Firstname, followed by
‘yur surname; also stored its oun variable (surname).
ry
ED) -2erostcvoncon
FED eccrine ssi sane
ERD tesserae,
‘eetnnae tec nomar iron seem
wee7
(User Input (2 mm
BETTE You dor'talwayshave te include quotedtext within
the input command, For example, you canaskthe
userthetrname, andhave the input inthe line below
tet eatin et =a x
The code om the previous step isoten esarded
SIES ‘as being alittle neater than having a lengthy
‘amount of tet inthe input command, buti's nat arule that’s etn
‘stone, so do as you lke in these situations. Expanding onthe code,
tiythis
What you've created here sa condition, based on
the user'sinputn short, we're using the input
From the user and measuring it against a condition. Therefore, the
User enters David astheirname, the guard wil allow them to pass
Unhindered. however, they enter aname other than Davi, the
‘uard challenges them to aight.
Bea
Asyoulearned previous, any input om user
Sie is automatically a string, so you'll need to apply a
“ype inorder totum Rint something eke, Th creates some
Interesting addon to thet command. For exam
EATER AD 52 9000 startto a text adventure game, pethaps?
Now we can expand oni and use the raw input
from the user to Flesh outthe game a ite:
Ando nals the ate and distance code, we can ad
distance = floatCinput(*Distance: *))
Print(“Time:", (distance / rate))
Saye and execute the code, and enter some numbers. Using the
Float(input element, veve tld Python that anything enteredisa
Floating point umber rather than astring,
Bea
wmtineciccoson CI=> First Steps into Python)
Creating Functions
Now that you've mastered the use of variables and user input, the next step is to tackle
functions. You've already used a few Functions, such as the print command, but Python
races eka scatman trem
FUNKY FUNCTIONS
‘Afunction is a command that you enter into Python in order to do something It's little piece ofs
takes data, works on
Ba
‘and then returns the result.
1's not only data thata function works on. Functions
cando all manner of useful things in Python, suchas.
Sort data, change items from one Format to another, and check the
length or typeof items. Basically, Functionisa short word followed
bybrackets. For example, lend, list?) or typed)
Dyan a
‘You can pass variables through functions in much
the same manner, Le’ assume you want the
rhumber of lettersin a person's surname, you could use the Flowing
code (enterthe text editr fos ths example):
‘function takes data, usually 3 variable, works on
itdepending on what the Function is programmed
todo, and returns the end value, The data being worked on goes
inside the brackets, sof you wanted to know how many letters
aren the word antidsestabishmentararism, then you'd enter
‘enC*antidisestablishmentarianisa”), andthe number 28
would return,
ry
ED) -2erostcvoncon
fython hastens of uncon ulin eto
GUE) ‘many to get into in the limited space available here.
vowevestoview telat of bun function nb Python
43, navigate to https://docs.python.org/3/library/Functions.htmi,
“haere the predefined actions bt snes ets heve ceed
many mare Beye ot the ony ones aaaPSTESED *sitional functions canbe added to Python
through modules. Pyehon has avast ange of
‘modules 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
‘import math
Once entered, youll have access to allthe Math madule Functions:
FORGING FUNCTIONS
There are many different Functio
Creating Functions Cl
BETTE 10.use2 function froma module, enter the name of
the module, followed by aful stop, then the name
ofthe Function. Forinstance, using the math module, since we've
just imported into Python, we can utise the square root function,
mmath.sqrtC16)
A yau can se, the codes presented a= module. function (data).
created by other Python programmers, which you can import and you'll undoubtedly come
Pee ae e en Sn tte ten Cen eee)
PEI choose File> New File to enter the editor, et
pase ee cost ay
Fel lo)
Gee
STEP 2 isaatee
ae eet
Print CHetto™, nave)
ee eee eee ee
Sn ce ae
BED to mociy ic fur ee een la
Peers Petits
aoe
rn aren te ha
ce ets eee eh ey
aren
[cer oddca, b):)=> First Steps into Python)
Conditions and Loops
eon nee eer ue ee MS nee Ce Ceca
ee as Ute ut ea er mM ater cnn ere
Rivet satan ed Cer cates essence Toots on
TRUE CONDITIONS
Keeping conditions simple, to begin with, makes learning to program a more enjoyable experience
checking if something is TRUE, then doing something else ifit isnt.
BEER Letscreatea new Python program thatwilaskthe ETE Now weil use anifstatementto checkifthe word_
ser to input a word, then checkittosee i's a length varable is equal to Fou, and pint friendly
Fourletter word ornot. Start with Fle > New File, and begin with conformation iit applies tothe rule
the input variable:
FETED Now we cancreste anew variable, thenusethelen [PRT The colon atthe end off tells Python that this
Function and pass te word variable through itto statement i true, do everything ater the colon
‘get the total numberof letters the userhasjust entered that's indented. Next, move the cursor backto the beginning oF
the Editor
vee >a x
ssPRPEEM P1255 5 and save the code to executeit, Ente
afourletter word in the Shel to begin with, you
should havethe returned message thatthe words Four letters.
Now press FS again, and rerun the program, but thistime, enter a
Fiveletter word. The Shell wil display thatt’snot a fourletter word
LOOPS
Although a loop looks quite similar to a condition, they are somewhat dif
Conditions and Loops Cl
BETESTD Now expand the code ta include other conditions
Eventually it could become quite complex We've
added. condition for threeetter words
wordinput(*Please enter @ four-letter word: “)
‘ord_lengthelenCword)
if word length == 4:
print (word, “is @ four-letter nord. Well
done.”)
elif word_length == 3:
print (word, “is a three-letter word. Try again.”)
else:
print (word, “is not @ four-letter word.)
eee ee
same block of code a number of times, usually with the support of a condition,
eter
eet
mere
Pe unee estas
Peeer ee ear er ene ne
STEP 3 Hiden
eet!
ordseT "Cae "Doge
print Gnord)}
"Uni core
Ce
The
Sr ca
For x in range Ci, 10):
eed
irene eerie=> First Steps into Python
Python Modules
einen hare Mea ema ater ee eee uot ted
Pema eet ee chee edie ana ne tec et
alittle more time to them.
MASTERING MODULES
Think of modules as an extension that's imported into your Python code to enhance and extend its capabilites. There are
countless modules available, and as we've seen, you can even make your own,
Aiur gon het inceevihnp on EERE teresa erorine eso ate
oe?) are limited. The use of modules, however, allows us SUE? S) ‘Pygame module isn’t recognised or installed in
tomate mote sophteatedprogarns Asyousreoware modes, Pho, Total mode we canuse i PpinsalsPelaged
de thon sits tata mpared sch sinoor mah Close down the DLE shel ane dopo a commend promote
Terminal session, At an elevated admin command prompt, enter:
pip install pygane
Some modules, espedalyon the Raspberry are The PP instaaton requresan ee
Biee included by default; the Math module is a prime SUE
toitinstaling components a diferent locations
‘example. Sed, other modules aren't always avalable. A goed Stare with asearch For CMD, via the Start button, ight-click the
example on nan platforms isthe Pygame module, which contains result, and then click Run as Administrator. Linux and Mac users an
‘many functions to help create games. Try-import pygame. Use the Sudo command, with sudo pip install package.Python Modules
‘Pygane, the module willbe imported ino the code without any
problems. oul find that most code downloaded, or copied, From
the Internet will contain amodule, msinstream or unique, and their
absence is commonly the source of errors in execution
‘lose the command prompt or Terminal, nd re-
launch the ILE Shel. When you now enter import
&
‘The modules contain the extra code needed to
achieve a certain result within your own code, with
hich we've previously experimented. For example:
‘import random:
Brings inthe code From the Random number generator module. We
can then use this madule to create something Ike:
for i in range(to):
pprint(random.randint(1, 25))
ww
ESTEEM ultple modules can be imported within your code.
To extend our example, use
‘mort random
for I in rangeC5):
print(random.randint(1, 25))
rint(math. pi)
(a nny cheat
The results astring of random numbers followed
by the value of, as pulled from the math
‘madule using the print(math.i) function. You can also pullin
certain functions From a module by using the From and import
commands, suchas:
from randon import randint
for i in rangecs):
print(randint(1, 25))
oe
This code, when saved and executed, wil display ten
Siery random numbers from 1 to 25. Youcan play around
vith the code to display more or less, and from a greater or lesser
range. For example:
‘import random
for i in range(2s):
pprintCrandom.randint(1, 100))
This helps create a more streamlined approsch to
Sy programming, You can also use: import module*,
hich willimport everything defined within the named module.
However is often regarded as a waste of resources, butit works
onetheles. Finally, modules canbe imported as alases
‘import math as m
print(m.pi)
OF course, adding comments helps to tell others what's going on
es=> First Steps into Python)
Python Errors
Ieee Tes Cate ere eur mec RT
Event sc rics
not able to continue due to something being missed out, wron
CP oan aon cate nunca oh T acca
DEBUGGING
Errors in code are called bugs, they're perfectly normal and can often be easily rect
isto keep looking, experimenting, and testing. Eventually your code will be bug free.
Code ct as fluid a the written word,.no matter
how good the procramming language's. Python is
certainly easier than most languages, bt even tis prone to some
“annoying bugs. The most common are typos bythe user, and while
easy to find in simple dozertne code, imagine having to debug
‘mult-thousand tne code.
Ba
1d with a litle patience. The
‘Thankfully Python is helpful when it comes to
displaying error messages. when yourecelve an
error inredink from the IDLE Shel til define the error itself,
‘alongwith the line number where the error has occurred, While in
the IDLE Ector this alte daunting for lots of code, text editors
help by including tine numbering
Asie ve mentioned, the most common oF rors it
Biee the typo, often at the command level, mistyping the
pn commander example. However, the ale occ whee
‘ot numerous arable allof wich have lengthy names The est.
‘thceisto simply othvough the cade and checkyour speling
(Dremirone =e x
seston
PEPE Syntax rors are probably the second most
common erors you'll come across a programmer.
Evenif the spellings corcect, the actual command teal wrong, In
Python 3 ths often occurs when Python 2 syntaxes ae applied. The
‘mast annoying of these is the print Function In Pythan 3, we use
print words"), whereas Python2 uses print “words”
oineasvia =a x(_ Python Errors Cl
ATED Pes) brackets are also a culos of programming
‘errs, especially when you have something ke:
print(batanced_checkCinput©)))
Remember tat for every''there must be an equal numberof
There are thousand of online Python resources,
Bee code snippets, and lengthy discussions across
forumton how best to aleve something We 99% fk good
cose, dart ays be re inte copsng an pasting random
codeine your edt More ften than ot, won warkand
Trateatingy, you wont have earned aryhing
FRED csvset vores
from the Conditions and Loops section, where the colon means
everything indented Fellowing the statementisto be executed
along as t's true? Missing the indent or having too much oF an
indent, will come back with an errr,
Anexcellent way to check your code step-bystep is
touse Python Tutor's Visualse web page, Found at
‘wurw pythontutor.com/visvalizehtmlsmode=edit. Simply paste
your code into the editor and cick the Visualize Execution button to
run the code line-byine. Thishelp to ear bugs, andany
rmisunderstandings.
Planing mates fr good code, While te old
Sie ‘school, it's a good habit to plan what your code will
obefore sting down totypeteout Usk thevaribes that lle
Used, along with the modules, and write outa serpt for any user
Interaction o outputs,
PRPETBD Purely cut of interest, the word debuaging in
‘computing terms comes From Admiral Grace
Hopper, who, back inthe 0s, was working on a monolithic Harvard
Markl lectromechanical computer. According to legend, Hopper
Found a moth tuck n a relay, thus preventing the system from
working. Removal ofthe moth was hence called: debuosing,ZZ » Steps into Python )
Combining What
You Know So Far
NST A TM To ure Rol a ree CEL eo coke EA
looked at so Far and apply it to writing a piece of code. This code can then be used to
Resa ane eM aa usu n Ua
PLAYING WITH PI
For this example, we're going to create a program that will calculate the value of Pito a set number of decimal places; as
described by the user. It combines much of what we've learned, anda litle more.
BEER %2"tby opening Python and creating a New Fein
thatcan accurately calculate P without rendering the computer's
(CPU useless For several minutes. The recommended calculation
Lsedin such creumstancesis the Chudnovsky Algorithm, you
can find more information about at enwikipedia.org/wik/
(Chudnovsky_algorithm,
the Editor Fist, we need to get hold of an equation
‘We can utilise the Chudnovsky Algorithm to create
(ur own Python script based on te calculation.
\We'l begin by importing some important modules and Functions
within the modules
Bee
from decinal import Decimal, getcontext
‘import math
‘This uses the decimal and getcontext functions from the decimal
‘module, both of which deal with lage decal place numbers, and,
naturally, the math module
BRPED ow we can incertthe Pi calculation algorithm
pattof the code. This is aversion ofthe
CChudnovsky Algorithm:
ED -serostcvoncon
The preiosstep define the les that makeup
Siz both the algorithm and creating the string that
wi evetualy ply thevalve of according tothe Chudrovaly
brothers algo. syou have na doubt alead surmise,
would be hands tact autpt the value of ito the scree, To
recy that wean ad
printGcale(1))
aE You c27 save and execute the code at this pont if
you tke. The output wil print the value of Pito 27
decimal places: 3.181592653889734207668453591. hile pretty
impressive on its on, we want some user interaction to ask the
\seras to how many places Pishouid be calculated.
ESTED Wc can insertan input tine before the Pi calculation
Def command need to be an integer, ast wl
otherwise default toastring, We cancallit umberofdgits, and use
the getcontext function:
nunberofdigits = intCinput(“please enter the
runber of decimal place to calculate Pi to: “))
getcontext().prec = nunberofdigitsPSTTSERD Wiccan execute the code now, anditilaskthe user
tohow many decimal places they want to calculate
Pi,and then output the result inthe IDLE Shel. Try it with 1000
places, but dont go too high or else your computer will be locked up
freatedting
Partofprogenmingis
SEO being able to modify code,
making more preserabe ernie
dreomert tha tines ow ong tales
Conputrtocalesatethe dial pares
ond preset the hformatonin afferent
{Stour Forth chopintothe comand ire
soderpo the cea oe wee
aeadyhavet stated
pinnate
From decimal import Decimal, getcontext
import math
import time
import colorana
fron colorana import Fore
colorana.imit©
runberofdigits = intCinputC“please enter the nunber
Of decimal places to calculate Pi to: “))
getcontext().prec = nunberofdigits
start_time = tine. time)
ef cale(n):
Combining What You Know So Far Cl
BRPEED Now we nced to import the colorama module
(nhich wil output textin diferent colours), along
with the Fore Function (which cctates the Foreground, ink, colour,
and the time module to start a virtua stopwatch to see how long
‘ur ealeulations take:
import time
import colorana
from colorana inport Fore
= Decinal(a)
i = Decimal (a)
‘deno = Decina(@)
k=o
for k in range(n):
t = @ecimal(-1)**K)*(nath.
factorial Decimal (6)*K))*(13591409+545140134*K)
deno = rath. factorial(3*k)*(nath.
Factorial (k)**Decimal (3))*(640320**(3*K))
i 4= Decimal (t)/Decimal (deno)
pi = pi * Decimal (12)/
Decimal (640320**Decimal(1.5))
pi = pi
return str(pi)
print cale(1))
rintCFore.RED + “\nTine token:”, time.time() ~
start_time)Manipulating
DataData is everything. It’s more valuable
than gold or oil. With data, governments
can change the world, politicians can rise
or fall, and companies, large or small,
can impact our Future in ways we
wouldn't have imagined just a Few years
ago. Data is power, and learning how to
manipulate and control it are essential
aspects of any coding language.
Here we'll take a look at how you can
use date and time functions, write to
filesin your system, and even create
graphical user interfaces that will take
your coding skills to new levels and open
more doors for you.
sts
Tuple
Dictionarie:
and Time
9 File
toFile
Pyth
mbiniFE) Weritnoose
Lists
Lists are one of the most common types of data structures you will comes across in
Python. 4 list is simply a collection of items, or data if you prefer, which can be accessed
asa whole, or individually if wanted.
WORKING WITH LISTS.
Lists are extremely handy in Python. A list can be strings, integers, and also variables. You can even include Functions in iss,
‘and lists within lst.
Brea
Alistisa sequence of data values called tems. You
create the name of your ist followed by an equal
‘sign, then square brackets and the items separated by commas,
note that strings use quotes:
(Beuirone =
ERT Once youve defined your list. you can call each by
referencing its name folowed by number. ists
starthe fist tem entry a5 0, followed by 1, 2,3, and so on.
Forexample:
‘umber
‘ocalluptheentie contents of the Uist.
‘umbers[3]
“Tocallthe tem thie rom zero inthe list (21 inthis cas).
You can also access or index, the lastitem in alist by
Using the minus sign before the item number [-1], or
the second to las item with [2], and so on. Trying to reference an
Rem that isnt in thelist, such as [10] will rebum an error
FEEL Sicraissimiarto indexing, butyou can retrieve
‘multiple items ina ist by separating tem numbers
vith acolon.For examle:
‘willoutput 4 and 7, those beng item numbers 1 and2. Note that
the returned values don’ include the second index position (as you
‘would numbers{t:3] to return 4 7 and 21),Bea
You can update items within an existing list, remove
items, and evenjoin ists together, For example, to
Join two lists we can use:
‘everything = nunbers + mythical_creatures
‘Then view the combined lst with
PD tems canbe added toa list by entering
runbers=nunbers+[201)
OcForstrings
(Or by using the append function:
FE scr icn excite soe ntn is yer
BED veovcaneeee
tmowaierortee avatar ceos eta roe
Inserts the number 62 at tem index 4. Ane:
ill emove
FEAT) You alo use thelist function tobreak string down
Into its components. Fr example:
ListC*Devid")
Breaks the name David into'D,
toanewist:
1, V, 1, 'e This can then be passed
Siery is by the item number:
“The second, byitem name:
Removal ofitems can be done n two ways. The First
‘Based on that, we can create a program to store
someone'sname and age asalist:
“The combined name and age ist called user, which canbe called
byentering ser into the Shel. Experiment and see what you can do,
oeED) ov
Tuples
Tuples are virtually identical to lists, however, where lists can be updated, deleted,
or changed in some way, a tuple remains a constant. This is called immutable, and
pened une neek elo
THE IMMUTABLE TUPLE
Reasons for having tuples vary depending on what the program is intended to do. Mostly a tupleis reserved for something
‘special, but they/re also used, as an example, in an adventure game where non-playing character names are stored.
FSPTSEM 2 tule iscreatedthesame mayacalis, but inthis BRIER You can create grouped tuples int its that contain
Instance you use curved brackets instead of square multiple sets of data. For instance, here we havea
brackets For example: tuple called NPC (Non Playable Characters) containing the character
‘name, and their combat rating, for an adventure game:
Dineen =e | [Brmmivonn aaa
ries rd ws heencaon, a PR
Ea *Svithlists.theitemswithinanamestuplecenbe — EATER Each ofthese dota items canbe accessed asa whole
indexed according to their position in the data range: ‘by entering NPC into the Shell, or they can be
mieetnorse Coermminihcll econeonderbe
sorted Shaolin wtom eo
tase on Horr amy aang det rag toene NCIC
Sireinatereneset vie.’sworth noting that when referencing mutiple
tuples within ais, the indexing is ight different
From the norm. You would expect the 95 combatting ofthe
character Valeria to be NPC[a[], however its not, k's actually
wecr2]t1
cy
FID this means, of couse, thatthe indexing follows thus:
This, as you can imagine, gets little confusing when you have alot
of tuple data to deal with,
Now unpack the tuple into two
Bea
corresponding variables:
‘You can now check the values by entering name and combat_rating
cr
Remember, as witht, you can also index tuples
sing negative numbers, which count backwards
Fromthe end ofthe data. So, Fr our example, using the tuple with
multipe data items, we would reference the Valera character wit:
Nect2]¢-01
iB
BETTER) Terles though, utilse a feature called unpacking,
where the data items stored within a tuple are
‘assigned variables Fst, create the tuple with two ers (name and
‘combat rating)
we can vsethe max andmin fonctions to rhe
SuzMO highest and lowest values of a tuple composed of
rpumbers For example:
“The numbers canbe integers and floats. To output the highest and
lowest, use
rimtCnaxCnunbers))
Print(minCnunbers))
a
oe:ED) ov
70
Dictionaries
Lists are extremely useful, but dictionaries in Python are by Far the more technical way
of dealing with data items. Although they can be tricky to get to grips with at First,
Nem er ee ee cen ence
KEY PAIRS
‘A dictionary is tke a list, But instead each data item comes as a pair, the
{are known as Key and Value. The Key part must be
‘unique and can either be a number or string, but the Value can be any data item you like.
Brea
Lev'ssay you want to create a phonebook in Python.
You would create the dilonary name, and contain
the data in curt brackets, separating the key and value bya colon
Key: Value. For example:
789}
J
swine ts tunes, nd0 on tings need
Gue2 to be enclosed in quotes (single or double), while
itegrscanbe left epen Remerser tht these on De ee
‘ing or anitege you ist need tense he eleven one
owes
honebook2={“David": “0987 654 321"}
Bresso =a x
woubampabiacenscom
‘swith ss and tuples, you can checkthe contents
of adicionary by caling the icionary name;
phonebook, in this example. This will display the data tems youve
enteredin similar fashion toa lst, whichyyouire no doubt familar
with by now.
Doane x
The benefit of using a dctonarys that you
5
ceca eee ae
Phonebook exemple from the previous steps, we can enter:
Brenton 7‘Adding toa dctionarys easy too. You can include
Bea
‘anew data item entry by adding the new key and
valueitemsas such:
renin
‘nd you can also remove items from a dictionary
byissuing the del command followed bythe
IRem’skey-the value will aso be removed aswel since both
‘work as pair of data items:
oe
Next, we need to define the user inputs and
variables, one forthe person's name, the other
for their phone number (we wil keep it simple to avoid lengthy
Python code)
Note we've kept the number as an integer instead
(oF astring eventhough the value can be both
aninteger anda string, Now we need to ade the user's inputted
variables tothe newly created blank dictionary. Using the same
process asin Step 5, we can enter
Phonebook[nane] = nunber
Dice come
FER sacs ssntwes encour cesegs
ED eee ee
trannaousaronantine hero eceal
eaten cy
BETTE Now when we save and execute the code, Python
wil ask fora name and a number. wil then insert
those entries int the phonebook dictionary, which we can test by
entering nto the Shell:
Ifthe number needs to contain spaces youineedto makeita
string, so remove the int par-of the input.
wonbampabiatenscomManipulating Data
Splitting and
Joining Strings
When dealing with data in Python, especially from a user's input, you will undoubtedly
come across long sets of strings. A useful skill to learn, in Python programming, is being
able to split those long strings For better readability.
7
STRING THEORIES.
‘We've already looked at some list functions, using .nsert, remove, and .pop, but there are also functions that can be applied
tostrings.
FRB te main tool inthe string Function arsenalis split)
‘witht you'e able to split apart a string of data,
based on the argument within the brackets. Fr example, here's a
string with threeitems, each separated by a space:
Sr
Nowe’ tun the string into alist, and spitthe
contentaccordingy:
panes=text. split“)
‘And enter the name ofthe new lst, names, to see the three items,
Bem
woubampabiacenscom
Note thatthe text split part containsthe brackets,
quotes then a space followed by closing quotes
and brackets. The spaceisthe separator, indicating that each Uist
Item entry is separated by a space. Likewise, Sv (Comma Separated
\Value) content hasa comma, owe would se:
Bee
Be
We've previously seen how using aname, we can
Bea!
sola string into individual letters asa
“The returned values‘, v7, While it may seem aitle
‘seless under ordinary circumstances, it could be hand) for creating
aspeling game, For example
aFEE he coneseore stenoses
‘lphabet
‘This wil splay ‘abede' in the Shell
Ferm the name:
‘nane="". joinCname)
‘pane
‘we've joined the string back together and retained the lst called
name, passing Itthrough th join Function.
&
we canthetefore apply jinto the separated name
SiGe ‘we made in Step 4, combining the letters again to
C Splitting and Joining Strings Cl
‘swith the splltfuncton, the separator doesn't
havetto be a space it can also be a comma, ora Full
stop, or hyphen or whatever you tke:
Bea
5 Theres some teretog nctons youcan apoyo
up ‘a string, such as capitalize and title. For example:
‘titlesconan the cimmerian”
title.capitalizeQ
title CeO
a
‘good example of sing the jon functions when
you have list of words you want to combine into
‘asentence
Note the space between the quotes before the jon function (where
there were no quotesin Step 6 joi).
Te? 10
ERD secrete Meee
tpewaterscriortracencematienes
wmtinesicconon QIManipulating Data
Formatting Strings
As you work with data, creating lists, dictionaries, and objects you'll often want to print
eaten raha ses ear alo eeu
Meso Rel a a ane ee neon coe oes] 8 RU acid
STRING FORMATTING
‘Since Python 3, string Formatting has become a much neater process, using the format function combined with curly brackets.
‘This makes things easier to Follow and, as with most coding, there are other ways to do things but this ways recommended.
FSPEB the basic formatting in Python ito call each ED Wiccan, of course, also include integers into the mix:
variable nto the string using the cury brackets: potent
BSTIEED Remember oclosethe pinefunction with wosets EINEM) there are many cifferent waysto apply string
OF brackets, 2s you've encased the varabein one, formating. some are aie simple, aswe've shown
‘andthe print Functonin another. You can include multiple cases oF _youhere, and others can be significantly more complex. all
string frmatingin single pit Function: a x
EE te incinccrsitmonreuge: seve EREEPB) tec wenmesowsrutins te
EESD wiscercnsctow es ae Tree Sette oon tee
Tom mcnonnbetoen derbies sated wih eoeaieoreet ae ae
arguments asi converts the time tuple into a string For exemple,
to display the current day ofthe week we can use:
tinder aes ‘ime. strftime KA")
8 kage ye os (Doenane a
: ond 061 (06 me apse)
© coyotes 096 (0 Monday)
7 oyot yee 12026 eta dy)
© bape saings 0,1, 2 means tary eters OST
BED vserostcvonconNaturally this means you can incorporate various
Functions into your own code, such a5:
Bea
Note the last two entries, with SH and HIKM, as
{you can see, these ae the hours and minutes and as
the lst entry indicates entering them as GM doesnt display the
time carecly inthe Shell we can easy rectify this wath
‘ime. steftine 38")
@
(Date and Time Cl
‘example, taking the above code, we can alter itsightly by including
\We can also use the Time maduleto display the
amount o time taken fr an event to happen. For
The output wil look similar tothe screenshot below.
‘The timer Function needs tobe ether side oF the
input statement, as thats when the variable name f being created —
‘epending on havi long the user took taog in The length of time &
then displayed on the last ine ofthe code, asthe endtime variable.
Pod = x
‘This means you'te going to be abe to display ether
thecurene ime, orthe time when something
‘eccurted such asa user entering ther name. Try this code inthe Eto
‘Trytocextendit further toinclude day, month, year, and s0 on
BPE there's alot thatcan be done with the Time
rmadule, some of itis quite complex too such
aslsplaying the number of seconds since January 1st 1970. Fyou
‘ane to dill dawn Futher into the Time module, then inthe Shel,
enter-he1pCtime to display the curent Python version help ile
For the Time madule.
@
7Manipulating Data
Opening Files
ene u ican aN hemor Car)
eae ee lor in en Mat Me ene tical etter
Tne eos era h Cn eRe ot ti os
OPEN, READ AND WRITE
InPython, you create a file objec, similar to creating a variab
usualy categorised as text or binary.
Startby entering some textinto your system's
text editor. The text editor is preferable toa word
processor, 3s word processors incude background Formatting and
‘other elements. n our example, we have the poem The Cimmerian,
byRobert E Howard, and we've saved the leas poem.
You se the open Fnceonto pass the eins
Gie2 variable as an object. You can name the file object
anything yo tte, bt youve tall enon the ame oe
lortonof the text ieyos reopening
‘The eason fr the double slash (\)isbecause Python wil read this
_as Unicode Error, thinking you've entered: \U-Thisis Windows-only,
Lux and Mac worthave tis sue
Donnene :
seston
only you pass in the file using the open() Function. Files are
ESTED "you now enter poem into the Shell you wil get
some information regarding the tet file you'vejust
asked tobe opened, We can now use the poem variable to read the
contents ofthe Fle:
Note than a/nentryin the textrepresents 2 newline, as wehave
sed previous.
[a
Ifyou enter poem ead) a second time, you wil
notice tat the texthas been removed From the
file, You wil need to enter poeriopen("C:\\Users\\david\\
Docurtent's\\poem. txt”) again to recreate the ile, Thistime,
however, enter:
Now the /nenties ae removed in Favour of new tinesand
Feadabletext.
Demian 5Bea
Forexample:
oem.read(S)
Dispaysthe Fis Five characters, while entering;
oem.read(S)
‘llislay the next ve. Entering (1 wil display one character at
atime,
‘As with sts, tuples, dictionaries and soon, you're
able ta index individual characters ofthe text
&
poem.readlinec)
‘ll display the Fist ine ofthe text. And
poem.readlinec)
‘ll display the nest tne of text.
Similarly, you can dsplay one tine of text at atime by
{sing the readline Function. For example.
FEE cscs cstroecyncnsreieoe
BED sitccrecnaeiees
multiple tists, These canthen be stored as variable
‘We can also use the fr statement to read the lines
cof text backtous:
‘And, since hiss Python there are other ways to produce the
same output:
‘As you may suspect, you can pass the readtine()
Function into a variable, allowing youto calli again,
Letsimagine that you wanted to print the text
character at time, a5 would an old dot matiix
printer. We can use the Time madule mixed with what we've looked
there. Ty this:
oe:
(0 Cl
(Opening FilesManipulating Data
Writing to Files
Being able to read external files within Python is certainly handy, but writing to a file
can be even more useful. Using the write() Function, you're able to output the results
of a program to a file, which you can then use to read() back into Python, or as a text
Geert
WRITE AND CLOSE
“The write() Function is slightly more complex than read(). Along with the filename, you must also include an access mode that.
determines whether the file in question isin read or write mode.
Start by opening IDLE and enter the following
(ebviously entering your oun username location):
‘Thiscode wil create tent Fle, called text.btin write mode, using
the variable there's no fil ofthat name inthe locaton, it wl
‘create one. Fone already exis, iwll overmite so be careful
vein ox
wean nou totetexFlewng the wnte0
Guee function. This works opposite to read(), writing lines
instead of reading them Try this:
Note the 109, t's the numberof characters you've entered.
(Bet =a *
However, the actual text fief still blank (you can
check by opening itup) This is because you've
"urtten the line oF text tothe fle object, but not committed itto the
fle itsel Part ofthe write Functions that we needto commit the
changes tothe Fle, we can dothisby entering:
Hyourowopen the tex feithatet ear yout
see thatthe line you created has been writtento the
fle This gives us the Foundation Fo some interesting posses,
perhaps the creation of your own logfile, or even the begining oF
an adventure game,
SS Ry Sgar one te a a, hr 8Fe occa neces
ED ieee sen
sreewoticgn ie mest tesdetne
we can keep extending the text tne byline
SiGe ending each with a new line (\n). When you're
done, Finish the code wth tclose(),and open the filein text
‘editor ta see the results:
(writing to Files Cl
\We can pass variables toa file that we've created
In ython, Perhaps we want the value of Pito be
‘written toile, We can cal Pifrom the Math module, create anew
file, and pass the output of Pinto the new file:
|
Wie also need to create anew file to write Pi to
Now e's create a variable called pi, and assign itthe
value oF i
Remember to change you le location to your own particular
system setup,
&
FE re vcs iperottcesta coer
ED icc esses
rere sancti encore
Tenth we en vesting fomatingtoclthe
SuzMO variable and write it to the file, then commit the
changes and close the file:
‘Asyou can see from the results, you're able to passany variable to
afle,ED) ov
Exceptions
PON ee EI on ean a Ec eee ess cr
circumstances that are mostly out of your control. Let’s assume you aska user to divide
two numbers, and they try to divide by zero. This will create an error, and break your code.
EXCEPTIONAL OBJECTS
Rather than stop the flow of your code, Python includes exception objects, which handle unexpected errors in the code. We
‘can combat errors by creating conditions where exceptions may occur.
You can create an exception error by simply tying \We can use the Functions raise exception to create
todivide anumber by zero. This wil report back ‘our awn eror handling code within Python. Lets
‘ith the ZeraDivsiontrror: Division by zero message, as seen assume your code has you warping around the cosmos, to0 much,
the screenshot. The ZeroDiisionéiror parts the exception class, of however, results ina warp core breach Tostop the game from
hich there ae mary. exting ue t the warp core going supernova, we can create 3
——— asst exception:
5 Nostexeptons Tolzagarveorin theca we can erase the
ue are raised ue? potential error within a try: block. This block consists:
dutomataly when Pon oF ty excep can here ode heist nef eres
Conese samen tats sree ianenede odessa a
inert wrong with che cde.
fowevee wees ese curt, = sy
‘exceptions that are designed to
‘contain the potential ertor and
Feact tot, 35 opposedto letting
the code fall.Deornig Sinica *
lets assume you want to open afile and write to
ERT Fo" example, using the divide by zero error, we can
create an exception where the code can handle the
‘error without Python quitting due to the problem:
TED ¥0u can useexcentions to hance a variety of useful
tasks, Using an example from our previous tutorials,
(Exceptions Cl
ESTE i2tuclly, we can quickly Fixthe issue by changing
the read onl instance with a"w' for wte This,
asyoualready know, wil create the Fle and write the content then
‘ommitthe changes to the ie, The end result wil report aifferent
seto cumstances in this case, a successful execution of the code
5 You canals us aia back which woksina
up ‘Similar Fashion, but you cannot use else with it. Hint:
‘ound to delete the este ile om your folder.
being opened as read only (the “part. So inthis.
‘ase rather than Python teling us we're doing something wrong
we've created an exception, using the IOError clas, informing the
user that the permissions ae incorrect.
— = or
Obviously this wont work due to the fie textfiletxt
‘Asbeforeanerrorwilocau seve wed the
Sie read-only permission. IF we change itto a “w", then
the code will enecute without the eror being depayed inthe DLE
Shel. Nedless to say, it can bea tricky getting the exception code
right the first time. Practise though, and you will get the hang of i
ew
Base ms
wmiinesicconon CEManipulating Data
Python Graphics
RGR een insta eee eee ue ne ae aie
Rem eu se neces ee hia einte ne)
has numerous ways in which to include graphics, and they're surprisingly powerful too.
5
GOING GRAPHICAL
‘You can draw simple graphics, tines, squares and so on, or you can use one of the many Python modules available to bring out
some spectacular effects.
ne ofthe best graphical modules to begin learning
Python grapicsis Turtle. The Turtle module sas
the name suggests, based onthe turtle robots used in many schools
that canbe programmed to draw something ona large piece of
paper on the Floor. The Turtle madule can be Imported with:
Import tutte.
Let's beain by Grawing a simple circle. Start a New
SLED tren ever the folowing cove
‘import turtle
turtle. circle so)
‘turtle. getscreen()._root.nainloop)
‘As usual pres FS to save the code and execute It This wll open up
ew window and the Turtle’ wil draw circle.
woubampabiacenscom
The command trtecrle(S) i what draws the
circle on the sceen, with 50 being the size. You
«can play around withthe sizes i you tke, going upto 100, 150, and
beyond: you can draw an ar by entering tuntle-cincle(S0,
180), where the sizes 50, but ou'e telling Python to only draw
480° ofthecirce,
‘The ast part of the cicle code tes Python tokeeo
5
SeatdechesSescers ersten
remain open, sothe user can cco else it. Now let's make a square
‘You'l notice weve inserted loop to draw the sides ofthe square.PTET To add some colour we can addanewlineto the
square code
turtle.color¢“Red”)
‘And.we can even change the character to an actual turtle by entering
turtle. shopec“turtle")
‘we can aso use the command turtle begin Fill, andturtle.end_
Fill to filin the square with the chosen colours inthis ase, red
outline, and yellow il
PETTSTD) *syoucan see, the Turtle madule can draw out
some pretty good shapes, and become alittle more
complex, asyou begin to master the way it works. Enter this example:
from turtle import *
color¢‘red’, *yellow’)
begin ALIO |
while True:
formard(200)
ef EC170)
if abs(pos@) < 1:
break
end F110)
‘done
We'sacifferent method,
but very effective,
*
STEED iow let's get thecodeby importing the pygame module
import pygane
pygane. init
‘mg = pygae. mage, LoadC*RPi pro”)
white = (255, 255, 255)
w= 900
h= 450
screen = pygane. display.
set nodeCn, HD)
sereen.6UUCGohited)
screen.flL(Guhite))
screen: bLitCing, (0,09)
pygane display. AipC)
vile True:
FETED the oreviousstep we've imported pygame,
intated the pygame engine, and asked it to import
cur saved Raspberry Pilogo image, saved as RPpng, Next, we
efined the background colour a the window to dspay the image,
and the window size as per the actual image cimensions. Finally, we
have aloop to cose the window.
w= 900 |
h = 450
screen ~ pygame.display.set_mode((m, h))
screen. fill((nhite))
screen. fill((white))
screen.blit(ing, (0,0))
pygame. display. flip()
while Tru
for event in pygame-event.get():
if event.type == pygame. QUIT
pygame.quit()
FERED other way you can csplay oraphics iby using
the Pygame module, There are numerous ways in
‘hich pygame can help you output raphicsto the screen, but for
ow lets ook at displaying a pre-defined image. Start by opening 2
browser and finding an image, then saveitto the Flder where you
save your Python code.
as
u Bs Ei se
FRRBTDD ress FS to save and execute the code, and your
image willbe displayed in anew window. Have 8
play around with the colours, sizes and so on, and take time to look
‘Up the many Functions within the Pygame module to.
jaspberryPi
oe:
(_ Python Graphics ¢ aManipulating Data
Combining What
You Know So Far
CEE Too Rar AM Lo ee Mea es Lee ook a EI Reo AY Rn)
piece of code that can easily be applied into a real-world situation; or at the very least,
Puna R nek etReulueen ec ian eta ileus
LOGGING IN
For this example, let's look to apiece of code that will create user Logins then allow them to log nto the system, and write the
time at which they logged in, We can even include an option to quit the program by pressing 'q.
BED seroma merece cory EER te stat sateen spats
dw dedonytoharde te usnames one Yorble om onethatan be ced veut
passwordsandeningavatuletowrauatetnecertsauseh te code thsway ne can se the aut clement whut bng
Ee progan urged naae he funton weve ao efrencedsoe newly
detent ond ewer sch wel ge tore
BSED the news Functonisnext:
FED ex we need to define some functions. We can
begin with creating the main menu, to where, ater
selecting the avaiable options, all users will retum:
“Thiscreates anew user and password, and writes the entries nto 3
fle called logins txtED onc wee vin aeastermyuten
parecer recent
comnaly ome acorn welts rhe
user, to the existing users(} dictionary. Therefore, the key and value
Fetter ste eiemcce
Creal Shin = upuec
1 erenatogan in ws
FS atreaty eee)
Toguneapet hep tncinent/ loping. ty
pense “erent 8S Gdn
PIM ovr to create the olduser Function:
‘There's a fairbithanpening here. We have login
and pasow variables, which are then matched tothe
users dictionary IF theresa match, then we have a successfllogin
‘andthe time and date ofthe loginis outputted. If they don't match,
then we printan error, and the process starts again
and gan Stil ope seen on, came scene)
(Combining What You Know So Far < O mm
Finaly we eed to conta heck thatthe ey
hasn't been pressed to exi the program. We can do
Athousha seemingly minor wo lines the wile
SIEE loop is what keeps the program running. At the end
ef every funtion checked agate current salue of tu F
that olba lust then the program continues. F's eq
‘then te roar can aut.
while status
status
gn
mainMenu ()
You cannow crate users, and then login th
Suz their names and passwords, with the logins.txt
Flebeing cesta store the login dita and sce logins bing
timestamped, Now ts upto youto futher imprvethe code
Pernaps ou can mpot thei of created ses rom aprevous
seson and spon aaicesullgh, dep gph?VV ola AinYeRVlan Sena
Modules 2Working with Modules
Modules are where you can take Python
programming to new heights; they are
the key ingredients to better code. You
can create your own modules, or you can
use some of those already available, to
help convert a mundane piece of code
into something spectacular.
Want to see how to make better use of
these modules to adda little something
extra to your code? Then read on and
learn how they can be used to forge
Fantastic programs.
Using the=> Working with Modules )
/
Calendar Module
Beyond the Time module, the Calendar module can produce some interesting results
Rieu te ten anol Rer Ma cae enema Cates
time module-like Format, you can actually call up a wall-calendar type display.
WORKING WITH DATES
‘The Calendar modules built into Python 3. However, if, it’s not installed, you can add it using pip instal calendar, as 2
‘Windows administrator, or sudo pip install calendar for Linux and macOS.
ESTEE 2uncneython3 andenter: import calendarto RSTSEY
«al up the module andisinheretFuetons. Once
istoaded into memory, startby entering
‘There are numerous Functions, within the Calendar
‘module that may be of interest to you when
Forming your own code. For example, you can splay the number oF
sep=cal endar.TextCatendar calendar .SUNDAY), panels
sep.prmonth(2019, 9) eops=calendar.Lecpdays(1900, 2019)
— _ Print Cleaps)
Rar eka es ae eT ‘The result fs 29, starting From 1904 onward.
Fn fot Su Oy Cis Winton tp
ATES) You cansee that the days oF September 2019 are EBABY You could even Fashion that particular examole into
displayedina wall calendar fashion, Naturally you apiece of working, ser interactive Python code:
‘an change the 2019, 9 partofthe second ine to any year and
‘month you want, a birthday for example (1973, 6 The Fist ine
‘configures TextCalendar to start ts weeks ona Sunday; you can ont
For Monday if you prefer.
EE) -serostasoncon