ares Python
Coding
@ Advanced guides
and tutorials for
programming C++
and Python
OVER
45)
SECRETS &
@ Next level fixes
and secrets get to j
the heart of the : tPF a a
Python language {
| ns
Mica Everything you need to take
of code with games, H
graphics anivation [iA Python programming
and much more skills to the next levelFREE Software! Great Games! Essential Hardwa
ak,
192ateere
Re. IES INSIDE!
ome
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 is limited reader offer running from Ist November 2023 to Tet March
2024. Terme and conditions apply and can be found at www.pelpublicationscomTRICKS
& 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.
A user that will make the
absolute most of their
Over the page
Our je
Journey continues,
a F
coding and ultimately aa on will be with you
Python coding itself. An inf 'Y stage to advice
achievement you can earn by inform and ultimately
simply enabling us to tnspire you to y
exclusively help and teach you 90 Further.
the abilities we have gained over
our decades of experience.ence
iow)
Crue
Lu 44
Gea uly uke
Gemeente
Seton
“Basic GUI File Browser cm
Mouse Controlled Turtle emi akect
Nakata
Playing Music
BIZ
pees
ued
i] ry V5 oa rx o
a ia Ae - a ae i
- e } a a) aya 1g, an)TEMITTE CS
Mig ag
> / aN if
“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.”G
Weelactiang at the
cose
ane
= False
ae a
i Coe’ -adUsing
Modules
Nan ea ieee
Seneca ae ay
Sere cage een e neu rr
variables. You can bind and reference
Ete eeu
and create even more spectacular
ec
Cee say
Menem ue Tey
cree aero d
eee teu
used to Fashion Fantastic code with
Pee RSet eclat)
Bsn ieeeED) virsiies)
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.
PEPPER Launch Python 3andenter: import calendar to
«allup the module andits inherent Functions, Once
it loaded into memory, start by entering:
Python 353 shal
le Got Shel pebug gptons wow wep
Peg 252 Geel, Sp 2 #8, STS)
Neopyrigh®; Straaits" or “License for more infornation
Pera
ee mira
Sarees)
Seren
‘You can see that the days of September 2019 are
clsplayed ina wall calendar Fashion, Naturally you
‘an change the 2019, 9 part ofthe seconde to any year and
month you want, a birthday for example (1973, 6). The first line
configures TextCalendar to start its weeks on @ Sunday, you can opt
for Monday if you prefer.
pyoon 53 Sal sex
TRF
i ea “em or re een
e BNSF Lae
FUE? 1TH
eeepc me
‘There are numerous Functions within the Calendar
‘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 years:
print (leaps)
‘The resultis 29, starting from 1904 onward,
‘Ele Eat shell Debug Options Widow Help
‘Python 3-5-3 (default, Sep 27 2018, 37:25:39)
{ee ¢.3:0 20370836) on Tan
Type “Copyright”, "eredsts” or “License()” for nore infornation
2S saport calendar
35> Andpescalendar:Leapdays(2900, 2030)
3 prantCieaps)
PEPTPD You could even fashion that particular exampl
_ piece of working, user interactive Python code:‘You can also create a program that wil display all
the days, weeks and months within glven year:
import calendar
yearnint (input ("Enter the year to dieplay: *)
int (calendar.preal (year))
|We're sure you'll agree that’s quite 3 handy bit oF code to have
tohand,
ey
Interestingly we can also list the number of daysin a
AD oscnby using asinpe-for loop:
import calend
cal-calendar.TextCalendar (calendar. SUNDAY)
for { in cal. itermonthdays (2019, 6):
print (4)
ssss>55>Backup completeccecceceee”)ED) sina
Using the Math Module
One of the most used modules you will come across is the Math module. As we've
mentioned previously in this book, mathematics is the backbone of programming and
there's an incredible number of uses the Math module can have in your code.
E=MC
‘The Math module provides access to a plethora of mathematical functions, from simply displaying the value of Pi, to helping
you create complex 3D shapes.
“The Math module i built-in to Python 3;s0 there's
no need toPIP install it As with the other modules
Cia
present, you can import the module's Function by simply entering
import’ math into the Shell or as part of your code in the Editor.
‘As you will doubt be aware by now, f you know
the narne of the individual functions within the
module you can specifically import them. For instance, the Floor and
Ceil functions round down and up afloat:
gion 5-43 CGefaule, Oek 19 F0H8, T3RT=T)
{ace 4.8.1) on Linwe
Type “copyrighe”, “eredsts” or “Licensed for wore infomation.
Imposting the Math module wil give you access to
the module's code. From there, you can call up any
‘of the avallable Functions within Math by using math, followed by
the name of the Function in question. For example, enter:
Siar
math.ein(2)
‘This displays the sine of 2.
{6Cc 4.951} on line
ype “cepyrighe™. “credits” or “License()™ for more information,
Python 3-4-2 (aefoult, Oct 18 2018, 1
(eee 4.8.1} on Line
Type “copyright”, "eredits™ or
Sees Setaath injort Floor. ceil
S>> Hertt-2)
D> eattca.2y
“License(D" for more information.
‘The Math module can also be renamed asyou
importit, as with the other modules on offer within
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:‘Although it's not common practise, its possible to
lmpott Functions from a module and rename them.
In this example, we're importing Floor from Math and renaming it
tof. although where lengthy code sin use, this process can quickly
become confusing:
from math import floor as £
£2)
Se emee te
Using the Math Module Cl
For further accuracy, when it comes to numbers the
‘exp and expmt Functions can be used to compute
precise values
from math import exp, expat
exp(ie-5) - 1 # value accurate to 11 place
expml (1e-5) # result accurate to full precision
‘Ble E6t_ shel Debug Options wows Help
eysion 34.3 Catal. Ook 192004, 123-11)
{ce 4.9.1] on Line
ype “copyrigne’s “credit” or “Iicense()" for more information.
DE" Seraathingort expe expe
‘TeonopSoscateastoe-os|
Seieipanes)
S5sipomsonvonseea
Impoxting al the Functions ofthe Math Module can
bbe done by entering:
Siar
from math import *
‘hile certainly handy, thisis often frowned upon by the developer
‘community 3 takes up unnecessary resources and isn’t an
efficent way of coding, However, Fit works for you then go ahead.
Python 34.2 (aetault Oct 19 2014, 13:3)
Gee 4.9!) on Lim
tor more information.
vovaeniedoesertaze
set
interestingly some funcons win the Math
Sua module are more accurate, or tobe more precise are
designed to return amore accurate value, than others. For example:
ea
willreturn the value of 0999999999, whereas:
returns the value oF 1.0,
he
Get 19 20Te, T9s3TT
F “License()* for more information.
aap
Soo" fsam(tete te te
This level of accuracy is really quite impressive, but
its diameter):
Amport math
print (math.e)
print (math.pi)
Python 3-47 (oetault, Oct 19 2014,
(ace 9.9.1) on line
Foe Sspyr she Meresites or tices" for
Ss a
iateanesssenies
Pel
“The weath of mathematical funcionsavatable
Suzrils through the Math module is vast and covers.
everythin from factors to infinity, powers to eigonomety and
angular conversion to constants. Look up https://docs.python.org/3/
Ubranyfmath mit fora ist of lable Math module unconED) vino
Random Module
BIN eee Caen RoR eee elect A Rel eae
Prec CTANUMN Mle UHM MMM AN Lele| (eee eK (ote cece Me KXAN OAL LI}
or letters. However, it’s not exactly random but it will suffice for most needs.
RANDOM NUMBERS
‘There are numerous Functions within the Random module, which when applied can create some interesting and very useful
Python programs.
ESTISED Justas with other modules you need to import FETED However, the Random module isn’t used exclusively
random before you can use any ofthe functions For numbers, You can use it to select an entry froma
‘we're going to look t inthis tutorial Let's begin by simply printing alist from random, and the lst can contain anything:
random number from 1 to 5: a
‘Ths will display one of the names of our adventurers at random,
“which is a great adeition toa text adventure game.
a
ee
Parmar eal
es
Sen he
sion biseune oe
mar
BEE ou canextend the previous example somewhat by
having random. choice) select from alist of mixed
variables, For instance:
EERE 01 abigger set oF numbers, including floating
point values, you can extend the range by using the
multiplication sign:
Amport random
Print (random. random() +100)
Ul cisplaya floating point number between O and 100, to the tune
cof around fifteen decimal points.
ee PS a women etnBRED | terestinaly, you can also use a function within the
Random module to shuffle the items inthe list thus
‘adding alittle more randomness into the equation:
‘random. shuffle (1st)
print (1st)
‘This way, you can keep shuffing thelist before displaying a random
item From it.
es
Using shuffle,you can create an entirely random lst
of numbers. For example, within a given range:
isd
import random
Aste [{1] for tin vange(20)]
‘random. shuffle (1st)
print (1st)
Keep shuffling the list and you can have a different selection of
items From 0 to 20 every time,
import random
for i in range (10):
print (random.randrange (0, 200, 7))
Results will vary but you get the generalidea as to how it works.
You can also select arandom number frama given
range in steps, using the start, stop, step loop:
FETED Letsuse an example piece of code which flips a
virtual coin ten thousand times and countshow
‘many times it wil land on heads or tals
Amport random
output={"Heads”:0,
coinsList (output. keys ())
wrasier 0}
for i in range(10000}
‘output [random. choice (coin) )
print ("Heade:", output ("Heads")
print ("faile:", output [*Taile"])
Here's an interesting piece of code, Using atext
Say
file containing 466 thousand words, you can pluck
a user generated number of words From the file (text file Found at:
-wwwwgithub.com/dwyVenglishswords):
import random
print ("ssssssssssRandom Word Pindercceceeeeee")
print (*\nUsing a 466K Englich word text file I can
pick any words at random. \n")
wgeint (input (*\nllow many vos
”»
Sar SETTER TERETE
je shall 1 choose?
"ease SLE
words = [w.rstrip() for w in words]
print ("=
for w in random.sample(words, wae):
print (w)
print ("~ =)ED) virsnoies)
Tkinter Module
ANA CHRA NMS R Vo Meole (Air MeNKCo MUNA n eS SC ee
Python is capable of so much more. The Tkinter module enables the programmer to set
up a Graphical User Interface to interact with the user, and it’s surprisingly powerful too.
GETTING GUI
‘Tkinter is easy to use but there's a lot more you can do with it. Let’s start by seeing how it works and getting some code into it.
Before long you will discover just how powerful this module really is.
Sse)
‘The ideal approach to add mainloop()intothe
EPID Teinter is usually uit into Python 3. However iFi's
available when you enter: import tkinter, then
youneed to pip install tkinter from the command prompt.
‘We can start to import modules differently than before, to save on.
code to control the Tkinter event oop, but well
{get to that soon, You've just created a Tkinter widget and there are
several more we can play around with:
typing and by importing all their contents:
ben.pack()
ben["text*]="Hello everyone!"
‘The first line Focuses on the newly created window. Clik back into
the Shell and continue the other lines.
1 jonas =e
PPIIED snot recommended to import everything froma
module using the asterisk butt won't do any harm
normally. Let's begin by creating abasic GUI window, enter:
wind
This creates asmall, basic window. There's not much else to do at
this point but click the X in the comer to close the window.
BETTER You can combine the above into a New File:
import tkinter as ek
yreraazstet
ete at ig arn a
‘ineenelpyRanehpDoare jon Coaareaceielpy BAZ) ~ 6 ™
(Git Fama in ten rds
tte everyeat™
Fn go ct nyTEED save and execute the code fromstep $ and a
‘window appears with ‘Hello everyone!’ inside. you
lick the Hello everyone! button, the Shell will output the text ‘You
just clicked met t's simple but shows you what can be achieved
with a Few tines of code,
FETTER Youcan also display both text and images within
a Tkinter window. However, only GIF, PGM or PPM
formats are supported. Sofind an image and convert it before using
the code. Here's an example using the BOM Publishing logo:
from thinter import +
gif")
WL = Dabel (root, root .title("BDM Publications”),
image=1ogo) .pack (side="right")
content = “"Y Prom its humble beginnings in 2004,
the BIM brand quickly grew from a single publication
produced by a team of just two to one of the biggest
names in global bockazine publishing, for two simple
weasone. Our passion and commitment to deliver the
very best product each and every volune. While
‘the company has grom with a portfolio of over 250
publications delivered by our international staff,
the foundation that it hae been built upon remaine
the same, which is why we believe BOM isn’t just
the first choice it’s the only choice for the smart
2 = Label (root,
just ity=LErT,
pad = 10,
text content) .pack (si¢
‘root .mainloop ()
The previous codels
‘quite weighty, mostly
‘due to the content
variable holding a part
‘of BOM's About page
from the company
website, Youcan
‘obviously change the
content, the oot ttle
and the image to suit
your needs
acme [pi /Dowloada/BOM lego.
C Tkinter Module ¢ 0 ma
PEP) You can create radio buttons too. Try:
from tkinter import *
root = T()
vy = mevar()
Label (root, root. titie(*options"), text="*"Choose:
a preferred language:"**,
justify = LEFT, pad
Radiobutton root ,
text<"Python",
padx = 20,
variable-v,
valueet) .pack (anchor)
Radiobutton root ,
textencre",
mainloop()
PEPID You can also create check boxes, with buttons and
‘output to the Shel
fom tkinter import *
root = T()
def var_evates(
print (Warrior: $d,\nMage: $4" ¥ (varl.get(),
var2.get ()))
Label (root, root.titie(*Adventure Gane"),
texte" >s>ssss>ss¥our adventure rolecccceccee<") «
grid(rows0, sticky=N)
vari = IntVar()
Checkbutton (root, text="Warricr*, variablesvart)
grid(rowet, sticky=W)
var2 = IntVar()
Checkbutton (root, text="Mage”, variablesvar2) .
grid(row-2, sticky-W)
Button(roct, text=’Quit’, commanderoct .destroy) «
grid(row-3, sticky-W, pady=4)
Button (root, text="Show’, command=var_states)
grid(row=3, sticky=#, pady=4)
mainleop()
‘The code from Step 9 introduced some new
geometry elements into Tkinter. Note the
sticky=N, E and W arguments, These describe the locations ofthe
check boxes and buttons (North, East, South and West). The row
argument places them on separate rows, Have a play around and
see what you getZz Using Modules )
Pygame Module
We've had a brief look at the Pygame module already but there's a lot more to it that
needs exploring. Pygame was developed to help Python programmers create either
graphical or text-based games.
PYGAMING
Pygame isn’t an inherent module to Python but those using the Raspberry Pi will already have it installed. Everyone else will
need to use: pip install pygame from the command prompt.
Naturally you need to load up the Pygame modules
into memory before you're able to utilise them.
‘Once that’s done Pygame requires the user to nitialise it prior to
‘any ofthe functions being used:
import pygame
ygame. init ()
Let's create a simple game ready window, and give
itatitle:
gamewindow-pygane. display.set_node ( (800,600) )
pygane.dieplay.set_caption(*adventure Gane")
You can see that after the First line i entered, you need to click back
into the IDLE Shell to continue entering code; also, you can change
the tite ofthe window to anything you like,
Sadly you cn close the ney rested Pygame
Suz? window without closing the Python IDLE Shell,
which tery practical For thiseason, you ned to workin the
editor (New > File) and create a True/False while (oop;
import pygame
from pygame. locals import *
pygane. init ()
ganewindowspygame .display.set_mode ((800,600))
pygane. display.set_caption ("Adventure Gane")
running=True
white running:
for event in pygame
AE event .cype=
running-False
Pygame.quit ()
le Edt Format Bun dptions Windows Heb
port pyasme
25S pypime locals soport *
O
runninget-ve
‘or tuent 9 pragme event. getERED the Pyaame windowstil wort =="
lose don't worry, it's ust a
discrepancy between the IDLE (whichis written
with Tkinter) and the Pygame module. I you
run your code via the command ne, It closes
perfectly well
FPED Youre going to sift the code around abit now,
running the main Pygame code within a while loop;
itemakes it neater and easier to Follow. We've downloaded a graphic
touse and we need to set some parameters for pygame:
import pygame
Pygame. init ()
runningeTrue
while running:
gamewindow=pygame .di splay. set_mode ((800,600))
pygame.display.set_caption(*Adventure Gane”)
black= (0,0,0)
whites (255,255,255)
( Pygame Module Cll
ingepygane . image .1oad (*/home/pi /Downloads/
sprite png”)
def sprite (x,y)
ganewindow.bLit (img, (st-y))
x= (800*0.45)
y=(6000.8)
gamewindow. £412 (white)
sprite(x.y)
pygame-display-update ()
for event in pygame.event .get()
if event .type==pygame.QUIT
running-False
FETED cts auickly go through the code changes. We've
defined two colours, black and white together
with their respective RGB colour values, Next we've loaded the
To pene
le pyganertocals import *
ene. insti)
gmenindowepygane display set node((800.600))
Breone sisplay.setccoption(-Aaventore cane")
Bisek=(0.0-0).
sntten( 258,235,255)
‘nespyeane. image, Load“ /hone/p3/Oornlosds/sprite} eng")
et spritecayz
‘omenindon-b1AtCing. 6.99?
downloaded image called spritet.png and allocated it to the
variable img; and also defined a sprite Function and the Blt Function
will allow us to eventually move the image.
ganeindow.F.11(4hite)
Speitecuy)
Preane: display update)
for event in pygame.event.getO:
SF event yper=@urr
romingeraiee
Preseesquito)
Peetez= Using Modules
Now we can change the code around again, this
time containing a movement option within the
loop, and adding the variables needed to move the sprite
‘around the screen:
import pygame
rom pygane.locals import +
pygane init ()
ganewindow=pygane.display.set_mode (800,600)
pygane.dieplay.set_caption (*Adventure Gane")
lack=(0,0,0)
whites (255,255,255)
4ing-pygame . image. 1oad (* home /pi /Downloads /spritel.
png")
def sprite (x,y)
ganewindow.biit (img, (x,y)
x= (800*0.45),
‘y= (600*0.8)
xchange=0
Sia}
imgepesd=0
if event type == pygame. KEYDOWN:
if event -key==pygame.K LEFT:
Lf event. key==pygane.K LEFT or event
keysepygame-K_RIGHT:
xchange=0
x = xchange
ganewindow. £411 (white)
sprite(x,y)
pygame.display.update ()
pygame.quit ()
Copy the cade down and using the left and rightarrow keys on the keyboard you can move your spite across the bottom of
the screen, Now, itlooks like you have the makings of a classic arcade 2D scroller inthe works.( Pygame Modules ell
BEER Youcan now implement afew adaltions and utlise
some previous tutorial code. The new elements are
the Subprocess module, of which one Function allows us to launch
second Python script from within another; and we're going to create a
New ile called pygametxt py:
import pygane
import time
import subprocess
pygane.init ()
screen = pygame.display.set_mode( (800, 250))
‘lock = pygame.time.clock()
font = pygene.font Font (None, 25)
pygame.time.set_timer (pygame .USEREVENT, 200)
ef text_generator (text) +
tmp ="
for letter in text:
tmp 4 letter
Af letter
yield tmp
clase DynanicText (cbject)
def _init (self, font, text, pos,
autoreset2600 or pos{1)
yas -ya
AE pos [2] >+800 or posto] <0
gul-update ()
time. sleep(.025)
Remove the code you enteredin Step 2 and insert
the code from Step Sinits place; again, between the
canvas.create_oval (5,5,60,60, £ill="red")
alll
{and the gui .main1oop () lines. Save the code and Run itas normal
IF you've entered the code correctly, then you wil see the red bal
bounce off the edges ofthe window untl you close the pragram.
Beara The bouncing animation .
takes place within the
While Teue loop. First, we have the values
‘of xa and xy before the loop, both of 5 and
10, The pos=canvas.coords (bal2) line
takes the value of the bal's location in the
window, When it reaches the limits of the
window, 800 or 600, it will make the values
negative; moving the ball around the seen.
Pygame, however, isa much better module at
producing higherend animations. Begin by creating
‘aNew File and entering:
STEP8
import pygame
from random inport randrange
MAX_STARS = 250
STAR_SPEED = 2
def init_stars (screen)
“*" Create the starfield “**
global stars
stars = (]
for i in range (MAX_sTARS)
# A star ie represented ae
format: [£,¥]
star = [randrange (0, screen
randrange (0, screen
stars.append (star)
a list with this
get_wiath() - 2),
get height () - 1)7
ef move_and_drax_stars (screen)
“ew Move and draw the stare “**
global stars
for star in stare
star(1] += STAR_SPEED
Sf star[1] >= acreen.get_height ()
starta] = 0
star(0] = randrange(0, 638)
acreen.set_at (star, (255, 255,255))
Basic Animation
|
PETE Now add the following
ae
Similat ion’
ses
main()
Jf maint) +
pygame. init ()
screen = pygane.display.set_node ((640,480))
pygame.dieplay. set_caption(*starfield
clock = pygane.time.Clock ()
init_stars (screen)
while True:
4 Lock the framerate at 50 FPS
clock. tick (50)
# Handie events
for event in pygame.event .get ()
Af event type == pygame-QUIT:
return
screen-£411 ((0,0,0))
ove_and_draw_stars (screen)
Pygame.display.£1ip()
maint)
yanme: nse)
[evoen =" pyyanesisplay. set. mode (640, 480))
pyanee. ds 5play-cateaption("erarf sels si tation")
Esch yoane tana chockt)
snst_stars( screen)
faoeke eLek(S0}
# wands events
for event in pyoame.cvent.g()
Proame. rt
Save and Run the code. You willagree that the
simulated starfield code looks quite impressive
Imagine this asthe beginning of some game code, or even the start
to.a presentation? Using a combination of Pygame and Tkinter, your
Python animations will look fantastic.ED) vino
Create Your Own Modules
Large programs can be much easier to manage if you break them up into smaller parts
and import the parts you need as modules. Learning to build your own modules also
makes it easier to understand how they work.
BUILDING MODULES
Modules are Python files, containing code, that you save using a .py extension. These are then imported into Python using the
now familiar import command.
STEERED Leis startby creating asetofbasicmathematics RBI) Now you're going to take the Function definitions
functions. Mutiny a number by two, three and ‘ut ofthe program and into a separate file
square or raise arumber to an exponent (power). Createa New Fle Highligh the function definitions and choose it» Cut. Choose Fle
in the IDLE and enter: > New File and use Edit> Paste in the new window. You now have
two separate flles, one withthe function definitions, the other with
def timestwo(x) + the Function calls,
return x # 2
get tineseneeeta: [mess
return x #3, ot timethreegs
IF you nowrtry and execute the basic_math py code
‘gain, the error Name€rror: name ‘timestwo' is
not defined’ willbe displayed. Thisis due to the code no longer
having access to the Function definitions.
Filet staan yan atau path", ine 2, in ale
fr TR: ot sti
sores
perenree
seen
ie nahn
pornos
so the basic_math.py window is
eeeCreate Your Own Modules ¢ 0 ma
BERD 22ckto the basic_math.py window: atthe top ofthe [ESEESESBM Finaly, you can now create a range of f statements
code enter:
to determine what to do with the number and
Utlse the newly created function definitions:
from minimath import *
Af choice == °1!
‘This willimport the Function definitions asa module, Press FS to ae eo
save and execute the program to see tin action.
elif choice == 12":
print (timesthree (num) )
elif choice == 13":
print (square (mum2) )
elif choice == 14":
puna = int (input ("Enter second number: "))
print (power (num, nun2))
else:
print (“Invalid input)
[= Eat Frm Bon Sloms xndows wep
BR cs cononactocontvmiraae
print ("Select operation. \n")
Print (*1-Timee by two")
Drint (*2.Times by Three")
print ("3 Square")
print ("4.Power of")
choice = input (*\nEnter choice (1/2/3/4)
OSSramec“atis irout->
FEI vec cnssovcvsrnoutcseubennce
EDD oscars:
uml = int (input (*\nnter number: *))
‘This will save the user-entered number asthe variable nur.
Note that forthe last available options, the Power
of choice, we've added a second variable, aum2
This passes a second number through the function definition called
Bile Edt Format Bun Options Windows Help power. Save and execute the program to see it inaction.
Tron minimath inport *
i
Square")
Power of")
choice = input("\nEnter choice (1/2/3/4)
rmt © sntcénputcmwsenter rumbert =>)Aenean AN meleUicy
Artificial Intelligence
Artificial Intelligence (Al) and Machine Learning (ML) are the new hot topics of the IT
industry. Al is fast becoming the working science fiction that it has been portrayed as in
Serene a aeons
Despite how close Al and ML are, there are distinct differences
between the two technologies. refers to the study of how te train a
‘computer to accomplice the things that humans can do significantly
better and Faster. Whereas, ML i the ability for a computer to learn
From its experiences, so that the outcome and performance will,
eventually become more accurate and accomplished.
De cee Rete eee Trey
Seneca ee cetaceans
Deer ae Te
poe
Cera ee ern ed
APPLICATIONS
Both Al and ML are hugely present in today's technology. Where,
just afew years ago, most of us associated Al withthe rise of
Peete ge te ee)
pete ne Liter cet)
Snorer
eee eee oe es
‘These devices have infiltrated most of our modern world, with
Pe ee cer eee
6 billion by the end of 2020, t's litle surprise to discover that Al and
eee its
DE eet ea ny
‘smartphone, the coding behind these devices has been developed
ers eet ae ee rl
ee eee ee eee
numbers called are pushed to the top of the ls, i-app and in-game
advertising is moulded around our browser and search preferences,
‘as wells other apps we've installed inthe past. And even our
Rema renee etre Ea eee area
eo ene
IGITAL ASSISTANTS
Dee eee ee eer
Al and ML programming, Sir, Cortana, Alexa and Google Assistant
are all coded using Python, and are designed to listen, learn and
eee etn ena)
surprisingly simple, thanks to the many libraries and customisation
Briers ren tere ieee rir ete
For intelligent coders, cutting down on the development time in
Cee ee eo ea)
‘complex algorithms, these developers can devote significant time to
Cee Caer het ore
Se eee ee
Eee ene ne tee eas .
ee ott ete ea as
ene et et
eer etre ae eee
ee eer meee eet
available music appsto select what tis we wanted. Allthe time,
the l code isbeing trained to listen more intent, while the ML
is learning from the Alresults so thats acuracys improved For
tani tesPython in Focu:
BEYOND THE SMARTPHONE
D y
te ee Es ed a J
have you entered a search string into Google, suchas car parts Fora Mkt e
Ford Escort and, when you've opened Facebook, you suddenly Find a group wt
Pier a a Ee E
ete neo Tema
Bee ee ee ne ae
suggested completions for sentences you ae typing. Fyou frequently sign
Bie trea ea caer at erg
the ML side ofthe equation to autofllthe remainder ofthe words For you. All
the time, the ML i earning while the Als telling what to improve on.
Fee ee ee
the popular press For some time. Throughout 2019, Fadal recognition systems
‘on both smartphones and CCTV Footage have improved dramatically.
ee oe ee ee
Gur a ere ed eed
Pee eee ee eee RS
Pee
Tesla's work on selfcrving cars means they are getting loser to being the
orm, and i's Python along with its controlling Al and ML work that's, excuse
Peer te ct riod
Cre Veter ee
designed to implement Aland ML In the background, yout usually Find
ee ort cea)
overall programin which the Aland Ml. are working,
Pee ar aes
eee eae
character recognition, handwriting recognition, image
processing, helping people with vistal and hearing
eee
ee ecu
pharmaceutical and drug improvements and
en hes
ability to travel. I's not all about two Al bots
Rete tei!
THE FUTURE
io) AN)
Pe ad
iller robots and self-aware
Eee eri)
pee eerie
emcee
Se ea Une d
possible Future humans can create
eee ag
Sunt
Cee ee
Peery
eee eee)
Cette cor
OR orun ow
DSPs eaneee el)
yey
eee
AC fei
Seek Ti
ae eS
See eh
\ Fa
Ja ee
lat mre)
Ie
eat Ones
ee
ae ele
R- FRG ce
tu Tol Teta be ey
aE cela)
Cre ress
Socal Te
IZ Vih aoe S.
loxatek tal Es
Jee ye
nie De Ro
an vee
eka cad
alo 6a
“19,Repository
MeN EN Sa csi
for you to freely use in your own programs.
There's plenty in here to help you create a
Pe ed re Ce
Pe todo
We've got code for making backups of your files
BC es etc
Deuces eet ey
code, animation code, graphics code, text
See ene euke eis cers
Pee Eten Mca tee uk al
some of the newer, and extended, concepts of
the code to help you better understand what's
Po eRe eee he
eres
BU Ur Cae tars Rta
inany other Python book. So use it, take it apart,
Feed eee ers
reer
ea)7
ie
A
r
i
5
c
in
H
M
in
C
ct
flare oe
aN,
Toke ad
Oye
fis gl) hae #
This file manager program displays
a list of options that allow you to
read a file, write to a file, append to:
afile, delete a file, list the Contents
OE Kelle acol eluent ad
REC RSet ele U eRe
Us Dole e Om elehaon
the code for each
he code within the
fe returns tothe main
art ofthe code that checks to see what OS.
he CLS comman
s the screen, whereasin Linux and macOS, the
lear command wipesthe screen. Ith
"0 run CLS when being used in Linux or mi
terror occurs, which then prompts to run te
command instead
These are the options, from 1 to 12. Each executes
He appropriate Function when the relevant number
Python File Manager
FILEMAN.PY
Copy the code below into a New > File and save it as FileMan.py.
(Once executed it wll display the program title, along with the
current time and date and the available options.
| import shutat
sport tine
| Amport subprocess
ot Road()
patheinput(Enter the fle path to reads")
‘Mie=open(path,"e”)
print(ite.read() J
npat('Press Enter...) t
‘le.close)
det weitey:
path=input(‘Enter the path of fle to write or exeate:")
Lf os:path.ishle(path)
Print('Rebuilding the existing file’)
print(‘Creating the new file’)
eoxtminput (Enter text:")
‘Ble-open(path,"¥")
‘le write(text)
det ada)
patheinput(‘Enter the file path:*)
toxteinput ("Enter the text to add”)
‘sle-open(path, "2"
sie.write("
det vateted
patheinpat(‘Enter the path of file for deletion:”)
Lf os:path.oxists(path):
rine(‘Psle Found’)
8 renove(path)
PFint(‘File has been deleted’)
else:
PFint('File Does not exist’)
det Dirlistd:
patheinput(Enter the Directory path to display:”)
sortlistesorted(os.Listair(path))
so
wasie(icien(sortaiet)
print(eortlist{s]+"\n)
ot chock)
‘Eprint input(‘check existence of \nl.File \n2,
Dizectory\n’))
AE Speed:
patheinput("Enter the fle path:")
os-path isfile(path)(_ Python File Manager
S£ o8.path.istie(path) true: S.tist files in a directory
print(Pile Found’) G.check fle existence
Print(‘File not found’) B.copy a me
sf Spaz: S.create a directory
patheinput("Enter the directory path:") 20.Delete a directory
fos.path.tediz(path) 22.0pen a program
Af os path-iedir(path)=-raiee: reese
print(‘Directory Found’)
else: mo
Print(‘Directory Not Found’) | decent:
Resa)
dee mover) (4 docan
pathisinput(‘Enter the source path of file to move:’) -==mriteQ)
smr=int (input (‘Rename \n2.Nove \n’) Lf docees:
Sf met: aaa
PAULQUinput( ‘Eater the destination path and fle name:") if deo==
‘hutl.move(pathipath2) deteteo
rint(‘File renanod’) (Ae dooms
sf mr=e2: birtisto
[path2-input (Enter the path to move:') (Af dee:
shutil.move (patht,path2) check’)
PEint(File moved’) © Af dacme
Move
aot copy0 (Af dooms:
pathisinput(Enter the path of the fle to copy or rename’) Copy()
pathZminput (‘Eater the path to copy to:") | 4 doce:
shuti2.copy (path path2) eo)
Eint(‘File copied’) | 4 deca:
Renovedir)
dee Maxeaix(: © Ae decm=n:
‘pathsimput("Enter the directory name with path to make Openfile()
\neg. CA\setio\\Wewdis \nithere Newdix is new © Af docmen2:
directory:") exit
‘os.nakedirs(path) | runednt(input ("Return to menu\n2.Bxst \n")
print(‘Directory Created’) (Ae rune
exit)
doe Removedix()
‘pathsinput(‘Enter the path of Directory:’)
troodirsint input('1 Deleted Directory \n2.Delete
Directory ree \n3.Exit \n'))
fos.zmdir(path)
Af troedixen2
shutil zmtroe path)
print(‘Directory Deleted’)
exit
do¢ opension
Datirinput( ter the path of program’)
ey
on startmetpatn) i
‘except :
PEint(‘File not found’) :
a Imports :
- wile ‘There are three modules to import here: Shutil, OS and :
=r Time. The isttwo deal wth te operating system and fle
eee management and manipulation and the ime module simply
fee <éspays the currentime and date
peine(\possopoorython 3 File Magerccceceecce\)
Se Cae ea eae eT inheiom oa Note how we've included try and except blockto checkit
ese (ctaoson] [opciones the users running the cde on aLinuxsystem or Windows
Seonintisnpst "1 Read a Be Windows uses CLSto clear the screen, while Linux uses dear
amcite to a Sle ‘The tr block should work well enough butts point of
S.append text to a file
possible improvement depending on your own system,
‘pelete a fileer ee eee
a
Cc)
b
ae
aor
Delta
This is.a simple little piece of code
but it makes good use of the
Random ‘module, print and input,
anda While loop. The number of
Fel eccocy ea DeL eg ated ce
Urea arate (ol aL ume e(ee-1A)
eee solieley
NUMBERGUESS.PY
Copy the code and see if you can beat the computer within
Five guesses. It’s an interesting bit of code that can be quite
handy when your implementing a combination of the Random
module alongside a while loop.
J smport randon = IT
| guessestsed =
| Nanecinput(Hollo! What is your namo? ")
| number = random randine(@, 0)
| prine(‘Grestings, "+ Kane + *, Vm thinking of a
Af guese < nunber:
PEint(‘Too low, try again.’) |
Af guoss > number:
PEint("Too high, try again’)
correctly in * + guessesUsed + * guesses.’)
=
|
Print(’Well done, "+ Name + ‘! You guessed |
|
YW
PEIne( Sorry, out of guesses, The number T vas)
thinking of is * + number) |
param, there are
fe that are worth pointing out. Tobegin
he Random module, as you're using
thin the code
random number
This section ofthe code creates the variables For the numb
of guesses used, along with the name ofthe player, and also
setsup the random number between 1
wider range of random number selection, then it
‘numbersrandomrandint(1, 30) end value of 3;
high though othe player will never be able to quest.
IF the player guesses too low or too high, they are given the
appropriate output and asked totry agai, while the numbe
(oF quessesis es than five, You canals increase the number of
‘uesses from 5 byaltering the while quessesUsed < 5: value
the player guessed the correct number then theyare givena
EAI ‘well done’ output, along with how many guesses they used up,
the player runs out af quesses, then the gare over output is
clsplayed instead, along with revealing the number the computer
was thinking of. Remember, if you do alter the values of the
random number chosen by the computer, or the number of
he player can take, then along withthe variable values,
need to amend the intructions given in the print
staternents atthe start of the code,‘Code Improvements.
Since this is such a simple sri to apply to astuation, there's
plenty of roam to mess around with itand make more
interesting, Pethaps you can include an option to take score, the
best out of three rounds. Maybe an elaborate way to congratulate
the player For getting a ‘hole in one’ correct quess on their Fis try.
} Moreover, the number guessing game code does offer some room
Forimplementing into your code ina different manner. What
we mean by thsi, the code can be used to retrieve random
number between a range, which in turn can give you the start of
character creation defined Function within an adventure game,
Imagine the start of a text adventure written in Python, where
the player names their character. The next step isto roll the
virtual random dice to decide what that character's combat
rating, strength, endurance and luck values are. These can then be
‘awied forward into the game under ast of variables that can be
reduced or increased depending on the circumstances the player's,
character ends up.
Number Guessing Game
For example, as per the screenshot provided, you could use
something along the lines of:
Endurance=0|
cro
nek=0
Endurance = random.randint(t, 15)
(oR » random.randint(t, 20)
sek = random-randine(1, 20)
Print("Your character's stats are as follove!\n")
Print("Endurance:”, Endurance)
Print(*Combat Rating:", CR)
Print("tuck:", Luck)
‘The player can then decide to elther stick with their rollor try again
forthe hope of better values being picked. There's ample ways in
wiih to implement this code into a basic adventure game.
oanUser input and the ability to
manipulate that input are important,
urea ae er TL)
language. It's what'separates
Breccia tions
Preemie titccs
odie let Dae le) Kel
frida cie renee
eee eed
ta
More Input
While an easy code to follow, could be more interesting Ifyou
[prompt the user for more input. Perhaps you can provide them
with adeition, subtraction, multiplication elements with their
‘numbers. you'r Feeling clever, see i you can pass the code
through a Tkinter window ar even the Ticker window that's
available on Page 16.
Furthermore, the core ofthe code can be usedin a text adventure
‘game, where the character fights something and their healt,
‘along with the enemy's isreduced by arandom number. This can
be mixed withthe previous code from Page 32's Number
Guessing Game, where we defined the stats forthe adventure
‘game's character.
You can also introduce the Turtle module into the code and
perhaps set some defined rules For drawing a shape, objector
something based on a user inputted random value from a range
‘of numbers. takes alittle working out but the effects certainly
really interesting,
RNDNUMGEN.PY
It might 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
print (*\sp>s5>952>Random Number Generator>>>>>>>>>Text to Binary Conver tor<<<