0 ratings0% found this document useful (0 votes) 148 views84 pagesPython Tricks and Tips
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
au
Tricks and Tipstech
Python
Tricks and Tips
Welcome back... Having completed our exclusive For Beginners
ital guidebook, we have taught you all you need to master the
basics of your new device, software or hobby.
Yet that's just the start!
Advancing your skill set is the goal of all users of consumer
technology and our team of long term industry experts will help you
achieve exactly that. Over this extensive series of titles we will be
looking in greater depth at how you make the absolute most from
the latest consumer electronics, software, hobbies and trends!
We will guide you step-by-step through using all the advanced
aspects of the technology that you may have been previously
apprehensive at attempting. Let our expert guide help you build your
understanding of technology and gain the skills to take you froma
confident user to an experienced expert.
Over the page our journey continues, and we will be
with you at every stage to advise, inform and ultimately
inspire you to go further.uous Areca Roy
EraaUK Cremer
Ere cy eric Playing Music with the Winsound
coke uel LNG
H cea ae rg Bore iain
reneer inertia
See rueicnccas
Cue Wec as
ie 4 eee ee
Cee tec cnn
Ceo Cuune ied
a a ae
c
ES
N fs V5 3
a) Ce eel J Fe tw ie Ff H
ee en nL)Contents
Master Python
with the help of our
Fantastic Code Portal,
Featuring code for
games, tools and more.
SEITE
[hig ag
“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.”Loney
ata
On at the} end -ad
i epee ae .
in ame ] - ¥@SING
~. Modules
Oe Cea ie)
source file that contains the necessary
code for classes, Functions and global
Mere ec
modules to extend functionality,
and create even more spectacular
Python programs.
te sa ry
Netgear ee Ey
ecenes crs teed
See Een tury
used to fashion Fantastic code with
eee eau starlets)
ReneeED) wanes
Calendar Module
Beyond the Time module, the Calendar module can produce some interesting results
Mica cee Rimu tiger Maerua ose meet reat
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.
FERED L2urch Python 3andenter: import catendarto [ERTEENEMM There are numerous functions within the Calendar
callup the module end its inherent Functions. Once ‘module that may be of interestto you when
it’s loaded into memory, start by entering: Forming your own code, For example, you can display the number of
leap years between two specific years:
‘The resultis 29, starting from 1904 onward,
‘Ble Edt Shel) Debug Astions Window eb
fe ae
Se ene mo)
SE Sat a, a
umeact
BED orc eetecosct serena EREIB vxcousccntaiontat ower exngeine
displayed in a wall calendar Fashion, Naturally you apiece of working, user interactive Python code:
‘ean change the 2019, 9 part ofthe second line to any year and
‘month you want, a bithday For example (1973, 6). The irst line
‘configures TextCalendar to start its weeks on a Sunday; you can opt.
For Monday if you prefer.
Phan 52aCalendar Module @~}
BETESED) Youcanalso create a program that willdisplayall EFM You're also ableto print the individual months, or
the days, weeks and months within a given year: days, of the week:
inport calendar
print (calendar.preal (year))
‘We're sure you'll agree that's quite a handy bit of code to have
tohand.
iukes sie
Interestingly we can alsolist the number of daysin a [REESE The Calendar module also allows us to write the
‘month by using a simple: For loop: functions in HTML, so that you can display it ona
‘website. Let's start by creating anew file:
daysinmonth py -/home/pi/Documents/daysinmor
‘Ble Est Famet_Bun Options dow telp ‘This code wll create an HTML Fle called cal open twith a browser
Taport calendar and it displays the calendar for January 2019.
ccal=calendar Textcalendar (calendar SUNDAY)
For Tarleth Atermonthnys(z0i, 6
rine’
PEPIEM) You cansee that, atthe outset, the code produced RPM of course, you can modify that to display given
some zeros. This is due to the starting day ofthe ‘year asa web page calendar:
‘week, Sunday in this case, plus overlapping days from the previous
‘month. Meaning the counting ofthe days will start on Saturday 1st
June 2019 and wil total 30, as the output correctly displays.
Be 6 Se Bo
‘This code ass the user Fora year and then creates the necessary,
‘webpage. Remember to change your file destination.
saa |OS Module
MIO Murols Cel EAo RM ome e-ceANe Manele eee Toe I Manele
operating system. Commands vary depending on the OS you're running, as some will
Mor aMM Ine Mena ean en Me aun ne nC hu rleOse
INTO THE SYSTEM
One of the primary Features of the OS module is the ability to list, move, create, delete and otherwise interact with files
stored on the system, making it the perfect module for backup code.
BRTEERD Youconstart the OS module with some simple FETED The windows outputis different as that’s the
system environment that Python is running on. IFyou're using Linux by the system; as you might suspect, the os.getcwd) Function fs
‘or the Raspberry Pi try this: asking Python to retrieve the Current Working Directory, Linux users
‘willsee something along the same lines asthe Raspberry i, as will,
import 8 wise some
home=o8..getcwd ()
print (home)
a
PEED The retumedresultfrom printing the variable home [EWA ver another interesting element to the OS module,
Is the current user's home Folder on the system. isits ability to launch programs that are installed
Inour example that's fhome/pit willbe diferent depending on _inthehostsystem.Forinstance if you wanted to launch the
the username you log inas and the operating ystem you use Chromium brouser From within a Python program you can use
For example, Windows 10 wil output: C\Program Files (x86)\ the command:
Python36-32 Inport 08
oD browser=o5. ystem(*/usr/bin/chroniun-browser")
10 aeFETED The os.systern() Function is what allows interaction
with external programs; you can even call up
previous Python programs using this method. You will obviously
Need to know the full path and program file name for itto work
successfully. However, you can use the Following
import 08
os.system( ‘start chrome “https: //waw.youtube.com/
feed/musict”)
For Step 5's example we used Windows, 0 show
SuaG that the OS module works roughly the same across
all platforms. in that case, we opened YouTube's music feed page, so
Ristherfore possible to open spec pages
smpor 08
conv eyeten(chrontum-browssr *httpi//
bbtapublications.cow/"")
[Note inthe 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 specified page. You can even use variables to call
multiple tabs in the same browser:
inport os
a= (‘chromiun-browser *http://bdmpublications.
ecom/"*)
bbe (‘chromiun-browser *hetp://waw.google.co-uk"’)
os.system(a +b)
(osModule ell
—
Bisa)
‘The ability to manipulate directories, or Folders iF
you prefer, is one of the OS module's best Features.
For example to create a new directory you can use:
import 05
5. mkdir ("NEW")
This creates a new directory within the Current Working Directory,
named according to the abject in the mkdir Function,
You can also rename any directories youve created
byentering:
import 08
os.rename (*NEW", “OLD")
Todelete them:
import 08
os.rndir(*0LD*)
‘Another module that goes together with OS is
shutil. Youcan use the Shutil module together
with OS and time to create a time stamped backup directory, and
copy files into it
Amport os, shutil, time
root_sre_dir = x’ /hone/pi/Documents*
root_dst_dir = */home/pi/backup/’ + time-asctime()
for src_dir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_sre_dir, root_
dst_dir, 1)
Af not os.path.exists (ds
08 makedirs (dst_dir)
for file_ in files:
src_file = os.path.join(sre dir, file)
Gst_file = os.path. join(dst_dir, file)
Af Os.path.exists (dst_file) :
5. remove (dst_file)
shutil.copy(sre_file, dst_dir)
ain):
print ("ssssssssssackup conpleteccecececee")ED) ties
Using the Math Module
One of the most used modules you will come across is the Math module. As we've
MENON ete Mee aur acl ental me ea
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 builtin to Python 3; so there's ‘As you will no doubt be aware by now, if you know
noneed to PIPinstallit. swith the other modules the name of the individual functions within the
present, you can import the module's function by simply entering module you can specifically import them. For instance, the Floor and
import math into the Shell or as part of your code in the Editor. Cell functions round dawn and up @ float:
| Ele ot_shed Debug Spins _ndows_ Hep
Python 3-42 (default, Oct 19 20Ve, 3a)
(ee 4.8.1) on hinue
ype
Aleense()™ for more anformation.
pyragne”, eredits
pee" nSePe ats
St
Taefault, 0et 19-2018, 138
{eee 4.9.1) en inue
Type *eapyrighe™, "eredits or "License()" for nore information.
De" Selaath Inport Fleer. ceil
35> Hser(t-2)
B>> cettcr.2y
2
PEPER ieorting the Math module will give you access to BEAM the math module can alco be renamed as you
the module's code. From there, you can callup any import it, as withthe other modules on offer within
‘of the available functions within Math by using mats 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
Ele Est Shel Debug Gotens wndows Help
Python 3-4-2 (Gefaule, oct 19 2014, 13aTTID
{6CC 4.8.1) on linge
Hype “Cooyright"; “credits” or “License(}" for more infamation.
2S sapere
>>> math-sin(2)
erFETED Athough iv's not common practise, itis possible to
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 confusing:
rygbon 3-4. Carta. oct
{ee 3:4jon ine
ys Sige eregter or “scene for more snforation.
be Fetay
BREED Porting all the Functions ofthe Math Module can,
bbe done by entering:
from math import +
‘hile certainly handy, thisis often frowned upon by the developer
‘community 3 it takes up unnecessary resources and isnt an
«efficent way of coding, However, iit works For you then go ahead,
ype “copy
- ie Merete” oF “License()” fo
‘inport
ESTED cterestinaly, some functions within the Math
‘module are more accurate, orto be more precise are
‘designed to return a more accurate valve, than others. For example:
SME a i
Using the Math Module e
Ears (0° further accuracy, when it comes to numbers the
‘exp and expr Functions can be used to compute
precise values:
ytbon 34-3 COeaule. Oct
(ce 4.9.1) on Linwe
Hype cepyrighe’: Sereaits” or “License()* for more information.
2S corte art Sap expt
ETEGERD Tis level of accuracy is really quite impressive, but
‘auite niche for the most part. Probably the two
‘most used functions ae e and Pi, where e isthe numerical constant
equal to 2.71828 (where the circumference ofa circle divided by
itsdiameten):
Ceefaatt, oct 19 20
tj op lane
Eredits" oF “License()” for more information.
reisanesssenio3
Ea
PFET The wealth of mathematical functions available
trough the Math module is vast and covers
everything from factors to infinity, powers to trigonometry and
angular conversion to constants. Look up https://docs.python.org/3/_
Uibrary/math html For alist of avaliable Math module Functions.ED) wanes
Random Module
Deu CCAM Re eet a Na ee
CE cme aeMeetes emote corns rece teat Pants
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.
PETER 2ustaswith other modules you need to import FETED iowever, the Random module isn't used exclusively
random before you can use any ofthe Functions for numbers. You can use itto select an entry From a
‘we're going to look atin this tutorial Let's begin by simply printing 8 list From random, and thelist can contain anything:
random number From 1 to 5:
‘This wil display one of the names of our adventurers at random,
“which isa great addition toa text adventure game.
nour example
the number four
‘was returned, However, enter
the print Function a few more
times andit will display different
integer values from the set of
numbers given, zero to five. The
‘overall effect, although pseudo-
random, is adequate or the
‘average programmer to utlsein
their code.
Cases ceacm You can extend the previous example somewhat by
pean) BALD 09 andom.cote select from lst of mined
Foner variables Forinstance:
ESTESEDD Fora bigver set of numbers, including Floating
point values, you can extend the range by using the
multiplication sign:
Amport random f
print (xandom.random() +100) oe ae TT
‘ill splay 3 floating point number between 0 and 100, tothe tune
‘of around fifteen decimal points,
eer
4Random Module e mm
ESTEE ixterestingly, you can also use afunction within the [RNIB Let's use an example piece of code which flips @
Random module to shuffle the itersin the lst, thus virtual con ten thousand times and counts how
‘adding alittle more randomness into the equation: ‘many times it ill land on heads or tails:
randon. shuffle (1st) import random
print (1st) output=("Heads":0, *Tails’:0}
‘This way, you can keep shuffling the ist before displaying arandom _ S#n=248E (output -Keys ())
ikem from it. for 4 in range (10000!
‘output [random.choice (coin) ]+=2
print ("Heads:", output ("Keads"))
print (*Tails:", output [*fails"])
sng shuffle, you can create amenity random ist
SUPT of numbers. For example, within a given range:
Amport random
Let=[(i1 for 1 in range (20)1
random. shuffle(1st) Here's an interesting piece of code. Using a text
print (Ist) file containing 466 thousand words, you can pluck
a user generated number of words From the File textile found at:
‘www github.com/dwyfenglish-words}:
import random
keep shuffling the list and you can have a different selection of
items from 0to 20 everytime,
print ("ssssssssssRandom Word Findercecceeecee")
print (*\nUsing a 466K English word text file I can
[eeu sth entine ee pick any words at random. \n")
Feather wdseint (Anput (*\nHow many words shall T choose?
Hated =
with open(*/home/pi/Downloads/words.txt", “rt") as
f:
words = £.readlines()
words = [w.rstrip() for w in words)
BREED Youcanalso select arandom number fromagiven print (
range in steps, using the start, stop, step loop: VEE RRTTEELE ENTER
import random print (w)
for i in range(20) +
print (random-randrange(0, 200, 7))
“)
Results will vary but you get the general idea as to how it works.Evins)
Tkinter Module
CAT ate VolUmeole Miran Leo ure RR ACER BS od Kren ARN
Pee Soe Meme caet ier ienmutascs
upa Graphical User Interface to interact with the user, and
Se SIA cn
GETTING GUI
‘Tkinter is easy to use but there's alot 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.
FETED Tkiteris usually builtinto Python 3, However, if 's
available when you enter: import. tkinter, then
youneed to pip install tkinter fromthe command prompt,
‘We can start to import modules differently than before, to save on
typing and by importing all theircontents:
BPD snot recommended to import everything froma
‘module using the asterisk but itwon't do any harm
‘normally Let's begin by creating abasic GUI window, enter:
winder ()
“This creates a small, basic window. There's not much else to do at
this point but click the x in the corner to close the window.
Pyeensca oat
‘The ideal approach isto add mainloop0 into the
code to control the Tkinter event oop, but we'l
{get to that soon, You've just created a Tkinter widget and there are
several more we can play around with:
Sse}
ben["text*]=*Hello everyone!”
‘Theft line Focuses on the newiy created window. Click backinto
the Shell and continue the other lines.
I hon 42 Sat -o*
“Setar py ealpiDonave. Yen Cobia p/BAT) — ©
Be Fam Sm gions nde ee