100% (1) 100% found this document useful (1 vote) 1K views 194 pages The Ultimate Python Coding Manual, 5th Edition 2021
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
Go to previous items Go to next items
Save The Ultimate Python Coding Manual, 5th Edition 202... For Later The Ultimate
a
Coding Manual
Master Coding Skills @ Step-by-Step Guides (% Learn Python 3
>)
10
1
BR
S
Learn the latest
version of Python
Featuring Python
program listings
os
Packed with top
tips and tutorialsYat Black Dog Media
a Begi
Master Your Tech ) "peer
To continue learning more about your tech visit us at:
www.bdmpublications.com
FREE Tech (25)
—o
iphone
EXCLUSIVE Offers on
our Tech Guidebooks
© Print & digital editions
© Featuring the very latest updates
© Step-by-step tutorials and guides
© Created by BDM experts
Check out our latest titles today!
GuideBook
SPECIAL DEALS
and Bonus Content
Sign up to our monthly newsletter,
and get the latest updates, offers
and news from BDM. We are here
to help you Master Your Tech!
bdmpublications.com/ultimate-photoshop
Mega ieee earl tutorial
ute omc RedThe Ultimate
PYTHON
Coding Manual
The Only Python Manual You Need..
This manual aims to help you build a knowledge base around one of the best
programming languages available: Python. Python is a fantastic programming
language that has taken the world by storm. I's easy to use, powerful, useful,
and fun. It works with other programming languages, and with all the major
computer operating systems and platforms available today. It's the ideal choice
for entry-level programmers who want to learn a new skill, or simply want to
discover how they can create something on the computer that works for them,
and it's used by data scientists and engineers who demand complexity and power.
Within these pages are the essential tutorials that will help you progress through
the process of building your first piece of code, to tackling variables, numbers and
expressions, user input, Python modules, and building and manipulating lists of
data. Learning Python is great fun, so what are you waiting for? Let's get coding!Contents
Print (“The World of Code”
8 Being a Programmer
50
10 ABrief History of Coding eat
12 Choosing a Programming Language A
14 Creating a Coding Platform a
16 Using Virtual Machines ra
18 Equipment You will Need ra
2
eC a
e pees. ee
(Tinea.
Pras Co a re
ote laeerey 6s
6
Welcome to Python 70
n
22 Why Python? ™
24 What can You Do with Python? 16
26 Python in Numbers 7
28 — How to Set Up Python in Windows 80
30 How to Set Up Python in Linux 82
32 Python on the Pi 84
34 Getting to Know Python 86
went
Starting Python for the First Time
Your First Code
Saving and Executing Your Code
Executing Code from the Command Line
Numbers and Expressions
Using Comments
Working with Variables
User Input
Creating Functions
Conditions and Loops
Python Modules
Python Errors
‘Combining What You Know So Far
64
Manipulating Data
Lists.
Tuples
Dictionaries
Splitting and Joining Strings
Formatting Strings
Date and Time
Opening Files
Writing to Files,
Exceptions
Python Graphics
‘Combining What You Know So FarMey re MUM exe Cory
90
92
94
96
98
10
Calendar Module
0S Module
Using the Math Module
Random Module
Tkinter Module
10 Pygame Module
104 Basic Animation
106 Create Your Own Modules
Learning Linux
410 Whats Linux?
112 Why Linux?
114 Using the Filesystem
116 Listing and Moving Files
118 Creating and Deleting Files
120 Create and Remove Directories
122 Copying, Moving and Renaming Files
124 Using the Man Pages
126 Editing Text Files
128 Getting to Know Users
130. Ownership and Permissions
132 _ Useful System and Disk Commands
134 Managing Programs and Processes
136 Input, Qutput and Pipes
138 Fun Things to Do in the Terminal
140 More Fun Things to Do in the Terminal
142 Linux Tips and Tricks
144 Command Line Quick Reference
146 AZof Linux Commands
Contents
‘Master Python with the help of our fantastic Code
Repository, featuring code for games, tools and
150
152
154
155
156
157
158
159
160
162
164
165
166
168
170
m
m
174
178
180
182
186
188
190
192
More. See page 148 for more details.
Code Repository
Python File Manager
Number Guessing Game
Polygon Circles.
Random Number Generator
Random Password Generator
Keyboard Drawing Script
Pygame Text Examples
Google Search Script
Text to Binary Convertor
Text Adventure Script
‘Mouse Controlled Turtle
Python Alarm Clock
Vertically Scrolling Text
Python Digital Clock
Python Scrolling Ticker Script
Simple Python Calculator
Playing Music with the Winsound Module
Hangman Game Script
Coding Projects & Tips
Creating a Loading Screen
Text Animations
Tracking the ISS with Python
Using Text Files for Animation
Passing Variables to Python
Python Beginner's Mistakes
Glossary of Python Terms
wumubangubteaionscom (BiPaine Galas
World of Code")
oo
~ ;
< era ae
E ON
ee aN
3
.& »
o Bs ee :
vay 4 Nao
3 4 A < D
ck a us De
a m
73) As, x CS at
4 %
4
si “ OePrint (“The
Where to start learning how to code?
Remarkably, this is the most difficult
step. There are plenty of programming
languages out there, and a seemingly
unlimited number of tools to help you
achieve what you want; but where do
you begin?
In this section, we look at what you will
need to take those first tentative steps
into the world of coding. You won't
suddenly become a programmer in
twenty-four hours, learning how to code
properly takes time and patience. But
with a litle help, you can master the
basics and start your coding journey.
A Brief History of Coding
a Programming Language
irtual Machine
Equipment You will NePrint ("The World of Code") }
tz
Being a Programmer(Being a Programmer € »
MORE THAN CODE
For those of you old enough to remember the ‘8s, the golden era of home
‘computing, the world of computing was avery different sceneto howitis
today. 8-it computers that you could purchase asa whole, as opposed to
bing in kit orm and you having to solder the parts together, were the stufF
‘of dreams; and geting your hands on one was sheer bls contained within
a large plastic box. However, ie wasnt so much the new technology that
‘computers then offered, moreover it was te fat that forthe First time
ever, you could control what was being viewed on the ‘television’
Instead of simply playing one of the thousands of games available at the
Times have changed since programming in thes, time, many users decided they wanted to create their own content, thelr
but the core values stil remain, ‘wn games; or simply something that could help them with thelr homework
‘orhome finances. The simplicity ofthe &-bit home computer meant that
‘creating something from a few ines of BASIC code was achievable and so
“It’s up to you the first generation of home-bred programmer was born.
ie 2) a
Sores cea ctesoarenrrra heart
your coding {areone wh codon soreontesren nd maemo the
press of akey.
adventure!” Trays tes move on end wht the technology tot we
However, the Fundamentals of programming remain the same; but what
exactly doesit take to bea programmer?
The single most common trait of any programmer, regardless of what
they're doings the ability to see a lagical patter. By this we mean
someone who can logically follow something from start to finish and
teuisage the intended outcome. While you may not Feel you're sucha
person, its posible to train your brain into this way of thinking. Yes,
takes time but once you start to think n this particular way you wil be able
toconstruct and follow code,
Second to logis an understanding of mathematics. You don't have to be
ata genus level but you do need to understand the rudiments of maths.
‘Maths all about being able to solve a problem and code mostly fas under
the umbrella of mathematics
Being able to see the big picture is certainly beneficial for the modern
‘programmer. Undoubtedly, 35a programmer, you willbe part of a team
‘of other programmers, and more than tkely parcof an even bigger team
‘of designers, all of wham are creating final product. While you may only
be expected to create a small element ofthat Final product, being able to
‘understand what everyone else i doing wil help you create something
thats ultimately better than simply being locked in your own coding bie
Finally, there's also a level of creativity needed tobe a good programmer.
‘Again though, you don't need tobe a creative gens, st have the
imagination tobe able to see the end product and how the user wil interact
witht
‘Theres of course alot more involved being a programmer, including
learning the actual code itself. However, with time, patience and the
determination to learn, anyone can become a programmer. Whether
You want ta be part oF 3 triple-A video game team or simply create an
‘automated routine to make your computing life easier, it's upto you how
far to take your coding adventure!
———>4
@
PU Gteenpece ie |
eee aura te eRe UEC r cep crete al ele Rls
Poet een ine ein ead
etn MMe ae eect net ieee ue ne
RRC RR RCRD
eT | a)
1842-1843 1930-1950
Ce eres
mm terr
ree eee ene
eat eset
etree
Cea
pe ere
scholars who worked inthe House of
eens
Pere ieaeetcl
Ee eee
eee teers
eerie)
ee eensreo
res
ee ees
Seren
eae ed
rte eed
Re ay
eeu
Cees
Sau
pee eet
ee
Us
eos
Ce eee
eens
peers
ener
Perr
eerteee eerie
Bee ee uri toon
Exeeeniee!
From the 1970s the development ofthe tkes oF SQL Cwith
Classes (Crs), MATLAB, Common Lisp and more came tothe
fore. The’80s was undoubtedly the golden age ofthe home
compute atime when siicon processors were cheap enough for
‘ordinary folkto buy. Thisled to boom in home/bedroom coders
with therise of bit machines.
oS
eee ‘e
the development of BASIC AE ascaiO me
(Beginners All-purpose 3 #4
the mid-sixties.
‘Adeital Grace Hopper was part oF
ee er ero aay
Coeur cs
eet eee ad
Deemer inane
Rese eres
Cee eens
Co ea
the team that developed the UNIVAC
computer and she eventually
‘developed a compiler Frit. time,
the compiler she developed beca
COBOL (Common Business-oriented
Language), a computer language that’s
stillin use today,
nr
Cee «1Choosing a
Programming
Language
Sel TM lotess 91 Lod ces
SCCM eu tcIny
PE oanieeroe Canetti
and ways in which to ‘talk’ to a computer
or device and set it instructions are being
Parole le ae lL Ad
eee RM Mr
ee ot eee Leo
Pelincedatucictcouiale tie
ET Renn OMAK
context. select
onl one.nan
elect
TOR CLASSES
anehae
7 a Eee aac es
ect 5 ee ee orl
(American National Standards Institut) standard, there are different versions of
the SQL language. However, tobe compliant, they all support atleast the major
Poomeeets eer tea ess etc Lester rate
aCe ae JavaScript (often shortened to JS) isa lightweight,
ee ese rer uted
Functions JavaScript runs onthe client side ofthe web, that can be used to design
SE nee tre cet
_an easy to learn and also powerful scripting language, widely used For controlling
Sod
Pe Onn en gee)
Se eee eee eee
based content, games and mobile apps. The two main components ofthe Java
platform are the Java Application Programming Interface (AP) andthe Java Virtual
"Machine JVM) that translates Java code into machine language.
eee eee eer ces
bull a variety of secure and robust applications that run on the NET
Framework. You can use CH to create Windows client applications, XML Web
ee eee ee ere
eee ete ere eae
ota
ara Pythonisa widely used high eve programming lanavage used
ee ee Tae)
Pees eee eet
philosophy that emphasises code readablity and syntax that allows programmers
ieee ner renee ae een
Boas
oom cot ery ec auae)
language. thas imperative, object-oriented and generic programming
ace
See ied
Deere oss
iepeley ee ocean end
‘Matsumato, blended part of his Favourite languages (ert
Seer iano sie ee
Ruby has drawn devoted coders worldwide, Ruby is een 35a exible language,
CeCe ee eae ea Loca?
pret.
cca Cee ee eu ea eer oe ed
range of tasks including system administration, web development,
network programming, Gul development and more. ts major Features are that’s
Berar et ty Coca (neues
powerfulbuiltn support for text processing and has one of the most impressive
earners
ES eg Ore ges
eee en EN ener
the syntax is concise yet expressive and Swift includes modern features that
developers love. Swift code is sae by design, yet aso produces software that runs
Pee eet recta!
————Print ("The World of Code")
Creating a
Coding Platform
HARDWARE
‘Access tothe internets necessary to dawnload, install and
update the cacing development environment, alongside
computer wit indows 10, macOS, o Linux installed.
YYoucan use other operating systems, butthese are the ‘big
et and you wll Find that m sources are written
with one, oral of these in ming
Coding canbe one oft
Perera eae ee ener
Soyer
eee eer
reer te) rer
Peres
Internet and discover that t
eae
pee
ree
language in Perens
nee teen ae ic
Rec re ene a ee ta
Into coding Like all good projects, you need a sol
et te ee eee ee:
available to hand to enable you to complete the basisteps. This
Peter ate tet
rao
Peay re
SOFTWARE
ntermsof software,
smostof the development
‘evonments:thetocs
hatalow youto code
compile the code and
executelt-aefrely avaiable to dovmioadandinstal. There
are some specialist tals avaiable that wl coat, buat this lvel
hey re not necessary; so dort be adledint thinking you ned ta
purchase ary exrasoftwarein ore to start leaming how to code.
(Overtime, you may ind yourself changing from the mainstream,
development environment nd using collection of your enn,
cdscovered, tools to write your code in. t'sall personal preFerence
eithe end and as you become more experienced, you wil stat
touuse diferent tok to get thejob done, Sore environments
willenhance sections of code, making esse to read others wil
mplng and execution ’sallamatter of testingwindows 10% the most
sed operating system in
OPERATING SYSTEMS.
the world, s0its natural
thatthe vast majority oF
coding toois are written for Microsoft's leading operating
system. However, don't discount macOS and especialy Linux,
J macOS users enjoy an equal number of coding tools to their
‘windows counterparts. In Fact, you wil probably ind that a
locof professional caders use Mac over aPC, simply because
ofthe fact that the Mac operating system is built on top oF
Unix (the commandine OS that powers much ofthe world’s
E lesystems and servers). This Unix layer lets you test programs
in almost any language without using a specialised IDE,
Linux however isby far one of the mast popular and
important, coding operating systems avaliable. Notonly
4 does t have Unictke backbone, but i's aso free to
download, install and use and comes with most ofthe tools
necessary to start leaning howto code. Linux powers most of
the serversthat make up the Internet's used on nearly all oF
the top supercomputers, as wells speccallyin organisations
suchas NASA, CERN and the military andi forms the base oF
Android powered devices, mart TVs and in-carsystems. Linux,
153 coding platform, isan excellent ides anditcan be installed
inside a virtual machine without ever affecting the instalation
(OF Windows ar macOS,
‘THE RASPBERRY PI
\fyouhver'talready heard
ofthe Raspberry, then
we suggest you head aver
{to wwnwcaspberrypi.org, and
4 checkitout. In short, the Rasoberry
4 Piisasmall fully functional computer that comes with its own
| customised Linncbased operating system, preinstalled with
| everything youneedto start eaming howto codein Python,
(Ces, Scratch and moc.
Isincredbly cheap costing around €35 and allows youtoutise
Ediferent hardware, the form of robotics nd electronics
projects, as wells offering acomplete desktop experience,
Altheugh not the most powerful computing devcein the wor,
the Raspberry Phas alot going Frit, espedalyin terms of being
‘one ofthe best cocing platforms avaiable.
YOUR OWN CODING PLATFORM
Whichever method you choose, eemember that your coding
platform wll probably change, as you gain experience and Favour
‘ne language over another. Dont be afraid to experiment along
the way, as you will eventually create your own unique platform
thatcan handle all the code you enter ina.
4 Avitualmachine isa pece of software that allows youto installa
2 Theadvantage ofavitual
4} machineisthatyoucan work
} allthe Functionality of Linux while stl beng able touse Windows.
dedicated toa particular taskin a fraction ofthe time
VIRTUAL MACHINES
fully working, operating stem within the confinesof the software
‘elf The installed OS wilallocate userdefined resources Fromthe
host computer, providing memory, hard dvespace eas wellas
sharing the host computer's intemet connection.
with Linux, Forexample, without
{eaffecing your curently
‘rstaled host 0S. This means
thatyoucanhave Windows 10
‘unnig, launch your vitual machine cert, Bootinto Unuxand use
This ofcourse, makes it fantastic cading platform, as you can
have oifferent instalations of operating systems running fom
the host computer while using offerent coding languages.
You can test your code withaut Fear of breaking your host OS.
and it’s easy to return to a previous configuration without the
‘eed to reinstall everything again
Virwalistion s the key to most big companies now. You wil
probably ind, For exemple, rather than having asingle server
with an installation of Windows Serve, the IT team have
instead opted Fora vetuaised environment whereby each
Windows Server instance is a vitual machine cunning From
several powerful machines. This cuts down on the number
‘oF piel machines allows the team to better manage
‘resources and enables them to deploy an entire server
MINIX NEO N42C-4
‘TheNEON#2C4 kan extraordinary
smal computer fom mini-PC developer,
‘MINOX. Measuring just 139 138.x30mm, thisntelN4200 CPU
powered, windows 10 ro preinstalled computers one ofthe
best coding platforms we've come across.
‘The beauty ofcourse lesinthe fect that with increased storage
and memory avaiable, you're able to create a computer that cn
‘easly host mubipl vital machines, The vitual machines can
cover Linux, Android and other operating systems alowing you
‘towrteand test oss platform code without fear of damaging,
‘or causing problems with other production or home computers.
‘The MINDKNEOIN42C-4 stats at around £250, wth the base
32GB eMMEC and 4G8 of memory. Youll need to add another
hundred and fifty, ors, to increase the specications, but
consider tata icense for Windows 10 Pro alone costs £219
from the Microsoft Store andyou can begin to see the benefits}
‘oF opting fora more impressive hardware foundation over the
likes oF the Raspberry.
wwbmpubeaonscom
Creating a Coding Platform 4HZz ) Print (“The World of Code’ )
Using Virtual Machines
PTV aE nee Se UE
Oe al ae mC ted Peat cs eecu MDE ete Cen
isolated environment. In short, it’s an ideal way to code
Sounds good, but what exactly isa Virtual Machine and how
does it work?
The official definition ofa virtual machine isan efficient, isolated
upliate of a eal computer machine’. This basically means that 3
virtual machine san emulated computer system that can operate in
exactly the same way as a physical machine, but within the coofines
of dedicated vitual machine operator, or Hyperisr.
The Hypervsoritsel, js an app that wil allow youtoinstalla
Separate operating system, creating a virtual computer system
vith itself complet with access t the Intecnet, your home
retwark and on,
The Hypervsor wil take resources from the host system -your
physical computer, ta crate the virtual computer. This means that
partof your physical computers: memory, CPU hard drive space
and other shared resources, willbe setaside For use inthe virtual
‘machine and therefore won't be available tothe physical computer
Lunt the hypervisor as been closed down.
This resource overhead
‘canbe crippling for the
physical machineif you
‘dont already have enough
memory, or hard rive
space avilable, or your
‘computer hasa particularly
slow processor While is
entirely possible torun
virtual machines ona ite
13268 of memory, tno
‘adhisabe. deal, you wil
need a minimum of 82
‘of memory (you can get
‘away with 4B, but again,
‘your physical computer
wil begin to suffer with
the lass of memary tothe
virtual machine), atleast 25
Deel
Coding for
Linux
ur Linux itles contain ta 8068 of Free space on
stepson how toinstalla_yourhard drve and a quac-
hypervisor and 0 cove processor (again, ou
can havea dual-core CPU,
but that cn cause a bottleneck on your physical computer)
The imi to how many different virtual machines you host on your
physical computers restricted, therefore, by the amount of physical,
"System resources you can allocate to each, while stil leaving enough
for your physical computer to operate on
pararro wa
You're abe to install Linux, and code inside a virtual
machine ona Windows 1Ohost.
VIRTUAL OS
From within a hypervisor you're able to runa number of different
‘operating systems, The type of OS depends greatly onthe
hypervisor you're running, as some are better a emulating 2
patticular system over others, For example, VitwalRox, a free and
easytouse hypervisor from Oracles great at running Windows
and Linux viral machines, but isn’t so good at Android or macOS,
QEMUs goad For emulating ARM processors, therefore ideal For
‘Android and such, but itcan be officl to master.
There are plenty of hypervisors available tory for free, with an
equal amount commercialy available that are significantly more
powerful and offer better Features. However, for mast users, both
bbeoinner and professional, vttualBox does a good enough jb.
‘Within a hypervisor, you're able to set up and install any ofthe
newer distributions of Linux, orf you feel the need, youre aso able
tonstall some ofthe more antiquated versions. You can instal early
versions of windows, even as Far back as Windows 3 complete with
(DOS 6.22 ~ although you may ing some Functionality ofthe VM ost
Cueto the older drivers (uch as access tothe networ
\With tis ia mind then, you're able to have an installation of Linux
"Minor che ates version of Ubuntu, running inan app on your
\Windows 10 PC. This the beauty of using a virtual machine
Conversely, i your physical comouter has Linux. ts installed
‘operating system, then with ahypervsor you're able to create 3
Windows 10 vital machine although you will ned to have a
licence code avaible to register and activate Windows 10.Using virtual machines removes the nee to dua-boot. Duak booting
shaving two, oF more, physical operating systems installed on
«he same, or multiple, hard drives ona single computer. As the
‘computer powers up, you're gven the option to choose which OS
you want to boot ito, While this sounds like a more idea scenario
sn aluays as straight forward as ie sounds, as all the operating
systems that are booted into wil have Fullaccess to the computer's
entice system resources
‘The problems with dual-booting come when one ofthe operating
systemsis updated, Most updates cover secunty patching, or bug
ning, however, some updates cn alter the core -thekernel, of
the 05. when these changes are applied, the update mayalter the
way inhi the OS stats up, meaning the initial boot choice you
made could be overwritten, leaving you without the ability to access
th other operating systems installed on the computer. To rectify
his, youll need to access the Master Boot Record and alter the
configuration to reallow booting into the other systems. There's
aso the danger of possibly overwriting the Fist istlled 0S, or
‘overwriting data and more oftenthan not, mast operating systems
don play well when cunning sde-bysde. Indeed, while good, dua:
booting has more than its far shar of problems. ncontrast, using a
vietual machine environment, tile stil problematic at times, takes
‘ut some ofthe mre nasty and dsastraus aspects of using multiple
‘operating systems ona single computer.
Scere ee ere
ewes
Virtual machines can be as simple, or as complex a5 Your
needs require.
(_ Using Virtual Machines G4
ADVANTAGES FOR CODERS
For the coder, having a virtual machine setup offers many
advantages, the most popular being cross-platform code. Meaning if
you write code within Windows 10, then with an installation of
Linux astro ina hypervisor, you're able to quickly and effortlessly
Power up the reual machine and test your code na completely
{ferent operating system. From this you'e able toiron aut any
bugs, tweak the code soit works better ona diferent platform and
‘expand the reach of your code to non Windows users
‘The advantage of being able to configure a development
environment, specific ways or spect projects s quite
invaluable. Using a virtual machine setup greatly reduces the
‘uncertainties that ar inherent to having multiple versions oF
programming languages, ibraris, IDEs and modules installed to
support the mary diferent projects you may become involved in as
acoder. Elements of code that ‘talk’ directly to specifics ofan
‘operating system can easly be overcome, without the need to
utter up your mai, host system with cross platform braves,
\ihich in turn may have an affect. on other libraries within the IDE.
Another element to consider is stability I you'e witing cade that
could potentially cause some instability tothe care OS during ts
development phase, ten executing and testing that code ona
virtual machine makes more sense than testing iton your main
computer; where having to repeatedly reboot, o reset something
duetothecode’s =
instabilities, can
become
inefficient and
Just pain
annoying
The virtual
machine
environment can
beviewedasa
sandbox, where
youre able to test
Unstable code
without it causing harm, or doing damage, to your main, working
computer. Viruses and malware canbe isolated within the VM
without infecting the main computer, you're able to set up
anonymity Internet use within the VM and you're able to install
third party software without it slowing down your main computer
Coding in Python on the Raspberry
Pi Desktop OSinside a VM on
Windows 10!
GOING VIRTUAL
While you're atthe early stages of coding, using a vitual machine
‘may seema ite excessive. However, it's worth looking into because
coding in Liu can often be easier than coding in Windows, as some
versions of Linux have IDEs pre-installed. ither way, virtualisation of
an operating system is how many of the professional and successful
‘coders and developers work, so geting used toi eary on in your
skill set is edvantageous,
To start look atinstaling VirtualBox. Then consider taking a look
at our Linux titles, https//odmpublications.com/?s-linuxBpost_
typesproduct, to learn how to install Linuxin a virtual environment
and how best toutlise the operating system,
wrebdrbaerscon@) Print ("The World of Code”) )
Equipment You
Will Need
aoe TRA AR ROM ESL Cold
dor't need an incredibly powerful computer and any software that's required is
freely available.
WHAT WE'RE USING
Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linux, Raspberry Pi and more. IF
you have one of those systems, then you can easily start using Python,
[| COMPUTER
Obviously you're going to need a computer inorderto lean howto program in
Python and to test your code. You can use Windows rom XP onward) on ether a 32,
or 6#-bit processor an Apple Mac or Linuxinstalled PC.
[] AN IDE
'An IDE (Integrated Developer Environment is usedto enter and execute Python
code. Itenables you to inspect your program code and the values within the code, as
well 5 offering advanced Features. There are many different IDEs available, so fing
the one that works For you and gives the best results
PYTHON SOFTWARE
‘macOS and Linuxalready come with Python preinstalled as pat of the operating
‘system as does the Raspberry Pl However, you need to ensure that youre running
the latest version of Python. Windows users need te download and install Python,
which well cover shorty
|_| TEXT EDITOR
‘Whista tex editors anideal envrorment to enter code int, it's nt an absolute
necessity, Youcan enter and execute cade directly From the IDLE but a text editor,
such as Sublime Text or Notepad, offers more advanced features and colour coding
when entering code,
[_] INTERNET ACCESS
Pythonisan ever evolving environment and as such new versions often introduce
new concepts or change existing commands and code structure to make ita more
efficient language. Having access to the ncernet will keep you up-to-date, help you
jot when you get stuck and give access to Python's immense numberof modules,
|_| TIME AND PATIENCE
Despite what other books may ead youto bebeve. you writ become a programmer
in24hours Learning to code in Python takes time, and patience. You may become
stuck atimes and other timesthe code wl flow lie water Understand youre leaning
‘something entirely new, and you wil get there.
vmbignnscon( Equipment You Will Need G4
THE RASPBERRY PI
\Why use a Raspberry P? The Raspberry Pisa tiny computer that's very cheap to purchase, but offers the usera fantastic learning
platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many modules and extras
RASPBERRY PI
‘The Raspberry 4 Model Bs the latest version,
incorporating 2 more powrerful CPU, achoice of 168,
2.68 oF 4GB memory versions and WiFi and Bluetooth
support You can pick up a Pifrom around £33, increasing
up to £54 for the aGB memory version, or as apart oF kt
for €50+, depending on the kt you're interested in,
= FUZE PROJECT
The FUZE isa learning environment builton the atest model
ofthe Raspbery Pi, You can purchase the workstations that
comewith an eletroniskt and even arobot arm For you
tell and program. You can Find more information onthe
FUZE at wwnFuze.co.uk,
BOOKS
‘Wwe have several great Raspberry P titles avallable via www,
‘bdmpublications.com, Our Pi books cover how to buy your
RASPBIAN
‘The Raspbery Ps main operating systems a Debian based
Linux cstrioution that comes with everthing you need in
‘simple to use package Its streamlined for the Piandis an
ideal platform for haroware and software projects, Python
programming and even asa desktop computer.
Fist Raspberry,
setit up and use
itthere are some great step
bystep project examples
and guides to get the most
from the
Raspberry
Pitoo,
wrebdrbeersconWelcome
to Python
aWelcome to Python
Python isa 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 companiesin the world, it’s also
one of the easiest to learn.
This chapter will help you get Python set
up on your computer, and introduce you to
this remarkable and powerful language.
y Python?
What can You D
Python in Numbers
How to Set Up Python in V
How to Set Up Python in Linux
Python on the Pi
jetting
wm bampublcatenscomWhy Python?
PCr isc ieee ents ie em rane
EI Ronee eon uck secu tcteio eS iutaa ted etl
are designed For scientific work, others For mobile platforms and such. So why choose
Prarattee ttn
PYTHON POWER
Ever since the earliest home computers were available, enthusiasts, users and professionals have tolled away untilthe wee
hours, slaving over an overheating heap of circuitry to create something akin to magic.
“These plonee's of programming carved thelr way into anew Regardless of whether you use an Android device, iOS device, PC,
Fron forging smal routines that enabled theletter'® toscroll Mac, Linux, Smart TV, games console, MP3 player, GS device builtin
across the screen. It may not sound teribly exciting toa generation to aca, set-top box orathousand other connected and smart’
that’s used to ultrahigh definition graphics and open world, mult appliances, behind them alls programming
player online gaming, Homevey,Fortysomething years ago twas
binginglybeitant. ‘Allthose aforementioned digtal devices needinstrucionsto tell
them what to do, and allow them tobe interacted with. These
"Naturally these bedroom caders helped form the Foundations For instructions Form the pragramnming core of the device and that core
every piece of cial technology we use today. Some went onto canbe built using a variety of programming languages.
bbecome chief developers for top software companies, whereas
others pushed the avalabe hardware tos limits and founded the The languagesin use today differ depending onthe situation, the
billion pound gaming empire that continually amazes us. platform, the device's use and how the device willinteract with its
rid seraycertsschiLaLestFocual)
i
ittcurgor >= 0)
Relrtehgor(cursor}:
certTrchitaostrocest:
vid srrayeerL:cpaint(Ora w) (
‘tbanePaine™
‘ge see = esize(0;
fel ieee eectentoeere i rested
ast er ae a,
TPCT seta attend flo colm.cntonnt() - 11) = 0)
iy
STEEL cxtcaunt(d) (
TjecenteseyGl «by
SilrPeop S stze sy) beaks
fibotton = F'top t cetanscyta):
ortint 32 jas < cola cetcoupe(): 364) ¢
{at Rasher Saevabangeh
= header 7ab(j)-cattarsin():
Attar signed) Treenvironment or users. Operating systems, such as Windows, macOS
and such are usually combination of C++, Ci, assembly and some
Form oF vsual-based language. Games generally use C++ whilst web
pages can use a plethora of avaliable languages suchas HTML, Java,
Python and 0 on
More generat purpose programming is used to create programs,
apps, software or whatever else you want to cal them. They're
widely used across all hardware platforms and suit vitually every
conceivable application. Some operate Faster than others and some
areeasierto lear and use than others. Python sane such general
purpose language.
Python s what's known asa High-Level Language in that talks
tothe hardware and operating system using variety of arays,
variables, objects, arithmetic subroutines, loops and countless
‘mare inceractons. Whilst’ nots streamlined as a Low-Level
Language which can deal directly with memory addresses, call,
stacks and registers, tsbenefits that’s universally accessible
and easytoleam,
Tee ava fava
pore java langereflect.*;
ase anole
aie teretSefe vod matnc string (2 args 9 {
"hikes c = class. fornane( arge(0) );
tethod's = cagetnethout angel}, mw class
Ge) 3s
Syect tee
nefnyoke( nul, tT 93
tees ees sey
LTE mcd
eek ERED 5
TT Glass torkanel 5 cane Hid the class
» lee forimet 3, i
da incase
1 Leak et titan 2
Heer ee es Saad ena
oe : exception of ) {
HE amoqattomargetecpcion
ch zona omarion tt La.
CE d
+ args{i
sree):
S)sten.oue.princIn¢
wetshetnode threw an: “+ 04
getvargetexception( *)
}
z
Javaisa powerful
language that's used
web pages, set-top boxes,
‘TWeand even cars
Why Pythor C4
Python was created over twenty sixyears ago and has evolved to
‘become an ideal beginners language for learning how to program 3
computer. I's perfect forthe hobbyist, enthusiast, student, teacher
and those who simply need to create ther own unique interaction
betwen either themselves or apiece of external hardware andthe
computer itself
Pythons Free to download, install and use and is avalable or Linux,
Windows, macOS, MS-D05, 05/2, 20S, IBM series machines, and
even RISC, thas been voted one ofthe top Five programming
languages in the world and i continually evolving ahead of the
hardware and internet development curve.
So to answerthe question: why Python? simply put, t's Free, e25/to
learn, exceptionally powerful universally accepted, effective and a
superb learning and educational tool.
BASIC was once the starter language that early
‘Sit home computer users learned.
Python sa more modem take on BASIC, t's easy to learn
‘and makes or an deal beginner's programming language.
————ry
What can You
Do with Python?
Python is an open-source, object-oriented programming language that’s simple to
intel Tele Tue ae ale AWM ced el it ene sk uu Cle Cd
eT feeder ago Met sekeclalel Cle] Tel Nod
ie eee
Ce ene ret
Cee era ee ny
eee ees
mr rare se
reer recente
ee ae eis
Pe ere ea erent
‘coding word, that require more efficient code, stil use Python.
ee ee ed
and 952 bridge between other programming languages. This way,
De eee ee steerer ety
CC ert neon
Ce erase
Oe Mn as
a eee eal ree
© ES
Tey
Big data isa buzzword youre Ukely to have comeacrossin the last couple of years
Basically, it means extremely large deta sets that are avaliable for analysisto reveal
patterns, trends and interactions between humans, society and technology. OF course,
eerie Cte ons
one eee eee eee epee eens
error!
eee eee eae ea eee teers
ent ee eee ese acute)
‘on whatthe user/company requires fom the wealth of numbers present. Thankstoan
Dee eer a eee
et eee ena aie ene)
Peers crore
eres ee ee ee een cee’
Sa ete ee)
clusters For example, CERN uses a custom Python module to help analyse the 600 milion
Pepe eaten nett eter near
Dee ere ence crew en ead
‘they want without the needto leam afar more complex programming language
peatedPure a aancel-y ce
Poi m lay
ee ee eres
Coe nee tay
Cees oe een sere ei
or eee
aero
pooner eee iin
ees
Ronan eee
tare aie ea!
Found ina variety of day-to-day computing applications here
eee ta
eee ur ater
the inputs likely to require, or do, next.
ee ene eee ker Rc
Instagram and so on. Have you eve laoked up a celebrity on
Instagram and then discovered that your searches within other
Pen eee eer eed
ee re ue ae er
targeted advertising and behind the code an algorithms that
Breiner elas
td too mary triple ra
Python you may be sured to lean tha Py
many othe hghanking moder
Se eeu)
athe tings o analyse yourmustal habtsand =
Pee settee
inthe past lesalldever stuff and, moving
aetna
Renseoeeeinenmare ti i
Wrereaisteg cs
‘Web development has moved on considerably since the early
days of HTML scripting nalimited text eltor. The many.
Frameworks and web management services available now
‘means that building a page has become increasingly complex.
are Python compatible and you wl
uld any mad for games such as The Sms
nine, MMORPGs (Massively Mtiolayer Olin
ne] avaiable tise Python as.a companion Irguage
he servers elem
cheating oa
cnatchmaking an
matches the ser
‘with Python, the web developer has the ably to create
_dynamicand highly secure web apps, enabling interaction with
‘other web services and apps such as Instagram and Pnterest.
Python also allows the collection of data from other websites
Eater a acca
a i Tala PYTHON EVERYWHERE
Pe Ez psvou tn sa, Pxthon sat avesatte
o Poe eeanreant ined :
eee eee eta
See ets
computing, cither professionally or simply as
Bess
Cee ee
eee emt ed
rst
eez= Welcome to Python
There’sa
lot to like about
Python; butdon'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.
ri 2
& re
Alea, Amazons Vitul Dat nays and
Personal scat, ses Machine Learing ae the
thon tohelp with two most used Python
seech recognition oxamples.
jai) seeeee . 7
Deceaen
PYTHON.AND
et LINUX SKILLS
ARE THE THIRD
‘Seranwen hemos MOST POPULAR inishendernan sofware
Aiacussed language on LT. SKILLS IN tooperate between other
the internet “THEUK. sreohis pocages
f.N
saaaWnne
%
“ayy
oven 75%0F 0% OF AL irs esrmareo
RECOMMENDED raceBoox Posts THAT ovER 3% OF
CONTENT PRON NETFLIX RE PLTERED NASAS WORKFLOW
IS GENERATED PROM THROUGH PYTHON: ‘AUTOMATION
MACHINE LEARNING CODED MACHINE sysTEns ON-BOARD
coord BY PYTHON EARNING. THELSS. USE PYTHON.
BE) vs seroitctoncn16,000
PETTITT
sttitit
‘There are over 16,000 Python jobs
posted every six months in the UK.
G
Google's the top
Python Data Science's
thoughtto become the
most sought-after job in
the coming years.
developers, closely
‘company fer hiring Python
followed by Microsoft.
(Python in Numbers 4
PYTHON SKILL-BASED
POSITIONS ARE THE
6th:
MOST SOUGHT-AFTER
JOBS IN THE UK.
real
¢
&
—
Data Science, Blockchain New Yorkand san
‘and Machine Learning Francisco are the top
are the Fastest growing Python developer cities
Python coding skills inthe world
Python developers enjoy an average salary of
= £60,000
SeO@
9596 OF ALL BEGINNER, 175% OF ALL PYTHON, 79% OF ALL 149% OF WINDOWS.
‘CODERS START WITH DEVELOPERS USE PROGRAMMERS 10 DEVELOPERS.
‘AND STILLUSE, PYTHON 3, WHEREAS USE PYTHON USE PYTHON 3
PYTHON AS THEIR 25% STILL USE THE REGULARLY, 21% USE AS THEIR MAIN
>RIMARY OR ‘OUTDATED PYTHON 2 ITASA SECONDARY PROGRAMMING
SECONDARY LANGUAGE. VERSION, LANGUAGE. LANGUAGE,
a@) Welcome to Python)
How to Set Up
Python in Windows
Windows users can easily install the latest version of Python via the main Python
Dee yee aed entteee it eee eM eee ar
platform of choice for building their code, it’s still an ideal starting point for beginners.
INSTALLING PYTHON 3.X
Microsoft Windows doesn't come with Python preinstalled as standard, so you're going to have to install it yourself manually
Thankfully, it's an easy process to Follow.
Startby opening your web browser tow pthon
ue org/downloads/. Look for the button detailing the
unload ink or thon 3 Pythons regularly updited, changing
telat tor eachbugfixand update. Therefore, don"twory
youseePythan’.73, more aslongasivsPython 3 the codeln
ths book wl work ne
FETESED Choosing the customise option allows youto
speaiy certain parameters, and whist you may
stay with the defaults, tsa good habit to adopt as sometimes (not
vith 2ython, thankfully installers can include unwanted adcitional
Features. On the frst screen avalable, ensure al boxes are ticked
and clickthe Next button,
‘Optional Features
Clete downoad button for veson 3 and
STER2) ‘save the file to your Downloads Folder. When the
fel dounloaded,doublacekthe exectable andthe Python
instalation wizard willaunch. rom hee you have two choices:
intallNow adCast talon We recommend opting fo
the Caste talon ike
31.
32-bit)
pathy Brat wera ne
wf Styne
The next page of options nude some interesting
euem) additions to Python. Ensure the Associate file with
Python, Create hott, Ad Python to Enter Variabes,
recom Standard brary and tal a Uses options are
ticked. These mate ung Python ater much eave Cicklntal when
youre readyto continue
Advanced Options
windows we (ors a‘windows authentication notification Simply click launch the Python Shel where you an begin
Yes and Python willbeginto install Once the installations complete your Python programming journey. Don’t wory I your version is
the final Python wizard page wilallow you to view the atest elease newer aslongasit’s Python 3x our code works inside your
notes, and follow some online tutorials Python 3 interface
Pes... | =
before youclsetheinstal wierd window, ERED reece ewnsorestcnizensgn
SIEEC) however, it's best to click on the link next | and this time type: CMD, you'll be presented with the
shelddetated DablePath Length Umit Miswilalow yon CommandPrompt lnk lek Rt getto the Windows command ne
tobypas the Window: 260 character Umitaton enbingyouto environment. To enter Python wn the command ine, au need
‘xecute Python programs stored in deep folders arrangements. __tolype- python ane press nce
Aga, cle esto authenticate the process then you can losethe
instalation window
© Disable path length limit
eo BEER cornensts eon peronvorsn
a sruch te same way as the Shel you opened in
Step 8;note the three lefe-facing arrows (>>). whilst’ a perfectly
Fine environment, t's nat too user-friendly, so leave the command
line for now. Ente: exit) to leave and cose the Cornmand
indows 10 users can now
Find the installed Pythor
3.xwithin the Start button
4 Birien 70
Recently Added section, ose Prompe window,
The fist lnk, Python 3.7
(G2-bi wl aunch the =
command ine version of
Python when clicked (more
‘on that in amamert), To
‘open the IDLE, ype IDLE
into Windows sat,Welcome to Python
How to Set Up
Python in Linux
PYTHON PENGUIN
Linuxis such a versatile operating system that t's often difficult to nail down just one-way of doing something. Different
distributions go about installing software in different ways, oor this particular tutorial we will stick to Linux Mint.
Fist youneedtoascerain which veeson of thon (nce the update and upgrade competes eter:
ual 's currently installed in your Linux system. To begin sue) python3 --version again to see if Python 3.xis
wth, drapiotoa Terminal session romyour vos menu, ochtthe updated or even nal Aslong at youRave Python 3x youre
Chivalry turning te mos recent major vero, the numbers ater the 3
indicate patches plus futher updates. Often theyre unnecessary,
davidedavid-mint:~ but they can contain vital new elements,
FR eect terstn ote ema
both Python 2 and 3 by default, as there's plenty of code out there
still avalable for Python 2. Now enter: python3. =-version,
davidedavie-mine:~
Fle Edt View Search Terminal_Help
a a
Fae eoe BREED Vere toronorce ates ctingese
ee SED son yov'tnced to bul Python rom source.
Mi) Startby entering these cornmands into the Terminal
sudo apt-get install build-essenttal. checkinstall
So aptaget install ibreodLine-optv2-cev
ann scenester [GpneurseshSedey Uibssledev Tibsglited-dey tkédev
Inoucasewehavebothfython2and3instales. Ltbgdbnedew LibeG-dev Libb2-dev
Sues ‘As long as Python 3.x.is installed, then the code in
ur tutorials i work ts ays worth hecng tose the dso
hasbeen updntediththe ate versions, ete sudo apt-get
update 88 sudo apt-get upgrade to upeaetheytem
vidodovidin:-
‘wseumpubictionscom
You might also like The Python Bible 7 in 1 Volumes One To Seven (Beginner, Intermediate, Data Science, Machine Learning, Finance, Neural Networks, Computer Vision) by Dedov, Florian PDF
The Python Bible 7 in 1 Volumes One To Seven (Beginner, Intermediate, Data Science, Machine Learning, Finance, Neural Networks, Computer Vision) by Dedov, Florian
537 pages