0 ratings0% found this document useful (0 votes) 100 views82 pagesPython Coding Tricks and Tips - 16th Edition - November 2023
Python_Coding_Tricks_and_Tips_-_16th_Edition_-_November_2023
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
@ Advanced guides
and tutorials for
programming C++
and Python
@ Next level fixes
and secrets get to
the heart of the
Python language
Moca Everything you need to take
Teoh aia elma Meleeyere line
and much more skills to the next levelILEUS
& 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.
fiche tate our an ne page
absolute most of their and ae ath eontinues,
coding and ultimately at every op, © with you
Python coding itself. An OY Stage to advice
achievement you can earn by taform and ultimately
simply enabling us to taspire you to
exclusively help and teach you 90 further.
the abilities we have gained over
our decades of experience.Ey
32
34
35
Ey
38
cy
cr
gn
Pec
Saeco oi
Ug
Mouse Controlled Turtle ST
en ured Ey
Beer hc
Ceram ie kes tae
Oren}
Module J
Ree
ema mecca
SO erence
EOC UCU Re eatim
erg
NEES ast
\
= —“) Pesy aa es
"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.”i aa) ee:
arte RT Dat
ata
wo a es Corea. |Using
im \UlerelUltass
A CEE ate aes
source file that contains the necessary
code for classes, Functions and global
Re CoRR U CEC
Merete ene
Put kee eur teeta cs
eee Ce
INN Te ta TTT
your use of these modules to add a
ecu ier seed
Then read on and learn how they can be
Used to Fashion fantastic code with
Plea RE eek ele LaTe)
BreeseE) vinatoaies
Calendar Module
Beyond the Time module, the Calendar module can produce some interesting results
Pataca Len ol meee Mel ACTEM e Neeley
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.
SR oars schon sondern port catendarto There aremurerous futons within he Calender
Calp the morte ndtsinterent Fncions Once module that may eo eet to youwhen
it’s loaded into memory, start by entering: forming your own code, For example, you can display the number of
lap years between te pecieas
‘The result is 29, starting from 1904 onward,
FAL I sett mnohent
ee “ [Ble Edt Shel Debug Options window Help
‘3 (default, sep 27 2018, 17:25:38)
‘zoresie) on Tine
ght, "eredits” or "Hicense()" for nore information
eS 235° sort calendar
wise 2 Hecehendar teapsays(200, 2030)
Yovciseettiedasctsetente 20190 REE voucos een fon tpi
Sue displayed in a wall calendar fashion. Naturally you cue? apiece of working, user interactive Python code:
canchangethe 20139 part ofthe secondlineo ay yer and
‘month you want, a birthday for example (1973, 6). The First line
configures TextCalenda to start its weeks on 2 Sunday, you can opt
For Monday iFyou prefer.
bn 3 ShaYou can also create a program that will display all
the days, weeks and months within a given year:
Interestingly we can also list the number of daysina
‘month by using a simple; or loop:
Siar
daysinmonth py -/home/pi/Documents/daysinmor
[Ble Edt Farmat Bun gptions window Help
‘Calzcalendar TextCalendar (calendar SUNDAY)
Sor ge s"cal seermonthaays(2019, 6)?
prine(a)
‘oucanseethat atthe oust the code produced
Sud ‘some zeros. This is due to the starting day of the |
week, Sunday in this case, plus overlapping days from the previous.
ont Mesrng the courting oF he cael tar on Sarda It
June 2019 and will total 30, as the output correctly displays.
[est Shh Cen ine arabe Sb
Calendar Module (79
You're also able to print the individual months, or
days of the week:
FETED The Calendar module also allows us towrite the
Functions in HTML, so that you can displayit on a
website, Let's start by creating anew file:
This code will create an HTML file called cal, open it with a browser
and it displays the calendar for January 2019.
‘Of course, you can modify thatto display a given
year as a web page calendar:
‘This code asks the user Fora year and then creates the necessary
‘webpage. Remember to change your file destination,z= Using Modules
OS Module
The OS module allows you to interact directly with the built-in commands found in your
Olea eee Ce RNY Teka LOSI Aeon a TL
Pe aN Uo eR Uk tte eR TI AoA AMET a LaTe RT e Oo
INTO THE SYSTEM
One of the primary Features of the OS module is the al
y to list, move, create, delete and otherwise interact with files
stored on the system, makingit the perfect module For backup code,
FEPTIEDD You can startthe 0S module with some simple BSED The windows outputs different as that's the
Functions to see howit interacts with the operating curent working directory of Python, as determined
system environment that Python s running on. Fyou're using Linux by the system: as you might suspect, the os getcwd Function is
cor the Raspberry i, try this: asking Python to retrieve the Current Working Directory, Linux users
will see something along the same lines asthe Raspberry Pi, aswill,
import os macOS users
home=os.getewa ()
print (home)
PEPTSED) The returned result From printing the variable home [VFM vet another interesting element to the OS module,
isthe current user's home folder on the system. Isis ability to launch programs that are installed
inour example thats home/pi; twill be different depending on _inthe host system. For instance, if you wanted to launch the
the user name you lag in as and the operating system you use. ‘Chromium browser from within a Python program you can use
For example, Windows 10 will output: C\Program Files (x86)\ the command:
Python36-32C 0S Module Cl
FETED the ossystem( function's what allows interaction
with external programs you can even call up
previous Python programs using this method. You will obviously
‘eed know the Full path and program filename for itto work
successfully, However, you can use the Following:
import os
os-system(*start chrome "https://wmw.youtube.com/
feed/masic*')
PEPER 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 os
ce-eystem(‘chromiun-browser "hetp://
banpublications.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=(‘chromium-browser “htt
com/*")
be(‘chromium-browser "htty
os.system(a + b)
+/ Poampublications.
(Juve google.co-uk")
The ably to morblte rectors or folders
STEPS you prefer, is one of the OS module's best features.
For example, to create anew directory you can use
import os
(os mkdir (“NEW")
‘This creates @ new directory within the Current Working Directory,
named according to the objectin the mkdir Function,
You can also rename any directories you've created
byentering:
import os
os.rename (*NEW", "OLD")
To delete ther:
import os
os.rndir(*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
Amport os, shutil, time
root_sre_dir = r'/home/pi/Documents"
root_dst_dir = ‘/home/pi/backup/" + time.asctime()
for ere_dix, dirs, files in oa.walk(root_sre air):
dst_dir = sxe_dir.replace(root_src_dir, root_
dst_dir, 1)
Af not og.path.exiete (det_dir):
os makedirs (dst_dir)
for file_ in files
- os.path.join(sre dir, file,
dst_file = os.path.join (dst_dir, file,
if Os.path.exists (dat_file):
08. remove (dst_fi1e)
shut il.copy(sre_file, dst_dir)
Print ("ssssssssssBackup completecccececece")via)
Using the Math Module
One of the most used modules you will come across is the Math module. As we've
Deon se MND Col MMC ea Td rere Cee eee ELT)
eee Mere mo tLe Eleanore) (Keeani T Rot 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.
tohelping
“The Math module is builtin to Python 3;so there's Asyou will no doubt be aware by now, if you know
noneed to PP instal t.As with the other modules the name of the individual functions within the
present, you can import the module's Function by simply entering madule you can speccaly import them. For instance, the Floor and
into the Shell, or as part of your code in the Editor. _Ceil Functions round down and up afloat:
reten 34. (Seal, 0ce 120 TRV
[ee 4.9.4) on tinue
tip, SonyraghesSeregie” ot scene)" for more infomation.
3> anne.
Ineatngtebthmadievilgesevaceto ESE he ihn coatobe ana
sue the module's code. From there, you can call up any cua? import it, as with the other modules on offer within
‘of the available functions within Math by using math, followed by Python. This often saves time, but don't forget to make a comment
the name of the Function in question. For example, enter: to show someone else looking at your code what you've done:
math.sin(2)
This displays the sine of 2.
ren Sz eet eee BOT, TTT
igpe Scopyrighe™. “credits” or “License()" for more snfornation.
Hype “copyrighe’= “credits” or “Iicense()” for more infomation. | 268, SPU AER": "S
See east S33 alteranct 29.95)
S33 mathesincs) B‘though’ notconmon act, possbleto
SuePS import Functions from a module and rename them.
In this example, we're importing Floor from Math and renaming it
to although where lengthy code isin use, this process can quickly
become confusing:
from math import floor as £
EEE porting al the Functions ofthe Math Module can
bbe done by entering:
from math import +
while certainly handy, ths is often frowned upon by the developer
community asittakes up unnecessary resources and isn't an
efficent way of coding, However, iFt works For you then go ahead.
(( Using the Math Module G4
For further accra hen comes tonumbersthe
Sues ‘exp and expm1 functions can be used to compute
precise vales
from math Amport exp, expat
capiie-s) 1 value accurate to 12 places
5) # result accurate to full precision
1 “Iicense()* for nore information.
FETED This evel of accuracyis eally quite impressive, but
Auite niche for the most part. Probably the two
most used Functions are e and Pi, where eis the numerical constant
‘equal to 2.71828 (where the circumference ofa circle is divided by
its diameter}
import math
print (mathe)
F (aetaule, et 1 Oe, TST
pe sarecé)
veratetsetassertane
sot
FETED terestinaly, some functions within the Math
module are more accurate, orto be more precise are
designed to return a more accurate value, than others. For example:
LET
will return the value of 0 999999999, Whereas:
feum((-1, 2,
returns the value of 1.0,
TET
2 (aefoule, Get 19 2014, 13
tion Lime
yrighe, ergdits” or “License()” for nore information
0
mn
Tipe Seopytagne’. creases” or “License” for more information
Sa geet math
Pnkiateseasno0s
Sistasstaasios
ea
FEET) The wealth of mathematical functions available
through the Math module is vast and covers.
‘everything from Factors toinfnity,powersto trigonometry and
angular conversion to constants. Look up https:/docs.python.ora/3/
Ubrary/math.htmit for als of available Math module Functions.
|Evins
Random Module
SO eur Crue Cc een CN la Tey
programming lifetime; as the name suggests, it’s designed to create random numbers
ela eee ma Nn eau Celet clan VReIaNe olny ode] a UTI OU ae A Kolm Cos a LLem
RANDOM NUMBERS
There are numerous Functions within the Random module, which when applied can create some interesting and very useful
Python programs.
Just as with other modules you need to import
random before you can use any ofthe Functions
we're going to look t inthis tutorial Let's begin by simply printing @
random number from 1 to 5:
ED bn curexample
the number four
was returned. However, enter
the print function afew 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 utlse in
their code.
PEPER or bigger set of numbers, including floating
point values, you can extend the range by using the
‘multipication sign:
\will display a Floating point number between 0 and 100, tothe tune
(of around Fifteen decimal points.
eee tiowever, the Random module isn’t used exclusively
for numbers. You can use it to select an entry froma
lst From random, and thelist can contain anything:
‘This will display one ofthe names of our adventurers at random,
which is great addition toa text adventure game.
| as ee gt are
sr :
Youcan extend the previous example somewhat by
EUS having random.choice() select from a list of mixed
variables. Forinstance:Random Module eG 7
Interestingly, you can also use a function within the
‘adding alittle more randomness into the equation
random. shuffle(1st)
print (ist)
‘This way, you can keep shuffling thelist beFore displaying arandom
item from it.
Gis
import random
Aete[ [i] for 1 in range (20)1
yandon.ehuffie(1st)
print (1ee)
‘of numbers. For example, within a given range:
Keep shuffiing the ist and you can have a different selection of
items From 0to 20 every time,
You can also select a random number from a given
range in steps, using the start, stop, step loop:
import random
for i in range(10):
print (random.randrange (0, 200, 7))
Results will vary but you get the general idea as to how it works
Random module to shuffle the items in the ist, thus
Using shuffle, you can create an entirely random lst
Levsuse an example pece of ode wich ipsa
Sua virtual coin ten thousand times and counts how
many times land on heed or tals
output “Taser :0)
coinelist (output .keys()}
for 1 in range (10000) +
output [random. choice (coin) ]+=1
print (*Heads:", output [*Heads"])
print (“Taile:", output [*aile"])
Here's an interesting piece of code. Using atext
File containing 466 thousand words, you can pluck
‘a.user generated number of wards from the fie (text file found at:
‘wwe github com/dwylenglishawords):
import random
print (*s>>s>>5s>oRandom Word Finderces>>s>>>>>Your adventure rolece File) and create aTrue/False while loop:
import pygame import pygame
pygane.init () from pygane.locale import *
pygame. init ()
‘ganewindowspygane. dieplay.set_mode ((600,600))
pygane. display.set_caption("Adventure Gane")
a running True
while running:
e for event in pygane.e
Af event .type==QUIT:
running=False
ygame quit ()
le Est Famat Bin Qptens windows Hep
Tare pram.
is pygmes locals apt #
PPIIP DD Let's create asimple game ready window, and give
itatite:
ganewindow-pygane. display.eet_wode ((#00, 600) )
pygane. display.set_caption (*hdventure Gane")
gmorindon-pygane display set node((800.600))
Prose display: set-coption(-Adverture cane")
Sot"tuent in pygane event. ge
SP event. typeesdutT
urningersiss
pramersuit0)
You can see that after the fist ine is entered, vou need to click back
into the IDLE Shell to continue entering code; also, you can change.
the title ofthe window to anything you lke(Pygame Module Cl
ETE ithe Pygamewindowstil won't [=
close don't worry, it'sjust a
dliscrepancy between the IDLE (whichis written
with Tkinter) and the Pygame module. f you Fie eat Tas Hep
un your code va the command ine, it closes
perfectly well
You're going to shift the code around abit now, ingzpygame image. lead (*/home/pi/Downloade/
running the main Pygame code withina whileloop; apeitel.png")
Itmakes it eater and easier to fallow. We've downloaded a graphic
to-use and we need to set some parameters for pygame:
def eprite(x,y)
‘ganewindow.b1it (img, (x,y)
import pygane
pygame. init () on
y=(600%0.8)
sunning-Teue
gamewindow. £411 (white)
while running sprite(x.y)
ganewindowspygane. @isplay.set_node ((600,600)) EEE
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) munningeFalse
PTSD L2t's quickly 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 andthe Blt Function
with their respective RGB colour values. Next we've loaded the willallow us to eventually move the image
port prea 30(900%0.45)
Pea pypiterocats import * yrteoore:e)
ensie merindon.fill(ohitey
unningetve Spritecxey)
Praame: display update
she runing:
ganenindow-pygune. display set_mode((800,600))
Brame dispiay-set-caption(-saventore. cone")
Blscee(0:0°03, ‘or event in pygane.event.get0)
vaniten( 258,235,255) SP"eventRypersqutT
“ngspyeane image load(~/hone/ps/Donnloads/sprite}.png") onninges sis
Pramesquit
dot sprstece.y):
Hmenindon b1St¢img, (4.99)z= Using Modules)
FeTeeR AD ow we can change the code around again, this
time containing 3 movement option within the
while loop, and adding the variables needed to move the spite
around the screen:
Amport pygame
‘from pygame.locals import *
pygame. inst ()
unning-True
ganewindow=pygane. display. set_node ((800, 600))
pygane.digplay.set_caption(*Adventure Game")
black= (0, |
whites (255,255,255)
4ing=pygane . inage. load (*/home/pi/Downloads/spritel.
png")
def sprite (x.y):
‘ganewindow.bLit (img, (x.y))
x= (6000.45)
ye(600*0.8)
xchange0
qamertittyseteaptta Sree)
Pest ape aan rommtesses
Par aesteca yy,
ER came. com
Af event.type == pygame-KEYDOWN:
Af event .keye=pygame.K LEFT:
xchange=-5
‘gamowindow. £11 (white)
sprite(x,y)
pygame.display.update()
pygame.quit ()
Copy the code down and using the left and rightarrow keys on the keyboard you can move your sprite across the bottom of
the screen. Now; it looks ike you have the makings ofa classic arcade 20 scroller in the works.
EE eae So eeeypome essa
cee(Pygame Modules Cl
Ee You con now implement afew additions and utilise
some previous tutorial code. The new elements are
the Subprocess module, of which one function allows us to launch a
second Python script From within another and we're going to create a
New Fle called pygametxt.py:
import pygame
import. time
import subprocess
pygane. init ()
screen = pygane.dieplay.set_node( (800,
clock = pygane.time.Clock ()
250)
font = pygane.font Font (None, 25)
pygane. time. sot_timer (pygane.USEREVENT, 200)
def text_generator (text)
tmp = 1
for letter in text:
tmp ¢= letter
Af letter
yield tmp
class DynamicText (object)
def _ init__(self, font, text,
autoraset-Palze)
‘elf done
aelf.font = font
eelf
pos,
= Falee 7
_gen = text_generator (self.text)
‘pos = pos
autoresct
update)
aelf
self._gen = text_generator(self.text)
self done = False
‘self update ()
def update (self)
Af not self. done:
try: eelf.rendered « self.font.
render (next (self._gen), True, (0, 128, 0))
except Stopiteration
eelf.done = True
time sleep(10)
subprocess. Popen|"python3 /howe/pi/Decumants/
Python\ Code/pyganel.py 1", shell=Trus)
def draw(sel£, screen)
‘screen.blit (self rendered, self.pos)
text=(*A long time ago, a barbarian strode from the
frozen north. Sword in hand...")
message = DynamicText (font, text, (65, 120),
autoreset -True]
while True
for event in pygame.event .get ()
Sf event.type == pygame.QUIT: break
if event type == pygame-USEREVENT: message.
update ()
else
‘screen. £11 (pygane color. Color (‘black’)
mneseage.draw(screen)
pygane. display.£1ip()
clock. tick (60)
‘continue
break
ygame.quit ()
‘When you run this code it wil display along,
narrow Pygame window with the intro text
scroling tothe right. After a pause often seconds, itthen launches
the main game Python script where you can move the warrior sprite
‘around, Overall the effect quite good but there's always room
Forimprovement.Evins
Basic Animation
Python's modules make it relatively easy to create shapes, or display graphics and
Puree ieee ucla ela mcuaaee care ail
Coole ETN ecu ae ee R SU RUC teen sre
Moon ete clu Rte
LIGHTS, CAMERA, ACTION
The Tkinter module is an ideal starting point for learning animation within Python. Naturally, there are better custom modules
‘out there, but Tkinter does the job well enough to get a grasp on what's needed.
PEPER L= ecreen.get_height ()
atari] = 0
star [0] = randrange (0,639)
screen. set_at (star, (255,255,255) }
Basic Animation ¢ A mm
ESTED ow ads the Following:
sf main () +
pygame. init ()
screen = pygane.display.set_mode ( (640,480) )
pygane. display-eet_caption ("Starfield
Simslation*)
lock = pygame.time.Clock ()
init_stars (screen)
while True:
# Lock the framerate at 50 FPS
clock. tick (50)
# Handle events
for event in pygane.event .get ()
Af event .type == pygame.QUIT:
return
screen. fi21((0,0,0))
nove_and draw stare (screen)
pygane-4isplay.£1ip()
Af name
vain ()
*_ain_*
ef min)
rgawe: ase)
xfacn =" pyganedicplay.set mode( (640, 480))
pyoaee.dsSplay.set taption( sear! eid simulation")
EXger"= pyoane-tine-cioek()
nde stara(sereen)
‘hock: eLek(S0}
= wandie events
event. get):
proane rr
screen. £511((0,9,9))
Sietead arta seerdtecreen)
Pras display. 90)
ar
PEPPER Seve and Run the code. You will agree that the
simulated starfield code looks quite impressive.
Imagine this a the beginning of some game code, or even the start
to. presentation? Using a combination of Pygame and Tkinter, your
Python animations wil look Fantastic.eo Using Modules
Create Your Own Modules
Peele arse cm ene ea a eau Teese ca
and import the parts you need as modules. Learning to build your own modules also
Poet eee con ne teehee NAN OL
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.
Let's start by creating a set of basic mathematics "Now you're going to take the Function definitions
Functions. Multily @ number by two, three and ‘utoF the program and into a separate fie
square or raise anumber to an exponent (power). Createa New File Highlight the Function definitions and choose Edit> Cut, Choose File
inthe IDLE and enter: > 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 calls
IF younowtry and execute the basic_math py code
again, the eror‘NameError: name timestwo' is
not defined’ willbe displayed. This s due tothe code no longer
having accessto the Function definitions.
Fie Sor ett myn “Coderbasic.nath.py". Line 3. in caodule>
TP ti
PEED Retunto
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.PEPTID) G2ck to the basic_math.py window: atthe top ofthe
code enter:
from minimath import *
‘Thiswillmport the Function definitions asa module. Press FS to
save and execute the program to seeitin action,
You can now use the code Further to make the
program alittle more advanced, utilising the newly
created module tits Full Include some user interaction, Start by
creating a basic menu the user can choose from:
print ("Select operation. \n")
print(*1.Times by Ewor)
print (*2.Times by Three")
print (*3.Square")
print ("4.Power of")
choice
input (*\nBnter choice (1/2/3/4):*)
PEPE DD iow we can add the userinputto getthe number
the code will work on:
unt = int (input (*\Enter number: *))
‘Thiswillsave the user-entered number as the variable num
| Ble Edt Format Run Options windows Help
Tron minimath Inport *
print("select operation.\n")
int("t Times by to")
freee Tames by Three)
rintt"3. Square")
Brant(a.Poner of")
choice = input(“\nénter choice (1/2/3/4):")
punt = intCinput("\nEnter number: "))
(Create Your Own Modules Cl
Finally, you can now create a range of if statements
Sua to determine what to do with the number and
utilise the newly created function definitions:
Af choice == 11's
print (timestwo (num) )
elif choice == 12°
Print (timesthree (mum) }
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 Frm in Grtns Wows ey
Note that forthe ast valable options the Power
Susilo of choice, we've added a second variable, num2.
Tis pases asecond number trough the function defniton cle
power Save and execute the program to see kin ation,Python in Focus:
Artificial Intelligence
Artificial Intelligence (Al) and Machine Learning (ML) are the new hot topics of the IT
iret en Acca eoulaeR ea Role ere ue Maeno n sat] a apd ella P etary tek Taa)
fue eed Le dee
Cee CL eee eed
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, ML isthe ability For a computer to learn
eee usa
See ea rete ecu
Rc Re eed
CEs e mee rece
Rear eer ny ee ced
and, thanks to Python, that gap is getting loser every day.
Both Al and ML are hugely present in today’s technology. Where,
eee ese ey
ere a a ae eet een een]
ees ater cn Tar)
peer
Pe og eas
Set ete
«global coverage reaching 5. billion for 2019 and set to rise to over,
Ce ett ete eer rid
eee Eid
CE Ceca ge)
smartphone, the coding behind these devices has been developed
to take individuals into account. These devices are designed to
ene et it eee
‘numbers called are pushed to the top of thelist, i-app and in-game
‘advertising is moulded around our browser and search preferences,
ee ee eee
eee Deere
Dee nee
DIGITAL ASSISTANTS ?
eee ee ee eect
Re en Ree eer eed
are ll coded using Python, and are designed to listen, team and
respond to what we ask of them. With Python, this level o Ais
surprisingly simple, thanks to the many libraries and customisation
Se gee eno
for inteligent coders, cutting down on the development time in
Cee ie ee eee
complexalgorithms, these developers can devote significant time to
eae een aa
CO ge tee ee
er ee tae ated
‘we're asking by plucking out key words and acting on them. IF we
Pere emcees eter cet
Function; if we ask For dinner suggestions, it'll open a specificset of
Re eae eae erect
peer ea ete
ee ee a rs
ne sed ect
cerery
BEYOND THE SMARTPHONE.
Caer ee neat toy
eee rao ren
er eR ee ert)
Oe ae eas
Retr Renate
‘Another example of Aland ML working togethers Gmail's recent addition of
ee eee ese eee ery
Pe trea em een eats
the MIL side ofthe equation toautofil the remainder of the words For you. All
the time, the ML i earning while the Ais telling it what to improve on.
Facial recognition another element of Aland ML that's been the target of
Ce eae ee ee erga
‘on both smartphones and CCTV footage have improved dramatically.
eee ae Ee eee ee
Comer hie Raney re rc
Pree ene Rt td
ea
ee wr Reg cy
ee erence iete c ae ats
the pun diving it forward. In these circumstances, Python is doing alot
Preece eme ei eet ey
designed to implement Al and ML. Inthe background, youl usually ind
C++, or some other language, thats supporting the performance and
‘overall program in which the Al and ML are working.
Reena ears
Ce el
Seg a een oe
‘processing, helping people with vistal and hearing
Ce ee ers
Pe luca sko aad
Beer ame
Ce er ue
Sorte et
Ber een ere os
at a ene)
OF Al
Whether we'llend up creating true
SOO ee Ce
‘androids is up for debate. There are
ee ee eind
een
believing that Al willbe theworst
eee ey
ee un eed
Penna
Se eas
repeat
advancements and improved
Penal or)
ners)
that’s getting better by the hour.
caerSia eee]
Fn eet ee
eat
vee fem ae
Se ese Ii
a ee
See eke!
eae
Same)
an ei) 1-5-4 Le)
ra)
Seattle
reer Le
aie lee-le
ae
a t= ees
eed
Cre ee!
Eon iloie
cee ees
0, ERE 250),
ore at
hI
es
on ed
ee
tenorak
tp
ij cl
eet
Repository
We've included a vast Python code repository
ela Li Sn Te lls ES
Bice cg anc N rey
ec kee Ch ate
Peace
We've got code for making backups of your files.
Ete cue ue cu
number generators, Google search code, game
code, animation code, graphics code, text
adventure code and even code that plays music
Reet RAC cut
Pet aM ou Reece
the code to help you better understand what's
Pe eC eu Sc e
evince
Breer ure Cut ett sc mci)
in any other Python book. So use it, take it apart,
adapt it to your own programs and see what you
can create.
ce aeeee
Pee terre ete.
eels ea
lm Eae ed
TEE
Pee ee)
RISES meee eT
a list of options that allow you to
read a file, write to a file, append to.
Eve (Melee Bal Mima Kaela ed
of a directory'and much more. It's
(prc eae t elle h iia
ise) Tela code, or add to.
ofthe code imports the necessary modules.
cess modules deal withthe
the program.
within the
othe main
art ofthe cade that checks to see what OS
the useris running, in Windows the CLS comman
lears the screen, whereasin Linux and macOS, the
-ommand wipes the screen, the code tres
torunCLSwhen being used in Linux or macOS, an
error occurs, which then prompts torun the Clea
nese are the options, from 1 to 12. ach executes
thesporort Fincion hen the elvennmbes
FILEMAN.PY
Copy the code below into a New > File and save it as FileMan.py
Once executed it will display the program title, along with the
current time and date and the available options.
| Amport shuts
| import os
| import tine
“ Amport subprocess
dee Read):
patheinput(’Enter the file path to read:")
‘lesopen(path,"r")
printigie read)
dee writen
patheinpat("Enter the path of file to write or create:")
S£ o2.path.tafile(path)
print('Rebuilding the existing Mie")
ese:
rint(‘Creating the new file’)
textainput ("Enter texts")
‘Mlosopen(path,"w")
‘le.write(text)
oe aad)
[patheinput("Enter the file path")
textninput ("Enter the text to add")
‘Mlesopen(path,"2")
‘Sle.write( \n'ttext)
dot delete)
patheinput("Enter the path of file for deletion:")
£¢ o2.path. existe path)
rint('File Found’)
‘8 renove(pat)
Eint(‘File has been deleted’)
ese:
Fint('Pile Does not exist’)
dot Dirlist:
patirinput(’Enter the Directory path to display:")
sortiistmaorted(os.1istdiz(path))
ino
while(icten(sort1ist))
int (eortlisttil+/\n)
seed
dee checks)
fpeint(input ‘Check existence of \ni.File \n2.
Dizectory\n')),
AE Speed:
patheinput("Enter the file path")
os-path,dsSle(path)Af 0 path tanta patn)—tzve:
rint(‘File Found’)
PEint(File not found’)
LE Epmet:
path=input(*Enter the directory path:”
fs path dedix(path)
Lf os path isdir (path)enFalse:
print(‘Directory Found’)
[Print(‘Directory Not Found’)
ee Move()
pathieinput( ‘Enter the source path of file to move:')
Ie-int(input(/1 Rename \n2.Move \n'))
‘path2uinput(‘Enter the destination path and fle name:’)
‘hutil nove(patht,path2)
print(File renamed’)
Af mrmed:
patharinput(‘Enter the path te move:')
shutl move(path1,path2)
Print(‘File moved’)
det copy
‘pathisinput(‘Enter the path of tho file to copy or ronane:")
path2ainput(‘Enter the path to copy to:’)
shut copy (path path2)
Print(‘File copied’)
dee Makedir()
‘patheinput(Enter the directory nase with path to make
\nog. CA\Welto\Wiewdte \nitiere Novas i= now
dizectory:")
os.makodirs(path)
Print (‘Directory Created’)
dot Ronovedir()
pathainput(‘Enter the path of Directory:')
treedir=int (input('L Deleted Dizectory \n2.Delete
Directory Tree \n3.fxit \n!))
os endir(path)
Af troedixen
shut rmtree(path)
print( ‘Directory Deleted’)
Af troedixen:
exito,
‘det opensiiet)
patheinput('Enter the path of program’)
try:
on startale(path)
excep
PEInE(File not found’)
whte(rune=)
try:
of. system elese’)
except Osteror:
os.systom(cls")
print(\\mspooospoobython 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 fe
S.Append text to a tle
Python File Manager
C}
Tove 3 B18
8.copy a mie
o.create a directory
io.Delete a directory
11.Open a program,
st
st
writen)
doom
naa0
Delete)
Dirlisto
check’)
move)
doom
Makedir)
Renovedt=()
doomed
openste()
exit)
uneint input("l Return to mens\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 weve included a try and except black to checkif
the userisrunning 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.fae ees
cy
ym EH: Be
lm Eae ed
MCSE tua) allae (aol te el maolely NUMBERGUESS.PY
SS 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 mete ea handy when you Implementing a combination of the Random
felt ews hy a1 Lw alegre leh tee)
and the'randomndamber range'tan Eee +
easily bé'altereditoo. | guessestized = 0
| Nano=input('Hello! What is your nano? *)
number = random.randine(, 20)
print(‘Greetings, ‘+ Name +‘, 1m thinking of a
number between 1 and 30.’)
While guessesteed < 5:
‘guess=int (input (Guess the nusber within 5 guesses...)
guossesUsed = guossosUsed + 1
Sf guess < number:
Eint(‘Too low, try again’)
Af guess > number:
rint(‘Too high, try again.’)
Af guess == number:
break
guessestsed = str(guessestised)
Print('Well done, "+ Name +‘! You ques
‘Sorrectly in * + guesseslsed + * guesses.’) ]
Af guess '= number:
number = str(nunber)
pEint('Sorzy, out of guesses. The number I was}
thinking of i= + number)
Athoughths sa reasonably ea tofolow rota there are
FEW corre ctemens tote code that oe woth porting out Tobesin
‘ith jouneed to mportthe Random module youre sg
and numbers thine code,
Ths section ofthe code creates vibes forthe number
I long vith the nae ofthe player aaa
1 and30.Fyouwanta
fon then
vue ora
‘number=random.randint1, 30)
ito high though or the player will neverbe able to guess
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
{uesses from 5 by altering the while quessesUsed <5: valve,
IF the player quessed the corect number then they are given a
well done’ output, along with how many guesses they used Up.
IF the player runs out of guesses, then the game over outputs
clisplayed instead, along with revealing the number the compute
was thinking of. Remember, you do alter the values ofthe
-andom number chosen by the computer, or the number oF
‘quesses the player can take, then along with the variable values,
yyoualso need to amend the instructions given in the print
staternents attheCode Improvements
‘Since this is such a simple script to apply to asituation, theres
plenty of raom to mess around withitand makeit mare
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 ina 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 start ofa text adventure written in Python, where
the player names their character. The next step isto roll the
virtual random dice to decide what that characters combat.
rating, strength, endurance and luck values are. These can then be.
cared 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
( Number Guessing Game (3
For example, as per the screenshot provided, you could use
something along the lines of
choo
usck=o
Endurance = random randint(2, 15)
(CR = random.zandint(1, 20)
ek = randon.candint(l, 10)
Print (‘Your character's stats are as follows:\n")
Print (‘Endurance:*, Endurance)
Print ("Combat Rating:", CR)
Print ("huck:", Luck)
‘The player can then decide to elther stick with their roll or try again
forthe hope of better values being picked. There's ample waysin
which to implement this code into a basic adventure game.
7ny ee te
Random Number Generator
AUT nyo) Lee- pen enka oy
Mee cacaa tee alelehls
Tala er LATA)
language. It's what'separates
Eve fore hcee ne nhl
ergo ume la Ranta) Wogan at
eed le Tela yeh a Te tole
that Tato ; A
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 thelr
numbers. IFyoue feeling clever, see if you can pass the code
through a inter window or even the Ticker window that’s
available on Page 16,
Furthermore, the core ofthe cade can be used ina
game, where the character Fights something 2
‘along with the enemy’, isreduced by arandom 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
adventure
ath,
This can
fae ees
‘You can also introduce the Turtle module into the code and
perhaps set some defined rules fr drawing a shape, objector
‘something based on a user inputted random value from a range
of numbers. it takes a ttle working out but the effects certainly
really interesting,
eee
lm Eae ed
RNDNUMGEN.PY
lt might be simple but this little piece of code will ask the user
For two sets of numbers, a start and afinish. The cade will then
pluck out a random number between the two sets and display it.
from random import +
print (*\n>soo>sp59Random Munber Generatorccccccccce\n")
Iableint(input ("Enter the start number: "))
mb2=int(input(*Enter the last munber: "))
x = randint (ambi, nmb2)
[Print(\xfhe random munber betwoon” nb, ’and”;nmb2,"is:\n")
printed
For example, the code could be edited to this:
from random import *
printi(\noossp>20>Random Turtle Imagecccececcce\n")
imbinint(input "Enter the start number: ))
rmb2nint(input (“Enter the second number: "))
rnb3eint(input ("Enter the third number: "))
mmbéeint(input (“Enter the fourth munber: "))
‘turtie.forvardtambt)
turtie-ieft(50)
‘turtle. forvard(nmb2)
turte.1e£t(00)
turtle. forvard(amb3)
‘turtle.1eft 00)
turte.forvardianbs)
turtle. lett 00)
\Whilstt'salitle rough around the edges, you can easly make'lt
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 numberof 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 For their new password.
‘Aninteresting aspect to this codes the ability to introduce loop.
{and print ary numberof random passwords. Lets assume you have.
alistof 50 users for acompany 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 will be very difficult For a password cracker to hack.
import string
import random
def randompassword():
charsvstring.ascii _ uppercase + string.ascii _
lowercase + string digits
size @
return “'join(random.choice(chars) for x in
range(size,20))
print (randompassword())
‘Adding a loop to print a password fifty timesis extremely easy, for
example:
smport string
smport random
def randompassyord():
charsestring.ascli _ uppercase + string.ascii _
lowercase + string digite
sizes 4
return V.jein(random.choice(chars) for x in
ange(size,20))
mo
white neso:
This will output fifty random passwords based onthe previous
random selection of charactersText to Binary Convertor
Ly 5
y ery as
NCS ue eS refed TXT2BIN.PY
Sessa seo te naturally n'e wsng the fomat uncon cone the
ite geod fun.'Ittalso § a user's entered text string into its binary equivalent. If you
Sete el el want to checks accuracy, you can plug the binary into an
ear)
a
nae)
icone
wen Sr EET RETR
peint(* ‘join(formatiord(2), ‘b’) for x in text))
a
ts a) ae
oe eee Ces anklet
File Edit Format Run Options windows Help
(">>>>>>>>>>Text to Binary Conver tor<<<<<<<<<<\n")
text=input(“Enter text to convert to Binary: ")
( *.join(format(ord(x), *b*) for x in text)(_ Text to Binary Convertor
1000010 1101001 1101110 1100001 1110010
1111001
‘Thetextto binary convertor does offer some room for EERE ENTE Ts
improvement and enhancement. There are many uses:itcouldbe __PYsame.Gispiay.set.—capbion(pinazy 2
Ublisedin a password or secret word script as partof an adventure done = False
‘game oF just a novel way to display someone's name, clock = pygane.tine.clock()
\with regards to improvernents, you could display the binary ext _rotate _ degre
conversion ina Pygame window, using the animated text options
From page 18, You could also askthe userif they wanted tohave -Bnazy=(* “Join(format(ord(x), ‘b’) for x
‘another go, or even ask they wanted the binary output to be sn conversion)
saved toa fle.
=o
wate not done:
ith regards to rendering the outputted binary conversion to a =
Pygame window, complete wth rotating text, you can use [lefaranista pal ST pyaRaa grr
‘done = True
import: pygame
ygame.init) ‘screen. (WHITE)
font = pygame.font.sysFont('Calibri', 25, True, False)
BLACK = (0, 0, 0)
WRITE = (255, 255, 255) text = font-render(Binary, True, BLACK)
BUIE = (, 0, 258)
GREEN = (0, 255, 0)
ED = 255, 0, 0)
print((s>>oospooomext to Binary Convertorecceceeccc\n") ygame.display.f3p0)
conversionsinput(‘Enter text to convert to Binary: ") clock. tick(6o)
size = (600, 400) ygame.quit()
screen = pygane.display.set _node(eize)
Print(® ‘join(format(ord(x), °b’) for x in conversion)
See.ray oe
Pete ene es
Basic GUI File Browser
ere AUER ei-cielate} FILEBROWSER.PY
St EU ‘Tkinter isthe main module in use here but we're also using
File browser that's presented in'a idlelib, so you may need to pip install any extras if the
Pe ee eee dependencies fail when you execute the code.
Tkinter module, There's a lotyou can
learn from this code and implement:
NV ge ees ue ‘from idlelib treetiidget import Serolledcanvas,
Filefresitem, TreeNode
; : Amport of
‘from tkinter import Th
root = TKO.
root title("File Browser”)
‘sc = Scrolledcanvas(root, bg="white”,
hightightthickness=0, takefocue=l)
‘s¢-frane.pack(expand-1, fill="both’, side="left”)
Aten = Filetreertem(os.getowd)
node = TreeNode(sc.canvas, None, iten)
node.expand\)
oot mainloop()
ci
e
zi
ep]
Ad
‘il
i
fl
a
a]
4
> BE 2.9 ©
Ea eh ele,
Serta aed
Pere
lm Eae ed
a
er(Basic GUI File Browser
‘Advanced Filing =
When exected the cde wil pla the current drecton/s ‘ten open(nane'e') as uaerite:
‘contents. Fyou want to see the contents of another directory, you ‘print(VeeFile.read0)
‘cantun the code from a commandline within the chosen directory; S*°8PE:
just remember to call the code From where it's located on your wee
system, as per the second screenshot. You can also double- EH © =
lm Eae ed
PVR Eee cana iti ct
module being controlled by the
user via'the keyboard but'now We
thought we'd'see how thé user can
use theirmotise asa drawing tool
within Python. We'have two possible.
code cS ieee aT)
Melis irc conn
g LrO A
rey
CR
MOUSETURTLE.PY
‘The first piece of code presents the standard Turtle window.
Press Space and then click anywhere on the screen for the
Turtle to draw to the mouse pointer. The second allows you to
click the Turtle and drag it around the screen; but be warned,
it can crash Python,
1st Code Example:
from turtle import Sereen, Turtle
screen()
yertle = Turtle”)
dof 21010)
sereen.onscreenclick(click _ handler)
dof click _handler(x, y)
sereen.cnscreenclick(one) # disable event inside
‘event handler
yortle.sethoading\yertle.towards(x, y)
yertle.gototx, y)
screon.onscreenclick(click_handler) # reenable
screen.onkey(k101, ") # space turns on mouse draving
sereen.Listen()
scxeen.mainloop()
2nd Code Example:
from turtle import *
‘shape(*eizele”)
pencolor("biue")
width (2)
ondeag(gote)
Listen)
Ninja TurtleMouse
This code utilises some interesting skis, Obviously itwil stretch
your Python Turtle skis to come up with any improvements
which is great, but could make fora nice piece of code to
insertinto something a young child wil use. Therefore it can be
a fantasti project for ayounger person to get their teeth into;
or perhaps even as part of a game where the main character is
tasked to drawa skal and rossbones or sornething similar.(_ Mouse Controlled Turtle/ Python Alarm Clock
Python Alarm Clock
Ever taken a quick break from working
at the computer, then suddenly realised
many minutes later that you've spent all
that time on Facebook? Introducing the
Python alarm clock code, where you can
drop into the command prompt and tell
the code how many minutes until the
alarm goes off.
ALARMCLOCK.PY
This code is designed for use in the command prompt, be that
Windows, Linux or macOS. There are some instructions on how
to.use it in the main print section but essentially it's: python3
‘AlarmClock.py 10 (to go off in ten minutes).
import sys
import string
from time inport sleep
sa = sys.argv
ea = len(eys.argv)
Af Isa
print (Usage:
in _ minutes”)
print (Example: [ python3 ] AlarmClock.py 10")
Print ("Use a value of 0 minutes for testing the
Slam innediately.”)
Print ("Beeps 2 fow times after the duration is over.”)
Print ("Press Ctrl-C to terminate the alarm
lock early.”)
sys.exit()
{ python3 ] AlarnClock-py duration _
try:
minutes = int(ealt))
‘except. Valuesrror:
print ("Invalid numeric value (ls) for minutes” sa(t])
Print (‘should be an integer >= 0")
sye.exit(0)
Af minutes < 0:
print (“Invalid value for minutes, should be >= 0°)
sys.exit(l)
seconds = minutes * 60
Af minutes = 1
unit _ word =" minute”
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”)
bys.exit()
Wakey Wakey
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 a user input atthe beginning to ask the user For the
length of time they want until the alarm goes off, rather than
having to include tin the command line.
Windows users, Python 3s the only version installed on your
system then you will need to execute the code without adding
the 3to the end ofthe Python command. For example:
python Alarmclock.py 20
‘Again, you could easly incorporate this into a Windows batch
file and even eta schedule to activate the alarm at certain
times ofthe day
+ stefminutes) + unit _vord)a ar oe
ea eee
} Vertically Scrolling Text
Viel ecaa lela ce coe lolol ta Cet] EPICSCROLL.PY
No dw 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 nel eae nein? and red text. We think you'll agree, it's quite epic.
Clg P Ce SUV hele
‘from pygame.locals import *
pg.inito
text _list =
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,
ur gaunt land lay! So when a man climbed up
A rugged peak and gazed, his shaded eyo
Slope beyond slope, each hooded like its’ brothers,
It was a gloony 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.
0
rH
"
q
a
im
A
ia
fa}
a)
r
«
2)
e
x
y
Bt was so long ago and far amay
T have forgot the very name men called me.
The axe and flint-tipped spear are like a dream,
‘are shadows. I recall
Of that sombre Land:
‘The dinness of the everlasting woods.
Cimmeria, land of Darkness and the Right,
ed
oll)
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? T search my heart and find
Cimmeria, land of Darkness and the Night!
poeta tae
Pere
wr gplse(\n’)
et E ee ea
Eee)
Bo
lm Eae edC Vertically Scrolling Text (3
class Credits:
dof __ init__(self, screen_rect, ist)
ALLong Time Ago.
‘The obvious main point of enhancementisthe actual text
IE SAE: itself. Replace it with alist of credits, or an equally epic opening
eee Sorin toyou Python are and wl certain tthe
- ae mark with whoever plays it. Don’t forget to change the screen
Sultibot? _contery = velf.srect-baight/2 + 5 s
eee ane reslion needed we've cent runing at 80x60,
felfdelay = 0
aaa ann
of make _toxt(solf message)
font = pg.font.SysFont(Arial’, self.size)
text = font.render(essage,True,self.color)
rect = text get _ rect{center = (self.srect,
centers, self.ercct.centery + self.buff _centery) )
def make _surtaces(se1é)
self.taxt = () Oc, st ie
for i, Line in enunerate(self.1st): ar arectcmuary
1H self.make _text(line) s
Aly += itselE burt lines
self.text.appenda)
def update(sels):
Lf pg.tine.get _ticks()-self.timer > self delay:
self.tiner = pg.time.get _ticks() Sie cere
for text, rect in self.taxt: ae
recty -= 1
def render(self, surf): sre = ep siete ot
for text, rect in self.toxt: Bie ceca
surf.blit(text, rect) =
screen = py.display.set _mode((200,600))
screen _rect = screan.get _ rect)
clock = pg-tine.clock()
running=Truo
cred = Credits(ecreen rect, text _ list)
for event in pg.event.get()
if event.type == QUIT:
screen.fi11((0,0,0))
cxed.update0)
cred.render(screen)
pa.display.update()
lock tick(60)