Python 3| Raspberry Pi| Linux
Coding for
Pyt
Master Python and expand your
programming skills
Packed with © LearnPython3 ® Code games,
top tips and and apply it to real Teal ta (oeie Le)
fav iKeyer) hy world programs TNtC@an nel)Discover more of our complete
manuals on Readly today...
The Complete
© The Complete
Ubuntu
_Manual
& TheCompkte
MacBook
Manuali Black Doc h Se
Codin
Pyt
Unlock the Power of Python
Python is a fluid, easy to learn, powerful and creative programming
language that has fast become one of the most popular coding languages
available. It’s used by students, experienced programmers, scientists,
engineers, teachers and enthusiasts the world over. There's a huge
community of Python users who are willing to help, share and create
incredible code and projects, Now it's your chance to join them.
Coding for Python has been expertly crafted to help you learn this
amazing language. Within these pages you can discover how to get
started, how to write Python code and how to create your own unique
code For everyday use.
Whether you're looking to learn Python for future career prospects or just
have some fun and discover something new, our step-by-step tutorials
and guides give you that much needed foothold to help you on your way.
Let’s dive in then, and start learning Python.
FD cvdmputs FJ 20m pusications:
ontents
Coding for Python
ee lletaiatyy e
8 whyPython?
10 Equipment You Will Need
12 Getting to Know Python
14 Howto Set Up Python in Windows
16 Howto Set Up Pythen on a Mac
18 Howto Set Up Python inLinux
20 installing e Text Editor
Pee he
24 Starting Python for the First Time
26 Your First Code
28 Saving and Executing Your Code
Executing Code fromm the Command Line
32 Numbers and Expressions
34 Using Comments
36 Working with Variables
38 User input
40 Creating Functions
42° Conditionsand Loops
44 Python Modules
46 Python Errors
48. Combining What You Know So Far
50) Working with Data
52 Lists
54 Tuples
56 Dictionaries
58 Splitting and Joining Strings
60 Formatting Strings
62 Dateand Tine
64 Opening Files
66 Writing to Files
68 Exceptions
70 Python Graphics
72 Combining What You Know So Far
76 Calendar Module
78 OSModule
80 Random Module
82 Tkinter Module
84 Pygame Module
88 Using the Math Module
90 Create Your Own Modules
aT US Seri cola
94 Python ile Manager
96 Number Guessing Game
98 Polygon circles
99 Random Number Generator
100 Random Password Generator
401 Keyboard Drawing Script
402. Pygame Text Examples
103 Google Search Script
104 Text to Binary Convertor
106 Basic GUI File Browser108 Mouse Controlled Turtle 130 Listing and Moving Files
109 Python Alarm Clock 132 Creating and Deleting Files
110 Vertically Scrolling Text 134 Create and Remove Directories
112. Python Digital Clock 136 Copying, Moving and Renaming Files
114 Pygame Music Player 138 Using the Man Pages
415 Python Image Slideshow Script 440 Fditing Text Files
116 Playing Musicwith the Winsound Module 142 _Gottingto Know Users
148 Text Adventure Script 144 Ownership and Permissions
420. Python Scrolling Ticker Script 146 Useful system and Disk Commands
121. Simple Python Calculator 148 _ Managing Programs anc Processes
122 _ Hangman Game Script 150 Input, Output and Pipes
152__Fun Thingsto Do in the Terminal
154 More Fun Things to Dain the Terminal
156 Linux Tips and Tricks
126 What is Linux? 158 AZof Linux Commands
128 Using the Filesystem 160 Glossary of Python Terms
Rear ode a eniam
Say Hello r
to Pythonsay Hello to Python Cl
There are many different programming
languages available to learn and use.
Some are extremely complex and
incredibly powerful and some are very
basicand used as minor utilities For the
‘operating system. Python sits somewhere
in the middle, combining ease of use
witha generous helping of power,
which lets the user create all sorts, from
minor utilities to excellent games and
performance-heavy computational tasks.
There's more to Python than simply being
another programming language though.
Ithasa vibrant and lively community
behind it that shares knowledge, code
and project ideas, as well as bug fixes
For Future releases; it’s thanks to this,
‘community that the language has grown
and thrived. Now, it’s your turn to take
the plunge and learn how to program
in Python.
This book will help you get started with
the latest version of Python. From there
it. guides you through using some of the
most common and interesting Functions
and features of the language. Before
long, you will be able to code your own
helpful systems tools and text adventures
and even control a character as they
move around the screen.
& why Python?
10 Equipment You will Need
12 Getting to Know Python
14 How to Set Up Python in Windows
16 Howto Set Up Python on aM
18 How to Set Up Python in Linux
20 Installing a Text EditorWhy Python?
There are many different programming languages available for the modern computer,
Pier ENE nciemat teen hasan tices ckiay alent etc
are designed for scientific work, others For mobile platforms and such. So why choose
Python out of all the rest?
PYTHON POWER
Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee
hours, staving aver an overheating heap of circuitry to create something akin to magic.
‘These pionee's f programming carved their way intoa new
Frantier,Farging smal routines thac enabled the lester to scrol
axrousthasereen. may net sound verily exciting 26.2 generation
‘hats used to ultra high-lefinitian graphics anc qpen world, mult
player online gaming, However, Fortysomnetning yeersago ie was
blindingly brillant.
Regardless of whether you use an Android device, iOS device, PC,
ac, Linux,Smarc TV, games console, MP3 player, CPS device busin
oa ear, set top box ora thousand ather connected and ‘smart
nallances, behind tiem alls pregramming
‘Allthose aforementioned digital devices need instructions to tel,
hein what Lodo, ane allow thern to be interacted with. These
“instructions form the proarariming care of the device anc thet core
Naturally nese bedroom coders helned Form che Foundations For
‘every piece of digtal technology we use today. Some went en to
become chief developers for top software companies vehereas
aathers pushed the avilable hardware to ts limits anc Founded the
biion pound garning emavre that conc nually amazesus.
ccanibe bul using variety of programming languaaes.
“The languages in use today differ depending on the situation the
slatform, the device's use and now the device wiliateract with Is,
cxrtssettasotrecied
asia
oid srrayctrl::childbostFecus()
i
ifteursor == 0)
efreshine cursor)
ceTehsidtacteacest}
i= es
ere (RF Pie scram ceeinaars
eet ieee cue
gra Shaw Pedi s arty
Staaf mcman ee
Sete Btvowene || ES
sarc Be eee
po ee ieee eee
Smescew [Biecs igs
Siero Ses a OT re
me ca ire nce aanait
come gat tree —
too oes
ee oe
Bearer Stace
Secpome race ‘scaloroissbled, scolerPaper?:
ee Hea
ee sitet corcameily
Sree Grass Lifeoe alg) ints
Erato cy Gta fibotton = stop osteanecy li)
af secanh 8 Ogcakr far(int Us = column cotcounet); j++) (
Strat [Steer i deta uum cases
- ih > Stacie!
bets [Secret Here
grec” Bass Jo crm
foot” Seeusers, Operating systems, such as Windows, macOS
‘and such are usually a combination of Cr+, C#, assembly and some
Fox of visuabbased language, Games generally use C-r whilst web
pages can use a piethors of avaliable lanauages such as HTML, Jv,
Pythan ane s9.an,
More general-purpose programming is used to create programs,
‘pps, software or wharever else you want to cal them, They're
widely used across alt hareware platform's and sult virtually very
conceivable application, Some operate fester than others and some
‘are easier to learn anc use than ochers. Python is one such generat
purpose language.
Python is what's known 25a Migh-Level Language, in thatit take
to Ene hardware ane operating system using a variety of arrays,
‘aviables, objects, aithmeli, sut-outines, loops and countless
‘more interactions, Whilst i's ret as streamlined as 3 Low-Level
Language. which can deal cirectly w tt memary addresses, call,
slacksand reaisters, is benefiLis Ut W's universally access bie
land easy to learn
[File Tevake java
oport javaclaagireflect.+;
lass Tovoke {
publievstatic void main( String [) args) (
try
Glass e = Class-forname( args(0] );
iethod y= c-getllethod( args{1], new Class
Thee 2
object ree = m.inyoke( null, null 9;
SYStER.OUE.princing
or class: + args(a]
+ wath no args\nkesules: "+ ret):
} catch ¢ Gassnocroundexception e ) ©
77 Class fornane(-) cane. rind the class
} earch ¢ Nosuchiethodexception e2) £
77 that wethod doesn't. exist
3 eavch € THlegataccessexception ¢3 ) [
if ve ont Pave pereiasion £0 favOkE that
} catch ( trvocationtargetexception e¢ ) £
Wan excaprion ocurred white Invoking that
feethod :
Systen-out.print'In¢
Wesucthod threw an: " + 04
getTargetenception( “)");
+ args(1]
e Javais a powerful
language that's used In
web pages, set-top boxes,
TWsand even cars.
Python vss created over twenty six years ago and has evolved to
‘become anideal beainner's language for learing how to program a
compiter. 's perfect For the hobby's, enthusiast, student, teacher
{and those who simaly need ta create the'r ewn unique interaction
Between either themselves ora plece of external nardware and te
computer tse
Pythons reece download, installand use ends avallaoe for Linux,
vwlindows, macOS, b4S DOS, O5/2, BeOS, IBM isevias machines, and
RISC 08% has been vated one ofthe top Five programming
anguages in the ward andis continually evoling ahead of the
hardware and internet development curve
Soto answer the cuestion: why aythor? simaly put its ree, easy to:
lear, exceptionally powerful universally acceated, effects anda
Supetb learning and educational toe
BASIC was once the starter Language that early
bit home computerusers learned.
iy eset ree forme
Python is amore madern take on BASIC, it's easy to learn
and makes or an ideal beginner's programming language.
—>
whvinon CEz= Say Hello to Python
Equipment You
Will Need
You can learn Python with very little hardware or initial financial investment. You
fololntaun-t-re ea arene 0) goo uit Cee Ree MUTE nC eae eel Rey
iets) ele
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
Obviausly you're going to need a computer in order to learn howta program in
Python and to test your code, You can use Windows (from xP onward} oncithera 32,
0 64-bit processor, an Apale Mac or Linux instaled PC.
__| AN IDE
An DE (integrated Developer Environment) inused to enter and execute Pychon
Code. It enables yauta inspect your proaram code and the values within the code, as
wel.as offering advanced features. There are many efferent IDEs available, se Fing
he ane that works For yeu and gives the best resuls,
PYTHON SOFTWARE
acOS and inux already come with Python prelastalled as part of the operating
system, as does the Raspberry i. Hawever, you eed to ensure that youre running
the latest version of Python, Windows users need to downlad and nstall Python,
‘ohich we'll cover shorty,
TEXT EDITOR
\whist a text ecitor san iceal envitonment wo enter code into ts nat an absolute
necessity. You can enter anc execute code directly fram Ue IDLE buta text eater,
sich 25 Sublime Text or Noteoades, offers more advanced Featuresand colourcoding
\when entering code
INTERNET ACCESS
Python isan ever evolving environment and as euch nev versions often introduce
new concepts a! change evis\ing cornmands and wade sLuchute ta makeika move
cfficent language, Having sccessto the Interecwill keep you un-to-dete, help you
‘outiwhen you ger stuck and alve access to Pythan’s immense number ot modules,
TIME AND PATIENCE
Despite what other
haus. Lesming
mayleacyou wo believe, you wor't become a pragrammmer
sein Python takes Eime end patience, You ma
‘ctv ke water, Understand you're leaming
aoa ssameth ng enurely new, and youll 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. it's main operating system, Raspbian, comes preinsta led with the latest Python along with many Modules and extras.
Ula ca
The Raspberry Pi isthe latest version, incorporating amore
powerful CPU, more memory, WiFi and Bluetooth suapart.
1 can pickup a Pifor around £32 or as a part af kit Fo
depensing on the kityou'e interested
The FUZEisa leering environment bull onthe latest model
the Raspberry Pi, You can gurchase the warkstetions that
with an electronics kt and-even a rebot arm For you
19 bulld ané program. You can fird more information on the
FUZE at wausefure.cn
BOOKS
We have several great Raspberry Pi titles avarlable vis www.
‘bdmpublications.com, Gur Pi books cover how to buy you!
first Raspberry i
it up and use
i thereare some
aves step by
The Respberry Ps main operating system isa Deblen-besed
Linux distribution with everychina you need in
simple to use package. Us streamlined For the Piand is an
ideal platform For hareware and software projects, Python:
programming ang even as2 desktop computer
guidesta get
he most Fram
az= Say Hello to Python
Getting to
Know Python
Python is the greatest computer programming language ever created. It enables
Vo eoM ETA Ea ed ear Medel ime Reel el e-LeERCINe Les Marea Cc)
Ion taT ess: Te
WHAT IS PROGRAMMING?
Ithelps to understand what a programming language is before yau try to learn one, and Python is no different. Let’stake a
look at how Python came about and how it relates to other languages.
eT PROGRAMMING RECIPES tnt
Propane sre Mes reohes (Sieg ers Put 180 grant of self-raizing flour in a bowl.
programming anguage ccopeto oakescake could go ike th ps te ere ot ae et
isallst of instructions that gM 180 niLLELitees oF nil.
acomputerfollows These | Put 100 qrams ofselFracng flourin a bow
instuctonscanbess simple} Aca 100qams of utter tothe Dont
2s deplaing your name Ack 100 miles oF rik
slaving ors le or Bake for alfa ou
Sscompexss bulcg 2
wielavtaavortdrtion f°
viporencn isos
conceived inthe late 19805 CODE
by Guide van Rossum Just like avecipe, a program consists of instructior
a certrumvishonde 8 inorder program tap dessibes cake mighty
Iformaten CW nthe
# Netherandsasa successor to
F tease ianguge
Guido van Rossum, the
father of Python.
oH eppendC [flour butter ,miLk])
ake, cook(bONl)
PROGRAM COMMANDS
tke bowl apnend and cake, caok(aow)
book, The main thing to know is
at the commends do, W's easy to
You might not understand some ofthe Python commands,
The Firs isa lst, the second an object; well look at both
nas its easy Lov ead commands in Pylon, Once you lest vl
Figure out how 2 prooram works,HIGH-LEVEL LANGUAGES
Computer languages
are easyto read are known as
hiah-ewel
Thisis because they Fiyhigh above the hardware falso referred tn as
“the meta"), Lanquaces thet“ closeto the metal” Ike Assembly
commands ead bit
reknown a5 “loweevel’. Low-level languages
licethicmsg db ,@%a Len equ $ = mse
PYTHON 3 VS PYTHON 2
“ Gatting to Know Python (ee
ZEN OF PYTHON
thon lets you access all the pawer ota computerina language
hat humans can uncerstanc). Behind! ll thisisan ethosealled "The
Zen of Pychon,” This sa collection of 20 softwere arinciples that
fluences the design ofthe language. Srinciples include “Beautiful
s better th han complex
aly’ ane "Single s
Deer Cau ei aan ecu sens
Brora cues
Downinad fr Windows
eariua? Goya aetna ey
PYTHON 2.x
ereeteet
and
Co
eas
eeu
Caran!
ar
ec
ec unary
Features are
ve
peasant
cence
3.x WINS Jie
cunts
ernie terre
ee
Cae)
has meant that
eer
fips agate ras time te mez= Say Hello to Python )
How to Set Up
Python in Windows
Aneto eae eke re Mee] Aen M Rl EU enn LO MUTI SOLD
[yo aer-ferg>y tel Ma Cet ieee =e a arene (Ae) ea Me A COLE EL
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.
Sixty opnignebbionetonananton, REESE) cocingthe canara tn lon yuo
Susy org/cow nloads/. Look For the button detailing eu specify certain parameters, and whilst you may
the downloadilinktor Pychon 3. The latest version atthe ime of stay with the deFauits t's 2 qood habit to acopt as sometimes (not
‘weiting is 3.7.0 butas Pythan isfrequently updated thismay bea sth Python, zhankfuily) installers can include unwanted accitional
different version for you.
Features. Om the fst ser een avalable, ensure ali boxes are Uicked
‘and clic the Next bution,
oa
ete a
Optional Features
terete amen
eae ae
FEES Click the download button forversion 3.x and ERTeeERD The rest page of optionsinclude some interesting
save the file teyaur Downloads Folder When the sccitionsso Python. Ensure the Associete ie with
Piles daviloaced, double click the executable and the Python ychon, Create Shortcuts, Add Python to Environment varlaies,
installation wizare will launch, From here you have bo choices Precompile Standard Urery and install for \l Users options are
Install Now end Customise Installation, We recommend onting for Cieked, These make using Python later much easier. Click Inscall when
the Customise Installation in. you're ready te continue.
J Install Python 3.7.0 (32-bit) Advanced Options
Sata mn at i ne neater
at i ae
cs * Eincwos atari
pyth puthe tars
windows Famnnnsronae eam windows [Ni (ena( How to Set Up Python in Windows Cl
ED Cliceing on the IDLE (Python 3.7 32-bit) tink
launch the Python Snell, where you can begin
{your Python programiming journey: Don't wary iFyout
rewer as lang asil’s Python 3.x aur cade works inside
lersianis
a
putin ,
windows
Before you clre tena wizard window iryou
Sug however, i's best to click on the link next to th gues and this time type: CMD, you'll be presented with the
shield detated Disable Path Legit. hs alo thon
Cmmand Prompt link. Chee it to get to the Windows comuand line
acter limitation, enabling yout __erviron-nent. Ta encer Python within che command ine, ouneed
«din deen Falders arrangements. ype: python andi pross Enter
Aga, ¢ then you en Clase he
installation window = a
le path length tri
ya macine co
yan incu thon
te
HA ® so | REED Me comretee resin ot ton verisin
Mf way as the Shell you opened
as Step 8 note the three leFacing arr
A Bees Fine environment, i's na
ise
Windows “0 users can now
Find the installed Python
“Sxcwithin the Start button
Feverny Aekded section,
The Fist link Python 37
(G2-i) will launch the
ominend line weision of
Pysnon wher licked fm
cen that in amomentl. To
ss (=), hls k's a perfect
00 userriendly, 50 leave che command
exLtG to leave anc clase the Commandz= Say Hello to Python)
How to Set Up
Python on a Mac
If you're running an Apple Mac, then setting up Python is incredibly easy. In fact a
AeololM MINER TNA] Clemo molMe ole r | Ce M ola CMa ie}
[eprVCcse I es(o
INSTALLING PYTHON
Apple's operating system comes with Python installed, so you don't need to install it separately. However, Apple doesn't
update Python very often and you're probably sunning an older version. So it makes sense to check and update first.
(pena ew Terminal indy cling ca» Cckon telat. veston of rythan 3, nou
suze Utilities, then double-click the Terminal icon. Now Sue) pase this is the download nutton for Python 3.6.2,
Python =-version,Youstoucsee Syenon 2S rane THe wl auton ersionar thon and
‘even lates, Aaple has updates the OS and Pytnon iastallation. depending an how you've cet your Mac configured, i automaticaly
sin. stars the installation wizard,
Either way, t's best to check forthe latest:
Bi wanna cra! Bol z ard-anen, cide on
5, Just 5 th te Windows setup the Cantinue gutton to beginthe installation k's
ppracedurean the previous aages, youcan see nwoyellew download worth taking a moment to read through che Important infarmation
buttons: one For Python 346.2, and the other For Python 2 Section, in case ik references something ta anniies to your version
Note, that version numbers may be different due to the Frequent
releases of Python.
DECC Rea aT oN aaa“The nest section details the Software
Agreement, and wills n
to mast Folks, i's probably worth ares
the Continue button ance agai
particularly interesting
ASTOR AND LCE
Final youre be aesentedth te aout oF
BUSS space Python will take up on your system and ary
ital baton, whieh you amet tr te all tlaton
cttytnon on fo your Mise You mej nese to enter our passion
ro uuthenvcatethe ntlaton proce
Tre inmalason shoals rake roolong ewer
susie Mac Mini we used in this section is a little slow.
rte htoder Moe racinesand fel took round ty
‘seconds For the Installation Successful prompt to be displayed,
hen you're ready, clek an
How to Set Up Python on a Mac Cll
“There'snothing much sel to doin the Python
UES sstallation wizard so you can click the Close Sutton.
fyounow drop backintes Terma session an reenter the
command: yon =-¥erstod, you cansee the new veins
listed, Taenter the command line version af Python, you need
python3, Toext, is exitO.
ene Piensa
Pytnon 3.6.8 3.6. 0:41PM, Dee 22 PNG, 37-293)
1 tags ine, bala S64) (st 3)
‘of Toute (85.9) inne soy be oe
FRPIETB Older Mecversions may have trouble with the
wer versions of Python, in which case you wil
need to revert to a previous Python 32: ble as (ong as yourre using
Python 3, the code inthis book will wark For you.
[pyenon 3.1.2 (2312
‘9360K, Mar 24 7010, 01:33:18)
[écc 4.021" (apple Inc. build 5493)) on’ darwin
Type Topyrisht', 'credite" or “Licesse()* for mo
3]Say Hello to Python
How to Set Up
Python in Linux
PYTHON PENGUIN
Linux is such a versatile operating system that i's often difficult to nall down just one way of doing something. Different
distributions go about installing software in different ways, so we will stick to Linux Mint 18.1 for this particular tutorial,
Fist you needa acertin which vert of Pon Sone Una dite arate
suse is currently installed in your Linux systerry, #5 eueee) the installation of Python to the latest
weve goingsneising ik Wine vo Fortyezestion, wneneverthe system supcatedTashec, ero ssyerem unde
Aevath macOs, dep toa ss
colvaths and uparace with:
aS sudo apt-get update 8% sudo apt-get upgrade
fie Ett aw Seach Tere ei Enter your password and let the system da any upeates.
savannas nine
edt aw Seah Seba tp
BED Necerte:pythoni
>> print(“Hello everyone!")
Hello everyone!
>>> |
TED vou rey h
then 1
the!
elements of Python cade, They are:
Bleck Dats and Variables
Green Stings
Purple Functions Lig
Orange Cormmends
Blue —User Functions
Red—Comments
ie Red Error Messages
IDLE Colour Coding
Geen | Stee | ctette wore |
Purp | Funct | ton) peiaec |
Despe | eommswe | oe ae
sive — | Geert
Bakes | conrene
| Hosted [Ere mestsoes
sudan
Starting Python for the First Time Cl
“The Python IDLE s# configurable environment. F
you den'tlike the waythe colours are represented,
em YOU can always change therm via Ontions » Configure IDLE ané
licking on the Highl'ghting tab. However, ave don't recommend
hat, a5 youmon'tbe seeing the some as our screenshots.
ust tke most programs available, r
‘perating system, there are numerous shorteut
sys available, We dent have room For themall here but within
‘Options » Configure IOLE anc under
oF the current bindings
cordless ot
BREET B). thePython|0Lcis=powerintertace and one
that sactualy been written in Python using one
of the avelable Cl tools, Fyou want to know the manyins ard
‘outs ofthe Shell, we recommend you take & Few moments to view
‘wnvw.docs python.or9/3ibrary/idlelntml which detais mary af
he IOL's Features,z= Getting Started with Python)
Your First Code
fess er) ROU R LUC ers Aa ecole maleate) Te cMelmeore Mii ea nea eel niils a (Coy
Ser Wane atau Meni eat secu hegre eres
Sere te ecu Menta hc ieca tiene heats
PLAYING WITH PYTHON
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.
youve dled >ycon IDLE reopen bin REED 1 ensue ersecte nantes one
ue) whichever operating system version you prefer. In ES utputis the 2+? yau asked to be printed to the:
he Snel erterthe Fania lowing ceen The suoston wars are detringumnaesteirg outpted
print'HeLlo") IneILEStl:to pint theta 21 2yeuncestoromowe
printc242)
PETTY 2st 2: predicted, the word Hello angearsin the
Shell astlve text indicating autput from astring,
les fairy straightforward and doesn't require too much excianstion,
Now ty now, enker
printc"2i2") oz
You can continueas such, printing 2+2,16442343
‘and soon tothe Shel, An easier vay s tose =
is something we will coverinmore depth ater. Forwhat you heve done here is assign the letters a
and b two values: 2and 2. These are naw variaates,
which can be called upon by Pythan te outaut sed, subtract. divide
«and so on for eslong as their numbersstay the seme. Ty this
printca)
printcb)
Sa veg Spent ween Hop
re outaut ofthe las sten dsplays the current
values of botha and bindivcualy 2s youve asked
tine to be printed separately. F you want to acd them up, you can
use the Following;
printcare)
This code simaly takes the values of and b, adds them together
‘and outputs the result.
If: =,
SL and the Print functian, For example, you could
_iga wa lables For someone's name
‘You can play around with ciferent kinds of weriables
ane="David”
printname)
PEED Nowlet’s edd a surname:
surnome="Haynara”
printCsurname)
‘You now have two variables containin
{and you can print them inceaendentl.
ewe were to apply the same routine s before,
using the + symbol, the name wouldn't appea
cconrectiyin the output inthe Shell Ty
printChomersusnane)
“You need 2 space between the two, defining themas two separate
valves and not something you mathematicaly play around wich.
Ih Python 3 youcan separa
witha space usiag a com
printcname, surname)
Alternatively, you
printcname" “+surnane)
The use ofthe carime is much neater, as you can see.
Congratulations, you've just Laken your Fist stepsintothe wide
warld oF Python
madd the space yourself
ono Ciz= Getting Started with Python)
Saving and Executing
Your Code
While working in the IDLE Shell is perfectly fine for small code snippets, it’s not
designed For entering longer program listings. In this section you're going to be
introduced to the IDLE Editor, where you will be working from now on.
EDITING CODE
‘You will eventuslly reach a point where you have to move on From inputting single Lines of code into the Shell. instead, the
IDLE Editor will allow you to save and execute your Python code.
ath sn BRT E RD ou cn see that the same col ngisinplace
click on File 1 inthe IDLE Editor as isin Lhe Shell ensbling you
tsa ‘ 0 better understane what's qoingon with your code, However, to
2 the code you ned to Fest save Press FS and you get a
Save...Check box open.
Bree) Te OLE Ecitoris, forall intents and purposes, a STEP 4 Ok buttonin the Save box anc'sele
sin editor with Pytnon Features, colour sdescnation where you'l save all your Python code,
codingan " Yau enter The destination ean be a dedicated fold Python oF you
canfust dump it wherever youlike. Remember to keep a tiey dive
out in the FutureETEREDD ferename for sour code, rit hel ar
‘exemple, anc click om the Save button. Once
Python code is caved i's exeeuted ane the outpur willbe detailed in
Lhe IDLE Shell In tis case, the words 'Hello everyone!
Piste how the vast joy of your Python code
uaa will be conducted. Enter it into the Editor, hit FS,
‘smu the cde ancdionca the gutput it Shel Somaties things
wer depending on vhether youve requested a separate
Sindov, bur estan thats te process. t'ste process we wil
de Uvoughout ths book un
cs otherveie stated,
Sih
(_ Saving and Executing Your Code Cl
FRPP 12's exterd the code andenter afewexamles
From the previous tutors:
a2
bz
‘none=" Davia”
surnane="Hayward™
printCname, surname)
print Cab)
f you press FS now youll be askec to save the Fle, again, as k’sbeen
snodified From before,
ERED sou cickthe ox button, tne fle will
overwntten withthe new code entries, ane
executed, with the autput inthe Shell, It’s nota problem wich|ust
ese Fev lines bucifyou were caecia larger file, verwmiting can
ecome anissue. lsiead, use File» Save As From within the Editor
aback,
BETTE DD you openthe file location ofthe saved Python
code, you can see thatit ends in a.py extension,
Thisis the default Python file name, Ary code you create will be
‘whatever py and any code downioaced From the mary internet
Python resource sites wil be py. Just ensure that the cade is wi tien
for Python 3,
Now create nerf, Closethe ctor ang open
cua Me anew instance (File » New File from the Shell.
ner the fe
Python”
brig
‘c"c001!”
printCa, by ©
lowing and save tas hello py
“You wil use this code in the next tutoria
2Getting Started with Python)
Executing Code From
the Command Line
COMMAND THE CODE
Using the code we created in the previous tutorial, the one we named hello.py, let's see how you can run code that was made
inthe GUlat the command ine level.
Bap ist 34 before,© Executing Code fram the Command Line
Now enter: exit() ts leave the command ln
sessionand return you back to the command
prompt. Enter the folcer where you saved the code Fram the
previous tutcrial and st the avalable Mes within
should see the hella py
quice obvious, Whilst it
ne diferencas between the
‘nt com mand over Python 2, the result
ne expected. Using Sublime for the moment, open the
nelopy file
areata ten Sie sosmenu fo ti’
uE going ta run, enter the fallowing inte the mus Pi, you're gaing Lo Lemporarily leave th
omer amet ad seSbline a an exe tha youdont neces
python3 hello.py thhehells py le open, alter ito
The will execute the code we created, which tore nd you temeenenistennentemaneeiiit
print(*Hello,", name)
eerenoul? 7
print(a, b, <)
ERT Neterely: since tisis code, using the PRUTSET BD. Save the helo.pyFleand crop back ta the
sglaxand layout thats unique Le Pytion 3, only nmang line, Now execute the newly saved
wwarks when you use the python3 command, Fyou the, trythessme code with
with Python 2 by enterna:
python hello.py
python3 hello.py
“The rescle willbe the original Python is cool statement, togethe
‘sith the adced input command asking you For your name,
displaying it inthe cammand windoz= Getting Started with Python )
Numbers and Expressions
We've seen some basic mathematical expressions with Python, simple addition and the
like, Let’s expand on that now and see just how powerful Python is as a calculator. You
TE tates ee gs cle a
IT'S ALL MATHS, MAN
You can get some really impressive results with the mathematical powers of Python; as with most, if not all, programming
languages, maths isthe driving force behind the code.
openotie a vase oars snr ERE ou ee aaa opto
eae you can Use either the Shell or the Fciitor. For the SEES divide, multinty, brackets and so on. Practise with a
Sheteloioleicetae i oinerad tte muchireenpls
muscle, which we believe isa smal land located at the back ef the
brain (or nat
25293
e244)
FE sloth long FR codon sno
= Xesol mbes nevaentec eed fats
2a crtontng pone etonce Hever Fyourec epee
seecclad opposed to a decimal answer, then you can use a double slash:
99867344°27344484221 ~ oes eee -
And soon,
a ba toes oeYou can also use an operation to see the remaincer
leftover from division, Fer example:
10/3
Will splay 3 333333333, whichis oF course 3.3-recurring, F
now enter:
eK,
This will splay 1, which isthe remainder let aver trom eivicing 10
Next upwehove the power erator
sug ‘expanentiation if you want to be technical. To work
vero somthing you can ne adouble mu iaton
Symbol or counestaonthe
eee
torso
Essentially e's 2x2x2 but we're sure-you already know the basics
indmaths operators, This s how you would werkt ou
jorean tonquestwisters, For
frta numberta bina’y, use:
Crmenioneson CE
“This will be displayed 25 ‘9611, converting the
Integer nto binary and aeding the prefix 0 to the
Fyou want to remove the Ob prefix then you can use:
format(3, “b*)
‘on
“The Formac command converts value, the num
malted representation as controlled
e'b oat
r3,t0a
he Faimat speciation,
‘A Boolean Expression sa losical statement that will
rither be vue or False, We can use these to cen
cosee fis equal
lata and tex
na NewFile:
less than or greater than. Try this,
a=6
b-7
printct,
print(2,
print(3,
printc4,
print¢s,
printce,
printc?,
printcs,
print(9,
not (a = 7 and b
rot a = 7 and b = 6)
txecitethe coe rom Step 9, andyou censeea
cused series of True or False statements, depending on
the result ofthe buo defining values: 8 and 7. I's an extension of
shat you've laoked at, and an important part of programming,z= Getting Started with Python
Using Comments
When writing your code, the Flow, what each variable does, how the overall program
will operate and so on isall inside your head. Another programmer could follow the
code line by line but over time, it can become difficult to read,
#COMMENTS!
Programmers use a method of keeping their code readable by commenting on certain sections. IF a variable i
Programmer comments on what it’s supposed to do, for example. It's just good practise,
used, the
PUTER ED St by creating anew instance of the DLE EdLor BRIBE) Resave Le code and execute ik You can see Liat tne
(File = New Fie) and creace asimple variable and purputin the IDLE Shell is still the same as befor
command despice the extralines being added. Smply put, the hash symbol)
ene a line of text the programmer ean lngertto infer chern,
and others, of whats going an without the user being aware
print("The value of A is,", a)
‘sive the fleand execute the code, a
GED) Pecvina the codewill eturvthe lne:Thevalue o's ERIM e's assume thatthe vasabie A that we've created
i510 nto the IDLE Shellwindow, which iswhat we is the numberof lvesin a game. Everytime the
‘expected. Now, a¢d some of the typesot commentsyou'd normally alayer flue is decreased by 1. The programmer could
seewithia cove nserta routine along the lines of:
# Set the start value of A to 10 o-a-1
o=10 print¢“You’ve just lost a Tife!”)
# Print the current value of A printc*You now hove”, a, “Lives left!")
print("The value of A is,", a)
‘Eh Sam Bi pre enn be page oe nert kw tkhist we knew that che variable Ais ves, and
that the player has ust last one, 2 casual viewer or
someone checking the cade may nat know. imagine for a moment
tat the code istaenty thousand tines long, insleed of just our
seven, Youcan see haw handy comments are
Essentially, the new code together with comments
ould lack ike:
# Set the start value of A to 10
o=-10
# Print the current value af &
printC'The value of A is,”, a)
# Player lost a Uife!
o=0-1
# Inform player, and display current value of A
Clives>
printCYou've just losta Life!”)
printC'You now have”, a, “Lives Left!"
You can use commentsin citferene ways. For
fxamale, Bloc Commenisare a lage s
tex tat details what's going on inthe code, such as telling the code
reacer what wariaaies you're planning om using:
w# This is the best game ever, and has been
developed by a crack squad of Python experts
# who haven’ slept or washed In weeks
being very smelly, the code at Least
# works really well
Despite
Cvirecomens CE
FID line comments are comments that follow avection
‘of code. Take our examples From above, inscead of
nsertina the coc on 2 separate in, we could use:
o-10 # Set the start value of Ato 10
print(“The value of A is,”, a) # Print the current
value of &
o-a-1 # Player lost a Life!
printc“You’ve just lost a life!*)
printC“You now have”, a, “Lives left!”) # Inform
player, and display current value of A (Lives)
# print(“The value of A is,", a)
7 Set the start value of
m0
| Forint che current value of A
f prine("the value of A 1s
§ Player loses 1itet
F intern player. and display current value of A (Lives)
peine("vau've Just lest a, 1ise!")
Brint(-You now have”, a. “lives leftt
comments Place them before and after the areas you want to
commenter them to work
‘This is the best gane ever, and has been developed
by @ crack squad oF Python experts ho haven"
slept or washed in weeks. Despite being very
smelly, the code at Least works really well.
Yau also use three single quotes to comment
out aBiod mule ne section atz=) Getting Started with Python
Working with Variables
ARO e NC Me MU Iiro| MOU Ma uTosa Rare (E-llerLeN aoe eee INT
Pt acu ae eer cu nite eae nett ety
Nate Nees
VARIOUS VARIABLES
You'll be working with the Python 3 IDLE Shell inthis tutorial. IF you haven't already, open Python 3 or close down the previous
IDLE Shelt to clear up any old code.
PER losonepregamming languages you'e required — RII vou've sean previously hat variables can be
to use adolarsiqntodenar=astring, which 2 ronestenated using the pls symbol between the
vvaniablemace up of multole characters, suchas aname of person. arable names. nour exemple we canuse:print Chane + “
In Pythan this sn’ necessary: For example, inthe Shell ente "4 title). Themidcle part between tha quotations allows usto
ane="David Hayward” for use yur awn name, uniessyou'te add acolon ard apace, variables are connected! without spaces,
‘also called David Hayward) owe needa add them manually,
fH oh Ges Gr eo He ae Se
PRD vou can check the Lype of variable in use by oo:
issuing the type 0 command, placing the narne oF combine varables
the variable inside the braexets, In aur example, this would 2e: within anothervansble, For
‘type: Chame). Add a now string varlaie: t8tLe="Descended bio bath name
Fron Vikings”
charactersname +: +
title
Then output the content of the
ne viable a
print (character)
Numbers arestored as different
‘variables
age=44
Type Cage)
Which, as we know, are integers.
BED oct Dog Htee series -Wolurne 37However, you can't combine both strings ant
integer type variables in the same command, 25408
‘would 3 set of similar variables. You need to eltherzurn cneinta the
rer OF vce versa, When you da Ly to combine both, yauget en
‘error messaae:
print Chane + age)
nists a process known as TypeCating, The Python
code
print character +
old.")
is “+ str(age) +“ years
print Ccharacter, “is, age, “years old.”
Notice again that in thelast example, you dan'-reed the spaces
bbetureen the words in quotes as the commas teat each argument
to print separately
35> print Crane = 392)
‘Traceback (most recent call Jas)
File "cpyshelleva>", Lane 1. in enodule>
print (a
Typettror: Can" nt" object to str implicitly
335" print (character = ie" + str(age) ©" years old")
David aynsrd: Descended from Vikings tz 24 years old
53> print Ceharaeeer, "in", age. "sare ld.)
David! Hayward: Descended fron Vikings 1s 84 years old)
3
ESTED ercther example of Typecestingiswhen you ssk for
input From the user, such as a name, for exarnele,
en
‘age= input (“How old’ are you? *)
‘lista stored from the aut commandis stored asa sting variable
ett Shel bon sonore wows lp
pe “eapytsgneSerestts" or “Licene()* for more sntoration.
PoE age na tig char eat SF
P33 pete}
Set
( Working with Variables (eo
FID This presents abit of problem when youwant to
work with 2 number that's been Inputtec bythe
user, a¢29e-+ !O.won't workdue to belnga string vanable ane an
meger instead, you need to enter
‘intCage) +10
“This wk Typeca
worked wit
we age sting inte an oteger that car be
The use of Typecast tate important hen
cus dealing with floating point arithmetic; remember:
nuinbers that have a decimal int in tiem. For exarnple, enter
shirt=19,99
ki
w enter type(shirt) and youll see that Python has allecated
re number 85a Float’, because the value contains a decimal point.
fle Eat Shel Debug Gotare now lp
Privan 3a? Caefoule, Gee Fete TST
Ge 28.9) on irae ;
eelasethoat">
the rever
\inen combining integers anc Haaes Python
usually conwerts tieintogerto afloat. but should
‘ever be appliedit’s worth remembering that Python
doesnt return the exact valve. When converting afloat ton
coger, Python wil always round dawn to the nearest inceger,
calles truncating; in our ease instead of 19.99 it becomes 19.
{EAS Soo ne
aaa ae ee aT
Tyee fama. “credits” oF License)” for more information,
ars
e
aZZ: » Getting Started with Python
User Input
We've seen some basic user interaction with the code From a few of the examples
earlier, so now would be a good time to Focus solely on how you would get information
ue te eek ocala
USER FRIENDLY
The type of input you want from the user will depend greatly on the type of program you're coding, For example, a game may
ask For a character's name, whereas a database can ask for personal details
IF it ook already, open te Python 3 IDLE Shel BED Now that we have the user's name sored ina
LED oj careaNeweleincnerchior Lets bean th — Maa cocpte of nisleswe con callthem up whenever
something realy simple, enter: ‘we want:
print¢“HeLlo”) print(‘Welcone”, firstname, surname, “. T hope
firstnane=input (What is your first none? you're well today.)
printc"Thanks.”)
Surnane=inputC*And what is your surname? “)
FETED Sec and execute the cove, and asyaualieadyno RAAB ren the codeandyou can seea sight issue, the
‘Gout suspected, nthe 1DLE Sheil the program il Fullstop after the sumame Follows blank space,
{skforyourfirst name, storingit asthevariable firstname, followed To eliminate that we can adda pus sign instead of the comma in
bby yaur surname; alee stored in its own variable urna che code:
printC“Welcone™, firstname, surnames. I hope
cE ae you're well today.")
te SnoCosmet
C
PPI vou don'taheayshavetoinclide quoted textwithin EMAMMM what you've createcihereis«coneltion, which we
theinput command. For example, you can ask the vill cover soon, In short, we'fe using the input Fram
user their name, and haverthe input n te ine below "e user and measuring Itagainsta condition. So, Fhe user enters
print(tHeLlo» what's’ your’ name?" Davia thei name, the quar nil allows them Lo pass uahindered
up - mhomerpi/Docume
He Edt Faymat pun gptens windows Help
print Helle, what's your name?)
ames Seput()
BERD the codetromme previousstepisatten regarded — RUPP suse syoulearred sreviously, anyinoutroma
as being alle neater than having a lengthy user automatically 2 sting, se you need to appiya
‘amount of text in the input commanc, ut it's nk aula thal’sset in TypeCast in order toturn itinto something else, This creates same
stone, 50 60 as you lke in these situstions, Expanding on eeresting additions tothe input command. Far exemole
aes # Code to calculate rate and distance
printC“HaLt! Who goes there?” printC“Input arate ond a distance”)
one=inputC rate = floatCinputC*Rate: “)
ese raat Gat Sone ode Hae [coat Geen: hier:
ErTeGAD (252 goodstarttoa text adverturegame.sernans? EEE To finalise th
Now you carsexpand on itand use the raw input distence = fleatCinput(*vistence:’ 9),
From the userto flesh out the game alittle: Loe ee
‘save and execute tre code ane enter some umbers. Ushg the
iat{iput element, we've told Python that anything entered isa
loating point number ather thana string
rate ane dlstance code, we can add:
print (*Welcone, good sin. You may pass.")
else:
printC"T know you not. Prepare for battle!)z= Getting Started with 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
enables you to define your own Functions,
FUNKY FUNCTIONS
‘A function is a command that you enter into Python to do something. It's alittle piece of self-contained code that takes data,
‘works on it and then returns the result.
Ihsnobjust data shat ¢ functign watks on, They can
ee) doll manner of useful things in Python, such as.
Sort dats, change items from one Formac ca another and checkthe
length or typeof items, Basicaly, function isashart word thats
«by arackets, Far example, fen(),list() or type).
PED) 6 urcicn takes data, usually avariable
itdepencing on wihat tre function is
to do and retuns the end value. The data being worked on goes,
inside the nary letiors
he word antisestablishmentarianism, then you!
‘LenC“antidisestablishnentarianism™) and the number 28
would return,
vrkson
Jackets, so you wanted to know how
“You can pas variables Unvough Functions in much
thesame manner Lets assume you wantthe
‘umber of letters in a person's surname, you could use the Following
code [ete
he Lex editor
artis example:
rnane=input ("Enter your surname: *)
count=1en nan)
print (“Your surname has, count, “letters in
+7)
ress F and save the cade to execute
Python has tens of Functions builtiatol, far too
‘manyyco get into nthe limites saace avalable here
However, to view'the ist oF builtin Functions avalableto Python 3
navigale to wwn.docs psthan.org/3/lbranyfunetonshtml These
redefined Functions, but since users have
1e only anes avaliable,( Creating Functions Cl
EPID Pcsivional functions can be added ra Pychor: PRP ses function from mexule enter the name of
through madules. Python has avast ra the module followed by a full swap, en the nar
‘modules avalabe that can cover sumeraus programing cut ‘ofthe function. Far instance, using che math module since you've
They add functions ane can be imported as and when recuired ust imported into Python, you can wlilse the square root Function,
‘example, touse advanced Mathematics Functions encer: Todoso, entes
import: math math.sqrt(16)
(Once entered, you haveaccessto all the Matin madulefunctions, You cen see thet the code is aresented 5 module functionicata}
ie eS Gi eh
FORGING FUNCTIONS
‘There are many different Functions you can import created by other Python programmers and you will undoubtedly come
_across some excellent examples in the Future; you can also create your own with the def command,
ED.
reeset)
emarcasaiis
[from Hello import Hel lof
tel loC“David”)}
ee LULU AE UL
meee
I 2 < now expand the function to accept >
Pt ee
rae hello to David. Chretien
ee eee
eee
aca, 0) :)z= Getting Started with Python
Conditions and Loops
Conditions and loops are what make a program interesting; they can be simple or rather
Conc ae ates ent cnee ee RMR rate net icmetayiteh ceased
they could be the number of lives left in a game or just displaying a countdown.
TRUE CONDITIONS.
Keeping condi
iF something is TRUE, then doing something else if itisn’t.
Lats create anew Pon progam that il ask
ee the User to input e word, then check it ta seeif it’s
‘sfourletter word or nat. Start with File> New File, are begin with
the input variable
word-input(“Please enter a Four-Letter word: *)
Now
Function and pass the word:
tal numaer of letersthe user has
we can ceatea news variable, then use the ler
able thrauah itto
stentered!
Grd
input (“Please enter @ four-letter word: *)
word_length=Lentword)
's simple to begin with makes learning to program a more enjoyable experience. Let's start then by checking
SUES word length variable is equal te Fox
Friendly conformation i itapples to the rule
Now you can use an i statemente checkif the
and print a
ordi nput(“PLease enter a four-letter word:
word_Length=Len(word)
if word Length = 4:
print (word, “is @ four-Letter word. Well done.”
“The double equal sign (==] means check something's equal ta
something else
FEF) The colcnal the end of Ftels Python thal ith
statement fsciue do everything after the calon
at'sindented, Next, move the cursor back to che beginning of
che Eda
Word=input(“PLease enter a four-letter word: “D
word Length=lenCword)
if word length = 4:
print (nord, “is @ four-letter word, Welt
done.”
else:
print Cword,
“is not a four-letter word.)
ot met sw rte nny:
mmm CE
PI Press £5 and save the code to exerute it. Enter FRPP Now expand the cade to nchide anstherconsitions.
‘fourletter word inthe Shell Degin with, you Eventually, (tcould become quite cormptex, we
should have the returned messace thatitsche wordisfourletters. added cancition for three-letter words:
Now press FS agen and rerun the progiam but ths time enter 3
Fveletter wore, The Shell wil display that t's not aFourietter word.
Word-tnput(*Please enter a four-letter word: “)
word_Length=Lentvord)
if word.length = 4:
print Gword, “is @ four-letter word. Well
done.)
elif nordtength
print Gord, “is a three-letter word. Try again.")
else:
print Cword, “is not @ four-letter word.)
LOOPS
‘Aoop looks quite similar toa condition but they are somewhat different in their operation. A toap will run through the same
block oF code a number of times, usually with the support of a condition.
TEED cc cccevnecrnevnieasenert cei EPID sn rr nies nam a
STEP 1 Ce ec CMa STEP 3 Pere ge a eros cee
ees pce reareee at tral
=
re x <1
ie Est Frat Bat ane roe tp
Soe a
coer eee eter rr eet
for x in range (1. 18):)
print Oo)
eee
eee
eee eneGetting Started with Python)
Python Modules
MASTERING MODULES
‘Think of modules as an extension that’s imported into your Python code to enhance and extend its capabil
countless modules available and as we've seen, you can even make your own,
There are
ETE ERED 28) 2ugh good, the Buin Functions within Python ne (asus an ger in be !DLE Shall as Une
are mites. The ise oF mociules, however, allows us ygame module sn'trecogn sel ov insted in
programs. As you areawere, madules Python, To installa madule we can use Pi (Ip installs P
imgor ted, sue a mgr ath jase den Uhe IDLE Shell and drop ite a cevmanel
“Terminal session, At an elevated adrnin command prompt, enter
pip install pygane
Some modules, espacally onthe Raspberry Pi The PlP installation requires an eleva status
are include by éefaut, the mach mocule being ¢ sue tins sanents at efferent ocetions,
ple, Sadly other mi avaiable ‘winows users can seerch For CMD wa te Start butzon and ight
pigame module, which contains click the result then dle Run as Adminstrator Liowx and Mac users
example on non Pi pl
‘many Functians to help ereste games, Tx-import pygame, can use the Sudo command, with sudo pin install packsFRI close the command prompt or Terminal and
tunch the !DLE Shell when you now enter
‘import pygane, the module willbe imsartadinto tre code
without any protlems, You! ind that mast cade downloaded ar
copied rom the Internet wi contain 2 module, mainstream o
urique, these are usually the source:
then boing issn.
‘errors in execution dueto
aacheve acertah result withiayaur own code, a
we've previously expetimented with. For example:
‘inpomt: wander
ules contain che
Brings n the cade from the random num
can thes use this module to create sore
For i ih range(10) :
print(random.randint(1, 25))
nalike
BR riscade, when saved and ected, ll depay en
Suey random numbers fram 1 ta 25. You can play around
pnt iede eae nei es kel oon eae
Tange, For exerpe
import randon
for i in range(25):
printCrandom.randintct, 100)
et generator module. You
(Python Modules
‘Multiple modules can be imparted within your eo
Toextend ourexample, use
import: random
‘import math
for I in rangecs):
print (random randint(L, 25))
print¢nath.pi)
36 result i asering oF
dom numbers faliowed
by the value of Pia pulled from the math module
sig the print(math,p) function. You can also pullin cei
Functionstroma madule by using the from and import commands,
‘from random import randint
for 4 in range(s):
printGrandinst2, 259)
Trishelps create a mx
pen streamlined approach to
‘arrmning. You can also use import module
‘which wil impart eversthing defined within the named module,
However, i’s often regarded 25 4 waste of resources but it works
onezneless. Finally, madules canbe imports as aliases
import math asm
printcm.pi)
‘OF course, adeing comments helos te tell others whats acing onz=) Getting Started with Python
Python Errors
ET xelorer erence ew ep Ma LMUelUM Oia Reon erage Rem AR ol mere MN ky
Python declares it’s not able to continue due to something being missed out, wrong or
simply unknown. Being able to identify these errors makes for a good programmer.
DEBUGGING
Errors in code are called bugs and are perfectly normal. They can often be ea ed with alittle patience. The important
thing isto keep looking, experimenting and testing. Eventually your code will be bug Free.
STEP 1 Ce eee EATER [henkfuly Python is helprul when it comes to
haw good che programming language's. Python is lisplaying error messages. when youreceive an
certainly easier than most languages but even ti prane to some error, in. ree text tom the IDLE Shell ic wilidetine che error self
‘annoying bugs. The most cornman are bypes by the user and viilst__ along withthe line number where the errar has e
errors, especialy when you have something lke
Remember that For every" there must be an equal number of
sot bes cen
2 coarcter in reference ey)
Sore sch ppt “
nereare thousands of online Pychon resoure
‘on how best to achieve something, whist 99 per cent ofits goo
cade, dor't always be lured into copying and
part is that you havertt learnt any
Indents Python programming
SLT! that alot of beginners fall faul of, Recall the
From the Consiians and Loops section, where the colon means
‘everything Hadented following the statements isco be erecutec as
lang as t's ue? Missing the indent, arhaving toe much of indent,
wllecomeback wth an rior,
© crett menses
C=
in arograrnening
ode snippets andlengthy discussions acress for
dom coce
Inte your editor. Mare often than nat, k won't woreand the worst
Cnoenos CE
“Acvexcellent way to cheek your code stepbysstep
Ba]
ta use Python Tutors Visualise web page, found
vu puthonbutorcomMisualize nimlémode=edit Simo
naste yaur cade ito the editor ane cick the Viele Execution
Dutton to run the cade line byline. This helps to.clear buss and
any misunderstandinas.
7
Planning makes For good! code. whilst a ttle ola
nee school, it'sa goad hab
‘will co beforesieting down to tyae
Deused anc the moculestoo;cnen w
eraccon or outputs.
to plan what your cove
Ht Lis the variables that wil
‘out a scrot for any use"
Purely out ot interest, the word cebugaing in
computing terms comes From admiral Grace
10 backin the '40s was warking on a monolithic Herverd
ark ilelectromecharical computer, According tol@gend Hopper
Found a meth stuckin relay, thus stoaping the system from
Hooper,
working, Rernoval oF the mathwwashence called debuggingz= Getting Started with Python )
Combining What
You Know So Far
We've reached the end of this section so let’s take a moment to combine everything
we've looked at so far, and apply it to writing a piece of code. This code can then be
(ese ne eM eo oll me ON CelS TEES AMA Stel] ea Lol eee
PLAYING WITH PI
For this example we're going to create a pragram that will calculate the value of Pi to a set number of decimal places, as
described by the user. It combines much of what we've learnt, and alittle more.
EE Start by opening Python and creating aNew Fle
the Editor First we need to get hol of an ecuatio
ately calculate Pi without rendering the computer's
(CPU useless Far several minutes. the recemmended calculation
Used in such creumstancesis the Chudnovsky Algor tho, you
can find moreinFormation about itt en.whined’aaratsiki
Chudnovs_algosithm.
Besin by importing some important medules and functions within
the modules:
From decimal import Decimal, getcontext
import math
Thisuses the decimal ancl getcantext- functions Fram the decimal
module, both af which deel with arge decimsl place aumbers and
12 math module,
Now you ca insert the Pi calculation,
part ofthe code, This is 8 version of the
Chudnovsky Algorithm:
def calccn):
‘t = Decimal (a)
pi = Decinal.cay
dero = Decimal(O)
kao
for k in ranger):
t = ecinal 1)*H "math. Factorial
@ecinal(6)*4)* (13591409 45451401344)
deno = nath.factarial(3**(rath.
Factorial k)**De imal (3))*(640320°*(3°))
pi t= Dectmalct)/Decimal (deno)
Pi
pi = Vpi
retum str¢pi)
FRIED vou conutise the chudnowsky Algorithm to create
your own Python script based on the calculation.
pi * Decimal (12)/Decimal (640320**Decimal(1.5))
BRTeGE RD) The previous step defines the rules that make
up the algorithm and creates the string that wil
eventually display the value of, according the Chudnowsky
Brothers’ algorithm. You havens doubt already surmised that t
‘would be handy to actually output the value of Pito the scraen. To
rectify that you can adc!
printCealecay)
PTSD You can save and execute the code at trispoint it
you le, The autpub wl print the value of le 27
lecimal places:3.141892653589734207668453591. Whit prety
pressive anes avn, you went some user interaction, co askthe
sor as be how many places should be calculated
“ou can insert np tine before the icalclaton
ue Def command, Irneeds to be an integer, as it will
cthersecefaulia sstrng Wecancah rmumberefote are vee
the getconent Function
nunberofdigits = tntCinput¢*please enter the
number of decimal place to calculate Pi to: *))
getcontext().prec = rumberofdigitsPEPER vou can execute the c
how many dec
outputting th inthe DLE Shell. ry itwith 1000 places
laut don't go too high or else your comauter wil be locked ypia
calculating
BD seb oinaty coe
making t more presentable, Let's incluce
an elemen:chat ames naw longit takes ©
‘computer to calculate the ® decimal places
and present the information in efFeven!
‘colour. Far this, rop into the commandline
‘and impoit.uhe colorama module Pi users
alreedy have installed}
pip! instal colorana
“ Combining What You Know So Far (ce
PRIIED) Nowe we need to import the colerama modcle
whicnwill output text in lous} along
‘with che Fore Function {which dictates the Foreground, ink, colour}
and the time madule to tat avittual stogwatch ta see how laag
‘urcaleulations take:
inport: time
inport colorama
from colorana import Fore
BREED 2 fish ourcode, we needa intiaise the
olorams module and ine function
the point whore the calculation starts, and when i finches. The ead
resus @ coloured ink cisplaying how lang the sroces Lonk (inthe
Terminal or camrnand lng
From decimal import Decimal, getcontext
import math
inport time
inpart colorama
rom colorana import Fore
colarana.init©
nurberofdigits = intCinput(*please enter the nuniber
Gf decimal. places to calculate Pi to: "D)
getcontextO, prec = runberofdiaits
start.tine = time.tineQ)
‘def caLc(n):
t= Decinstca)
pi = Decinal(@)
dono = Decimal et
k=0
for k in rongetn):
& = @ecimal(-1)*4k)*(nath.
Factorial (Decimal (6)*k))*(135914094545140134%%)
deno = math, factorial(3*k)*(math,
Factorial Ck)" *Decimal(3))*C640320"7(3"K)),
pi += Decimal (+)/Decimal (dene)
pi = pi * DecimalC12)/
Decimal (640320"*Decinal (1.5)
pi = 1/pi
return strCpid
printceatecy)
print(Fore,RED + “\ntinme taken:", time. time) =
start_time)C2) index
Working
with Data. .
ar |( Working with Data
Datais worth more than gold these days
and with it you can display, control, add,
remove, create and manipulate Python to
your every demand. Over these coming
pages we look at how you can create lists,
tuples, dictionaries, and multi-dimensional
lists; also how you can use them to Forge
exciting and useful programs.
Then, you can learn how to use the date
and time functions, write to Files on your
system and even create graphical user
interfaces that take your coding skills to
new levels and into new projectideas.
A g Strin
Date and Time
hat ¥z= Working with Data )
Lists
eee Ton Moma Mure ecole some eR attest cea ole RT| Reon Lege ali)
Python. A listis simply a collection of items, or data if you prefer, that can be accessed
asa whole, or individually if wanted.
WORKING WITH LISTS
Lists are extremely handy in Python. A list can be st
and lists within lists.
5, integers and also warlables. You can even include Functions in lists,
Alita sceunasf dra ctediers es ETRIARB vou abo cs rn thet tenia ata
aE create the name of your list Follawedi by an equals SUES using the minus sign before the item number [-1],
sign, then square brackets and the items separated by commas; ‘or the second to last item with [-2] and 50 on. Trying to reference any
mote that strings use quertes: ‘tem that isn’t in the list, such as [10] will return an enter:
numbers = [1, 4, 7, 21, 98, 156] umber's[-1]
rythicot-creatures ~ Unicorn”, “Balrog”, niyehical_creotures[-4]
“Vampire”, “Dragon”, “Stinotaur"]
FRR once you've defined your tstyou can call exeh FRPP DD) Slicngissinilar loindexing bul you can retrieve:
byreferencing its name, follawed bya numer Lists multiple itemsina list by separating tern numbers
start the fstitem entry 250, followed by 1,2, 3 and san. ‘with @ colon. For example:
Foresample fumbers[123]
ae ‘will output the 4 ane 7, being tem numbers 1 and 2. Note that te
Tocallupthe entire contents ofthe list. retuened values don't Incude the second incex pasitlon (as you
iaEEED ‘would numbers[13] to return, 7and 21),
Tocallthe third From ze-o tein the tst (21 inthis case.
EREPRI You canupdateicems within an existing st, remove RIBS vou can view what can be dane with lists by entering
items ane even join ists together Far exampie,to ist) into the Shell Te ourputis the availanie
Join two lists you can use Functions For example, inert and pap are used to add and remove
ers at certain positions. To insert the number 62 at item index 4
nunbers.insert(4, 62)
Ta removeit:
everything = numbers + mythical creatures
Then
the combined lst with
everything
‘number's. popC4)
BRTD ers can be addec toa lst by enterin: PRRTSEM ou also use thelist tucson co areaka string don
al into its components, For example:
Tistc*Davia”)
Breaks the
oa pews
O-Forstrings:
ne David into‘ "a, V5, T,'@. This can then
passed
mythicalcreatres-nythrical_creatures+[“Griffin"]
O-byusing the append Function: fone=List ("David Hayward”)
mythical_creatures .append(“Nessie”) ‘nome
numbers. append(278) age=[44]
sae User = nane + age
Se eer ae — user
Removal oitemscan be done mntwoweys. The Fst, based onthat you can create sprogamtostore
ED 2 cor nt ED sccrc'sturneandageasa
del numbers[7] name=input(“What’s your name? “)
Alternatively by Kem name: nomestisCnare)
EN NS age=intG nputC*How old are you: *))
mmythical._creatures .renovec“Nessie”) ‘ogesLage]}
SS ee ae user ® Inane + Loge
‘The combined name and ace lst called user, which canbe called
jy entering user ino the Sheil Experiment and see whal you caida,z=) Working with Data )
Tuples
Tuples are very much identical to lists. However, where lists can be updated, deleted or
See een Oremus cman elmer tne
Peace oe cusp her ces
THE IMMUTABLE TUPLE.
Reasons for having tuples vary depending on what the program is intended to do. Normally, a tuple is reserved For something
special but they're also used For example, in an adventure game, where non-playing character names are stored.
POTTED Siuoleisceaed the same wayasa ist butin iis BUBB vou can ceate groupad tuples neo tists Unak contain
instance you use curved brackets instead of square multiple sets of data. For instance, Reve isa tuple
brackets. For example: called NPC {Non-tayable Characters) concaining the character name
imonthssC*January>yeMrebruaryryiMarchmsesaprinny) altel combat ating for an adventure game:
"Moy", “June™) NPC=[CConan”, 100), (*BeLit”, 80), C*Valeria”,
months 95)]
———
£6 Sa Gh 0s Are Se 9nd Se ee
Swe Mer Mc ee Ta, SEP ay , ee
PEED) est 2swithlists theemsuithinanemedtuple car [EWA cect of these data items canbe accessed asa
Ee be indexed sccordina to their positon in the data ‘whale by entering NPC nto the Shell or they can be
range, le. indexed secording to their position NPC[0), You can alsa indexthe
een ndvicualtuples within theNNPC Ist
rmonths[5] ecto} C1]
However, ary attempt at deleting or adding tothe tuple wil esti Will display 100.
in an error in the Shel,BRI 0s veort noting that when referencing multiple
tuples within lst, the incexingis sightly d erent
from the norm. ¥ou wauld axsect the 95 combat rating ot te
haracter Vales to be NPC{A5] but e'snot. I's actualy
NPCLZIE1
Fee BA tees ae re TEATTT
BERT D ris meancot course thac theindeving Fallows thus
® aya
0,0 z
0,1 20
a aa
1,0
‘hich as you car imaging, gets a ttle confusing when you've gata
lot of tuple data to deal with
aS a hahaa ee J
Tee) Now unpack the tuple ina two
corresponding variables:
ame, combat rating!
‘You can now check the values by entering name and combat atin,
feeb auth ite, yuean sonst
a using negative numbers which count backwards
From the-enel of the data list. For our example, using the tuple with
utiple cata items, you would reference te Valeria character with:
NCE -01
Tuples trough ue feature called unackng,
SLE where the data items stored within a tuple are
_sstgned variables Fist creste the tuole with two items (name and
‘combat rating)
NPC=C*Conan® , 100)
BBD ou cn use te matandminfunctonste Fate
lee highest and fowest valves of a tuple comaosed of
numbers. For examale
nunbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99)
“The numbers canbe integers and floats. To autput thebighest and
lowest. use:
printCmax(nunbers))
printGninCrunbers))
cainez= Working with Data )
Dictionaries
Lists are extremely useful but dictionaries in Python are by Far the more technical way
of dealing with data items. They can be tricky to get to grips with at first but you'll soon
ere aie ch ote acs
KEY PAIRS
alist but instead each data item comes as a pair, these are known as Key and Value, The Key part must be
tunique and can either be a number or string whereas the Value can be any data item you lke.
PUTER DD Letssayyou nanttoceate aphonebookin Python, BRBSSIEMM As ith ksts and tuples, you can sheckthe contents
You would create the dictionary name and enter ‘Bf dictionary by giving the dictionary a name
the data in curly rackets, separating the key andvalue byacolon _pahanebook, in this example. This wil display the data ems-you've
Koy: Value. For example: entered ina similar Fashion Coal, which you're no doubt Familiar
phonebook=t"Ema": 4234, "Daniel" 3456, "Honnak™:) ‘th bY now
6789}
reagan eee
PD est 2s with most lists, tuples andl so on, stings FETED) The benefit of using adictionaryisthat you
Teed be enclosed in quotes ingle or cousie, canenter the key'to index the value. Using the
‘whilst inzegers canbe left open, Remiember that the valuecan be _ahonebook exemple from the previous steps, youcan enter
phonebook (“Enna”)
phonebook ["Hannah™)
celther a suing or an integer, you just need te enclose the relevant
nein quotes:
‘David: “0987 654 321")
ae eT
ye eT rite nerete mocha
ies aie eo 10Adding te a cictiznary s easy too, Yau can include
anew dats cem entry by acding the new key ane:
value items ike:
phonebookE“David"] = “0987 654 321”
‘phonebook
enti,"
You canals remove iter rom a cctonay by
SUG issuing the del command followed by the item's
key; the value will be removed as ell, since both wark as pair of
deta tems:
el. phonebook [“Dovid"]
“Taking thisa step Furshes haw about creating a
suet) piece of code that will ask the user fer the dictionary
key an value tems? Create a new Fdtor instance and start by
codingin a new, blank cictionary:
honebook={}
New
variables: one for the person’sname, the ather
| you need ta define the user inputs a
fortheir prone number (
Python cade!
mone=inputC"Enternawe: “)
runber=intCinput(“Enter phone number:
‘skeen isimple to avoid lengthy
»
(eG faa bin Gm no ae
PID veicyciannanene wma
‘avigbles tothe newly created blank dictionary. Using the same
process asin Step 5, you car enter
phonebook(hane] = number
EM Fare tiny es
frente» tr
those entries inta che phonebook
entering into the shel!
phonebook
hionebook (“David”)
tf the number needs to contain spaces you need ro make ita string,
soremave the int part oF the input
Now shen you save and execute the cace, Python
wail ask fora name and 2 number, stall en inset
onary, which you can test by
caineWorking with 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 thase long strings for better readability.
STRING THEORIES
You've already locked at some list Functions using insert, remove, and pop but there are also Functions that can be applied
tostrings
BERD Te maintool inthe svingfncionarsenalis spit. RAUMMEMM Note that he txtsplt part has the brackets,
Lith tyou'e able to spt apart string of dat, uates, ten space followed by closing quotes
teased an the argument within the brackets, For exarale here's 9 and brackets, The space isthe separatoy, indicating tac each st
string with thee tems, each separated bya space tementry separated bya space. Likewise, CV (Carwma parted
caememaneen ‘alue} content has a comma, so you'd use:
‘text=" January, February, March, ApriL,May,June™
months=text. spLitC’,”")
months
FETED Nou let'stumthestring nto alist and spi rae Youve nreviousty seen how you ean splita string
content accordingly: Into incividual letters 25 a lst using e nemer
nones=text:splitc “) none=list ("David")
Then enter the name of the new ist, ames, taseethe chree iter
The returned value is ‘a, '¥, ye Whilst it may seem alittle
useless under ordinary eve stances, could be handy For ceating
«2 speling game For examplePEPER 2e opposite of the splc hinctianis join, where
you will have senarate items ina string and canjoin
them alltegathe zo forme a word or just a combination of items,
fepencing on the progtem youre wnting. Far instance
‘alphobat="".join(L“a",”b”,"c","a","2"1D
alphobet
This wil cisplay ‘sbede in the Shell
You can therefore analy join to the separated name
you rade in Step 4, cambining the letters agah to
fous the name:
nana" joinCname)
none
‘We've oinee the string back together, and retained the List called
name, gassing t trough the join Function.
‘We Et x) pep ote ramus ve
A goad exemple of using the join furctionis when
you have allstot wards you want to combine intoa
sentence:
List=["Conan”, “raised”, “his, “mighty”, “sword”,
Mand", “struck”, “the”, “denon"]
texte” “.join(list)
text
Note the space etwreen the quaies befa‘e the Join function (where
there wereno quotes in Step 85 join
( Splitting and Joining Strings Cl
“Aswith the splitfuretion,the separator doesn’t
Baa]
have ta be a space, tean slso bea comma, afull
stop, a hyphen or whatever you tke
eolours-[“Red", “Greén®, “Blue")
col=",”.join¢cotours)
col
‘There's some interesting functions you apaty to 8
string, such as capitalize and.utle.Far example:
‘title-"conan the cimmerian”
itl. copitalizer)
title. titled)
Yau can also use logic operators an strings.
eee with the ‘in’ and ‘notin’ Functions. These enable
‘you ko checkif a string contains (or daes not contain] a sequence
of characters
messages"Have a nice doy"
“nice” in message
bad” not in message
“day” not in message
“night” in message
ie Spat roma ar “hese tr ere arto,
cetnaeenz= Working with Data )
Formatting Strings
When you work with data, creating lists, dictionaries and objects you may often want
Cormac tas iat mora ean e erie ee eter aie En
SR eMCUae nonce eleke ster ce
STRING FORMATTING
Since Python 3, string Formatting has become a much neater process, using the .format function combined with curly brackets.
It’s more logical and better Formed approach than previous versions.
POTTED) Toe basic formatting inPythonistocal each BRTTSE DD ou cn ofcourse alse incu nteyars into the mic
veiableingo the string sing the curly brackets ae
rreme="Conan” printC*{} of mas a skilled mercenary,
rint("The barbarian hero of the Hyborian Age is: and thief too. He once stole {} gold froma
1". Format (nane)) mmerchant.".FormatCnane, place, nunber))
Remember Lo dose the print function with two sets ‘There are many difererLweysto apply sting
Of brackets, a5 you've encased the verable in one, Formatting, some are quite simple, as we've shown
‘end the print function in anather: Youcan incluce multiple cases of you heres others cade signiteantly more cormplex, tall depends
sting formatting na single print function: ‘on what you want from your program. A goad alace ta reference
Frequently reaarcing string Formatting the Python Bocs webpage,
Found at wwouedocs.python.org’3.ifibraryistring html, Here, you
‘illfine tons of help.
rnane="Conan”
place="Cimmeria”
print("{} hailed fron the North, ina cold Lond
known as {}".format(nane, place)?
ea We) en GPT a(- Formatting Strings Cl
(ees Pou lan seep is i iy as es einved Tmeeeereae Tbe
sae Formatting Function. You need to place an asteriskin eae in the same fashion:
Front oF thelist name:
ome=inputC“What's your name? “)
nunbers=1, 3, 45, 567546, 3425346345 print(“Hello {}.". format(nane)
printC’Sore munbers: 0, OG. G, O. 0".
Format ¢*nunbers))
ERTS Wien indexing in ists, che sare applies to calling 2 REMESIM vou con extend this simple code examate ta dspley
lstusing sting formatting. Youcan index each tem the firs: letter io a aerson’s entered name:
‘eccording ta ts position from to however many are present): ieemnieemeeneicinats
nunbors=1, 4, 7,9 print(*Hello {h.". Format (nane))
print('More runbers: {3}, {0% {2}, ‘Vname=1ist(nane)
{1}.".formatC*nunbers)) print(“The first Letter of your nane is a {0}".
format *Tname))
We Ba 2 Bt ie ds oe
And.asyou probably suspect, you can mixstrings EExD You can also call upon a pair of lists and reference
Sus and integers ina single list to be called in the Say them individually svichin the same print Function.
rt Fi aking Ba he ce Sen 7. cao Bo
characterse["Conan; “BelitTy "Valeria’y19 275) fmes=L"Conan”, “BeLEt “Valertar]
20) ages-[25, 21, 22]
print Ca} is 43} years old. Whereas {1} is 44}
STU cessona CA HaTackers
Creating two sts. Now you can call each ist, and individual items:
printC“{@[0]} is {1[@]} years old. Whereas {0[1]3
is {1[1}} years old.”.format(nanes, ages))z= Working with Data )
Date and Time
When working with data it’s often handy to have access to the time. For example, you
Oak eens eater tesa tla seta
rome M cn M ete eect te cea eta ohms ce
TIME LORDS
The time module contains functions Ehat help you retrieve the current system time, reads the date From strings, Formats the
time and date and much more.
Tea Fistyouncadto import tne Umemodule.tsone — RFPS MM) You can see the structure of how Lime is presented
that’s builtin to Python 3 so you shouldr’tneed to by entering!
drop into.a command prampt anc pip instal it. Once it’s imported,
‘you can cali Lhe current Lime and date with a simple oman
‘time Local timeQ)
‘The outputs displayed as such: "time struct timate
year-2017, tmron-9, tmnday=7, tm hour-9,
‘mmin=6, tm.sec=13, ta_nday=3, tmyday=250, tm
‘isdst=D)’; obviously depencent on your curent Line as opposed
{ca the time Chis book was waitten,
import time
time asctimec)
FED Tretine hncionisspltinto nine wples theseare RNIB, there are numerous functions bul into the line
chided up into incexed items, as with ary other module, One o the mast common ofthese is
tuple, anéshown inthe screen shot below serFémel), With you re able to presenta wice range of arguments
asic convertsthe line Cuple inca astring. Far example, La dspla the
current dey fF the week you can use
inet aloes ‘time. strFeinec*xA)
z om soe cw Ne) ome tet
: sn co)
6 bayorvess 096 (18 Hoy
1 ometyer 110266 le
4 Davnsvnge 10,1, -1 msn vay ater
Black Dag Fee Series Volume 37Coazandtine CE
BED itches eens EIR se teenth ti
sis Ow cole oat ss COHEe Stone det nie
: sin tee yuean time partcuar event sth Take
—— he Ende rm above ag elter sigh by ncn
‘time. strftimec“%b") stort_time=time.timeC)
time. strftime(“MH")
time, strftimeC“aHKM")
“Thenthere's:
endtimestime -timeC)-starttime
the last entry indicates, antering them as %H%iM coesn't display the —ingut statement, as that's when the variable name is bei
time correctiyin the Shell Youcen easly recty tis witty depending on hw long the user took to lagin, The length of time is
time. strftimeC*RHsx4") then displayed on te last ine ofthe code asthe endttime variable
Sk og pene ree
THismeaneyoure going tobe abe te doly There satot
SLE! either the current time ar the ume when een medule; som
nat can be cone withthe me
of ibis cuite complextoo, such as
Something orcurvee, such as a user entering thelr name, Try cfspleying the rurnberaf seconds since lenairy ‘st 1970. F you
thiscodein te Edtor, svantto dill down furtner into the time module, then in the Shel
center: helpCtime) to dsplay che current Python version help Fle
import time
Naneinput(“Enter Login name:
primtc'elcome”, ane, "\d")
printC"User:", nae, “logged in at", tine.
str ftime( “9H 254")
Try to extend itfurtherto include day, manth, year and soon.
5 Forthe time mocule,
az= Working with Data }
Opening Files
In Python you can read text and binary Files in your programs. You can also write to file,
which is something we will look at next. Reading and writing to files enables you to
output and store data From your programs.
OPEN, READ AND WRITE
In Python you create a file object, similar to creating a variable, only passin the file using the opent) Function. Files are usually
categorised as text or binary.
GED Sac byenerng some tentinte yoursysien’stet — EERE sryouncw enter poem into ure Shell you will get
editor. The text edlitaris best, nat a word processes, some information regarcing the text Fe you just
{as wore processors include backaround Formatting and omer ‘asked to be opened. You can now use the poem variable to read the
elements In-gur eample, wehavethe peem The Cimmeran,by contents ofthe file
okert E Howard. Youneed to save the Fle asp
poom:nead()
Note than a fb etry in the text represents anew line as you
ised previous
FETED Yousetheopend function topassthe fieintoa — EEIAB ir you enter poemead asecond limeyou wil
variable as an object. You can name the Fle object natice thet the text has been remaved fromthe fle,
‘enything you lke, butyou will needtoteliPythonthensmeand You will need to enter: poermopent/hone/pi/Doctanentts/
location ofthe text Fle you're opening Poom.text") again to recreate the file. Thistime, however, enter:
oem-openc“/none/pi/Documents/Poen. tx:
printcpoem:reaacyy
This time, the mn entries are remiovedin favour of new lines and
eaiable text.Opening Files
PIR st os with its, tuples, dictionaries and son, PRI ectending thisfursher, youcan use readies to
‘you'reableco index individual characters of the 1790 alithe lines of the text and store them 25,
text. For exam rmtipleLsts. These can then be stored 2ea variable:
poem.read¢s) oem-open(“/home/pi/Document’s/Poem. txt")
i ‘ines=poom.readlinesc)
isolaysthe Fst fue characters, whilst again encerin
Disolaysthe Fst ers, whilst 8 Lines [0]
oen.readcs) Lines[1]
Tines[2]
Willdsalay the ext Five, Entering {1 will lspiay one chi
atine.
sug using the readline() Function. For example: age ‘ef text back to us:
oem-opent"/fome/pi/Documents/Poem. txt”) for Lines in Lines:
oen.readLina() print(Lines)
vill isplay the fist line ofthe text wth ‘Since thisis Pythan, there are other ways to praduce the same culpa:
poem:readLineg) ‘poemaopen(*/home/pi/Documents/Poen.-txt”)
for lines in poem:
Displaying the next line of text ance more. aan
BETTER) You roy hove guesses thet you can pass BETTER EBD. leython of try. except, else, where the code isheld with try, then if ere's
‘comes across something that's an exception do something, e'se de someshing else
inherently wrong with the cade,
However, you can creste your
‘wnexceptions that are des-gned
to contain the potential erro! nel
react tot, 2s opnosed to letting
the code fal(eceotins CE
PI Fc example, se the dvidety zeroeror.Youcan ERM niotratyyoucan quickly Fix the enue by changing
create an exceation where the cece can hance the the" read ontyinstan
error without Python quitting due te the problem asyoualrendy know, wll create the Fle and witethe cantare then
commt thechanges ta thefie, The end result wil eportacifferen
try setofcrcumszances, nis case, successful execution ofthe code
GeintCinputC“Enter the first number: *)) a se ESE .
beintCinputC*Enter the second nunber: *))
print(a/b)
except ZeroDivisiontrror
printC*You have tried to divide by zero!”)
else:
print (“You didn’t divide by zero. Well done!”
PRE FIEP ou con atsouses nally: block which worksina
ur previous tutorials, nila fashion aut you can't use else with it. To us
PRET MD you can use excestions
tasks. Using an example
let's assume you want to opena fle anc write toi our example from Step 6
try: ty:
‘txt = open(“/hone/pi/Docunents/textfile.tat”, “r") txt = open(“/hone/pi/Documents/textfile,txt™, “r")
txt.writeCThis is a test. Normal service will es
shortly resure!™) txt.wnlteC*This Is/a’test. Normal’ service will
except T0EKror: shortly resume!”
print (Error: unable to write the file. check: finally:
permissions”) print C*Centent written to file successfully.
else Hove @ nice day."
print (Content written to file successfully, Have txt. closeC)
a nice day.”) except T0Error:
‘txt.closeQ, print “Error: unable to write the fle. Check
permissions”)
Obviously wont work tote etext Asbetore an er witocauras youve used the
SLT txt being opened as read only (the "r" part). Soin eee 'r” read-only permission. If you change ittoa“w",
ivca elthas he ion rut or dass) SNE Uva nuke nt ear bebotlinlsed he
‘rong youve creates exception shothe OETor cass OLE Sl Newest rearbe try getting the exception
IMonning the user thatthe pemisions re nore oe rghit the stine,Pactee though and youll gtthe hang
oi
He BO Hye Be eee Br BeBE) vesting wih oa)
Python Graphics
While dealing with text on the screen, either as a game or in a program, is great, there
Py een etna neue iodine tesserae acts et en ar one
Pounce ecient n haar tue acti itl
GOING GRAPHICAL
You can draw simple graph
some spectacular effects.
PATER 22 of the best graphical modules vo begin learning
Python graphics is Turte The Turtle mociule is as
the name suggests, based on the turtle rabots usec in many schoo
Una ean be plogrammed to caw something ava large piace
‘af paner on the car, The Turtle mocule can bei mportee with:
import turtle
ines, squares and soon, or you can use one of the many Python modules available, to bring out
PETER hs command turlecircletso) is whatdraws the
tele on the screen, with 50 being the sie. You
can lay around withthe sizes if you ike, gaing upto 100, 150and
soyond you can draw anarc by entering: tuntLe.cirelecs0 ,
180), where the size $0, uk you're teling Pytnon to only caw
80" ofthe crcl,
Gia
import! turtle
turtle.circle(S0)
turtle.getscreen()..root .mainLoop()
‘As usual press FS to save the code and execute it, Anew window will
how open up and te"Tu tle wil drawa cele
Let's begin by drawing a simple circle Sart. a New
File, then enter the following code:
PRI) The lst park ofthe circle cade tell Python to keep
the window where the crewing fs taking place to
remain oper, 50 the user can cickto clase it, Now, lets make a square!
‘import turtle
print(*Drawing a square..”)
for t in rangeC4):
turtle. fornard(39@)
surtle-left(90)
‘turtle, getscreen()._root.nainloopO
‘Youcan seethat we'veinserted loop to draw thesidesaf the squareCriton canis CE
PI vou can adi anewiinetothescuare cocetoadd — ERE Nowlet’s got the cone by mportingthe pygsme module
some colour
import pygane
turtle. color¢*Red”) pygane. init
‘Then you esn even change the character to a
ualturie byentering: ing’ = pygame, image: ToadC“RP -pag")
‘turtle:shapec*turtle”) white = (255, 255, 255)
‘You cen also use he command turtle, begineAILO, and —
turkie.end ALG tori nthesausreviththechosencolous; MTA acta ie
red outiine, yellow Ti set_mode((n, h)) |e
screen-flL(Gwhite))
screen-fill. (Gwhite))
screen-bILtCimng, (,9))
pygane.display.fip()
hile True
for event in pygane.event. get):
if event.type = pygane. QUIT:
pygane. ait)
Inthe previous ste you imported ygume, nated
ee! the pygame engine and asked it to import our saved
Ino carolecasyeu beaiito master the way works Ent his yPllogo image saved as png. Nes yu defined the
cee colour oft window to dply the image a the
inamncaiiiecoee sino a prs seine eee aly ou
coler(*red’, ‘yellow’ ) ——
begin_fllc) w= 900
while Tree Poe
Fornard(zoo) er Screen = pygane. display .set_mode(cn, h))
LeFEC170) Screon.Fill{{white)}
iF abscposO)< 2:
sek screen. fill((white))
end. AULO Screen.blit(ang, (0.09)
done een pygone. display: Fipc>
Ws different method, ee ———
; for event in pygame .event..get():
Af event. type == pygame. QUIT:
pygame.quit()
butvery effective
Another ay inpich ou con display graphics sracrnip areata
ED cis inecorenodic mere acnmecs MaMa oe wt becsstaedin ore
ways in which pygame can hel you output aranhies to the screen,
but for now lets look at displaying a precetined image. Start
de and you
window, Have a
id with the colours, sizes and so on and take time to look
tan che many functions within the pygamemodule to
pening abrowser and nding an image, then save It tathe Fé
where you save your Python code
RaspberryPi
cospbery!Working with Data
Combining What
You Know So Far
Based on what you've looked at over this section, let's combine it all and come up with
a piece of code that can easily be applied into a real-world situatio
Pela R ny
least, something which you can incorporate into your programs.
LOGGING IN
For this example, let's look to-a piece of code that creates user logins and then allows them to log into the system and write
the time they logged in at: You can even include an option to quit the program by pressing ‘.
FERTIM cinby importing the time module, creating
evs dictionary to handle the usernames ard
passwords and creating avarizble to evaluate the cur
the program:
import: time
Next you need zo define some functions. Youcan
pegin by creating the main menu, where all users
‘wilrezurn to after selecting the available options:
def mainMenuC):
global status
Status = input(“Do you have @ Login account?
yn? Or press q to quit.”)
if status == "y":
oldser()
elif status = “n":
rnenUiserO)
elif status = “a":
ent scatus of
“he ieba status statement eparasalo
suede variable fromane that can be called throughout
Te lesa) outa oa ong ic ptreoet oad
nged inside tre Function. We've aso reference sorme newly
defined Funcuons:alduser and newser which we'll get tonext
BRUM the newuserfunctionis next:
def nentiserC):
createLogin = input¢‘Create a Login mane: “)
if createLogin in users:
print C\nlogin name already exists!\n?)
else:
createPassw = input(“Create password: “)
users[createLogin] = createPassw
print(\nUser created!\n")
‘Logins=open(*/none/pi/Documents/Logins. txt",
“ar
‘Togins.witeC*\n" + createLogin + “+
‘createPas si)
logins .close()
“This creates 2 naw User and password, snd writes the entries ince 3
Fle caled ogins.ixk
site lienYou wil nec! ta specify your awn
lagins txt Fe, since we're using a Raspberry Pi
Lesentally thisadde the username ane paccword Inputs Frorn the
user Lothe existing user sf} dictionary, so the key and velue structure
remains: exch users te key, the passwardis the value
let smaeatey
print (*irkogan name already exists!\n")
‘Srestabuian = Uvis “reste pmo: *)
atesfereatecopini = erevearooor
Freon ene
PRRIIDD ow to create the oldUser function
def olduser(:
login = inputC*nter login name:
possw = input(*Enter password: *)
# check iF user exists and Login matches
possword
if login in users ond users[login]
print C*\nlogin successful! \n”)
print CtUser:”, login, “accessed the syste
on:”, tine.asctimeQ))
else:
print C*\nlser’ doesn’t exist of anong
password!\n"),
1
Ere a Tere' 2 fairbit happening here. There are login
and pass variables, hichave then matches ko the
users dictionary, IFthere'sa match, then you have a success‘ul login
and the time and dete of the lagin's autputted. If chey don't match,
Len you arintan evvar and the process starts
Filly, yourieec to continually check
hasn't been pr
th key
dco ext the program. We can do.
swith:
While status 1 “a
status = disployMenuC)
“Although a seemingly ina two lines,
loop iswhat keepsthe program running. At the end
against the current value of status. IF
hat global value it’ Lhen Lhe program continues. i's ecualto
then the program can quit,
‘of every Functionit’schec
while status ! a":
status = displayMenu()
ular names and passwords, with the lagins.txt file
neing created ta store the locin data and successful logins being
Emestamped. Now i's upto you to further improve the code,
Perhaps you can import the lst of created users froma previous
Session and display a graphic upen successful login?
You can now creste users, chen login with their
“ Combining What You Know So Far Cl“ Using Modules
Python module is a Python-created
source file that contains the necessary
code for classes, Functions and global
variables. You can bind and reference
modules to extend functionality
and create even more spectacular
Python programs.
IFyou want to see how you can better
use these modules and adda little
something extra to your code, read
‘onand leam how they can be used to
Fashion fantastic code,
76 — Calendar Module
78 OSModule
80 Random Module
82 Tkinter Module
aap
88 Using the Math Module
Create Your Own Modules
ame Module
asudoubisaionssn Coding frychon FBBE) rena: )
Calendar Module
WORKING WITH DATES
The calendar module is built into Python 3. However,
For some reasonit’s not installed you can add it
calendar as a Windows administrator or sudo pip install calendar for Linux and macOs.
PETTRDD Louich Python 3 andenter import calendar to
callupthe mocule and is inherent Functions. Once
Iesloaded into memory, start by entering
sep=calendan. TextCelendar(calendar.SUNDAY)
sep. prinonth(2017, 9)
You can see thatthe days of September 2017 are
ciso.aved in a wall calencar Fashion, Neturally you
canchangethe 2017, 9 part ef te second ine to any/year ane
‘month you want, abirthday For example (73,6). The Nirseine
Configures TextCalendar to stat its weeks on a5
for Monday if you prefer
Forming your awin cade. For example, you can
1p yoa’s betwen ls sped years
‘Leaps=calendar. LeapdaysC1900, 2018)
printCleaps)
There are numerous Turetigns within the calendar
module that may be of interest to
iaythe number aF
“The seault § 29, starting from 1904 onward.
Yow could ever Fashion thal particular exa
Suse y
‘a plece oF working, user interactive Python code:
‘inport. calendar
print('Sess>2>>s>Leop Year
Calcul atorecccececce\n" JylmintCinputCEnter the
first year: “)
y2eintCinput(*Enter the second year: *))
‘Leaps=calendar. LeapdaysCyl, y2)
print(‘Number of Leop years between”, yt, *and”,
y2, “isi”, Leaps)import calendar
year=intCinput(HEnter the year to display: “)
print(calendar .prcet(year))
We're sure youll agree that's quitea handy bit of code to have
tohand,
You can also create = prcsaram that vil display ll
the days, weeks and months withina aiven
Interestinaly we can ak
month by ustaga simple for loop:
import calendar
cal=calendar .TextCelendar(calendar-SUNDAY)
For i in cal, itermonthdays(2018, 6):
printci)
You cansee ha coce produced some zeros atthe
SLT! beginning, this is cue to the starting day of the
wee, Sunday nth ase, and overlapping day Fomthe previous
tmont, So teecuttng othe days ta on Friday st Jane
D1 an wi total 30 gs the outpu correc ph
esi a)
ero ep Tn
( Calendar Module eC
‘You're aso able to print the individual mon
sd3ys ofthe week
import calendar
for name in calendar.month_name:
print(nane)
‘import calendar
for name in calendar .day_name :
print(nane)
EO seh Duy EN HEH
FRETS The csienda-madule also allows us to wrte the
Functonsin HTML, so that: dsplayit on a
‘website, Let's start by cresting a new ile
‘import calendar
cal=open("/home/pi/Documents/cal .htmi" “w")
c-calendar.HTMLCaLencarCealendar . SUNDAY)
col .nrite(c. formatmonth2018, 1))
eal .close()
“This code wll create an HTML file called cal, open t-with a browser
and italspiays the calendar For January 2018.
OF course, you can madi
b page calendar:
ta display a given
‘import calendar
year-intCinputC*Enter the year to display as a
webpage: 9)
cal=open(“/hone/pi/Documents/cal .html”, w")
cal .write calendar, HIMLCalendar(cal endar. MONDAY).
Formatyear¢year))
cal .close()
“This code asks the user Fora year, then createsthe necessary
webpage. Remember tochange your fiez=) Using Modules)
OS Module
INTO THE SYSTEM
One of the primary Features of the OS module is the ability to list, move, create, delete and otherwise interact with Files
stored on the system, making it the perfect module for backup code.
You can stark the 8 macula
Functionsto see how itinteracts
ment ehae Python is running oa.
ty P iy tis
th the operating
joure using Linux
system envi
‘ithe Rasp
import os
hone=os .getond()
print¢hone)
Gia
Inourexample that's ho
be user name you login as.
For examle, windows 1D wil
Pychon3632
The returned result From arnling the vaslable home.
isthe current user's harie foiceron the system,
i ie willbe different cenending on
re operating system you Use,
put: CAProrar Files (x88)
EATER) [Windows output islifferentas Unat's the
ssurrent working ditectory oF Python, as determined
by che systern as you might sussece, the os.gezcstc) Function s
asking Python to etiiove the Current Working Directory. Linux users
willsee something alang the sare ines asthe Raspleerry Pi, a5 will
=racOS users
FRIIPD) vel srothe interesting element to the OS module
fs tsaoilty co aunch programs that are installed
in the host system, For instance, you wanted to launch che
chromium browser From within 8 Python pragiam you can use
import os
browser-o5. systen(*/usr/bin/chromiun-browser")FRI he ossisternd function iswihat allowsinteraction
with external orogrems: you can even call ua
previous Python oracrams using this method, You will obviously
need to know the fllaath and arogram fle name for eta work
successfully, However, youcen use the following
import os
os.systen('start chrome
Feed/ausic™*)
For Step ’ '
SENG that the OS module works roughly the same acrass:
allplatforms, in that case, we opened YouTube's music feed gage, so
itistheretor open specific nages
import: os
os.system¢ ‘chromiun-browser “http:/é
ie my
Note inthe previous tep'sexample he use of
SLE single and double-quotes. The single quates encase
aes onerous vey eters Had he
totes open the spaced sane ou co hen sears Cal
mle absinthe sme browse
import os
‘@=(‘ chroniun-bronser “hep: //ednpublications
cons”")
b-C‘chromium-browser “htto://iumi oongle, co.uk")
os. systenca +b)
osmedie CE
PRISED) the ability to manpulate directories or Folders
you arefer, is oneoF the OS module's bes Features,
orexample, to ereatea new directory you can Use!
import os
(os.mdir¢*NEW")
“This creates a new directory
in the Current Working Directory,
ip the mkeir function,
ee
import os
05. renane("NEN", “OLD")
e
telete then
‘import os
os. rndir¢*0LO")
Another module that goes together with Osis
shutil. Youcan use the shutil module together
eatea tmestaped backup drectary, and
‘sith OS ane time
copyils int it
import os, shutil, time
root_sredir - r*/home/pi/Bocuments*
root_dst_dir = '/hone/pi/backup/? + timeasctimeC)
for sredir, dirs, fles in os.walkCroot_sre_dir):
dst_dir = src_dir.replace(root_src_dir, root_
dst_dir, 1)
if not os.path.existsCdst_dir
os.mokedirsCdst_dir)
for file in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.pathjoin(dst_dir, file)
if 05. path.existsCdst file):
os.renove(dst_file)
shutitcopy(srefle, dst_dir)
print(“ssarssnnneBackup completecssassaess")ee
Random Module
RANDOM NUMBERS
‘There are numerous Functions within the random module, wl
Python programs.
when applied can ereate some interesting and very useful
PETAR E ust swith ovier modules youneed toimgort BUTE Hoveves ve random mocule is
Fandom before you can use any ofthe functions Fornumbers. You can use i to sele
‘we're going to lockat in 2s tuto‘al.Ler'sbean bysimply arininga ust Frariranéom, an the Ist can contain anything,
Fandom umber frre 1 to
sed enclusively
an entry froma
import random
import random randon.choice([*Conan”, “Valeria”, “Belit"])
BeinteraneeaNE eS. “This will display one of the namas oF our adventurers at random,
Which ag eal addilion Lea text adventure game.
Inout example
thenumber!
was returned, However, en
the print Funetion a Few mare
times endit ay different
integer values fom the set ai
numbers giver, zee to five, The
although pseudo
adequate forthe
aimmer to utlse in
oe FEI 0. can extend the previous example somewhat
: : teva random cho'ee selec arom alist or minec
variables, For instance
vera
their code,
inport: random
“David”, 44, “BOM Publications”, 3245.23,
' “Pi", True, 3.14, “Python"]
PRED Fo: a tigger set of numbers, including floating ESSIEN SISIERCR
point values, you car extend the rangedy usingche PremeCrnd)
imort random ie st Set 2 Si row He
printCrandom.random() +208)
‘willdsolay a floating point aumber between O and £09, oth
[oF sround Fifteen decimal pointsPERI | tecestinely, youcan also use aFunction within the
randori module to shuthe the itemsinshe st, thus
‘adding little more rang omness into the equation:
random. shuffleCLst)
printcist)
This way, you can keep shuffling the lit Before ciplaying avandem
item from,
BEAD (sing suffle, you can ceate an entirely renciam is
cof numbers. Forexemple, wiznin 2 given range:
import random
Ist=([4] for I in range(z09)
random. shuffeCLst)
printcist)
Keep shuffling the list and youcan havea differ
items rom to 20 every tme,
ction oF
ESTP) You conto select rendom numberfrome given
rangeinsteps, using the star, stop, stoa loop:
import random
For 1 in range(10):
printCrandon. randrange(®, 280, 7))
Results willvary but you get the general idea as tohowit works,
Random Module GC
FRIED 2's ose an example piece of code uhich fips =
virtual coin ten chousand times an counts Now
manytimesitwilland onnescs or tails:
import random
output={"Heads”:0, “Tats” 0}
coinel ist (output keys)
for i in rangec1@a00):
output random. choiceccoin)}i=1
printc‘Heads:", output[“Heads"))
printC*Tails:”, output[“Taits”])
FRPPIPTD. Here's an interesting piece of cade. Using atex
file containing 456 thousand words, you can aluck
‘user generated number of words From tne File
‘import random
print(*ssssssoaRandom Word Finder Fle] ad ereakeaTiue/alse while
import pygane ‘mont pygane
pygane. init From pygane. locals import *
pygane.init()
REE | ccmeninionepyoane, display. set-node (000, 6002)
Se pygane..di splay. set_coptiont “Adventure Game")
running-True
while running:
fer event in pygane.event.get@:
iF event. type=QUIT:
runningeFalse
pygame.quitQ
fe EAL Faymat Bin Options Wado Help
PRP ts create asimple came ready window, and give
ice tite:
anew ndon-pygone, di splay.set_mode(C800,620))
Pygame. display. set_caption(*Adventure Game")
ered you need to cick back
pg cade, alse, youcan change
i pybane Locals por
Bria display.sei-caption( Aventure cane")
soe, unnine —
TF tvanttypersGutT
pramesquitt)( Pygame Module
now stil
IFthe Pygame wi
close con'tworr,itsjusta
=P tHEIDLE fshich sarin
perfectly wel
You're going to shift the code around abit nom
running the main Pygame code within a while loop,
er anc easier tofollow. mteve downloaded a
use and we need to set some parameters Fo
‘img=pygame image . load“ /home/pi./Domntoads/
spritel.png")
def spritetx,y):
gamewindow.blitcima, (x,y)
8008.45)
itmaes tre
import pygame
pygane. init peers
‘ganewindow.ALLCwhite)
white running spritecxy)
ganenindow=pygone. display .set_node (600, 600)) Hen A aan,
pygane.display.set_caption(“Adventure Gane”) for event in pygane.event.get(>:
black-0,0,0) +f event. type—pygome. QUIT:
vhite=(255, 255,255) runningeFalse
fecgrrncnns:
PRP 2: cuickly gothrouch the cove changes. lownloadediimage calledsprite1 png and allocated ito the
Cefined two colours, black and white together \ariable imgtand alco defined = sorte Function and the Bic Function
with their respective RGB colour values, Newt we've loaved the ‘illallow us to eventually mave the mage.
—— xocooor0 45)
fm Bygame, Locals inpors * ee
* eptrindn Ftetsce
Pybsneslepay updater
gumerindow-pygane. display set mode(#00.600))
Dieses display set-cptient ‘Aventure san) weiccteccsmener
init ten( 255.255, 259) aT
eimenindon-BLACCing, (1.y))BE) rena: )
PRED ov we can charge the cade arounel again, this
time containing amavement option within ene
‘while lop, and acing the variables needed to move the spre
aroune the streen:
‘import pygame
Fron pygame.locals import *
pygane.imitC)
running-True
gamewindan~pygame. display. set_nodeCC80@,600))
pygane. display. set_caption( “Adventure Gane")
black=C0,0,0
White+C255,255,255)
‘img-pygame image. Load(“/home/pi/Doonloads/spritel.
png”)
deF spritecx.y):
gomewindon.blitCimg, Oxy)
'800*0.45)
y-(600"0.8)
xchange-9
‘ingspeede
while running:
for event in pygane.event.get©:
if event. type—QUIT:
runningeFaise
if event.type — pygame.KEYDONN:
if event, keys=pygome.K_LEFT:
xchange=-5
elif event. key=pygame.K RIGHT:
xchange=5
if event. type=spyygame.KEYUP:
if event. keyeeaygame.I LEFT or event.
key==pygame. K RIGHT:
xchonge-0
x 4= xchange
gamenindon AIL Gwhite)
sprite(x,y).
pygame.cisplay-updatec)
pygane.quit)
PEE tenis
PUTER 02% the code down and using the leftand right arraw keys on the Keyboard you cen move your sprite across the bottom of
the scieen. Now, looks like you have the makings of classic arcade 2D seroler in the worksPPI You can now implementa few actions and ils
some previoustucarsalcace, Thenew elements are
thesubprocess module, of which one Function alow usta launch
second Python scrigt Fo withinanather, andhwe'segoing La crestes
Fecalled pygametst py
impart: pygane
imart tire
impart. subprocess 1 bt Fam tom ne |
pygane. initO ——
Screen = pygane.display.set_mode((800, 250) || jcc iit
Clock = pygane.time.CLock a somo
Font: = pygane.font.Font(None, 25) fees ton
pygane, time, set_timerCpygame,USEREVENT, 200) |= ws-rwawe
J Pence
def text_generatorCtext):
eee
for letter in text:
temp t= Letter
if Letter I= *:
yield tmp
Glass DynaricText (object):
def _init_Gelf, font, text, pos,
self. font,
seLF.text = text
self._gen = text_generator(self text)
self.pos = pos
selF.qutoreset = autoreset
self update)
deF reset(self):
selF._gen = text_generator(self text)
self.done = False
seLf.updatec)
def updateCselF):
if not self.done:
try: self.rendered = self. Font.
renderCnext(seLf.gen}, True, (®, 128, 8)
except Stoplterati
self done = True
‘time. sLeepC19)
subprocess .Popen(“python3. /hore/pi/Documents/
Python\ Cade/pygaret.py 1”, shell=True)
def drancself, screen):
screen, blit(self .rendered, self.pos)
‘text=C"A Long time ago, a barbarian strode fram the
Frozen north. Sword in’ hand. ..”)
message = DynamieTextCfont, text, (65, 120),
‘autoreset=True)
while True!
for event in pygome. event. get):
Uf event.type —= pygane.QUIT: break
if event. type — pygame.USEREVENT: message.
updatec)
else:
screen. fill (pygane.color.Color¢ black" ))
message .dranCscreen)
aude.
ce
pygane display .AlipC
clock. tickCée)
continue
break
Pygane.quit©
PEPET) ween you run tis code it will dsplay a lors,
narraw Pygame window withthe intro text
scollinato the sight. Albers pause often seconds, then launches
che main game Python seri where you can move the wertiorsprite
around, Overall the etfeccis qi but mere's always room
For improvement
%ee
Using the Math Module
E=MC
‘The math module provides access to a plethora of mathematical Functions, From simply displaying the valve of Pito helping
you create complex 3D shapes.
present. you can import the module's function by simply entering
import math ints the Shell or as part of your cadein the Edita
The math modules bu
nna need fo PP install
ntoPythen2, sothere's
lust like the other moddies
‘He Fat shel Bobun Options wncows sly
{e2.813)-09 hin
yee “copyrigt™, credits" or “icenea for more information.
at
Nowoubty
thenames
ace ava by now that youkrow
SEES he individual Functions within the
‘nodule, you can speceay impor them Forinsanc, the Foor
Srv/ol futons rund Gown anda la
from math import floor, ceil
foor(1.2) # returns 1
ceil (1.2) # returns 2
Dyalen 343 (Sef, fet 18 004
“Eredites ar *lieanee()* for nero infomation
Ta
3m Hooray
See cenlc.2)
EES |! porena the math module gives yau access to the
module's code, From there you can call up ary oF
the avaliable functionsw thin Mat’ by using: math, Falwed ay the
ame of the function in question, or example,
math.sin(2)
ente
‘This displays the sine oF 2
le Eat She Debug gations windows tHe
Python 24.3 (detoult, Oot 9 2014
flee 4.9.1) on Linas
{tee Seepraghe' oreicey or tice
Sos anemia)
a
apse The meth module can also be renained asyou
Import, as wien the omer modules 07 offer within
yon, This often saves Lime but dont Forget to makea comment
show someore else looking at your code what youlve done:
import math asm
m.trune(123.45) # Truncate removes the fraction
fle Eat sho) Qebum Grint windows eb
eee o9ct} oe ince i;
Tyee “cooyr ign. redita” or “License()" tor nore inforntin.
meric 199-359PERI though k'snor the usual way, itis possible to
imperttunctionstrama madule and rename them
Inthis example we imporced Floor from Math and renamed ta f
This pracess can quickly become confusing though, where ler
code isin use:
Fron math import floor as fF
Fa.2)
Bis EOt shel Debon Options wndoas Hee
Python 3.4.2 (Gefoult, oct 19 2016, 15:31eT1)
flee t.actj en mx
Petco tect ae
So rth
SErygate™ or "senee()™ for sore snton
( Using the Math Module Cl
srecsevalues:
For Further accuracy whenit comes to numbers, the
‘exp and exp! funccons can de usectto comaute
from math import exp, expmt
exp(le-5) = 1 # value accurate to 11 places
expml(le-5) # result accurate to full precision
in Est Shel Debug Opens wsnoms Hop
Pyehen 3.4.2 (eae oct 19 2008, 13r3TeT
(eee sation
Type “eopyraghe’. =
Som eapcress) = 1
aeerpe te.
ue
bor "Blears for more in
From math import *
Importng2llthe functionsof the math module can
be done by entering
While certainly hands, this is often frowsed upaniy the developer
community as it Lakes up unnecessary resources and ft
efficient way oF cocing, However. fit wcrks For you then go ahead,
2 Getaal, Oct 18 2008, HT
jan irae
ines serge” or
se
4
STEP7 ae some functions within the met
Imadle are more accurate or to bemave precise, are
designed to return 2 more aecuratevalve, than others For example:
Sint Lapin eet)
Returns the value of 0.999969999, whereas
AO ele ie)
Reus the value af 1.0
Sle Eét Shell Gabig Sotone rdows Hele
ythen 3.4.2 (Geta, bet We 20re, eT
(ee sat} on Lim
pe, ceeyrage!eredits™ or “Licese()" for mare infomation
Sos Siettsty vtyeate ote oT ate at an
SP Reim trae ct ote ote ote ot ote ote ADD
asudouiaionssn
he tora eae eae
ou ‘quite niche For the mast part. Probably the two
cesta 2a oherethestamference fo ts hed by
import math
printGnath.e)
printGnath.pi)
la Eet Shel Getue Geter nndows Hee
Pron 3.4.7 Caetautt, bce 18 Fla, TTT
foee $9.1) on Linx
Hime “copyrsgne”, Meresste or “License()
SS coat ase
bay
tor nore information
angular conversion co constants, Look ua wwww.docs.python.ora/3/
Ubrary/math heels for 2 list of availanle math madule Functions,
—BE) rena: )
Create Your Own Modules
BUILDING MODULES
Modules are Python files, containing code, that you save
now familiar import command.
square or raisea number saan exponent power)
inthe DLEard enter
Let's starLby creating a set cf basic Mathematics
Functions. Multiply a number by two, cree and
eate aNew File
dof timestwotx):
return x * 2
dof timesthreeCx):
return x * 3
def squareOd:
return x * x
def poner(x,y):
return x ** y
Under the above cade, enter unctians to call the
Gia
code:
print Ctimestwo(2))
print Ctimesthree(3))
print CsquareCé))
print Cponert5,3))
‘Save the progam as basic_math,py ard execute I to get the results.
[erences
NT
ve
a py extension. These are then imported into Python using the
Now you'te going to ake te Function definitions
ure the program ard into a separate file
Highlight the funccion definitions and cheose Cale > Cut. Choose
Fie
> Naw File and.use Ldlt > P:
wo separate files, one wit
Function cals,
ste in the new win
he Function defini
You nowha
ny the athe with
PRP) (you now iyandexecule the basle mathgy code
‘agen the err '‘NameE ror: name timestwo'
‘not defined’ vl be displayed. Ths isdue & nolenger
having access to the funcisndefinitions
Bia
‘yindaw conlaining Le Function
definitions anc cick File» Save
18s, Marne ths minimath.py
‘and save tin the same lacation
ssthe orignal basic_math,
py program, Now close che
‘vinimath.py window, sothe
jow lee
Returntothe
nasie_matiupy:
‘open,( Greate Your Own Modes (7
Back tothe basic mathpywindow atthe top oF he Proll uc maectsiea ees Esabanarty
SLES code enter: ese to determine whet to do with the number and
utilise the newly created! function cetinitions:
Fron minimath import +
if choice == 1":
print CtimestwoCnunl.))
elif choice = «2":
print (timesthreeCnuml)),
elif choice == 3:
print (squareCnisnd))
This wilimaartthe function definitions asa made Press FS to
elif choice == ‘47:
nunz = ineCinputcEnter second number: “))
= print(powerCnum1, num2)
print(“InvaLid: input”)
PRIM 0. can now use the code furtherto make the
program aletle more advaneed, ulising the nevaly
created module ta its ful. ncluce some user interaction. Start by
creating 2 basic menu the user can choose from: itt 3
print(“SeLect operation. \n”) Jcposce = sngure-rncner cnoice (1/2/3049:"»
printC'L.Times by tno")
print¢*2.Tines by Three") et =arteettere eer Th
printc'3. Square”) cate oe
print(4.Pover of”) ist eetagnms
choice = inputC*\nEnter choice (1/2/3/4):") iain
ERD or ve can add tre userinpurtogettne:
thecoe i
uml = intGinputC*\nenter muners “))
Thiswiks
the userentered numberas the variable numt,
Note tat for he last aalabe options, he awe
euseu) of choice, we've added a second variable, num?.
This pezes second rumberhrousm the etonceitoncalet
aa NSP naar GST ower Save and enetts ne progiar ta seein scien
Trem wininath import * :
print("Select operstion.\n*)
int("t.Tames by two")
rint("2.Times by Three")
rint(“3. Square")
print(“a-Poner of")
choice = input(\nenter choice (172/3/4):")
pumt = int{input("\ntnter number: "))bs de ke
ee
SAAN
Psst
Ww
Saital
woo ea
b Be
opi ee
‘We've included avast Python code
repository for you to freely use in your
‘own programs,
There's code for making backups of your
files and folders, number guessing games,
random number generators, Google search
code, game code, animation code, graphics
code, text adventure codeand even code
that plays music stored on your computer.
We've broken down some of the newer, and
‘extended, concepts of the code to help you
inunderstanding what's going on.
This is an excellent resource that you won't
Find in any other Python book, so use
it, take it apart and adaptit to your own
programs, and see what you can create
94 Python File Manag
96 Number Ci
98 Polygon Circ
99 Random Num
106 Besic GUIFile
108 Mouse Control
108
110
2 nn
ov a) Ce eea Pte eer eee
Mele lei ea Elia ete)
SR EC Tan ute
Ea cv eH cease
ee Eee Eee teem eee
tet ely ese eel otal
oi Mag oe ea Crt :
of the cade imports the
2d Subpracess med.
Each det xxx)
of the menu's
This art ofthe codethatch
theuser sunning, In wind
error accu, which
command instead.
These are the
the appropriate Function whenther
on 9 to 12, Each executes
i wim
aor tle eee
el
FILEMAN.PY
‘Copy the code below into a New > File and save it as FileMan.py.
‘Once executed it will display the program title, along with the
ccurrent time and date and the available options.
import 08
import time
Amport subprocess
det Read):
[patheinputt"Eater the ale path to ceed")
Siewopen(eath,"=")
print (ite-read())
input('Prere Enter.)
cuviatoet
dst weit)
athsinputt"Enter the path of fle to write or create:")
if ce.path tafile(path):
PHInt(‘Rebullding the exieting sie")
print((Greuting the new file’)
textrinput('Eater text")
Slomopenteath,"*)
Slewrice(text)
det add:
athsinputt"Enter the fle path:")
texteinput("Enter the text to add:”)
‘ienopen(path,"a")
Siewzite(\n'teexe)
ase batetai)
patheinput{Enter the path of Sle for deletion:")
Af ox path avizts(path):
Brint( ‘Pile has been deleted’)
else:
rint(‘File Dose not exist’)
der biziist()
[atheisputt"Ester the Directory path to aiaplay:”)
sortlistrsortedios.2istdir (path)
io
hills (icten(sortlict)}
der checkt)
paintlAnput(‘Cheek existence of \nl Pile \n2,
Dizeetezy\o"))
pathsinput(Estar the Sle path:")
Se.path.istla(path)Python File Manager
sFempuenaariapay mee S.idat files ina directory
Print (Yale Found’) G.check fie existence
eint(‘Fale not found’) B.copy a aie
sf spe S.orasta w dixectory
path-input(“Enter the dixectory path") Diets Sececberd
os.path tedir(pathy 2Lopen a program
Af on path adi ripathy False: see
print (Directory Found)
else: »)
print (Directory Net Bound’) At doce
Resa()
of Mawe(): Af dace=2
pathisinput(‘Enter the source path of Sle to movs:!) waite)
Rrsine(inpue (1 Rename \n2.Nove \n’)) a
Sf mast:
[Path2-input(Enter the destination path and de names’) | £
shut move (pathipath2)
prine(File renamed’) af
sf a2: iris)
‘pathoninput (Eater the path to move:’) st dec==é:
shutSl move (peti path2) cheek)
print(File aoved") Af doce
sove()
set Coy
athl=input(‘Encer the path of the fle to copy or renames’)
Path2=input(Eater the path to copy toi")
sShut4l.copy (patht,path2)
pHIME((ELIe copied")
Makesse()
if dec==i0:
set Makati): at
patheinput("Eater the dizactory nane with path to mele [|
\nog. Cr\\elio\\Mewdss \alheze Newsir is new as
aarectory:”) exit
os.makedis(path) ‘suorint linpub(™LRatusn to menu\o2. Exit \a")
Pring(Darectory crested!)
det Removedir
Patheinput( "Enter the path of Directory:’)
Ereedireint (input("I Deleted Directory \nZ Delete
Directory Tees \aB.xt \e'))
af treedir=i:
peemtscteth)
shuts] entres path)
prine(Uarectory Deleted’)
Af txeect
exit)
‘det Opensiet)
pathetzpat( Tater the path of progeas:’)
try:
be.sternaie (path)
PEint(‘FSie not found’)
saci Imports
ventte(run==) There are three medulesto import here: Shut OS and
1 try: . . Time, The first bwe deal with Lie operating system and file
eae "manegemens and manipulation; ane te Time masiie simply
ie entra ey srenctimeane este,
print \moossooopoomython 3 Pile Monagarcecceeccccln')
pee erry prrergrepre
Prine(‘\nthoose the option amber \a')
deominctinput(""1.Read a file
2itrite tos Ble
‘Append text te a fle
Aelete a fle
Note hows we"veinclu ced a try end except bloc ta check iF
the ser is runnina the code ona Lnuxsyster or wincows
Windows uses CLS to clearthe screen, while Linux uses cea
The ty block should work well enough but t'2 point of
improvement deaending o7 your oven system.
aude Coding for Pythianeras
(Netto oe ee
Tor u
m3
* Tig einefete Peete #4
ere dita eee iret
Rahdom module, print and input,
Bit Bra eta
Petey ee urerseee te end
Ee faee ni} Dae
ea aa 0.
eae in|
NUMBERGUESS, PY
‘Copy the code and see if you can beat the computer within
Five guesses. t's an interesting bit of code that can be quite
handy when your implementing a combination of the Random
module alongside a while loop.
Amport random
‘e(HelLo! What is your name? )
number = random.randint(1, 30)
Print(‘Grestings, ‘+ Name + \, Vm thinking of
number between 1 and 30")
While guessestsed < 5:
quessnint(input(\Guese the nunber within 5 guesses.)
gqueesecUsed = queseectized + 1
Ef guess © number:
Print("Too low, try again.)
A£ guess > number:
print("Too high, try again!)
Af guess == nunber:
Break
Af guess == number:
quesseavead = stz(guessecveed)
Peint('Well done, © + Nane + '! You guessed
correctly in ‘+ guessesteed + * guesses’)
Af gues |= number:
nunber = str(number}
Print(’Sorry, out of guesses. The number I vas|
thinking of is ° + number)
‘Although this is area
some elements
‘win, youreedtte
-crably easyte follow program. there are
rewarth painting out. To begin
reusing
wider renge oF random aumber
rnumber=random.eandint(1,30) end
it tooligh though or the player yi never be ale to guess
IF the nlayer quesses too law or tooth, they areaiven the
appropriate output. to Uyagain, while the nurmaes
fof guesses les then Five, You can also increase the number oF
quesses From 5 by acering the while quessesUsed « 5:xclve,
IF the nlayer quiessed the correct number thea they are given a
well dore’outpat, along with how many rey USEC UP
IF the slayer runs outof guesses, then the game over outputs
cispayed instead, along with revealing the rurnber the rom
iF you do alter tre values of the
umber chosen by the campucer or the numer of
guesses the player can ake, Een along withthe variabe vl,
ualsoneed to amend the instuctonsaiwenin te print
estarcafthe cadeCode Improvements.
Since hiss such as simple script to aaplytoasiustion, theres
plenty of room to mess around withitand makeit more
interesting, Pethaps you can include an option totake score, the
best out of three rounds Maybe an elaborate vay to cenerstulate
the player For geting ole in one’ carrect quess on thelr Fist
Moceaver, the number guessing game code does offer someroom
Forimpiementing into your cadein 2 manne: What
ean by this, the code can be used to retrieve arandom number
th inturn can giva yourthe start of acharacte
entre game,
between arange,
creation defined Function thin ana
Imagine thestart of text adventure wetienin Python, where
the player names theircharacter The next sen isto rll the
\irtual random dice to decide what that character's combat
ating, siength, endurance and luck values ave, These cant
cartiet forwardinto te game under a set of variables tha
‘educed or increased depending on che circumstance
character anes up in
Number Guessing Game
ple, as per thesscreershat provided, you could use
meting alona the ines of
sekeo
Endurance = random randint(1, 15)
(oR = random.randint(t, 20)
Yack = random randint(t, 10)
Print("Your character's state are as follows:\n")
Print (“Endurance:", Endurance)
PrLot(*Combat Ratlng:*, CR)
Print("Luck.", Ick)
ver stick wit their rol or tay again
picked There's ample waysin
“The player canthen dec
Forthehope of better values bein
‘shich to implement this coce into abasic adventure gare
Coding for Pythianats cy Aa 5a Peace at c| POLYGONCIRCLES.PY
Pare esis aR: Here's ats of mathematics used here along with some
UTMOST y Ela) Bel ny u intricate coordinate manipulation with the Turtle module.
Penal mang cere H Enter the code and execute itto see how it turns out
Rees eres es rom tuct ls Anporte
Ce oe) fom math Lnport ska, eon, pl
Re aoe es cla Sie ee ieeteni/in
Des Pope for Ric for 3 in zange(Q00):
isin(t};ylextoos(t)
xz=xtein(t#n):y2-rtcos(ttn)
penup0); gotolxl yl)
Pendown();getolx2 92)
ota l(oTr ace
Graphical Enhancements
leral ways in which you
sting. You can inset eal
ple
see 4 aa eangetn0n)
xieetein(t);
xoresinttin)
‘speod( farte
panup(); goto yt)
ppendonn():gat0tx2.2)
eke
fescan take awhile co map out and draw, depending
big ane how ince an image i
“This un through the test’ speed possible for
the Turtle. e certainly makes isworth consicering
you're drawing Turtleimagesf presentations.
yeec() wil quicken things un,
Say Say
ciewere Bee
fant
Fron turtle ingore *
ron math inpor! in, cos, pa
experiment with the various soeecs by adding the Fun
erat: gotacrt yt)
Benoni) =goto(a2 72)
ie u
PR eer rere“ Polygon Circles/Random Number Generator
Random Number Generator
User input and the ability to
manipulate that input are important
elements with any programming
language. It's what separates a good
program from a great program, one
that allows the user to interact and
see the results of that interaction.
RNDNUMGEN.PY
emight be simple but this little piece of code will ask the user
For two sets of numbers, a start and a finish, The code will then
pluck out a random number between the two sets and display it.
from randon import *
print (*\mo>o>sop>Random Mumber Generatorcceeceecce\n")
ambisintlinput(Enter the start number: "))
‘AnE2ULnt(Snput("Enter the last number: "))
= randine(anbt, ana)
‘Print("\ithe random munber between" rmbt,
pristis)
amb, "is:\0")
More Input
hile an easy code to Follow, could le mare interesting you
prompt the user Formore input, Perhaps you can provide them
‘with acétion, subtraction, mutipication elements with thei
numbers. yout Feeling ever, see f you can passthe code
through Tkinterwindow or even the Ticker window that's
available oaPage 128,
srthesmore, the core ofthe code can be used ina text adventure
‘game, where the character fights something and their health
along with the enemy’s, reduced by a random number, This
can bermixed with the previous code from Page 90's Number
e,suhere we defined the stats for the adventure
‘introduce the Turtle module into the code and
defined rules for drawing ashape, object or
something based on user inputed random value fiom arenge
of parmbers takes alitie working ou aut te effects certenly
pally Interesting.
Fo exainple, the code cauld be elted to ths
from random import +
amport turtle
‘peLnt(”\mopppooppomandam TuEtte Taageccceceecce\n")
faabinint(input{"Ester the start number: *))
‘nnb2=int input(Enter the eecond munber: "))
panicintlineut(Ester the third susher: "))
nabinine(input('Ratar the fourth number: *))
turtle.torvardinmbt)
turtle-Left(80)
turtle. forvard(amn2)
turtle 1eFt(90)
turtle. forward (ambi)
turtle left(90)
Se Uassevereembdl
turtie 1aft(o0)
‘whilst i's lie rough around the edges, you can easly make i
Coding for thanRondon Password
Generator
aE ca:
F vs ices Tle) ie oy
Pee ane eat
Re ote ot)
en fee) oy Ovni
Pe EEL Benen password
Perel eeclar tain caret
Parsee tecst nme 4 rele
i onl ey Cele v sera
oe " a
ou can do tomedfy this cade and impreve it
n yaucanoulout
securely compress itusing the
filepassword and serdit
[an interesting sspectto this code isthe ability to introduce sloop
and printary number of random passwo assume you
a lstof 50 uses for acompany arcl you're in charge of generating
m
De: oan een
RNDPASSWORD.PY
‘Copy the code and run it; each time you'll geta random string
‘of characters that can easily be used as a secure password
‘which will be incredibly dificult for 3 password cracker to hack,
import string
Amport random
dee randampasewordy)
charssstring.ascii _vppercase + string.ascii _
Jowercase + string digits
size @
return "join (random.choice(chars) for x in
xange(size,20))
print (randompassword())
Addingaloop to printaps
ys Fey times
i extremely easy, fe
amport: sneing
Amport zandoa
08 randompacensrd()
a + string digits =
Jein(randon.choice(chars) for x in
ange(s12,20))
while 2660:
print (rendompascword())
previous“ Random Password Generator/Keyboard Drawing Script
Keyboard Drawing Script
The Turtle module is an excellent resource
for the Python programmer. However,
what makes it more interesting, is its
ability to enable the user to control the
turtle on the screen. This piece of code
does exactly that, allowing the user to
unleash their inner artist.
KEYBDRAW.PY
‘There are two modules inthis script: Turtle and Tkinter. The
Turtle module is the main display, where the user controls the
drawing, whereas Tkinter simply displays the user controls.
‘ALL movenente and turns are by inerenents of
Right arrow key = move forward
fess ee
eens
Tovneclset, soot title Conte eights, wit
‘aad
Tinwett(N, “Right. erry tay = nove forvard\
Woe erie ee reece ee
eee ar tears vesareal ie ia
bodecy
= =m
Fae mainp
aa)
teed
Pirenlecrow
Stern, =)
meron, 8)
omeyteles, "e)
Smteyibene “2
Sateyanban forward), “night
Snte/lonbds: bck), are)
ctitfumsan ieeeey ox)
ategUanbde: signet), >)
Listen) =|
return “Done!”
ae
Printineg)
mainloop()
aude
ays room For improvemen’
ge the colours or ask Ue usa
ith and then include ak
‘contraiste change the pen colour whist crawing, The
alseroam to increase or decrease the speed of the pen, again
hat. coule be a user-defined seee, You can also expard the
Aninicia set of comments to display the contro, hich can
also be outputted asa sega abe hiner window i you wank,
fara importnathe necessary modules: rnter ane turtle
Setting up the separate enter window displaying the controls
and creating afunction to define the width, speed and colour
of the ine being draw, alsa setting up the onkey Functions for
the cantrals of the oen.
‘A neakwayto finalise the code andlleap i x0 you can eankinue
craving withthe pen,
Coding for yaneer
ays rT ras Jo an do ee a
Fy Me retiree
) dis i phics. The module
contain manly Furiétions Which ey
Piste send iene ee
SE ete ae
SU cee ia) aati oa
re
ete
pee ee
Sep oouy
re Pygame mpd ule. Each
the code, sayoucan pull
text = font.render("“Upside down text’, True, BLACK)
‘text = pygane.tranaform.zotate(text, 180)
screen.blit(text, (30, 0})
text = font render(“Flipped text”, True, BLACK)
text = pygame.transformfip(text, False, True)
soreen.biit(text, [30, 20))
taxt = font.rendar("Rotating text’, Meus, BLACK)
text = pygane.transform,rotate(vext, text _
rotate _ degrees)
text _Fotate degrees 4= 1
scresa.blit(eaxt, [100, 59])
ygaze.display.flip()
elock.tiek(60)
Fygane.quit()
E The Joy OF Text
eile senate rh ston
Pepeee Me ees eee
P apegrarmer
3 1X9] UMOpP episdj
2 ELlbbeq sexs
:
2 %
a
4
Ww
5
%
ce( Pygame Text Examples/Google Search Script
Google Search Script
Using the OS and Urllib modules, this
small snippet of code will display a
window for the user’s input, then pass
the input to a Google search in their
browser. It's really quite a handy script
and one that's easily introduced into
your own code.
Searching For More
used the Zenty command to ceatetthe clog box
jermentioned & only avalable to Linx machines (such as
ad sant la execute
couple of possibite inda
jan of Zenity and passthe user's query through if or
you can create a Tenierclalog box to pas the infaimation
«can see that this particular code uses the Chromium browser
ich comes preinstalled on de Raspberry P and some versions
OF Linux. To use your Favourite browser in Wineaws, for example,
you will need to change the command in thel:
to read Firefox, or whatever you use, together wit
command. So essentially, ove of the Following
tart firefox hitps/lmoccoonte.coml
(Googie!)
os.system(atart chrome pttps/inewanosie.com!
searchtqzte’ + (googie)
os.eystan(‘start implore hite:/éne.congle.coal
searchiaste’ ¥ (goegle))
Boman
GOOGLESEARCH.PY
‘You willneed to pip install the urtlib module, unless i's already
installed. It also uses Zenity, which is a Linux-based (GNOME)
tool for creating dialog boxes.
import 0s
import urllib.parse
google = os.popen(zenity —-entry --text="Enter your
Google search: itle="Google Search" ).readQ)
google = urllib.parse.quote(google)
ce.ayetem( chromiua-browser bite: //nm.gaeale,com/,
searenegns’
* (google)
The la
for Chrome and Internet Exolores respect
“Theresa Zenity for Winclows project. avalable on Git at wwe
(btn ccraikeaeetreareeeteas (es aco worn Geson
[But yau co need to install it toa Folderon your system where you
‘equi administrator access ta be able ta run the Zen
program. when you have Zenity installed you can modify te
in Pytnon to read
See een
googie = os.popen(‘start c:\tomp\zenity\\bin\
renity —entry —text="Entar your Google search: *
~-title="Google Search’").read()
google = urllib parse. quoteigeogle)
ce.eysten( ‘start srefox bitp://no.gacaie.com.,
searchtgste! 4 (google)
coding for PythonTXT2BIN.PY
Naturally we're using the format function to convert the
user's entered text string into its binary equivalent. IF you
Edel er ed q ‘want to check its accuracy, you can plug the binary into an
hake A online convertor
Pert Tasca inison7syt an
aie 7 textainpt("Enter text to comert te Binary: “)
print(* ‘join(format(ord(x), "!) for x in text))
Pear Pee eee tare ay wal
File Edit Format Bun Options Windows Help
print(">>>>>>>>>>Text to Binary Convertor<<, $0 you may need to pip install any extras ifthe
dependencies Fail when you execute the code.
From thinter import Me
from idlelib.treelidgat import Scrolledcanvas,
Filetreeften, Treallode
import os
root = Tk()
Foot bitle("File Browsers")
se = Scrolledcanvas{soot, bg='white’
ighlightthickness=0, takefocus=)
se-frama.packlexpand=1, fill="both", side="left”)
iton = Filetreertem(os.goterd())
node = TreeNede(sc.canvas, None, item)
nede.expand()
reot.matntoop()Advanced Filing
When executed, the cade wil dsoiay the current directory
contents, you want to see the contents ef another directory, yau
canrun the cade from acommang line within the crosen directonst
lustremembestoeallche code fram where t's iocated on your
system, as per the second screenshot, You can ais double clk any
ofthe file names shonin the direct \drename them,
This an interesting pl
your own programs, You can extend the code to include use
specified cirectoryto browse, derhaps your ovan unique fle icons
too. Ff you're using Linux create an alas to execute tne code and
hen you can rum i rom wherever you ate inthe ester,
code and one that you can inser into
Windows users may have some trauble with the above code, an
alternative car be ach eve Ly using the Following
from tkinter import +
from thinter import tk
fro tkinter.Oiedialog import askopentilenane
‘root = TR)
def Opentirel)
‘name = askopenfilenanelinitialdic="C:/",
Sletypes =(("ext Fite", Moet"), (ALL
Ne
"choose a fle.”
“ Basic GUI File Browser
‘with open(aane,‘r') ag Userile:
rint(UseFile.readi))
except:
peint("No Miles opened”)
Mele = soot titlel FL Openas")
label = tek Lebel{root, text ="File
‘Open foregronnd="red",font=("Walvetica", 16))
Iabol:pack()
nena = wenu(root)
‘Foot. configinenunena)
‘ie = Mens(sens)
e.add_conmand(Lebel
‘Sie.add_ conmand(isbel =
lambda exit)
‘open’, command = Opentile)
"Exit", command =
inenv.add_cascade(label = ‘File’, meno = file)
oot nainoop ()
[snot quite the same but this cade allows you to open files
Inyour system via the forilar Windows Explore, ls woth
‘experimenting with hatyou caneo witht
Coding for ythanA mi fLey res cai ae fi
eral
Torsha wi
rete Ea fea
Fi jouse as.a drawing
ec mumoan war
part eee eae
Sa a est re ag
ba
my
i
1
PI
cI
5
|
Pele por ae
aac’
MOUSETURTLE,PY
“The first piece of code presents the standard Turtle window.
Press Space and then = 0")
syeexte()
Af minutes < 0
print ("invalid value for minutes, should be >= 0")
sys.exit()
seconds = minutes * 60
Af minutes = 1:
unit _word = ” minute”
else:
unit _word = ~ minutes”
Clock
tay:
if minutes > 0:
print ("Sleeping for
sleep(eeconda)
print (Wake up")
for 4 in range(s}
peint (che(7),
sleep (1)
except KeybonsdIntarcupt:
Print (interrupted by
Bys.enit(l)
+ stz{minutes) + unit _word)
ser")
Wakey Wakey
There's same good use of ty and except blacks here, alongside
some other useful loopsthetcan hela you geva firmer
undersiancing hoy werkin Python, The cade itselr
an be used inavariety of ways in 2 game where something
happersafter aset amount of time orsmaly asahandy
desktop alarm cock loryourtea break.
aux users, try making the alarm elock code inka an alias, s0
sou can runa simple commando execute ft. Then, whynot
ntegrate auser input atthe beginning to askth
length of time they want until the alarm goes
nq to include itn the commmand line
3s the only version installed on your
zed tocxecute the code without adding
ha. to Le ond af tha Pythan cornmand, Far exarnpl:
python Alamnclock py 10
ies of the day
Coding For Pythanroe crlct a,
Seon
Pele rae
Tenet ere aN
evar recite acre e els
ME ae Lise eg eee
CU ea ceaar anne oe ect
BO i
#3 4 J
area tel
;
@
3
3
ba
i
j
Fy
a
ra.
7
Hl
a
A
a
EPICSCROLL.PY
We've used the poem Cimmeria by Robert E. Howard for the
code’s serolling text, along with a dramatic black background
‘and red text. We think youll agree, it’s quite epic.
import. pa
‘from pygane.2
import *
praniea
tent _liet =
1 renamber
The dark woods, masking alopes of sombre hile
The grey clouds’ leaden everlasting arch:
The dusky streams that lloved without 2 sound,
‘Asd the Lone winds that whispered down the passes
Vista on vista marching, hilis on hilas,
Slope beyond slope, each dark with sullen trees,
‘ur gaunt land Jay. So when a man climbed up
A rugged peak and gazed, his shaded eye
Saw but the endless vista ~ hill on hill,
Slope beyond slope, each hooded like its brothers,
ALL winds and eloude and dreans that shun the sun,
With bare boughs rattling in the lenesone winds,
And the dark woodlands brooding over all,
Not even lightened by the rare dim sun
Which made squat shadows out of men; they called it
Cimperia, land of Darkness and deep Wight.
Ht was s0 long ago and far away
T have forgot the very nase men called me.
The axe and flint-tipped spear aze like a dreen,
only the 021 ‘that sombre land
The closds that piled forever on the hills,
The dimness of the everlasting woods
Cimmeria, land of Darkness and the Night.
Oh, oul of mine, born out of shadowed hills,
e clouds and winds and ghosts that shun the sun,
How many deaths shall aceve to break at last
Appavel of ghosts? 1 search my heart and find
Cimseria, land of Darkness and the Night!
wr split (Nn)clase Credita:
imit_ _(self, screen rect, 1st):
selelet = let
If eize = 16
(255,0,0)
self Duke _contery
aalf buff lines = 50
self timer = 0.0
sf delay
self.make_surfaces()
self.erect.height/2 +5
def make _ text{oel# message):
font — pg font Sysront{‘Aial, se2f.aize)
text = font rendar(nessage,true,self-colar)
rect = text get _rect(centar = (eeif.erect.
canters, self.srect.cantery + self.buff_cantery) )
return text rect
def make _ surfaces(selt):
af .taxt = (1
for i, line in enumeratelsel¥. 1st)
1 self.make_text(line)
Luly + itaelZ.bute _ lines
elf text append.)
def update (els):
Af po.tine.get _ticks()-self tiner > self delay:
self timer = pg.tine.get _ ticks()
for text, rect in self,text:
recty = 2
def render(eelf, surf):
for text, rect in self.texe:
sure b1it(test, rect)
screen = pg.display.set __mode((800,600))
screen _ rect = soreen.get _ rect)
clock = pg.time,Clock()
zunning=teve
cred = Credite(screen_rect, text _ list)
while cunning:
for avent in pg.event.get():
LE event.type —= QUIT:
running = False
screen, £11((0,0,0))
‘seed upcately
ered. rendez(screen)
Py.display. update”)
elock.tick(60)
( Vertically Scrolling Text
ALong Time Ago.
The obvious main point af enhancements the actual text
Itself. Replace twith alist of credits, or ic opening
storjlineto your Pytion game, and twileertainly hit the
‘mark with whoever playsit. Dant forget to change the screen
resolution if needed; we're curently ranningiat 200 «600.
Coding for Pythian2 ese |
a
oF
PS
ok
Fa
iP
(Netto oe ee
a” eae
is Gs een Orie
Ca) eee eee Coc eia is
once
ee
Sau cd Feat mr alls
creat Deere eas
eo Soa Cn eaneL Pa
oR a
er ee te
eke ee er
DIGCLOCK,PY
‘This is a surprisingly handy little script and one that we've
used in the past instead of relying on a watch or even the
clock in the system tray of the operating system,
import time
import tkinter as tk
def tick(tinet~"’):
f get the current time from the PC
Eine? = tise steftine(‘an-ames’)
Se timed |= timed:
clock.aftar(200, tick)
root = th-Tk()
clock = thLabel(root, font=t'arial’, 20, ‘boLd'),
1bg='green")
clock packifile’hoth’, expand=l)
tei)
reot-maintoop()Tick Tock
Thisis 2 piece of code we've used mary tines in the past ta keep
trackof time while working on multiple monitors and with just 8
uick glance to where we've placed ion Uescreen,
‘The Tkinter box canbe moved around without affecting the time,
mavimiged or elosed by the user at wil. We haven Egven the
Titer dlack wondaw a Ue, so you can ad ta thal easily enough
by snipping the code From cine examples inthis ook
‘Another area of ingrovernent iste inelude this code when
Windows or Linux stars, sot automaticaly paps up om the
desktop, See als, ryou're able to imarove its Functionalty by
Including Tesent time zanes: Rorne, Faris, London, New
Mescaw and soon.
Another example, exoanding on the original>ooopp>awasome Adventureccceeccc *)
Printiname, “the barbarian, svord in hand and looking
for adventore!")
tie. sleep(l)
print(lowever, evil is lurking neazby..)
fies. sleep{l)
PEINE(A pair of bulbous eyes regards the haro...")
tine.slesptl)
PHnt(WLL", name, “prevail, and win great fortune...)
Hime. slept)
peint(-or die by the hands of great evil...2*)
tine. sieep(l)
print\e" $3)
Print (Only tine will tall..."
Eine. slesptl)
pane.)
tine. sleep(l)
print (9)
time. sleep{l)
peiat(’/)
‘time. eleeptl)
print’)
Hime, s10ep(5)
rink("w 1200)
print(”" You find yourself at a smali inn, There's
Little gold in your purse but your svord is sharp,
‘and you're ready for adventure,
With you are three other customers,
A ragged looking man, and a pair of dangerous
ooking guards."’)
dee start:
peint("\n === zh
Brint{"Do you approach the...")
print("\n")
print("l, Ragged lesking man")
Print("2, Dangerous looking guards")
endlist=['I", °2"]
endegetend(cedlist)Af ond == *V
ragged()
elif ond
quarda()
a
det ragged)
petne("\a" * 200)
peint|"""You walk up to the ragged looking men and
greet hin,
He smiles a toothless grin and, with a strange
accent, says
“Buy me a cup of wine, and I'L1 tell you of
great treasure...)
time 2leep(2)
det guards)
pEine(”\n" *200)
Peint(‘""Zou walk up to the dangerous lecking quarde
and greet them.
‘The guards look up from their drinks snd
anerl at you.
“What do you want, barbarian?” One guard reaches
for the hilt of his sword...""")
tine. sleep(2)
(Text Adventure Script
def gatend(endlist):
‘end = Anput(sanes">")
A€ ond in ondlict:
return end
if end —= “help:
Print("\nEnter your choices az detailed sa
tthe game")
Print(‘or enter “quit! to leave the game”)
return getcnd(codlist)
elif ond = “quit”
Print(\—--—-——")
Eime.sleep (1)
print(‘Sadly you return to your homeland without
fane or fortune...")
time. eleep (5)
exit)
sf __name *
start)
Adventure Time
‘This, asyou can see, fjust the beginning ofthe advertsure ane
takes un a far Few lines of cade, When you exaand it, andwveave
the stary along, youl Find that you can repeat certain instances
sacl as 3 chance meeting with an enemy or the tke,
‘We've created each ofthe two encounters asa derined set
of Funcions, along with alistot poste choices under the
ich isalso defined Function
-xpanding on this s culte easy, just map outeach encounter and
choice and create ade'ined function araund iL Praviding re user
doesn tenterquit into the adventure, they can keep payne,
‘amis Ist, and end var abe
There's also room inthe acventure For aset of variables designed
or combat, lek, health, endurance and even a inventory
amount oF gold eared. Fach successful eombat scvation can
reduce the main character's hesth but increase thel- combat sklls
OF enclurance, Plus, they could loot the body and gan
‘goldtheovgh quests
Fall
about Intseducing the ra
dale, This wil enable
nclude ar element of chancein the game. For example, in
‘combat, when you strike an enemy youll arardom amour
‘of camage as willthey. You could even work cutthe maths
behinclimpioving she chance of abebe hit based on your
opponent's combat skis, currencheatth, strenath
you
endurance,
YYou could createa game oF cicein the Inn to see Fyou win or lose
‘gold fagain,improve vie chances:
luck Factor nto the equation
ning by waking out your
Needless to say, your Lext adventure an graw exponentially
fang prove tobe @ wrk of wonder, Good luck, and Fave fun with
youradverture.
Coding for Pythaner ere
(yet toe aor ad
Ticker Scrip
eee ay
PM dete ccd ae
ee a et ee
Mest eu ha sg ea
Fotin bF Scrolling ticker. Whilst®
tein er ae) Fi
ARS or! creat ius a ‘
Errol tits MIME A st tickero
Ky ais) cr-1 oS fo keep
Cece reel toa toa
rs
r
»
Ticker Time
he Teker code ligin
wild splay
seyoucanc ‘deolout af
icker window the Font and the font-colovr, along
the geometry of the Trinte
the backan
YYetanatherincerestina ees
nbrodu of the many
available for
ew speech medles
10m 3, You could pip install oe, import,
hen asthe tice the text, thecext tospeech
‘action wil read outhe variabie
hemi text store in th
thesame time, since
nab labeled
plecan be useal warnings,
pethaps something thet wil spay across your work ar
home network deraling che shutting down oF a server
ces the weekend for maincerance: a
inform everyone asto what'shapaening
you wil come up with same good use
Python Scrolling
C
TICKER.PY
‘We're using Tkinter here along with the Time module to
determine the speed the text is displayed across the window.
import tkinter as tk
root = Heme)
tk.Canvas(reot, root.title ("ticker Code")
- widthe=800, by="yeL low")
canvas. pack’)
font = (‘courier', 48, bold’)
text_ width = 15
Wext blocks Insert here
sl = “This is a scrolling ticker example. As you
cen 00, it's quite long but can be a lot longer $f
necessary...
2 = "He can even extend the length of the ticker
ge by including more variables.
“the variables are within the
the coda, "
st = "Don't forget to concatenate them all before the
For loop, and rename the ‘spacer’ s-variable too.
4 pad front and end of text with spaces
iS =) teat _aeen
¥ concatenste i© al)
Stal tad tad teh t+ 25
y
text = canvas.create_textix, y, anchor='n
font=font)
deel
ay = 0 # use horizontal movenent only
4¥ the pixel value depends on dx, font and Length of text:
Pixels = 9000
for p in zange(pixals)
# move text object by incresents dx, dy
A dx -> right to left
canvas nove(text, -dx, ay)
canvas. update)
shorter delay —-> faster movement
Hine. eleep (0.008)
Apeine(hy # test, helps with pixel value
reot.naintoop()( python Scrolling Ticker Script/Simple Python Calculator
Simple Python Calculator
Sometimes the simplest code can be
the most effective. Take for example,
this Simple Python Calculator script.
It's based on the Create Your Own
Modules section seen earlier but
doesn't utilise any external modules.
CALCULATOR.PY
We created some function definitions to begin with, then lead
‘onto the user menu and inputs. It’s an easy piece of cadeto
Follow and as such can alse be expanded well too.
dof subtracts, »]
return x-y
def multiply(x, y):
return x" y
det divides, y) st wei
return x fy al
peint("Select operation \a") a
peint(*L Ada")
Print("Z.Subtract”)
rint("3.Mottiply")
Print(™4.divide")
choice = input(*\ninter choice (2/2/2/8:")
‘nun = int(iaput("\nnter fizet number: °))
und = intlinput("Enter cecond nuaber: *))
Af choice =v
Peint{numt,"4",ava2,"=", ade(nom],nom2)) Improved Calculations
SLE choice = 12’: The obsious contender for improvement here is using the
print(numt *-",num2,“=", subtract{mund mam2}) eae Your Own Modules route and extracting the function
Gefnitios as a module You canthencallthe mod le an focus
elif choice == 13: con the body of the code.
peint(nuni “*"num2,"*°, multiply(eumt,sua2})
of improvements
making calcul
while loop, so once a value is presented the user's sent back
1, Perhata,ipravement to the Invalid input
ingintoas welt
alie choles ==
peine(nunt,*/" rund,
‘peint("Invalid inpot")
"=", Airs (set mz))
ado Coding for Pytanmae il oe Pts on ) | HANGMAN.PY
eg Sune ‘ fe've made a Hangman game board (the gallows) out of
extremely.complex, displaying! aaa te ay be dcplayed in me IDLE Skolt sions with
Se eda i RE a res ‘ahuge bank of words to randomly choose from.
tSee coals
available wor ) import random
Pats] eu Cas ear Fr; ees
Pear Pieced crs WA ei) a
uh Lira) Cy cn
Re 4
Chee us
>ppopppppiannmancececceece
r
(oye to ole addef _ init__(self word:
nalf.miseed letters = []
self guessed letters = (]
def quess{sel£ letter):
sf letter in self word and letter not in self.
guessed _ letters:
self.guessed letters append(Letter}
elit letter not in eelf.vord and letter not in
self.migsed _ Letters
self.aieced letters sppend{letter)
else:
return ‘rue
ef hangean _ over(eelt)
return self hangman _won() or (len(eslf.nissed _
letters) = 6)
ef hangean _ won(eel)
Af 1) ne in aelf hide _word(}:
ef hide _wordisels)
for letter in self.vord:
if letter not in self.guessed _ letters:
else:
rin = Letter
def print game _ status(se1£):
print Goard[len(eel£.nissed _letters)])
FEint (Word: ' + selfhide “word())
Print (‘letters Missed: )
for letter in selfmissad letters
print (letter) =
print (
Print (‘letters Guessed: *)
for letter in self.guessed letters:
print (letter)
pEint ()
det rand _ wordt)
bank = ability about above absolute accessible
accommodation accounting beautiful bookstore
calculator clever engaged engineer enough
handsome refrigerator opposite socks interested
strawberry backgamnon anniversary confused
dangerous entertainment exhausted impossible
overveight temperature vacation aciosors
accommodation appointment decrease development
earthquake envionment brand environnent necessary
audios.
( Hangman Game Script
luggage xeeponeible ambassador eizcunstance
congratulate frequent’ eplit()
czeturn hank[randon randint(0,Len(bent))]
Sac sea:
‘gano = Hangnanirand _word())
while not. game.hangman _ over):
‘gane.print _ gana _ status()
‘user _Anput = input (\ninter a letter: ')
gane guess(user _ input)
game.print _gane _status()
if game.hasgman _von():
Beint (*\nCongeatulations! You have won!)
print (‘\nSorry, you have Jost.")
Print (The word was "+ gane.xor3)
print (\nGoodbye!\n')
QUIT)
‘Since this isthe last examale in our Python cade repose
thought weld go out with abang and feature the hancman
‘gallows being raven with each incorrect quess ofthe word,
Don't worry fittooks misaligned in the texchese this is merely
‘due tothe cif ferences between using the Python IDLE eit
and pastnathe code into @ ward processor shich formats
things different
There's plenty you cande to improve, enhance anc expand on
t weve presented here Vou canincudea routine that
Fetuinsan error ube user enters a number or character. You
ca inclicie extra points For someone wha guesses the ence
word inone garrther than one etter at atime and you could
perhaps add Chopin's Funeral March should you lase the game:
Or something celebratory you wi.
Consider replacing te bankof wares too. They're Found under
Ube bank is, and could easly be swapped out for something
ou download yaa cithub cami enc
asards you can ind atext documencavth ever 466,000 words
Perhaps you could swap tha words inthe bank Lo insleadraad
the contents of te text File
more offical
et rand _ word:
with open("7home/pi/Downloads/wards.tat", “re") as £:
Danke’ readiines()
‘setuen bank [renden,candint(0,en(bank))T
Coding for than( Learning to Use Linux Gl
Linux is a remarkably versatile and
powerful operating system. It's used
throughout the programming world
and in engineering, science, space
exploration, education, gaming and
everything else in between. It’s the OS
of choice for high performance servers,
the backbone of the Internet and it
Powers the Fastest supercomputers in
the world.
Knowing how to use Linux, and how it’s
structured, is key to being able to
create better Python content. The
Raspberry Pi, for example, uses a
Linux-based OS and as such makes For
an excellent coding platform.
Regardless of whether you're using aPi
like us, Linux Mint or Ubuntu, these
pages will prove invaluable while you
learn Python,
426 What's Linux?
128 Using the Filesystem
¥30 Listing and Moving Files
132 Creating and Deleting Files
134 Create and Remove Direstories
136 Copying, Moving and Renaming Files
138 Using the Man Pages
140 Editing Text Files
142. Getting to Know Users
144 Ownership and Permissions
146 Useful System and Disk Commands
148 Managing Programs and Pracesses
150 Input, Output end Pipes
152 Fun Things to Doin the Terminal
154 More Fun Things Lo Do im the Terminal
486 Linux Tipsand Tricks
158 AZof Linux Commands
160 Glossary of Python Terms
aLearning to Use Linux
BED seesitsetnn )
What is Linux?
ntact w A ae LIL ae Ae Ee areola eR ect
what exactly is Linux? Where did it come From and what does it do? In a world where
Mn ee inuccoste tert tenes camtarks tse Mit contacts aia i
aircon lem com A alte aan RTL NTOTN aUIMTIe Ny
isinaly powerful, Fast, secure and capable operating system. It's used as the OS of choice For the Raspberry Pi,
tthe Form of Rasphian OS, as well asin some of the most unlikely places.
Despite only enjoying a 1.968% share faccording tonetmarketshare,
com) ofthe total deskton onerating systern market. Linu has2
dedicated following of enthusiasts, usersand contibutors was
crested in 1991 by University of Helsing stucent, Linus Torvalds,
‘wha had become Frustrated with the imitations énd icensing ofthe
popular educaticnal system Minis, amniniature version ofthe Unix
‘operating system, in use a the tine
Unde sot was releasedin the early'70s, asa multitasking, modular
designed operating system originally daveloped for progiamme:
‘who reeded = stable platform ca code on, However, its performan
powerand portabiley meant tat t soon became the system of
Choice far companies ane universities where high-end camauting
tasks were needed
BOOTLOADER
The bootloader isthe software that iniialises and boots up
E yourcompurer. I loads up the various modulesthe OS uses to
begin toaccess the hardware inthe system. You can modify a
bootleaelet bo load more than ane OS installed on the system,
Daemons are backround services that start as tne operating
system ls booting. These can enable printing, sound,
networking andso oa. They run unaberusively rather than
under the direct control af the user, aften waitina to be
activated by an event or condition.
DESKTOP ENVIRONMENT)
The Destop Environment, or DE, isthe main Graphical User
InterFace (CUI) chat users Interact with l's tre desktop, thet
Includes internet browsers, productivity, games and whatever
program ar ana youre using. There are countless DES
avallanle Respbian uses PIXEL.
“Torvalds neededia system that could ieror Unis's performance and
Features, without the licensing cost. Thus was bom Linux, the
Unix-like operating system which used Freely available code from
the GNU project. This enabled users around the world to utilise the
ower of the Uniclike system, completely free of charge, an ethas
that still holels today: Linas Free to download, install and use.
ti
xismuch like any other operating system, such as Windows or
“0S inthat it manages the computer hardware, provides an
terface fr the user to access that harchware and comes with
rogram for productivity, communications, gaming, science,
‘education ang more. Linuxcan be brosen up intoa umber oF
i elements:
fee re es a8
‘This. a module withia Linux that provides a graphical outpuk
to your monitor Iesreferred tos the X server 0° simply fst
X Xisan application that manages one or mare graphical
displays and ane or meze input devices (zeyboard, mouse, ete)
connerced tothe computer,
‘The kemelis the care ofthe system and the single element
that is actually called Linux. The Linux kernel manages the
computer processor, memory, storage andany peripheralsyou
have attacned to your comautes provides the basic services
For all othe: parts oF the OS,
aele AUN Aaa)
\With Linux being an open source, free operating system,
also makes use of the tans of thousandé oF freely available
aaplications, The likes of LibveOfFce, GIMP and Python are jest
the bp of the icebergThe Linux shells commence interface enviranment that a
Linuxuser can use to enter commands to the O5 chat drecty
affect it. Within the shel you can add new users, rebootthe
system, create and delete files anwfolders, and much mace.
BASH (Bousne Again She!)
i the most pepular shell
Used in Linu, althaueh
more ate asilable, Te
shies also known asthe
minal, anc i's where
you're goingto work
from through this section
of the book
Tuxsthe
Linux
mascot
(nus tkes
Penguins).
aff
Raspbian-on the Raspberry PIs the
Linux distribution of chaice,
D4
my
‘ADesktop Environment can
beas complex or assimple as
the userdesires.
Curatsinnn CE
Linus Torvalds, the creator of the
Linux kernel
Linux i used throughout the werte, na number of Basie and)
quive unicue uses, hie may Look radicaly different Fa
lenviron-nent tothe rest, the actual linus kernel, cam be
rn modern smart Tvs, in-car entertainment syscems and GPS,
Supercomputers, loT davices and the Raspberry IS used by
NASA, both in the command centre ard onboard the 5. Linux
servers power the backbor: Internet, along witn most oF the
ebsites you visit daly. Android utilises components ofthe Linas
kernel as de sel b
reecet,
ones, ames consoles and even you Fridge,
fn and washing machine,
Linuxisiitjusta eto use opevatingsystern. e's stable,
powerful and fost, easly customised ancirecqires very tle
maintenance, However, t's more than just perforrmance stats
Linux means freedom from the walled garden approach oF he
operating systems. t's ively community of tke-minded iaivié uals
sho want more from their comauters without che shackles af price
confarmity, LinuxGETTING AROUND
To drop into the Terminal, click on the Fourth icon From the left along the top of the Raspberry Pi desktop, the one with a right-
Facing arrow and an underscore. This isthe shell, or Terminal.
BERD em etstaceuomauye BED crestsioverinconewernw cat
inside each a cl
Fhomefpi it means te pislrectany since the hi
Enter €lear and aressreturn to clean the screen, Ni you'll olQurs: executable Files
This stands for Print Working Directory and csalays, 1s} are tight green, archived flesare red and so on. Blue
andswhite are thebwo you need ka know to gel stivted,
hea yaulog in Le your Raspberry Pi, you daa! FPID) Now you're going la mave From the pidiecteryinto
start atthe bese of tnehard drive known as the the Documents cirectory, Encer: ed Documents,
9/35 the conost decoy}, steed you begin 2° Linuxis case sensitive, which means ou
inside your user crectory, which Is named by defaul. and ster the exact name including covreetcapitalsation. the
tselFina ¢ led home! Directaries are indicated by the'? d stands for change dtectary, Now enter ad again
ory called
called
symaol, 5 root 3 di
home, andthe next"/" says that inside “home” isa dire
*. Thats where you stant
FED cerneg steer series volume 37‘cots means the
ry. nee
never use "cd
rth knowing eceuse
ry bur t's
ABSOLUTE VS RELATIVE PATHS.
ED:
Pictur
your Doruments cirectory ch be this directory
to move pack up tu
4 Docunents/Pictures: use cd 2/s
It is important to know the difference between the warking directory, root directory and home, There are also two types of
path: Absolute and Relative, These are easier to understand than they sound. Let's take a look...
Ceca a meet ty
Ce eee et comets
ree ue conta cen
ea Geen at ain sd
ect ete eee etn ce
FED he soot directory is lays Entering LE
crear
perry eerie nea eeterriae
fe eee ees
ee mm ace Ute ean eel tale
ene rat Meat
Pen ae rename)
Beles ies
attemptsto list the content of Pictures in a
directory called Documents inside the root directory (because the
‘path started with J", whichis root), There is typically no Documents
Cen eee eed weed ek ee
eee na area tena
starting without the is known asa "relative path because itis
ea nt
pee tetas
Cr eau een
STEP 4
Entering: EEE always ists the contents of yourhome directory,
Ree ee ee eta ena
Ree eimemei a cueun cme nety
wherever you are: enter: [ERASMAS to cisplay
ReesLOOKING AT FILES
Operating systems are built on files and Folders, or directories ifyou prefer. While you're used to viewing your own files, most
operating systems keep other files out of sight. In Raspbian, you have access to every file in the system.
vic lists he les Ha Afber dhe permission letters came a single number.
oF files
theiters F's afi
least 2, This isdec
inwetory cx awitva single dat
ne with be Directories cantaining files or ot
rectoties will have = hicher rumber
ument.This's anoplion that mecifies the
ve I argument ls Hles and diectoriesin long
fle and directory's now on asin
inst you'l see lots of ecters
Next you see the word" ited
line, This refers to the user rather tar
your deravle username is pr). Tne First ist
wee on each
name of
‘and dashes, like 'ervxrarx. Da
sworty abut these for nows they
1n 35 permissions and well come to those later
the secandis the group. Ty
ly these wl ot
an enters Is =F
jas in the oot cirectory that belong to
foul see ether par Toot. Yo
BED ocr vog steer series volumes?ne next number relates
cuirent, Fis anc’ clrectories can be divectory with ack
neh
SOME COMMON DIRECTORIES
Now that you know how to view the contents of your hard drive you'll start to notice a lot of directories with names like bin, sbin,
vvar and dev. These are the files and directories that you are kept away from on a Mac, and won't encounter on a Windows PC.
STEP 1 peas (ch eee geese)
Cre mrmnt inerrant? eae
Ermer tay gem ester eee esi ee a eee Te eee eas
rmak@ up your Raspblan OS (whichis a version oF Linus). 'sworth From the default home directory. This is where you are expected
Prt cement to place mostof the documents you create, Don't confuse home
‘vith "usr the /ust directorys where find you Find program tools
eres
Be = onc ane ge
Soles dieconitresdnwies isthe ERIM isa duc tt consis code
STECZ Ce Ma eae oa SERS Ce en eeu
Sep cua eect si See ae ceca
"up your system. Dev contains references to your devices: hard re ee a en ee nat treet ary
drive, keyboard, mouse and so on. Etc contains your system Ee ee ce eee meee ea ee
eee ee eee en caeeuemu ena
ene ese Cerium)CREATING FILES
Once you learn to recognise the Files and directories that make up Raspbian OS, it's time to discover howe to make your own,
Knowing how to make, edit and delete files and directories is essential iF you want to make your own projects.
neeqongtouatestiengaconmard ated ERRRAEB seu to oue ae vat doe you
cut toe file, or directory, and updates i janges the system me ‘touich/testtfile and Ls /=I to view the files. You'lt now havea
siTyou'd ust opened the file), Youean see Teueh inaecessusing "ie ew fle ny aditettory called ‘testfle". Notice thatthe size
aralcheccna thetime next i aclrestary (such as Scratch) a the fileis ise thas nothing ini
Now enter: touch Serateh and 1S/=L again and EED Auick wore about filenames: remember thal
notice that the time has changed Linuxiscese sensitive, so you now encer Couch
fe currenttime. You might be wondering what this has TeStfile (witr a canitel 1) itdoesn'tupdate vestfle’ inscead, i
eating Mies or diectaries. Touch has seeane, more p creates a second fie calec Teste’, Enter: IS =L to see both les,
which istocreate files This isconsing, so most people sick rercase lettersAnother imaortant rhina to k
test file
fis", Technically there are we
ti
REMOVING FILES
oa Pur a Cece er ee ony uaLataretan a Cure
Deen iu eT ee
es
tro
Perea acy
Fallowed the steps before then youshould
ea)
et
Bee eco p ob eeu e
Mra caieet eames
Aas CCC eo
“Testhile” (with the uppercase “t").Enter: [ESET and youl find it's
Pee a eee ee oe
Cece ee eon mes tec)
Eee emt cis
De lee Oe e oe ne ergo
wo files, But again this is something you really
need to dowith care First use “sto lst the files and make sure
itsthe one you wantto delete. Enter: ISM to view files that
match the word "test and any other characters. The "* character
eee eee ere
Dee ene re
Rote mime
en ae emcee ect rtd
OT ee ee eee
ae RUURTUmeeag"n test Lee ue eeiE
Finally enter: IMI to get ri of the confusing file,Learning to Use Linux.)
Create and Remove
Directories
MANAGING FILES AND DIRECTORIES
Now that you know howto create files, you'll want to learn how to make directories, which are the same thing as folders, as
‘well as move items around. If you are more used to working with a desktop interface, this can take a bit of getting used to.
youcan eeate multiple director
“the mali command. Enter: ki
Enter: TS to quickly
ache home location,
ries are created
Enter mkelir
home direccory, Ente
Eestdim’to creat
Ts again ta see
| step 2 } ne “mkdir command ie diferent other using
Tedoesnt update the rindi Dosuments/
Airectory that aeady exists. Enter: mkdir es ain and yout side you
aget the ertor ‘madi esnnot este cirecory ‘testi File exists to akeary exist, though,
er: mkdir articles/reports and vous or
rere s no articles dre
BED sctnog steer series volumes?you need to
arts. Fier: 1S
GETTING RID OF DIRECTORIES
Create and Remove
Directories
d,option
Deleting directoriesis pretty easy in Linux, along with files, and this can bea problem. i's too easy to delete entire directories
Containing iles and these are instantly removed, not sent to a trash directory. Tread carefully
eee nen ceca
STEEs Gea ec ea
Ect tana
ee umenar mL f
(EESTZN and WS agsinto confi the directory has been removed.
Ree eter ec
TEP 2
Cette ane ers]
eee snes ae
Pee en eee tea
Ue nse cro!
BORE ta ere ets
sirectories, you return to the “rm command used
ee eee
Semen a Cu mae aetna
Ceres eget ne agen -k arciclosiay
Se es
BID 2: with multiple files youcan delete multiple
eee aad
ror cane
ee et eee eee sean
RO see es
Eis budreturniotce eu es eee TetCn
eer arene ate aceLearning to Use Linux.)
Copying, Moving and
Renaming Files
USING THE MOVE COMMAND
In Linux, renaming a file is simply moving it From ane name to another and copying a File is moving it without deleting the
original. Don't panic, it’s quite easy to ma
rove anythi Le testa and press cetusr
estivems incur zi ile dacument inti
olongerinthe
| step 2 } h files are moved inthe same:
ay testdir newparent zo movet
looked at so far x parent directory. Let's move into the
‘ommend line's commane, option, argument). TheFist atgument _cfrectoryto find the file Eater- ed nenparent/testdir and
isthe source (the Fle ordirectoryto be moved) and the secondis enter: LS to view the teste sting incide the directory
be cestination
directory
BED sce vog steer series volume 37th
ani th
isthe current diectar
Emerme testfile
ouble dot isthe parent
he t
RENAMING FILES AND DIRECTORIES.
Copying, Moving and Renaming Files
cd
nv nenparent/testfile nenparent
nave the testi from tscurrer
directory, Enter Is!
estdin/te:
location back insice the esc
nenparent/tiestdirr co view the Fle backin
Sea ern Ca eee eae me mCi gar aust)
eho meer tee ye
eee ene ems
Biogeouch esr cemete a tues
eee art
Contains the names of some people. So let'scallt something more
oe a ae
Enter (NEESER and Now we can
Seema eros ay
ere es let are reese
ee ee ee eee}
Ce eas ccc se
ils en
See eee ea ere es
STEP 3 ade aeebeaacedeaerur ara
‘which is now inside the weople directory, Enter: IMATE
estdir nanes/friendsaemeavagny names peop le/]
HARGIS to move the names file inside the friends directory.
ee er ae
a ee ene ad
cee ene erates
Exeirouch testh ieee |
Re easy
Cie perenne cy;
J Learning to Use Linux
Using the Man Pages
HEY, MAN!
‘The man pages are one of the best Features of Linux, and asa built-in tool it's invaluable For both beginner and senior level
Linux administrators. Let's see how it works.
Limos has @ bult-in manual, known as man fo
Short, Using the man command you ean ebtain
-mation on all che Linux talked about. Sime
entes:tan ar tlse name of the command you wan Lo learn more
aut. Start by entering: tan, 1 in the commandline
‘Most commands are prety easy Le Figure out ha
to use, sowhat you spend most ofthe time inthe
ing une he Description. Here you willsee all the
es used to activate tern, Mast man pages are
Longerthan asta page, so press any key, such asthe snace ha,
nove to the nex
EER Te man pagesare a bit more detalied than you
Imightbe used to. Fat se, hich tells
eae
the synopsis shows you haw ic works. tis case "'s
[aPnON]. (FILE J" Sa you enter: 1S followed by options (suchas
Aa and the File or citectory ta is
PresstheH key while laaking al aman page to view
the commands you can use to control the view
This iscalleg the Summary of Less Commands (che less camimand
s something we'll come to when welookat editing text, Far now
‘ove back and Forward with 7 and Wt, Press Q
alse that
witom a
Tyo
heman page
mation. Typically you wl find
[rns that can ae useful for mare infatration. Press Q to ext.the:
man page and return tothe commandline
USING MAN OPTIONS
ened
ing the Man Pages
uch
ran chaod
Cee er en Cora aerate er tore ae reg
Pea Or ais
Entering: HERE enables you to view some of
the options, But sometimes you'lljust want a quick
Pe ee eee ec
lists the options. Press Q if you're in a man page and enter: TEAMED
Bere
eget i Marites
em ea
Enter ARAB to view all of the man pages relating
Perce ear ee renee
ea maa ere ee eee erty
ees
F Go
STEP 2 ane tiarreeaunaree ateonirints i
peer e eet ar aer
Barre eaten
eet eae arertoe
eee
Cee ee eee
er ee
ere eet?
Care eee eMa eerie a ets
Se eee
Beene eat ear ciTHE JOY OF TEXT
Tobe able to edit or create a text file, youneed a good text editor. Linux has many but here are some inaction on the
Raspberry Pi
ee
either daubleclickan existing text filer click the
manwicon (inthe Lap let of the desktop) and fvem the
ssaries menu, chagse Text Ea
oe
mins, One oF the
vied aver From
launch any oF the d
na For ect
exit Nano
ithout saving
ng your“ Editing Text Files Gl
Emacs, or GNU Emacs, is an extensible and | steps ) Emacs can offer an uncomplicated wiew of your text
cuscomissble,seltedacumencing realime display Fle or one witha plethora ot information regarding
editor. 'sa Fantastic test editor and one thst'sworth cetting used rueture of the Fle In question it's up ta yout werk out your
s sagitas you cai. Sadly, t's rat installed on the Piliydefeult, awn preference. These’s aso a hitden tex! adventure
sovou'll need to instalit, Inthe Terminal enter sudo apt=get| hich we cover later inthis Book, why not see you can find it
install ewacs without our hela
ne previous command cores the Os sanother excellenttexedrar or Linx
aE {Raspbian is based on 2 Debian Linux distribution), Sure Again, it's not installed by default on the Raspberry
‘eposkories an pls don the infrration nee total nowt, by een: Sudo epteget tnstall ged ancl
Emacs When the Pigs tocontnde with the nstalation,press¥, accepting the stalation, the program can beon the I na matte
Thisinsalsthelatestverson and whenit’sdone,youllbebackto of seconds Once t's instal use Qe inte Terminal aunch
nea pronst 1 Ged sopeat tent ecto for cong
Oncetiinstlaton scope ener IIR Rouea arenas compare
ED iocsctamncttecnocspustsceet aves MaMa coc cae stgosegneandcentswth asestn
offering atutorial which we recommend yourun of features. To install t enter Sudo “apt-get install ed.
ation anc wien i's comalete, use; jed to launch
through and a guidec tour amongst other information. ‘Accept the insta
=
audomubiaionssn cosingtorrychon QIehtioe
Tet xagsy
WHAT IS A USER?
{An important part of using Linux is the concept of users and understanding which user you are and which group you belong to.
Like all modern computers, you can have multiple user accounts with each having different levels of access.
ineand press return. Ieshould you set up you essentiallyi'sthe h ghest evel o thes
name differently during setup). The “whoa” commandmightseer already installed text editers using sudo, You'll come aeress sud
abit simplistic, butt cames in very hancy sometimes, equeniyin Lin soles ceake # secand aceaunt to ges the hang
fit. Enter: Sudo Usenadd =m Lucy far pick vour nar}
when you are working im Linus, From line to time a EE Nove ade a password for the new account. Er
mrssion denied’ error wil occur, yaicaly when Sudo passiid Lucy andenter:a short pas:
ryto create, ecitor exeexce runjatlleer diveccory aurside Retype ‘and you'l now have owe ace
sf your area Jeathis enter:mkgim/ your Raspuerty P. Now enter: Us =U home Le view
testidin, Attempting to create anew d'rectory inyaur root dicectories for both users. Notice that the |
allowed. the owner anc group; and pi directory
iwlege. you want
Fea
perenne eee ees
Catena
Bee rat cessfully
a
re
o ToC a eee Cnet
renee etre) Preertyn” but the working directo
this Enter hoon
GETTING SUDO
( Getting to Know Users
reate files inthe /home/oi cirects
ee cota tne eae me ese ene eg ee een ad
Filesin fhomefpi. But there's also a third account, called "root", that sits above both lucy and pi.écan edit files anywhere.
Rosen ree mace tats
une cee
Se ace ee Cen eees
oom ean renter enema eee ey
Deere ecru nee eye ase
proc
Sa ents
raat
eer eee un
ieee)
BRTEEEED Most peonle think sudo stands For “super user",
ae dmeie emg
Trace mess. -u |
SYRIA PATSTIANTST ATO to create a File inside the licy
home directory, You wont aet an error because the lucy userhas
Pema Clarets
EOTeSEEDD I s'20e that you use sudo ta substitute another
eer eat
ee ie ected eec teas
Riri tent teema sudo couch /hone/tucy
Fanothertecth le Sfape tens Cony ies Rt re eererTeersTt
Poors
eee
pana ae cae an
it needs tobe added to the sudoers file. Enter to
view the sudoers file, Add LST TED MWTASS
tothe lastline and use Conrol+0 fo output the file. Remove the
poeta ure re teeters
Deine peers ree ere een errr
Cc
eee eee}Learning to Use Linux.)
Ownership and
Permissions
OWNER AND PRIVILEGE
Each user account in Linux isan owner oF a section of the filesystem: thelr Home area. Within this area, they do what they like
(within reason), as they have owner privileges. Elsewhere though, they usually just have read-only privileges.
sdthe ace pould now
ale
tia ase
vd
Now enver: ES =U and let’shiave a qood look atthe
nsfile, Qurtestile tt Fes starts
Doerr taeset to On, The sine
CHANGING PERMISSIONS
nership and Permissions
The presence of, oF xmesnsthat this asp
ole. adash means itisw Gur}
many lettes? Why not just thee; read, vi
letcersare for different
Group Other
Peet ae i ue ere
eer ene are ca
ene Ce ets reas
Ichnodhieticve aa tuemt
Re eee
to understand, There are two ways you can adjust
neuter nei
Sr ert en ea aires net id
ar Followed by = andthe letters or dashes you want. So enter:
EEG to make all three groups read,
HERE to see your handiwork.
Pee a ae a
eu mes
COM ak eats eM Eom!
Fe te econ ee Neer Lic cies
‘group, thereforeilf a group isread, write and execute it's 7, iFt's
ee ead eee eee ad
55 755, Enter: SUEEEMEISENER to change the file
Sees een!Learning to Use Linux.)
Useful System and
Disk Commands
LOTS OF LINUX
Linux is a huge and versatile command line Language and there are hundreds of commands you can learn and use. Here are a
Few that can help you get more from your Raspberry Pi
FETED the maspborry Pisa great tle computer so
let's start by gett formation Enter
tals on your Raspberry?
spbery Pi 3 you will see Faur pr
games.
responcistothe screen (outa). This sthe regular wayof doing ty Gat" autpuls the ist of hems ia anew text file calle “games.
dinput and output” (often called "sed
mes tt contains the output ror
mand. You ca tusing"
games Le sa ecitable Lex. file containing alithe permss.ens,
ser an filesize information and the names of
From thets-{ command, narmalty splayed on the
stead Sent Lo Uhl, Press Contsali x
les. The output
s Far as the computer is concerned, Input and
ult can be to and from a whole range oF
yours ven think about. A program
different sour
an get input fiom ath
drive andl a whole nos
ine, ut also toes, othe!input froma file. Make
files, boty
eae
Jefferson Airplane
a
USING PIPES
‘As well as directing input and output to and frat
neuen
‘nano
Input, Output and Pipes
ext il asinp
sort <
i uses the standard output
jut and outout togethes
rked txt to creat
tothe
bands. txt era
put sot spec
Files, you can send the output from one command directly Into another. This
PEPER 6: you start to get more advanced in Linux you
Cee eons
Poa iment ence
eterna
Pesan
BREED Wic've used the pine a few timesin the book ('ps
‘aux less), but you might not have understood
arena: The
i ea Career
isnt displayed on the screen, instead its piped into the we (word
aunt) function, This then tells us how many lines, wards and
er etre
Cua
re tec pe ec
pote wo ameu neces
fect bands ext T sort Tarep they
tthe band starting with "The" in alphabetical order, The output of
ead eet ees aed
‘output From sartis passed into grep which filters out the bands,
Se a eet
Soe en tetas
STEP 4
‘create complex expressions, Yau can also use >>
CEI eae
jands. txt Tne >>
REGIS This takes the ovtput From
the bandstxt file and pipes it into the we (word count} function,
Deon eeu e ae
Eeergcat bonds. txtLearning to Use Linux.)
Fun Things to Do
in the Terminal
TERMINAL FUN
All these commands are Li
Linux distributions
ETE Te first command we're goinoto use isl t's
rat stalled by cefault sa enter: sudo aptsger
EnstalW/SL. The commanc can be run with sianc to inezal the Terminal aoa, Fortune, irs
displays a Stearn Locomative traveling, Enter: sudo apt-get install Fortune ther simply encr:
Entering: LS (note the upper case) alsa works Fortune, nts the Terminal tosee what comes up
reveommandiscertainlyinteresting, and at
ule useless addition oo the
neseemingly unbreakable
ter: Rev anc then type some text, Then press Enter
tomel and everything you typed in is reversed, Press Cbs to ext
ied having the computer read
«om fortune out ta yoat then you's in luck
os the screen then
Bap =: of Star
Ea = Terminal By tink
len gets Fawhenitcomesto
toa remote server viathe BED =:
telnet commane, you can watch Episode IV: New Hope being cab
played out, albeit in ASCIL, Ta view this spectacle, enter: SUd@ nasswords
apt-get install telnet, Folowed by: tele
blinkenbights.oh
BED ee cog steer series votune a7Fun Things to Do inthe Terminal (4
jute stuck
work cual the possible really wantto expand the whole rom
ors for ary particular number, sirmphy en twhatever reason, then pine the Fortune
Factor Followedby the number. Fo example, Factor? ‘command throught, with: Foreune! | ‘coWsay: and forthe
Fer much output, whereas factor 60 dspleys mare, graphical cow equivalent: Fortune | xcowsay. Plus, there's
ss couthink. Tv Comthink «This book-is awesome,
ine line between che rather co EED Admittedly, the command tole doesn tinssine
ute weird, Having an ASCH cow repeat much canvidence. However, its notas bad as
xt Co you could potentially fal into the later. Start by nstaling First sounds, Start oy nsaling it with: Sudo onrteget "ins taLL
ay: sudo apt-get. install consay,:nenenter:consay) toilet, men aed, sype something along the ines of
Raspberry Pi is Acel. infact put the toilet David; or peshops is: the contents ofthe cutreat folder
‘onwnand through the cow, by entering: Ls” cowsay. ivough it, wid: US) Itoi let.
Jet commane, you can actually
lupe cance Ease Enter
Jang graphiesthreugh
ibwith: Sudo @pt-aet install xcousay, tren when it’s For example, by this toilet =F wionol2 —F metal David
installed enter something similar to cowsay, such as, XCONSAYBDM) You can enter: toilet =hellp for lst oF the command line
Publications are ace! arguments ta expand fuLearning to Use Linux.)
More Fun Things to Do
in the Terminal
MORE FUN, YAY
Since the Terminal session is already open, and your keyboard digits are nicely warmed up, here are another twa pages of
daysof computing, ARIA Having alittle white
Hello’, 20.got stound the clesktop may
Raspblan youcan ime, Oddy though it isnt. Entew sudo. apt:
1 neko, then type: oneka to have
Terminal nonsense.
pases. Use
rouse! cursor around the screen and
exit the action
than the previous
niuallyrepicates
one ofthe most) Ea i entryie alittle more serio
sdandthere’seven a version of For Bomb
‘or Lina Install tvsith: sudo. ape~gee
imply enter: CME 21386
ne encer ChartPAX ane Follow
install ematrix. when it’s
te rabbit Neo, Unlike the reat Matrix thouah,
to ent
ingrionate!
reboot,
prStringing several commands anc piping them
ercommendsis what makes srigcing
such a powerful ele n OS. Ferexample, using the while
‘mineral, taget her wit tole, can yieid same Impressive results
Enter while true; do echa “S(date ‘4x0 MT? | toilet
=f term -F border =-metal)"; sleep 1; done
ing computers were he Care che '05.Ta
Suse relive the fun enter: sudo apt=get' install:
speak ther:especk “This. 1s a Rospberry PL" ove
Tohune stared up andy the fling Ls Sora
‘ex BE espeak =f Folders txt. Ths gets Raspbian tovead
back the contents of the s commanc
BETTER 81027119 AS ire isr'tthe most useful command
ui but st
Sudo opt-get install Tibaa-bin thea use: cafire Ilsa!
exactiy warming but you get the idea, To-expand the above, enter
Sudo apt-get install bb caca-utils, sven: cacafire
More Fun Things to Do inthe Terminal
i
Nod
Used as. music demo from the sic
sigs ara
kes memories of three ard
half inch lopaies erammc ‘of dema scene goodies.
"You've alreal int from the previous steg, so just enter: Bb.
the onscreen inzructions and turn up your lume.
xo parts, Fist younees to get hala
ackages: sudo apt-get in
ne enter. €d DowiLoads/ 8%
get bttmi//search cran.org/CPAN/authors/id/K/KB
el tre necessary
KBAUCOM/Term-Animation-2.4.tar-gz && tar -xF Term=
Animation-2.4targz && cd Term-Animation-2.4/.
Folower by: perl Makefile.PL Smoke 88 make test 88
sudo moke install
=a
ED os
‘obobunny com
8B nget http: //mme
rojects/ase iquariun/asei i quar un
‘tor.gz 8& tar =xf asciiquarium,tor.gz && cd
asciiquariumt.1/ && chad 4x asctiquarium Providing
allwent well, enter: fase iquanium and enjoy your very een
‘ASCILbased aquarium,TAKING COMMAND
There are countless Linux tips, secrets, hacks and tricks out there. Some are very old, originating from Linua’s Unix heritage,
while others are recent adetons to Linx lore. Here are our ten favour tps and tics,
EASTER EGGS yew
bie to
tose | EINECS os trscess te
Leditor, a g
but ciel you kr
‘shidelen Easter Egg? with Emacs installed (suda aat-get install, ‘errinal? while not particularly useFul it isa fascinating thing to
ernaes24), drop Lea Terminal seccien and ent d. Te €0s0, onto
emacs -batch “1 dunnet sudo apt-get install elinks
Dunne fs tex: adventure vertzen by Ron Schneltin 1882, and Then:
hiddeninEmacs since 1994 —
Enter the website you went to vis
Pea eso cs 982 ace sae,
en home computers
Sue guia in La Tenaya
cking Atari
wget
aR hittns://aist gi thubusercontent.. con/sontek/1505483/
raw/74024715ea57e69b52632fee09F42753361¢402/
ssnowjob.sh
moon-bugay
He chnod 4x snowjad.sh
/smomjab .shate eemD Memos Hoos IFyouneed tose BBS :
sshich apps ere consuming the most twas made up of Bulletin Board Syst
memory an your RasaberryP, simple enter servers provides hangouts Far usersto ch:
‘and more. Using Telnet in Linux, you can stl connect to some active
nBSes
ps aux | sont -rnke 4
‘telnet battlestarabs.dyndns.org
“There are countiess one ational BBSes avaiable; ch
usutelnetbbsauide,com/bbsilistédetailf For “nore
BT en a hervou delete a Mle, there's stl achanceot
someone with te right software being abie te
retrieve it. However, files can be securely anc permanently deleted
ssing shred: ee —,
shred -zvu NAMEOFFILE txt CURES SSRIS)
olde) ree with a
cr EQFFILE with the name of the Fle
Ni
mkdir =p New-Din/
{subfoldert , subfolder?2, subfolders, subfolders}
“This creates « NeweDirwith Four subfolders within,
rartcan be quit
ASCILART tsking when ap ,
ane ieers Oe Caen ina rele ee (sncteey tying
apt jus: righ, You can create some great ASG art from the images eRe ENS
yyouaiready have on the Raspberry Piby using ima2vst: avallabie Linuxccommanes. Thankfully help,
imgtxt NAMEOFIMAGEFILE. png sine
Replace NAMEQFIMAGEFILE with the actual name of the image File
vf the conwnand
‘apropos “copy files”
‘apropos “rename files!”eee
fs
A-Z of Linux Commands
There are literally thousands of Linux commands, so while this is not a complete A-Z, it
Cooder ee oder ecumenism ciel Uke ais)
Cretan emarl cmesecenumueue stant etme ei tants inl
overall knowledge is still very useful.
A G
adduser ‘Adda newuser dd Data Dump. cenvert and gawk Find and Replace text
arch Print machine architecture Snag winnie se
HS tnintacioe "HATS ayocauciss BREET Sic a
be Aniatbitary precision
named filets)
te head ‘Qutput the first part
constant Ain sicriadteaeios orn
on the standard output eee
: ce web Sevens iecicar” asian” Pico Sega ane
chair hengerworing Sectory sree
chorp changathe aroun extended expression
onmersip of ies
; : on Bilayer emove cand
chroot: Change root directory environment variabies oe (OES lst)
cksum Print CRC checksum and expand Convert tabs to spaces wi Help inte
ae exer Eualuate mipressons a oon
op Gompare tu fies PS o
comm ‘Compare two sorted Files F
Unebe ine J
op Copy one or more files to Fae Bristirene oes join Join tines on a
anotyerlocstion fdisk comme ed
crontab Schedule acommand to mngnistor fer Liaue
runat aletertine farep Search Flt} For lines that K
split Salita fle into context: ae tae aed
cerermines pees fina Searehfortiesthatmeat MT ees
cut Divide a file into ee ee
sevralpans fn fefarnal pangaghent
fendi Wapieeisris LL
D specified width less Display output one screen
atime
on Pistay achat — a See In make links between Files:
dake & time fsck Filesystem consistency i is
ss ae check andrepsr locate
aLoaname
pe:
lor
lprm
nl
rnohup
P
passad
paste
pathchk
pr
printcap
printeny
print®
quota
quotacheck
quotact
R
Print current login name
Line printer
control sregram
oftlineprine
Remove obs from the
print queue
See Hela manual
(Create new Folders)
Make FiFOs inamed pines)
‘Make block or characker
special files
Display output ane screen
atatme
Int ale system
Set the priority of 3
‘commane or job
Number lines and
write Fes
Run a.command immune
to hangups
Med fy auser password
Merge lines o files
(Check Fe name porcabaity
CConverttext Files
for pitting
Pen
apablly dalabase
Priatenranmen: variables
Format and print data
Display disk usage
and limits
Scan file system for
tisk usage
Seta
ssc quotas
vm
rain
rom
rsync
sdiff
select
seq,
shutdown
sleep
sort
‘split
symlink
sync
tac
toil
tor
tee
test
time
‘touch
top
traceroute
tr
tsort
Mcfinxcomens CRE
sores U
ae tumour Unmount adeviee
eee unexpand Convert spacestatabs
unia Uniquify Files
units Convert units rom one
seale to anathe’
unshar Unpacishellarchiveseripts
useradd ——Crestenew user account
Terminatwindow manager USO == Modify use: account
eee users Listusers cnrenty
ge woo fies meractvely tose
Accept keyboard inpuc
Prrecceaues Vf
Shutdown ocrestatt NOt uy Verbosely ist directory
a Execute or display
Make anew name for ao HE
Spach onise data ondick lates ol pepe
‘with memory which Locate e pragrar file in
resin the user's path
who Print all usernames
currently loggedin
thoani Print the current user id
andname
te xX
Red
maltiple es
Resource Use
change filetimestamps
the system
Tr
Route to Host
anslate, squeeze andor
delete characters
lopological sortz= Learning to Use Linux. }
Glossary of Python Terms
Just like most technology, Python contains many confusing words and acronyms. Here
then, for your own sanity, is a handy glossary to help you keep on top of what’s being
Pema tecm cise ountueteslat neal cece Mush
Argument
The detaied extrainformation used by Python to perform more
detaied commands. Can also be used in the conmmand prompt to
specva vertain runtime event.
Block
Used to descnbe 2 section or sections of codethat are
grouped together
Break
‘A cormmand that can be used to exit afor ot while loop, For example,
IF key s nressed to quitthe program, Break willext Ere loop.
Class
‘class provides a means of undinadate and Functional together
They are usec za eneansuiate variables 2nd funetionsincoa single ent,
Comments
‘A commentisa section of eal ward worting inserted by the
plagrammer tohelp document what's going avin une code, They
‘can ae single line or multiline and are defined by a # or
Debian
{8 Lmcbased dstra or distrution hat Forms the Osbiaa P-oject
This erwironment offers the user a friendly and stable GUI to
interact with along with Terminal commands and other Forms oF
system evel administration
Def
Used ta define 3 function of method in Python,
Dictionaries
A dictlonaryin Python isa data structure that candistsof key and
vale pairs
Distro
‘Ako Distniution, an operating shen that uses the Laux cemel ass
‘core but offers something differenti its presentation cathe end user,
Editor
‘An india program, or 2 part ofthe graphical version oF Python,
that enables che user ta enter code ready for execution.
Exceptions
Used aa mears of breaking from the normal low of a code blockin
‘order to hance any potential errors exceptional cantons within
theprograr.
Expression
Essentilly, Python code tha producesa value of something
Float
‘An nmutable floating point numer used in Python,
Function
Usedin Python te definea sequence of statements that canbe
calles or referenced at any time by che programmer.
GitHub
‘A eb-39sed version control and collaboration portal designed for
Software developers to better manage source cade.
Global Variable
‘Avariable chat is useable anywhere in the program.
Graphics
‘The use of visual nzeraction with a program, game or operating
system. Designed to make it easier For Une user to manage the
jagiam in question
GUI
Graphical User interface, The interface which most moder
‘operating systems use to enable the user to interact with che
‘core aragramming of the system. friendly, easy 0 use graphical
clesktop enuitonment
High-Level Language
‘A progtamnming Language that’s signed to be way For people to read
HOLE
Stands or integrated Development Euironment or integrated
Development and learning Environment.
Immutable
Spiething that cannot be changed ales itis created,
Import
Uwdin Python tone modules togevier wih llthe
accompanying code, inctonsand variables they coal,
Indentation
thon uses indentation to delimit blocks oF code The indents are
Four spaces apart, and are often created automaticallyafter 2 colon
susedin te code,Integer
‘uur datatype that mustbea
2 decimal
Interactive Shell
‘The Python Shell hich is dlsplayed whenever you launch che
raphical version oF Python.
Kernel
The care of an operating system, which handles eata precessing,
memory allocation, input and cutout, and processes infermation
between the hardware and programs.
Linux
An open source operating system
Developed in 1991 by Finnish tude
at's modllled ont UNI
Linus Torvalds,
Lists
‘A Bychon datatype that contains collections of values, which can be
‘of any type and can -eaclly be maciied.
Local Variable
‘variable thay's defined insie 2 Function andiis only
that Function
Loop
‘plete of code tat cepeats tse unis certain condtion met:
Loops cn encase the ete code or jst sections of
Module
python fle that
jer rogram ta futher extendthe effectiveness of the
ans various Functions that car be used win
sno ode.
Operating System
‘Also 05. The proram that’s loaded into the comauterfrer the
intiak boot sequence hes completed. The OS the athe
programs graphical user interface (Gul), mput and output and
Physical herd ware interactions withthe use
Output
Data thats sen rom the program to sereen, printer or other
‘external perionera
PIP
Pip Installs Packages. A package management system used to install
2nd manage modules anc othe softwere wrten Python.
Print
‘function usec to cisnlay the output of something tothe screen,
Prompt
The element of Python, orthe Command Line, where the User
‘enters their commands In Python t's represented as >>> in the
interactive shel
Pygame
‘AP\thon nodule thas dessgned for wing games. Rineludes