0 ratings 0% found this document useful (0 votes) 266 views 82 pages Python Coding Tricks and Tips 16th
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Carousel Previous Carousel Next
Save Python Coding Tricks And Tips 16th For Later @ Advanced guides
and tutorials for
programming C++
and Python
@ Next level fixes
and secrets get to
the heart of the
Python language
neces Everything you need to take
Sah saat Nolte aM levee litte
and much more skills to the next levelFREE Software! Great Games! Essential Hardware!
GAD
APPS & GAMES Rebel
Bs gat ©
Head over to your web
browser and follow these
simple instructions...
1/ Enter the following URL: www.pelpublications.com/exclusives
2] Sign up/in and from the listings of our exclusive customer
downloads, highlight the Tech Shopper Magazine option.
3/ Enter your unique download code (Listed below) in the “Enter
download code” bar.
4] Click the Download Now! Button and your file will automatically
download,
5] Your file is a high resolution POF file, which is compatible with
the majority of customer devices/platforms.
PCL37862RE
NOTE: This iso limited reader offer running from Ist Novernber 2023 to Ist March
2024, Terms and conditions apply and can be found at wixwspelpublications.comTRICKS
& TIPS
Python
Coding
Python Coding Tricks & Tips is the perfect
digital publication for the user that wants to take their skill
set to the next level. Do you want to enhance your user
experience? Or wish to gain insider knowledge? Do you want
to learn directly from experts in their field? Learn the
numerous short cuts that the professionals use? Over the
pages of this essential advanced user guide you will learn
everything you will need to know to
become a more confident, better
skilled and experienced owner. Ova
Auser that will make the eeouee the page
absolute most of their abe ee Hh Continues,
coding and ultimately eae ee $e with you
Python coding itself. An info ‘Y Stage to advice
achievement you can earn by ‘eltm and ultimately
simply enabling us to taspive you to
exclusively help and teach you 90 Further,
the abilities we have gained over
our decades of experience.Er]
Ey)
35
36
40 Mouse Controlled Turtle "Simple Python Calculator
Creve cre eos
A ae i asf i
i Fa twa Ke 7 A i
a ear By(in
LGA
[Niwa am -
"There's so much you can do with
Python and within these pages you'll
find everything you need to know to
become a Python programmer, ready for
the next level of advanced coding.”False
Lore
ata
Ree enor) Py ae stil end -ad
Me eeUsing
Modules
Me ar unr
source file that contains the necessary
Cage eae nee
Ree ete eee
Merete nes
Puke eur teeta cs
Soe ces
INN Me a TTT
your use of these modules to adda
ecu ier serine
Then read on and learn how they can be
used to Fashion fantastic code with
Pea eMC eee ek CLL |
BreuerLE) vinatoases
Calendar Module
Beyond the Time module, the Calendar module can produce some interesting results
when executed within your code. It does far more than simply display the date in the
Time module-like format, you can actually call up a wall calendar type display.
WORKING WITH DATES.
The Calendar module is built into Python 3. However, if For some reason it’s not installed you can add it using pip install
‘calendar as a Windows administrator, or sudo pip install calendar For Linux and macOS.
FETIIEDD Leunch Python 3 andenter: import calendar to
«allup the module and itsinherent Functions, Once
itloaded into memory, sartby entering
- neh (2018, 9)
sepecalendar. TextCalendar (calendar. SUNDAY)
‘Python 353 Shalt
[Be Eat Shel ebog gptons wndow wep
Sleedits" or “2icense()" for sare information.
‘You can see that the days of September 2019 are
clsplayed in a wal calendar Fashion. Naturally you
can change the 2019, 9 part ofthe second tine to any year and
‘month you want, a birthday for example (1973, 6).The Fist line
configures TextCalendar to start its weeks on 2 Sunday, you can opt
for Monday ifyou prefer.
thon 383 shat
S terms gett meen
‘There are numerous functions within the Calender
‘module that may be of interest to you when
Forming your own code. For example, you can display the number of
leap years between two specific yeas:
3 (@afault, Sep 27 2018, 372539)
‘aokrasie) on Timex
copyright, "eredits” or "License()” for nore information
Se Sr calendar °
25> keeled anaanys(aon, 200)
You could even fashion that particular example into
apiece of working, user interactive Python code:
OiagYou can also create a program that will display all
1d
Amport calendar
yearsint (input ("Enter the year to display:
print (calendar.prcal (year)
(We're sure you'lagree that’s quite a handy bit of code to have
tohand.
»
Interestingly we can also list the number of daysin a
month by using a simple: For loop:
Ae
cece
i print (i)
ETE D the ossystem0 functionis what allows interaction
with external programs you can even call up
previous Python programs using this method. You will obviously
reed to know the ful path and program file name fort to work
successfully, However, you can use the following
import os
os-system(*start chrome “https://wmw.youtube.com/
feed/masic*’)
FEPTIDD For step 5's example we used Windows, to show
that the OS module works roughly the same across
all platforms. n that case, we opened YouTube's music Feed page, so
Itistherefore possible to open specific pages:
import 03
ce-eystem(‘chromiun-browser "http://
banpublicationa.com/*/)
Note in the previous step’s example the use of
single and double-quotes. The single quotes encase
the entire command and launching Chromium, whereas the double
{quotes open the spectied page. You can even use variables to call
‘multiple tabsin the same browser:
import os
a=(‘chronium-browser “htty
con/*")
be (*chromium-browser “heey
os.system(a + b)
+/ Podmpublications.
/rwee google.co.uk"")
The ably to marolte rectors or folders
lls you prefer, is one of the OS module's best features.
For example, to create a new directory you can use
import os
(os mkdir (*NEW")
‘This creates a new directory within the Current Working Directory,
named according to the objectin the mkair Function,
You can also rename any directories you've created
byentering:
import os
‘og rename (NEN
soup")
To delete ther:
import os
(os rmdir (*0z0")
‘Another module that goes together with OSis
shutil, You can use the Shutil module together
with OS and time to create atime-stamped backup directory, and
copy files into
import os, shutil, time
root_sre_dir = r*/hone/pi/Docunents*
root_dst_dir = ‘/home/pi/backup/" + time.asctine()
for ere_dix, dirs, files in oa.walk(root_sre_air):
dst_dir = sxe_dir.replace(root_src dir, rost_
aet_dir, 1)
Af not oa.path.exist (det_dir):
os makedirs (dst_dir)
for file_ in files:
src_file = os.path.join(sre dir, file,
dst_file = os.path.join (dst_dir, file,
Af Os.path.exists (dat_file);
08. remove (dst_fi1e)
shut il.copy(sre_file, dst_dir)
print ("sssassssssBackup completecceececece")ED) viene
Using the Math Module
One of the most used modules you will come across is the Math module. As we've
Nea sel McA Cole Uae Leader Ce nee Te)
eee Me tell NM aLmol mt Lela n ure t] (Ke- MMC TR ot R Sele a
E=MC?
The Math module provides access to a plethora of mathematical Functions, From simply displaying the value of
you create complex 30 shapes.
“The Math module is builtin to Python 3;so there's
noneed to PP instal t.As with the other modules
present, you can import the module's Function by simply entering
Amport. math into the Shell, or as part of your code in the Editor.
Importing the Math module wil give you access to
sue the module's code. From there, you can call up any
of the availabe functions within Math by using mati, followed by
the name of the Function in question. For example, enter:
sin(2)
This displays the sine of 2.
watt
Python S43 (aetaul®, Oct 19 201
{ce 4.9.1) on Linae
Hype “copyrighe’s “credits” or “License()” for more information.
See east
S33 mathesincs)
tohelping
EEPEED 4s ouwil no doubt be aware by now, ifyou know
the name of the individual functions within the
module you can specifically import them. For instance, the Floor and
Ceil functions round down and up afloat:
a ) # returns 1
ceil(2.2) # returns 2
3> enc.
‘The Math module can also be renamed as you
Import, as withthe other modules on offer within
Oiag
Python. This often saves time, but don’t Forget to make a comment
to show someone else looking at your code what you've done:
import math as m
m.trunc(123.45) # Truncate removes the fraction
‘le Ed Shel Debug tens Windows Hep
Bython SAF (Getault, Oct 19 20¥6, TBST)
(6ec'2.9:1) on Line
Tipe *epytaphe”, Seredses™ of “Licanse()* for nore information
PoE" seh asthe =
pas arnt.‘thoughts not common pats ts possible to
g1g?5 import Functions from a module and rename them.
In this example, we're importing Floor from Math and renaming it
tof. Although where lengthy code is in use, this process can quickly
become contig
‘from math import floor as f
£01.2)
‘le Eat Shell Debug Sions windows tielp
1 erggits” or “License()” for more information.
SE cseonath Inport floor 2° F
333 Fetes
STEP
Importing all the Functions of the Math Module can
bbe done by entering:
from math import +
while certainly handy, thsi often frowned upon by the developer
community asi takes up unnecessary resources and isn't an
efficient way of coding, However, iFt works For you then go ahead.
Pyahon 5-43 (Seoul, Ok TOKE, T3aTETTD
1s Mergdits* or “License()” for more information
2 sarecé)
333 easeay
FS)
FETE AD terestinaly, some functions within the Math
modile are more accurate, orto be more precise are
designed to retum a more accurate value, than others. For exemple:
LL ET
will return the value of 0 999999999, Whereas:
LE LET
returns the value of 1.0,
ys ergdits” or “License()* for more information
yy ete te ate ot
teats ate tnd
(( Using the Math Module [>
For further accra when comes tonumbers the
Sus ‘exp and expm1 functions can be used to compute
precise vals
fron math import exp, xem
exp(ie-5) = 1 # value accurate to 11 places
‘expml (1e-5) # result accurate to full precision
‘Teobabsoaooeaetne-05
232 arom)
;
SH °
ESTEE tis tevel of accuracyis really quite impressive, but
quite niche For the most pat Probably the two
most used functions are eand Pi, where es the numerical constant
cequato 2.71828 (where the circumference of crcl is vided by
itsciameten
import math
print (mathe)
print (math.pi)
Python 3a? (aetaulk, Oct 19 2
(ee 49:1) on dine
Tipe Seopytagne’. creates” or “Licensec)” for nore information
Sa ngoet math
>> prince)
>
‘The wealth of mathematica functions available
through the Math module s vast and covers
‘everything from factors toinfnity, powersto trigonometry and
_angular conversion to constants. Look up httpsi//docs,python.org/3/
Uibrary/math.htmit for alist of avaliable Math module Functions.Eins
Random Module
The Random module is
one you will likely come across many times in your Python
programming lifetime; as the name suggests, it’s designed to create random numbers
Cancer atie)
Drolet neler ont a ATI ile come aCe}
RANDOM NUMBERS
There are numerous Functions within the Random module, which when applied can create some interesting and very useful
Python programs.
“tatesuithothermedisyourcedtoimoort (EMEP, owever he Rondo sed exclsely
random before ou can Use ory ote reo formas Youcar oe tto sect aren roms
we're going to look at in this tutorial. Let’s begin by simply printing a _ list From random, and the list can contain anything:
‘andom number om 105
ED i ourexample
the number four
was returned, However, enter
the print function a Few more
times andit wil display different
Integer values From the set of
‘numbers given, zero to five. The
‘overall effect, although pseudo-
random, is adequate for the
average programmer to utlise in
their code.
‘multiplication sign:
Smport random
print (random. random() *200)
\will display a Floating point number between 0 and 100, tothe tune
(of around Fifteen decimal points.
PEPER Fora bigger set of numbers, including floating
point values, you can extend the range by using the
ies Sn Sie Sree or Lc fr mre ita
‘This will display one ofthe names of our adventurers at random,
which isa great addition toa text adventure game.
‘Youcan extend the previous example somewhat by
Bus having random.choice() select from a list of mixed
variables, For instanceRandom Module ¢ >
Ieingy ouceno seatincion wine EAR asic on nnple ee cote hc ga
Sue Random module to shuffle the items in the list, thus Gu)
virtual coin ten thousand times and counts how
adding alittle more randomness into the equation many times it wil land on heads or tals:
random. shuffle(1st) import random
print (ist) output “Taser :0}
Thisway,youcankeep shuffling the ist before displaying random SoAM=MsE (output keys) )
item from. for 4 im range (10000) +
ee ce eed
print (*Heads:", output [*Heads"])
print (“Taile:", output [*Taile"])
cera Using shuffle, you can create an entirely random list
‘of numbers. For example, within a given range:
import random
Aete[ [i] for T in range (20)1
yandon.ehuffle(1st) BSTESEERD Here'san interesting piece of code. Usinga text
print (1et) file containing 466 thousand words, you can pluck
‘user generated numberof words fromthe file text ile Found at:
Keep shuffiing the ist and you can have different selection of Se
Se acer ‘wwnwithub.com/dwyVenglish-words
import randon
print (*s>>s>>5s>>Random Word Finderce File) and create a True/False while loop:
import pygame import pygame
pygane.init () from pygane.locale Smport *
pygame. init ()
‘ganewindowspygane. dieplay.set_node ((600,600))
pygane. display.set_caption ("Adventure Gane")
rT
runningstrue
while running:
for event in pygane.c'
Af event .type==QUIT:
running-False
ygame quit ()
PPIIP DD Let's create asimple game ready window, and give
ita tite:
ganewindowspygane. display.set_wode ((600, 600) }
pygane. display-set_caption (*hdventure Gane")
gmorindon-pygane display set node((800-600))
Prose display-setcoption( Adventure cane")
or"event.in pygae.event.getc):
Youcan se thot tr the frst nested, ounce ck bck Pe eae
aa the DLE Shlto conte ering coda, youcanchoge aes
the title ofthe window to anything you tke(Pygame Module eC
EEE thePyaamewindowstil won't
close don't worry, it'sjust a
discrepancy between the IDLE (whichis written
with Tkinter) and the Pygame module. f you Ft Tae ep
un your code va the command ine, it closes
perfectly well
You're going to shift the cade around abit now, ing-pygame image. lead (*/home/pi/Downloade/
running the main Pygame code withina whileloop; apeitel.png")
Itmakes it eater and easier to follow. We've downloaded a graphic
to-use and we need to set some parameters for pygame:
def apritelx,y)
‘ganewindow Lit (img, (x,¥))
import pygame
pygane- init () x=(800°0.45)
y=(600%0.8)
sunning-Teue
gamewindow. £411 (white)
while cunning eprite(x.y)
‘ganewindowspygane. @isplay.set_node ((600,600)) ES
pygane.display.set_caption ("Adventure Game") for event in pygane.event .get()
black=(0,0,0) Af event .types=pygame. QUIT
whites (255,255,255) runningeFalse
FTI L2t's cuickly go through the code changes. We've _dawnloaded image called sprite png and allocated it to the
defined two colours, black and white together variable img; and also defined a sprite Function and the Bit function
with their respective RGB colour values. Next we've loaded the vil allow us to eventually move the image.
ao prams
"um pygame Locals snport *
premecaniti)
emenindon.fillovhite)
Spritecsy)
Prame-display.update()
ganenindow-pygune. display set_mode((800,600))
Prame-dispiay-setcaption( Adventure. cone”)
Elscee(0:0°0). ‘for event in pygane event. get0
vaniten( 255,295,255) ST oven. eypersQurY
Inespreme. anage-load(~/hone/pi/Domloads/spritet png") unninges sis
prame- quit
ot spratece.yy:
Emenindon b1St¢img., (4.99)@) Using Modules
FeTeeR AD ow we can change the code around again, this
time containing a movement option within the
while loop, and adding the variables needed to move the sprite
around the screen:
Amport. pygame
from pygame.locals import *
pygame. inst ()
punning-True
ganewindow=pygane. display. set_wode ((800, 600))
pygane. display. eet_caption (* 2 Game")
lack=(0,0, 0)
whites (255,255,255)
4ing-pygane .inage. load (*/home/pi/Downloads/spritel.
pn")
def sprite (x.y):
‘ganewindow.bLit (ing, (x.y)
x= (6040.45)
ye(600*0.8)
xehange=0
Lf event.type == pygane.KEYDOWN:
Af event .keyeepygame.K_LEFT
xchange=-5
eLif event -key--pygame.K RIGHT:
change=5
if event .types-pygame. KEYUP:
{Lf event .key==pygame.K LEFT or event
‘gamowindow. £11 (white)
sprite(x,y)
pygame.display update ()
ygame quit ()
FEED) Cut, Choose File
> New File and use Edit» Past inthe new window. You now have
two separate files, one with the Function definitions, the other with
the Function cals
IF you now try and execute the basic_math.py code
‘again, the error‘Name€sror: name 'timestwo' is
Oiag
not defined’ willbe displayed. This s due to the code no longer
having access to the function definitions.
ine etna drach. ine, in ale
se Tt: at eto
steps Wow
thenewly
created window containing
the Function definitions, and
lick File > Save As, Name this,
minimath.py and save tin the
same location as the original
basic_math.py program. Now
lose the minimath py window,
so the basic_math.py window is
leftopen.PPI) (2ck to the basic_math.py window: at the top ofthe
code enter:
from minimath Inport *
‘Thiswillmport the Function definitions asa module, Press F5 to
save and execute the program to seein action,
Sis
You can now use the code Further to make the
program alittle more advanced, utilising the newly
created module tots Full Include some user interaction, Start by
creating a basic menu the user can choose from:
print ("Select operation.\n")
print (*1.Times by two")
print (*2.Times by Three")
print (*3.square”)
print (*4.Power of")
choice
input ("\nEnter choice (1/2/3/4):*)
Now we can add the user input to get the number
the code will wark on:
muni = int (input (*\nEnter number: *))
‘Thiswillsave the user-entered number as the variable num
| Ble Edt Format Bun Options windows Help
From minimath import *
print(“select operation. \n")
rine(=1-Tanes by tro")
Feeetsa Ties by Thre)
inet" square")
printt"4.Power of")
choice = input("\nénter choice (1/2/3/4):
punt = intinput("\nEnter number: "))
(Create Your Own Modules eC
Finally, youcan now create arange of statements
to determine what to do with the number and
utilise the newiy created function definitions:
sum
Print (timestwo (num) )
Lf choice ==
elif choice == 12
Print (timesthree (num) }
elif choice == 43":
‘print (square (nut) )
elif choice == 44":
‘pun? = int (input (*Enter second number
print (power (num, mum2))
”
eu
print (“Invalid input*)
‘le Est Frat Groner Hey
Note that forthe ast valle options, the Power
Sui of choice, we've added a second variable, num2.
This pases asecond number trough te function defniton cle
power Save and execute the program osee kin ationPython in Focus:
Artificial Intelligence
Artificial Intelligence (Al) and Machine Learning (ML) are the new hot topics of the IT
iret en cea ee ulaeR ea Roe Reale Mace aCei naa] a apr cd ella n el ter re Ta)
lade heh de
Despite how close Al and ML are, there are distinct differences
between the two technologies. Alrefers tothe study of how to train a
‘computer to accomplice the things that humans can do significantly
better and Faster. Whereas, MLsthe ability For a computer to learn
ee eee usa
See ea rete ecu
Pc en eee.
Cee ty mee eects
Rear eer oy ee ceed
and, thanks to Python, that gap is getting closer every day.
Both Al and ML are hugely present in today’s technology. Where,
eee ester ey
pean a a ae eet et een
pees ater ear)
peer
Let's begin with the obvious use of Al and ML, the smartphone.
Set ee tee
»
ere
Olea ed
QKIb Ec Hw 4° |
Ve Ce ene,
Python File Manager
This File manager program displays FILEMAN.PY
Se et LS Copy the code below into a New > File and save it as FileMan.py
read a file, write to a file, append to. ‘Once executed it will display the program title, along with the
Lon rate current time and date and the available options.
of a directory'and much more. It’s
remarkably easy to edit and insert Amport: shuts |
Ca Re me Neols Ro iE econ foeeecee |
| Amport subprocess
def Read)
Datheinput (Enter the fle path to xead:") —]
‘le-open(oath,"=") |
printiaie. read) 4
Input (Breas Eater.) |
fie.closed J
dee writen
patheinpat("Enter the path of file to write or create:")
S£ o8.path.safile(path):
print('Rebuilding the existing Mie’)
else:
rint(‘Creating the new ite’)
textainput ("Enter text:")
‘Mlosopen(path,"w")
‘Sle.write(text)
oe aaa
patheinput("Enter the ile path")
text=input ("Enter the text to addi")
‘Mlesopen(path,"2")
Sle.write( \n'ttext)
dot detetor)
patheinput("Enter the path of file for deletion:")
£¢ o2.path.exista(path):
rint(‘File Found’)
‘8 renove(path)
EInt(‘File has been deleted’)
his part of the code imports the necessary modules.
BB the 0 and Subprocess modules deal withthe
the program.
ase:
withinthe Eint('Pile Does not exist’)
othe main
doe pinlist()
patirinput(’Enter the Directory path to display:")
artofthe code that checks to se what OS fovtlistesorted(os listdis(pat)
fs running. In Wind he CLS comman ad
sthe screen, whereasin Linux and macOS, the wideticien(sorttist):
command wipesthe screen. Fhe code tes oD
torun when being used in Linux or macOS, an *
error occurs, which then prompts ito run the Cle er
coma ‘peint nput(check existence of \nl.File \n2
Directory)
hese ae the options, from 1 to 12. Each executes Se tpn:
Bene appropriate Function when the relevant numbe pPatheinpet ("inter the fle pathi")
isentered be-pathistle(path)Af 0 path tania patn)—tzve
rint(‘File Found’)
PEine(File not found’)
Af fpmea:
pathainput(*Enter the directory path:”
fs path. dadi(path)
Lf os path isdir (path)enFalse:
Print (‘Directory Pound’)
[Print(‘Directory Not Found’)
dee Move()
‘athininput( ‘Enter the source path of file to move:')
Ie-int(input(/1 Rename \n2.Move \n'))
‘path2uinpat(‘Enter the destination path and fle name:’)
‘hutil nove(patht,path2)
print(File renamed’)
Af mrmed:
patharinput(‘Enter the path te move:')
shutl nove(path1,path2)
Print(‘File moved’)
ee copy
‘pathisinput ‘Enter the path of tho file to copy or ronane:')
path2ainput(‘Enter the path to copy to:’)
shutt copy path path2)
Print(‘File copied’)
dee Makedir(
‘patheinput("Enter the directory nase with path to make
\nog. CA\Welto\Wewdte \nihere Nowa i= now
aizectory:")
os.makedirs(path)
Print(‘Directory Created’)
dof Ronovedir()
pathainput(‘Enter the path of Directory:')
‘treedir=int (input(‘L Deleted Dizectory \n2.Delete
Directory Tree \n3.Exit \n!))
os endir(path)
Af troedixen
shut rmtree(path)
print( ‘Directory Deleted’)
Af treed:
exito,
det opensiie)
patheinput('Enter the path of program’)
try:
on startale(path)
excep
PEInE(File not found’)
white(rune=)
try:
of.systent cles’)
except Osteror:
os.systom(cls")
print(\\mspooosppobython 3 File Managerceccceeece\n!)
print(The current time and date is:',time.asctine())
[Print(\nChoose the option nuaber: \n’)
dec=int(input(""1.Read a fie
S.Append text to a fle
Python File Manager
Tove 3 218
8.copy a me
o.create a directory
a0.Delete a directory
11.Open a program
write
Sf doce:
aaa
Delete)
Dirlisto
check’)
move)
Sf doom:
copy)
Makedir)
Renovedte()
Sf doom
‘pense
exit)
runsint (input(/1.Return to ment\n2.Bxst \n"))
exit)
Imports
There ae three modules to importhere: Shut, OS and
Time, Te firsttwo deal with the operating system and File
‘management and manipulation; and the Time module simply
splays the current time and date,
Note how we've included a try and except black to checkif
the user isrunning the code on a Linux system or Windows.
\Windows uses CLS to clear the screen, while Linux uses clear
The try black should work well enough but it'sa point of
possible improvement depending on your own system.a a
EDS te he
BUCA CS-E Tua allae (aol re el maolel NUMBERGUESS.PY
Se i eek Copy the code and see if you can beat the computer within
Random'module, print and input, five guesses. It’s an interesting bit of code that can be quite
Pecan ei handy when you Implementing a combination of the Random
BNC a nee le .
and the'randomnamber range'tan (import random Hi
Cpe cca elcelon | guessestsed = 0 7
| Nano=input(‘Hello! What is your nane? °)
[number = random.candint(t, 30)
Print(‘Greetings, ‘+ Name +‘, 1m thinking of a
number between 1 and 30.’)
‘guess=int (input ‘Guess the nunber within 5 guesses...)
gues = guessosUsed + 1
Eint(‘Too low, try again’)
Af guess > number:
print (‘Too high, try again.’)
Af guess,
quessestsed = str(guessestsed)
Print('Woll done," + Name +‘! You gues
correctly in * + guessestsed +‘ guesses.’) | |
Af guess != number:
number = str(nunber)
Eint((Sorzy, out of guesses. The number I wa:
| thinking of i= + number)
ae ees
Beer ftew rare tere ae
some elements to the code that are worth pointing out. To begin
with, you need to import the Random module, asyou're using
andar numbers withinthe code
‘number=random.randint, 30)
it too high though orthe player wil co quessit
IF the player quesses too low ar too high they are given
‘appropriate output and asked to try again wile the numbe
(of quessesis less than Five. You can also increase the number of
{quesses from 5 by altering the while quessesUsed < 5: value,
my tele qused the coe ruberthnteyae gens
ibe player uns cut ass hate gue oe OD
delayed sta, ong wth revel the mbar the como.
wartngot Remember 300 doar he tes he
crib hapetig he gut ort renter
uses te payer canta hen ong with the arable ues,
ovat need toa ctansgeninthe pn
§
ci
BI
iP
a
i
vel edCode Improvements
Since this is such a simple script to apply to asituation, theres
plenty of raom to mess around with itand makeit more
interesting. Perhaps you cn include an option to take score, the
best out of three rounds. Maybe an elaborate way to congratulate
the player forgetting a hole in one’ correct. guess on ther First try
Moreover, the number guessing game code does offer some room
forimplementing nto your code na different manner. What
‘we mean by thsi, the code can be used to retrievea random
number between arange, which in tum can give you the start of a
‘character creation defined Function within an adventure game,
Imagine the star ofa text adventure written in Python, where
the player names their character. The next step isto oll the
virtual random dice to decide what that characters combat.
rating, strength, endurance and luck values are. These can then be.
carried Forward into the game under a set of variables that can be
reduced or increased depending onthe circumstances the player's
character ends up in
For example, as per the screenshot provided, you could use
something along the lines of
creo
‘Endurance = random randint(2, 15)
(CR = random.randint(1, 20)
lick = random. randint(1, 10)
Print (‘Your character's stats are as follows:\n")
Print (*Endurance:*, Endurance)
Print(*Combat Rating:", CR)
Print ('Luck:", Luck)
‘The player can then decide to elther stick with thei roll or try again
forthe hope of better values being picked. There's ample waysin
which to implement this code into abasic adventure game.cro aed
EDS te ee!
LUT ay) Lee- pe ea 8-1) ero}
Mee caelea tet a aleliehls
elements with any programming
language. It's what'separates
agood program from a great
Program, one that‘allows the user
ood le Tele ya Te tel
that Tato ;
pr er
More Input
‘hile an easy code to follow, Itcould be more interesting if you
prompt the user For more input. Perhaps you can provide ther
‘with adaition, subtraction, multiplication elements with their
numbers. Ifyou Feeling clever, see if you can pass the code
2 Tkinter window or even the Ticker window thats
on Page 16.
Furthermore, the core of
game, where + fightssomething 2
‘along with the enemy’, isreduced by a random nur
bbe mixed with the previous code from Page 32's Number
Guessing Game, where we defined the stats for the adventure
game's character
code can be used ina
ath,
fae eens
‘You can also introduce the Turtle module into the code and
perhaps set some defined rules fr drawing a shape, abject. or
Something based on a user inputted random value from arange
© =
really interesting,
eee] ed al
Ole eae ed
adventure
This can
cof numbers. takes a tle working out but the effects certainly
RNDNUMGEN.PY
ltmight 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 random import +
print *\mo>o>>oo>>Random Number Generatorcceceeccee\n")
nmbisint(input("Enter the start number: "))
mb2=int(input("Enter the last munber: "))
x = zandint (ambi, nmbz)
[Print(*\nfhe random number betwoon” nb, "and”;nmb2,"is:\n")
Eine x)
For example, the code could be edited to this:
‘from random import *
printi(\noos5p>20>Random Turtle Imageccceecccce\n")
imbinint(input "Enter the start number: ))
rmb2nint(input (“Enter the second number: "))
imnb3eint(input ("Enter tho third number: "))
mmbéeint(input (“Enter the fourth munber: "))
turtle. forward(anbi)
turtle. lett 90)
‘turtle. forvard(nmb2)
turtie.1eft(0)
turtle. forvard(amb3)
turtle.1eft 00)
‘turte.forvardianbs)
turtle. lett 00)
\Whilstt'slitle rough around the edges, you can easly makellt
more suitable,Random Number Generator/Password Generator
Random Password
Generator
We're always being told that our
Passwords aren't secure enough; well
here’s a solution for you to implement
into your own future programs. The
random password generator code
below will create a 12-letter string of
words (both cases) and numbers each
time it’s executed.
Secure Passwords.
‘There's plenty you can do to modify this code and imprave it
further. For one, you can increase the number of characters the
‘generated password displays and perhaps you can include special
characters too, such as signs and symbols. Then, you can output
the chosen password tafe, then securely compressit using the
previous random number generator asa file password and send it
toa user Fortheirnew password.
‘Aninteresting aspect to this codes the ability to introduce loop.
{and print ary numberof random passwords. Lets assume you have.
alistof 50 users fora company and you're in charge of generating
‘random password for them each month.
RNDPASSWORD.PY
Copy the code and run it; each time you'll get a random string
of characters that can easily be used as a secure password
which willbe very difficult For a password cracker to hack.
import string
import random
def randompassword():
charswstring.ascii _ uppercase + string.ascii _
lowercase + string digits
size @
return “'join(random.choice(chars) for x in
range(eize,20))
‘Print (randompassword())
‘Adding a loop to print a password fifty timesis extremely easy, for
example:
sport string
smport random
def randompassyord(:
charsestring.ascii _ uppercase + string.ascii _
lowercase + string digite
izes 4
return “.jein(random.choice(chars) for x in
ange(size,20))
mo
shite neso:
This will output fifty random passwords based onthe previous
random selection of characters4
: haa ee Ee ae) TXT2BIN.PY
this texttobihaly convertors < Naturally were using the Format function to convert the
actuallyquite good Fun.Ittalso B ) user's entered text string into its binary equivalent. If you
teat ea want to checkits accuracy, you can plug the binary into an
Roy ac eee
aa ae ‘toxtsinput("Enter text to convert to Binary: ")
eae)
Pa
peint(’ ‘join(formatiord(2), ‘b’) for x in text))
eluate a eet et tne
erry er ay
aL:
Sea eee |
oat] da
Bile Edit Format Run Options windows Help
print(">>>>>>>>>>Text to Binary Conver tor<<<<<<<<<<\n")
text=input(“Enter text to convert to Binary: ")
t( *.join(format(ord(x), "b*) for x in text)
Nm ed1000010 1101001 1101110 1100001 1110010
1111001
‘The text to binary corwertor does offer some room For
improvement and enhancement. There are many uses itcould be
Ublisedin a password or secret word script as pat ofan adventure
‘game oF just. a novel way to display someone's name,
\with regards to improvements, you could display the binary
conversion ina Pygame window, using the animated text options
From page 18. You could also ask the userif they wanted to have
‘another go, or even askif they wanted the binary output to be
saved toa fle.
\with regards to rendering the outputted binary conversion to
Pygame window, complete with rotating text, you can use:
import: pygame
ygame.init)
BACK = (0, 0, 0)
WRITE = (255, 255, 255)
BUIE = (0, 0, 258)
GREEN = (0, 255, 0)
RED = 255, 0, 0)
print /s>oosspoootext to Binary Convertoreccceeeccc\n")
conversionsinput(‘Enter text to convert to Binary: ")
size = (600, 00)
screen = pygane.display.set _node(size)
=
pygane.display.set _ caption("Binary Conversion”)
done = False
clock = pygane.tine.clock()
‘text _rotate_ degrees = 0
Binary=(° ‘Join(format(ordix), °b') for x
sn conversion))
wate not done:
for event in pygane.event. get:
Le event.type = pygame. QUIT:
‘done = True
‘screen. (WHITE)
font = pygame.font.sysFont('Calibri', 25, True, False)
text = font-render(Binary, True, BLACK)
Pygame.display.05p0)
clock. tick(60)
pygame.quit(
Print() ‘Join(format(ord(x), °b’) for x in conversion)
gubleatonscom 37ere AUER eci-cielate}
flreono exe eer orci
file browser that's presented in'a
graphical usef interface using the
BU ecim uilocolt) cot an -eeed Cole Colt Ke-]h)
Tire h eal Reels Fre Rua)
PS me te eel
ea Eee ed
4
>
ees
eee
Ove ad
FILEBROWSER.PY
‘Tkinteris the main module in use here but we're also using
idlelib, so you may need to pip install any extras if the
dependencies fail when you execute the code.
‘from tkinter import Te
from idlelib.treeWidget import Serolledcanvas,
FilefresItem, TroeNode
root = 70.
root title("File Browser”)
‘sc = Scrolledcanvas(root, bg="white”,
‘s¢-frane.pack(expand-1, fill="both’, side="left”)
Aton = FileTrecrten(os.gotowd())
node = TreeNode(ac.canvas, None, iten)
node.expand()
oot mainloop()‘Advanced Filing
‘When executed, the code wil display the current drectory’s
contents. I you want to see the contents of another directory you
‘anrun the code from a command tne within the chosen directory,
just remember to call the code From where i's located on your
system, as per the second screenshot. You can also double-= 0")
sys.exie@)
Af minutes < 0:
print ("Invalid value for minutes, should be >
sys.exit(l)
Af minutes
else:
‘unit _word =" minutes”
print (‘Sleeping for °
sleep (seconds)
print ("Wake up")
for 4 in range(S):
eint (chr(7)),
sleep)
except Keyboardinterrupt!
print (“Interrupted by user”)
syz.exit()
+ stefminutes) + unit _vord)
Wakey Wakey
E There's some good use of try and except blocks here, alongside
} some other useful loops that can help you get firmer
Understanding of how they workin Python. The code itself
can be used in a variety of ways a game where something
happens after a set amount of time or simply as ahandy
desktop alarm clock for your tea break.
Linux users, try making the alarm clock code into an alias, so
{you can una simple command to execute it. Then, why not
integrate auser input atthe beginning to ask the user For the
length oF time they want until the alarm goes of, rather than
having to include tin the command line.
Windows users, Python 3s the only version installed on your
system then you willneed to execute the code without adding
the 3to the end ofthe Python command. For example:
python Alazmclock.py 10
‘Again, you could easly incorporate ths into a Windows batch
fileand even eta schedule to activate the alarm at certain
times ofthe dayee)
er
rete
eer ape
ee ime
| Vertically Scrolling Text
Der axe
uf
e
I
5
AG
al
ss
0M
a
.@
Ole Pate ed
What's not to like about vertically EPICSCROLL.PY
So ed We've used the poem Cimmeria by Robert E. Howard for the
beginning of a game or introduction code's scrolling text, along with a dramatic black background
epee nee eee enna? and red text. We think you'll agree, it's quite epic.
Clg P Ce SUV ele
credits at the end of something} such
co:) air) Peele Loy ants list eee
i
po.inito
‘text _liet =
1 remember
The dark woods, masking slopes of sonbre hills;
‘The dusky streams that flowed without a sound,
And the lone winds that whispered down the passes.
Vista on vista marching, hills on hills,
Slope beyond slope, each dark with sullen trees,
our gaunt land lay! So when a man climbed up
A ragged peak and gazed, his shaded eyo
Slope beyond slope, each hooded like its’ brothers,
it was a gloomy land that seened to hold
All winds and clouds and dreams that shun the sun,
With bare boughs rattling in the lonesome winds,
And the dark woodlands brooding over all,
Not even lightened by the rare dim sun
Cinmeria, land of Darkness and deep Night.
twas so long ago and far aay
T have forgot the very name men called me.
The axe and flint-tipped spear are like a dream,
‘And hunts and wars are shadows, I recall
Only the stillness of that sombre land;
‘The dinness of the everlasting woods.
Cimmeria, land of Darkness and the Right,
eeey
Es
Deleted
Oh, soul of mine, born out of shadowed hills,
How many deaths shall serve to break at last
This heritage which wraps me in the grey
Apparel of ghosts? I search my heart and find
Cimmeria, land of Darkness and the Might!
eh a
Perr
eee yee
wr gplse cn’)
ete et Td
or}class Credits:
dof __ init__(self, screen_rect, 1st):
selelet = let
self.size = 16
self.color = (255,0,0)
selé_butf _centery
self_buff~ lines = 50
self-delay = 0
self.make_ surfaces()
self.crect-height/2 + 5
dof make _toxt(solf message)
font = pg.font.SysFont(Arial’, self.size)
text = font render (eessage,True,self.color)
rect = text get _rect{center = (self erect,
centers, self.eroct.centery + self. buff _centery) )
def make _surtaces(se1é)
self.taxt =
for i, Line in enunerate(self.1st):
1H selé.make _ text(line)
Ly + itself bute lines
‘self.text.appenda)
def update(sels):
Af pg.tine.get _ ticks()-self.timer > self delay:
self.tiner = pg.tine.get _ticke()
for text, rect in self.taxt:
recty -= 1
def render(selé, surf):
for text, rect in self.toxt:
surf blit(text, rect)
screen = py.display.set _mode((200,600))
screen _rect = screan.get _ rect ()
clock = pg-tine.clock()
running=True
cred = Credits(ecreen rect, text _ list)
for event in pg.event.get()
if event.type == QUIT:
screen.fi11((0,0,0))
cxed.update()
cred. render(screen)
pg.display.update()
clock tick(60)
C Vertically Scrolling Text
ALong Time Ago.
‘The obvious main point of enhancementisthe actual text
itself Replace itwith a list of credits, or an equally epic opening
storyline to your Python game, and twill certainly hitthe
‘mark with whoever plays it Don’ forget to change the screen
resolution if needed; we're currently running itat 800 x 600,et ea
a ees eae
oy
ia
©
B
0
BkIb Be Bw 4° |
eee ene,
Python Dig
BUN Eyl ele Ra le eel)
on the desktop of most operating
systems but it's always handy to have
one on top of the currently open
Wintel CMereitete Maat easel
a Python digitaliclock thatcan be a
4 feu ue) desktop widget foryou.
Been
en
Olea ad
>
Peyote)
DIGCLOCK.PY
This sa 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 te
def tick(timel=")
# got the current time from the PC
timed = time.strEtime("4H:44:tS")
Sf time? '= timel:
time = time?
clock.config(text=time2)
clock.after(200, tick)
clock.
eek
‘tkabel(root, font=('arial, 20, "bold’),
bg='green’)
clock pack{Gll="both’, expand=1)
tick)
oot aninloop()Tick Tock
This isa piece of cade we've used many times inthe past to keep
track of time while working on multiple monitors and with just a
‘Quick olance to where we've placedit onthe screen
‘The Tkinter box can be moved around without affecting the time,
maximised or closed by the user at wil. We haven't given the
Tkinter clock window a title, so you can add to that easily enough
bysnipping the code from other examples inthis book.
‘Another area of improvementsto include this code when,
‘Windows or Linuxstarts soit automaticaly pops up on the
desktop See als, iF youre able to improve its Functionality by
including afferent time zones: Rome, Pars, Landon, New York,
Moscow and son.
‘Another example, expanding on the original code, could bea:
>spp>op awesome Adventurecccecc *)
rint(nane, "the barbarian, sword in hand and leoking
for adventure!”)
time.sleepd)
Print(‘However, evil is lurking nearby....")
‘imo. leep()
Peint("A pair of bulbous eyes regards the hero...")
time.sleep(2)
PEint(‘Will", name, "prevail, and win great fortune...”)
time.sle6p()
pEint(‘Or die by the hands of great evil...2")
‘ine. sleep()
eine *\n" #3)
print (‘Only time will tell...”)
‘ine. leep(2)
peine(.")
time.aleep(2)
Eine(*..")
time.sleepQ)
eine")
‘ine. leep()
eine")
time. aleep(S)
PEint(*\n" #200)
peint(\”’ You find yourself at a small inn. There's
Little gold in your purse but your sword is sharp,
With you are three other customers,
A ragged looking man, and a pair of dangerous
looking guards."”)
dor start)
print(*\n — )
PFint(‘Do you approach the...”)
print (*\n")
Beint(*1. Ragged looking man”)
print("2, Dangerous looking guards")
end-getond(endlist)if ond
ragged)
elif ond = "2":
guards()
a:
def ragged):
‘Print("\n" * 200)
rint(’"'You walk up to the ragged looking man and
greet him.
Ho smiles a toothless grin and, with a strange
accent, says.
“Buy me a cup of wine, and
great treasure...”")
time.sleep@)
Vil tell you of
dof guards():
rint("\n” *200)
Print(’’'You walk up to the dangerous looking guards
and grect them.
The guards look up from their drinks and
snarl at you.
Swat do you want, barbarian?” One guard reaches
for the hilt of his sword...)
time.eleep@2)
Adventure Time
‘This, asyou cansee,s just the beginning of the adventure and
takes up afar Few tines of code, When you expand it, and weave
the story along, youll Find that you can repeat certain instances |
such as a chance meeting with an enemy orthe lke.
We've created each ofthe two encounters asa defined set
‘of Functions along witha list of possible choices under the
‘emit list, and cmd variable, of which isalso a defined Function,
Expanding on thisis quit easy, just map out each encounter and
‘choice and create a defined Function around it. Providing the user
doesn't enter quit into the adventure, they can keep playing.
‘There's also roomin the adventure fora set of variables designed
Far combat, luck, health, endurance and even an inventory or
‘amount of gold earned. Each successful combat situation can
Feduce the main character's health but increase thei combat skis,
‘or endurance. Pls, they could loot the body and gain gold or earn
‘gold through quests.
Finally, how about introducing the Random module. This wl
‘enable you ta include an element of chance nthe game. For
‘example, in combat, when you stike an enemy you willdoa
random amount of damage as will they. You could even work out
the maths behind improving the chance ofabetter hit based on
your or your opponent's combat ski, current health, strength and,
‘endurance. You could create a game of dice inthe inn, to see if you
win or lose gol (again, improve the chances of winning by working
‘out your luck Factr into the equation)
Needless to say, your text adventure can grow exponentially
{and prove tobe a work of wonder. Good luck, and have fun with
your adventure.
(Text Adventure Script
elif ond == "help":
print(*\ninter your choices as detailed in
the game.")
Print(‘or enter ‘quit’ to leave the game”)
return gotond(cndlist)
elif ead == "quit"
print (*\n-
time.sieep(2)
print (‘Sadly you return to your homeland without,
oer crA
ae ee
ey
er
Ole E ate ad
Sol Valassis tel cola tlm ala
one of thesnippets of code we're
ie olla aos
scrolling'ticker. Whilst we've covered
various forms of scrolling text
previously, the ticker is something
eect coker sient acon
ode) a A 4
nae
Ticker Time
ve obviousimprovernents to the Ticker code liein
the speed of the text and what the text will display
wise you can change the backaround colour of
window, the Font and the Font colour, along
with the geometry ofthe Tknter window i you want to.
‘Yet another interesting element that could be
introduced s one ofthe many textto Speech modules
availabe for Python 3. You could pipinstall one, import
thenas the ticker displays the text, the text to speech
Function will read out the variable atthe same time, since
the entice texts stored in the variable labeled s
Thettcker example cn be used For systern warnings,
perhaps something that wil dsplay across your work or
home network detaling the shutting down of a server
cover the weekend for maintenance; or even just to
inform everyone a to what's happening. We're sure
you willcome up with some good uses fori.
TICKER.PY
We're using Tkinter here along with the Time module to
determine the speed the text is displayed across the window.
import time
import tkinter as tk
root = te7k()
canvas = tk.canvas(root, root title("Ticker Code”),
hheight=80, width=600, bge"yellow”)
ccanvas.pack()
font = (‘courier’, 48, ‘bold’)
foxt blocks insert here...
a1 = “this ie a scrolling ticker example. As you
ccan seo, it’s quite long but can be a lot longer if
22 = “We can even extend the length of the ticker
message by including more variables..."
the code,
‘s4 = “Don't forget to concatenate thom all before the
4 pad front and end of text with spaces
# concatenate if all
Stal + a2 + ad + ah +05
‘text = canvas.croate_toxt(x, y, anchor~'nw', text=s,
horizontal movenent only
4 the pixel value depends on dx, font and length of text
pixels = 9000,
for p in range(pixels)
# move text object by increments dx, dy
# dx -> right to lest
canvas.nove(text, dx, dy)
canvas.update)
# shorter delay ~-> faster movement.
time. sLeep(0.005)
fprint(k) # test, helps with pixel value
oot mainloop()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 code to
follow and as such can also be expanded well too.
An")
dof addtx, ¥):
return x+y
dof subtracts, vit
return x - y
dof multiply(x, y):
return x * y
dof divides, yi:
return /¥
print("Select operation.\n")
print ("3.Maltiply”)
print (“4.Divide”)
‘choice = imput(*\ntnter choice (1/2/3/4):")
‘num = int(input(\nEnter first: munbe
‘mun2 = int (input(Enter second number:
»
”
Af choice == W:
‘print (uuml,"4")mum2,"=", ad(mam2,mun2))
elif choice == 2:
Print(numl,"-";mun2;"=", subtract (num mun2))
elif choice == 9:
‘print(num,"*",nun2,’=", multiply (mumi,mun2})
elif choice ==":
‘print num,"/";mum2;"=", divide (mami mum2))
else:
‘peint('Invalid input”)
ti 6 toma bm tte doe Ie
Improved Calculations
‘The obvious contender for improvement here is using the
Create Your Own Modules route and extracting the Function
definitions as a module. You can then cll the module and Focus
fon the body ofthe code,
‘The other area of improvementis code itself. where there's
Justa single shot at making a calculation, you could encase itn
awhile loop, so once a values presented the user is sent back
tothe main menu. Perhaps, improvement to the Invalid Input
sections worth looking into as wellPEI UrUE Ice Sueno Ic
into Python. It canbe extremely
complex, displaying graphics, the
number of guesses left in the secret
re lceME-altre Molla elm Cle) Rete
picked at random and countless
other eléments.It can also-be quite
Buco aac
vs
tule erates
ea Eee ed
CI
>.
2 alo
vette ed
HANGMAN.PY
We've made a Hangman game board (the gallows) out of
characters that can be displayed in the IDLE Shell, along with
a huge bank of words to randomly choose from
import random
board = [”"
ppp ppp plangmancceececkclass Hangman:
def __ init _ _(self,word):
selEword = word
self.nissed letters = (]
self.guessed_letters = ()
def guoss{sel£,ietter):
Af letter in selfvord and letter not in self.
‘guessed _letters
self.guessed _ letters append(letter)
elif letter not in self.word and letter not in
self.missed letters:
self.nissed _ letters.append(letter)
else:
return False
return True
def hangman _ over(sel#):
return self.hangman _won() or (len(self.missed _
letters) = 6)
‘def hangman _won(sel#):
Af *_" not dn self.hide _word0:
return True
return False
def hide _word(eel®):
a
for letter in self.word:
Lf letter not in self.guessed letters:
rin d=
else:
tn += letter
return rtn
def print _gane_ status(selt)
print (Goard{ien(self.missed _letters)})
print (Word: ‘+ selfhide word())
print (‘Letters Missed: *,)
for letter in self.missed_ letters:
print (letter,)
print 0)
print (‘Letters Guessed:
for letter in self.quessed letters:
print (letter,)
print 0
def rand _word0:
‘bank = “ability about above absolute accessible
accommodation accounting beautiful bookstore
calculator clever engaged engineer enough
hhandsone refrigerator opposite socks interested,
stravberry backgammon anniversary confused
dangerous entertainnent exhausted impossible
overweight tomperature vacation scissors
accommodation appointment decrease development
‘earthquake envizonnent brand environment necessary
Hangman Game Script
C}
luggage responsible ambassador circunstance
‘congratulate frequent’.split()
‘return bank[random.randint(0,len(bank))]
of main():
‘game = Hangman(rand _word()
while not gane.hangean over(:
‘game.print _ game _ status()
user _input = input("\nznter a Lette
‘game guess(user input)
gameprint _ game _ status()
4£ game.hangnan won):
Print (‘\aCongratulations! You have won!
else:
Print (\nSorry, you have lost.’)
print ("The word wae "+ gane.word)
Print ("\nGoodbye!\n')
Since this s the last example in our Python code repository, we
thought we'd go out witha bang and feature the hangman
gallows being drawn with each incorrect quess of the word.
Don't worry fit looks misaligned in the text here, this is merely
due to the differences between using the Python IDLE editor
and pasting the code into a word processor (which Formats
things differently)
“There's plenty you can do to improve, enhance and expand on
what we've presented here. You can include a routine that
returns an errorif the user enters a number or character. You
caninclude extra points for someone who guesses the entire
word in one go rather than one letter ata time and you could
perhaps adé Chopin's Funeral March should you lose the game;
Dor something celebratory if you win
>=
Consider replacing the bank of words too, They're found under
the banklist, and could easly be swapped out for something
‘more difficult: IFyou download waw.cithub.com/dwsvenglish
words you can find atext document with over 466,000 words.
Perhaps you could swap the wordsin the bank to instead read
the contents ofthe text ile:
of rand _word():
‘with open("/hone/pi/Downloads/words.txt", "rt”) as
bank readlines()
return bank[randon.randint(0,1en(bank))]
oer FIowes
CdUnderstandin
Linux
Linuxis a remarkably versatile and powerful operating
eu et eRe eel Maa aces EL)
engineering world, in science, space exploration,
eee CE ees ea cum
Resear erence ac
Peete eu eet
eee re
PO eee ee eet ae Ny
TT Chkag eee aa
Raspberry Pi, for example, uses a Linux-based OS and, as
such, makes for an excellent coding platform. Regardless
of whether you're using a Pi, like us, or a Linux Mint or
Pe een eee
Python learning. Master Linux, master Python, and start
CTT Rel meer Rite tom
CoeED) trending in
What is Linux?
Sess eM ne ect neSnau rs ee UR eeu erica cds
what exactly is Linux? Where did it come from and what does it do? In a world where
A YiaNeCone- Tare MuarleO MMe Er eel nM cco) MeL coke ole alamo e
Reuter ted eae un enue a tae lay
Linux isa surprisingly powerful, Fast, secure and capable operating system. It's used as the OS of choice for the Raspberry Pi, in
tthe Form of Raspbian OS, as well as in some of the most unlikely places.
Despite only enjoying a 1.96% share (according to netmarketshare,
com) ofthe total desktop operating systern market, Linuxhas
dedicated following of enthusiasts, users and contributors. It was
created in 1991 by University of Helsink student, Linus Torvalds,
who had become frustrated with the imitations and licensing of the
popular educational system Minix, a miniature version ofthe Unix
‘operating system, in use at the time.
Unix itself was released in the early "70s, asa multi-tasking, modular-
designed operating system originally developed for programmers
\who needed a stable platform to code on. However, its performance,
power and portability meant thatit soon became the system of
choice for companies and universities where high-end computing
tasks were needed,
‘The bootloader is the software that initalises and boots up
your computer. Ieloads up the various modules the OS uses to
begin to access the hardware in the system. You can modify a
bootloader to load more than one OSinstalledon the system.
Daemons are background services that startas the operating
systems booting. These can enable printing, sound,
networking and so on. They run unobtrusively rather than
‘under the direct control of the user, often wating tobe
activated by an event or condition.
‘The Desktop Environment, or DE, i the main Graphical User
Interface (GUI that uses interact with. t's the desktop, that
includes internet browsers, productivity, games and whatever
program or app you're using. There are countless DES
‘available. Raspbian uses PIXEL
“Torvalds needed a system that could mirror Unix’ performance and
Features, without the licensing cost, Thus was born Linux the
Unlike operating system which used freely available cade from
the GNU project. Tis enabled users around the world to utilise the
ower ofthe Unix-like system, completely Free of charge, an ethos,
that stil holds today: Linuxis ree to download, install and use.
Linux is much tke any other operating system, such as Windows or
‘macOSin that it manages the computer hardware, provides an
interface for the user to access that hardware and comes with
programs for productivity, communications, gaming, science,
‘education and more. Linux can be broken up into a number of
significant elements:
‘This is a module within Linux that provides 3 graphical output
toyour monitor. t's referred to as the Xserver or simply just
X. is an application that manages one or more graphical
cisplays and one or more input devices (Keyboard, mouse, etc)
connected to the computer.
“The kernel is the core of the system and the single element
that is actully called Linux. The Linux kernel manages the
computer processor, memory, storage and any peripherals you
have attached to your computer. It provides the basic services
For all other parts of the OS.
\With Linux being an open source, free operating system, it
also makes use ofthe tens of thousands of freely available
applications. The lkes of LibreOffice, GIMP and Python are just
the tip of the icebera.whatisinoe CE
SHELL
‘The Linux shellis a command:ine interface environment that 8
Linux user can use to enter commands to the OS that directly
affect it, Within the shell you can add new users, reboot the
system, create and delete files and Folders, and much more.
BASH (Bourne Again Shel)
isthe most popular shell,
used in Linux, although
more are available. The
shellis algo known asthe
Terminal, andit’s where
youre going to work
from through this section
of the book
2 tte
inst
(inus tikes
penguins)
Linus Torvalds, the creator ofthe
Linux kernel.
Linux is used throughout the world, ina numberof basic and
quite unique uses. While it may look radically different From one
environment to the next, the actual Linux kernel, can be Found
in modern smart TVs, in-car entertainment systerns and GPS,
supercomputers, lo devices and the Raspberry Pi. t'sused by
NASA, both in the command centre and on-board the ISS, Linux
servers power the backbone of the internet, along with most of the
‘websites you visit daly Android utilises components of the Linux
kemel, as do set top boxes, games consoles and even your fridge,
Freezer, oven and washing machin.
Linuxisatjusta free to use operating system. it's stable
powerful and fast, easily customised and requires very litle
maintenance. However, i’ mare than just performance stats,
Linux means freedom from the walled garden approach oF other
operating systems.’ lvly community oF ike-minded individuals
(> espbion onthe Raspbery the wiho want more fromther computers without the shackles of price
Linux lstribution of choice. or conformity. Linux means choc
(TLEETITE Oy
aa tee
‘ADesktop Environment can
bbeas complex or as simple as
the user desires. «
peerUnderstanding Linux
Using the Filesystem
GETTING 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 s the shell, or Terminal
older, however in Linux t's always called a directory These are and Downloads and Scrateh in Blue. You may also see other items
placed inside each other using a “/” character. So when you see, fepending on how much you have used yout Raspberry Pl, The
rome/piit means the pi directory inside the home directory, olour code is worth knowing: dtectories are bive while most Files
Enter: clear and press return to clean the screen, Nowenter: pwd, _afe white, As you go on you's other colours: executable Files
This stands For Print
king Directory and displays /home/p (programs) are bright green, archived files are red and so on. Blue
and white are the two you need to know to get stat
Ez \When you lag into your Raspberry Pi, you don! EED Now you're going to move from the pi directory into
start at the base ofthe hard drive, known asthe he Documents directory Enter: eDocument 8
‘root '(also known asthe topmost director). Instead you begin Note the capital "D. Linux is case sensitive, which means you have
inside your user directory, which is named by default and is toenter the exact name including correct capitalisation. The cd
tselFin a directory called ‘home’. Directories arencicated by the’ command stands for change directory. Now enter: pwa again to
fhome/pi tells you that inthe cory called view the directory path. I will display /home/pi/ Documents. E
he next "/” says that inside torycalled 18 toview thefi he Documents directo1uget back up to th
mand “ed... In Linux
fe, also knawn as the par
ectory? By using
dots meansthe
ctory. Incidentally, 2
Pictures directory inside
single dot." is used For the same directory. You never use "ed your Documents directory. You can switch to this directory using
switch to the same diectory bu knowing because some ea Docu Pictures use ca tomove back up tw
commands need you to specify the current directory parent directories
STEP 1 STEP 3
STEP 2 5Understanding Linux
Listing and Moving Files
LOOKING AT FILES
Operating systems are built on files and Folders, or directories if you prefer. While you're used to vis
operating systems keep other files out of sight. In Raspbian, you have access to ev
BED We've already looked at "Is", which ists the files in
the working directory, but you are more likely to
ommand tke “ist
he bit after the command (the
known as the argument
,ehaviour ofthe command,
his isan option that modifies the
BED The "I" argument lists files and directories inlong
Format. Each file and directory isnaw on a single
ine, and before each ie isa lot of text. First youll see lots of letters
‘dashes, ike ‘drwar-xr-x’ Don't worry about these for now; they
35'permissions' and we'll
ur own Files, most
File inthe system,
After the permission letters come a single number.
Thisis the numberof Files in the item. Fits 3 file
then il
each directory contains two hidden Files; one witha single dot ()
e 1, butt’ a directory itl be atleast 2, This is because
and one with two dots (.) Diectories containing Files of other
irectories willhave a higher umber.
ofthe le, a
Next youl see the word “pi lsted twice on each
ine. This efersto the user rather than the name of
ter (your default usernames “pr. The irs isthe owner
isthe group. Typically these will bth be
ie -1/
that belong to