The Complete Python Manual - Volume 35 2019 Text
The Complete Python Manual - Volume 35 2019 Text
£9.99
Volume 35
US$19.99
Can$24.50
Aus$19.99
NZ$ 19.99
Packed with top ^ Learn Python 3 and apply ^ Code games, Utilities
tips and tutorials * it to real world programs * and much more
POWj Ullim.ik' S*rit“i
Eupert
uitor^
to impfove
you r
1 CW HJLrtJ' E NCJt-W i
jjplicine - M&cSooks ■ iPad * Mac (fesKtaps * iPdd tcnuch * HWatch * *TV r 80W\ Speu J
£3 BDM'
The Complete
M A G A ZI N E Android WordPress
Esipert
tutoria!*
Manual
■TV+ toimprove
ftliat c Apple1: ntw IV jttocd?
to?? rt your pti'«
yuu vjuIlIi? Finii taA IflikJ*.
SUliSCHlPTlON
SEU Victi
m News+
the Pros
and i Mac
inside
m>
-M
Welcome to Python, the worlcTs best programming language
Within the pages oF The Python Manual, you can Find expert tutorials on
how to get started, what you will need and how to download and install
Python. Just take your First steps into Python programming and beFore
long you will be able to create a character and move it around the screen.
There’sa lotyou can achieve with Python and it'sgreat Fun to learn and create
something amazing that everyone can use; so what are you waiting For?
21 python P7oaZ
Tnd9 C°de
ar*d more Seo r%^ es' tools
fo^esrto',
92
1
A 1
6 on *
m
60 Formatting Strings
8 Why Python? 62 Date and Time
10 Equipment You Will Need 64 Opening Files
12 Getting to Know Python 66 Writing to Files
14 How to Set Up Python in Windows 68 Exceptions
16 How to Set Up Python on a Mac 70 Python Graphics
18 How to Set Up Python in Linux 72 Combining What You Know So Far
20 Installing a Text Editor
d 10
74■ j
d a ■21|H
i|u (appiiniiDiHTanHaa
i f «Si. V3 W93
•
KI A V VI I A
:y- Jf.r'
4 WA
;22 Iv
11
riMMfc H
rr< IBo BSrY W i ISI# aTaV |bT^H
WW A
I
WA m
76 Calendar Module
24 Starting Python for the First Time 78 OS Module
26 Your First Code 80 Random Module
28 Saving and Executing Your Code 82 Tkinter Module
30 Executing Code from the Command Line 84 Pygame Module
32 Numbers and Expressions 88 Using the Math Module
34 Using Comments 90 Create Your Own Modules
36 Working with Variables
38 User Input Code
40 Creating Functions
94 Python File Manager
42 Conditions and Loops
96 Number Guessing Game
44 Python Modules
98 Polygon Circles
46 Python Errors
99 Random Number Generator
48 Combining What You Know So Far
■■■■■■■■.....
109 Python Alarm Clock 116 Playing Music with the Winsound Module
110 Vertically ScroLling Text 118 Text Adventure Script
112 Python Digital Clock 120 Python Scrolling Ticker Script
114 Pygame Music Player 121 Simple Python Calculator
115 Python Image Slideshow Script 122 Hangman Game Script
Black Dog i-Tech Series-The Python Manual Editorial and design are the Copyright © Papercut Limited and is reproduced Black Dog (-Tech Series Volume 35-The Python Manual is an
Volume 35 - ISSN 2044-4060 under licence to Black Dog Media. No part of this publication may be independent publication and as such does not necessarily reflect the
Published by: .....Black Dog Media Limited (BDM) reproduced in any form, stored in a retrieval system or integrated into any views or opinions of the producers contained within. This publication is
Editor:.,..James Gale other publication, database or commercia! programs without the express not endorsed or associated in any way with The Linux Foundation, The
Art Director & Productioni.. Mark Ayshford written permission of the publisher. Under no circumstantes should this Raspberry Pi Foundation, ARM Holding, Canonica! Ltd, Python, Debian
Production Manager: ....Karl Linstead
publication and its contents be resold, loaned out or used in any form by Project, Lenovo, Dell, Hewlett-Packard, Apple or any associate or affiliate
Design:_._.._. .Robin Drew, Lena Whitaker
way of trade without the publishehs written permission. While we pride company. AU copyrights, trademarks and registered trademarks For the
Editorial:. .David Hayward
ourselves on the quality of the information we provide, Black Dog Media respective companies are acknowledged. Relevant graphic imagery
Sub Editon......Paul Beard
Limiied reserves the right not to be held responsible for any mistakes or reproduced with courtesy of Lenovo, Raspberry Pi, Hewlett- Packard, DeLl,
Printed and bound in Great Britain by: Wyndeham Press Group Limited inaccuracies found within the text oP this publication. Due to the nature Python, Scratch, Samsung, Canonical and Apple.
Newsstand distribution by: Seymour Distribution Limited oF the soFtware industry, the publisher cannot guarantee that all tutorials
2, East PoultryAvenue, London EC1A9PT Additione! images contained within this publication are reproduced under
will work on every version oF Raspbian 05. It remains the purchaseCs sole
International distribution by: Pineapple Media Limited www.pineapple-media. licence from Shutterstock.com.
responsi bility to determine the suitability of this book and its content for
com Prices, International availability, ratings, tities and content are subject to
whatever purpose, Images reproduced on the frontand back cover are
For all advertising and promotional opportunities contacti
solely for design purposes and are not representative of content. We advise change. All information was correct at time of print. Some content may
[email protected]
ali potentia! buyers to check listing prior to purchase Por confirmation of have been previously published in other volumes or BDM tities. We advise
Copyright© 2018 Black Dog Media. Ali rights reserved. actual content, All editoriaL opinion herein is that of the reviewer as an potentia! buyers to check the suitability of contents prior to purchase.
INTERNATIONAL LICEN5ING-Black Dog Media has many great publications individual and is not representative of the publisher or any of its afPiliates. Black. Dog Media Limited (BDM)
and all are available Por licensrng worldwide. For more information go to: Therefore the publisher holds no responsibility in regard to editorial opinion Registered in England & Wales No: 5311511
www.brucesawPordlicensing.com; email: [email protected]; and content.
telephone: 0044 7831 567372
Why Python?
Equipment You Will Need
Getting to Know Python
How to Set Up Python in Windows
How to Set Up Python on a Mac
How to Set Up Python in Linux
Installing a Text Editor
Why Python?
There are many different programming languages available for the modern computer,
and some stili available for older 8 and 16-bit computers too. Some of these languages
are designed for scientific work, others for mobile platforms and such. So why choose
Python out of all the rest?
PYTHON POWER
Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee
hours, slaving over an overheating heap of circuitry to create something akin to magic.
These pioneers oP programming carved their way into a new Regardless oP whether you use an Android device, iOS device, PC,
Prontier, Porging small routines that enabled the Letter 'A' to scroli Mac, Linux, Smart TV, games console, MP3 player, GPS device built-in
across the screen. It may not sound terribly exciting to a generation to a car, set-top box or a thousand other connected and 'smart'
that's used to ultra high-dePinition graphics and open world, multi- appliances, behind them all is programming.
player online gaming, However, Porty-something years ago it was
blindingly brilliant. All those aPorementioned digital devices need instructions to teli
them what to do, and allow them to be interacted with. These
Naturally these bedroom coders helped Porm the Poundations Por instructions Porm the programming core oP the device and that core
every piece oP digital technology we use today. Some went on to can be built using a variety oP programming languages.
become chieP developers Por top soPtware companies, whereas
others pushed the available hardware to its limits and Pounded the The languages in use today diPPer depending on the situation, the
billion pound gaming empire that continually amazes us. platPorm, the device's use and how the device will internet with its
Python is what's known as a High-Level Language, in that it 'talks' So to answer the question: why python? Simply put, it’s Free, easy to
to the hardware and operating system using a variety oFarrays, learn, exceptionally powerFul, universally accepted, eFFective and a
variables, objects, arithmetic, subroutines, loopsand countless superb learning and educational tool.
more interactions. Whilst it's not as streamlined as a Low-Level
Language, which can deal directly with memory addresses, call
stacks and registers, its beneFit is that it's universally accessible
and easy to learn.
77file: invoke.java
import java.lang.reflect.
class invoke {
public static void main( string [] args ) {
try {
Class c = Class.forNameC args[0] );
Method m = c.getMethod( args[l], new class
[] { } );
9 object ret = m.invokeC null, null );
10 System.out.println(
11 "invoked static method: " + args[l]
12 + 11 of class: " + args[0]
+ with no args\nResults: + ret );
14 } catch C classNotFoundException e ) {
15 // class.forNameC ) carit find the class
16 } catch ( NosuchMethodException e2 ) {
17 // that method doesn’t exi st
18 } catch ( IllegalAccessException e3 ) {
19 // we don't nave permission to invoke that BASIC was once the starter language that early
method
20 } catch ( InvocationTargetException e4 ) { 8-bit home computer users learned.
21 // an exception ocurred while invoking that
method
22 System.out.println( p r i nt (HAMGMAN [ 0 ]}
attempts * len(HAWGMAN) - 1
23 "Method threw an: " + e4.
| getTargetExceptionC ) );
24 } while (atteinpts ! = 0 and in word_guessed):
25 } print(("\nYou have {} attempts rerraining").format(attempts))
joined_word - M".join(word guessed)
26 } print(joined_word)
O
Java is a powerful language try:
player_guess = str( input(" \nPlease select a letter between A-2T’ f ,r\n> ”))
that's used in web pagesf except: # check valid input
print("That is not valid input. Please try again.")
se t-top boxes, TVs and continue
else:
even cars. if not player_guess.isalpha(): “ check the input is a letter- Also checks
print("That is not a letter. Please try again.")
continue
elif len(player_guess) > 1: $ ;heck the inpuc is cni. c n t lette
print("That is more than one letter- Please try again.H)
continue
elif player guess in guessed letters: # check it lette*’ hasn t b ‘Ti ei D
guessed_letters. append(player_gijess)
EquipmentYou
Will Need
You can learn Python with very little hardware or initial Financial investment. You
don't need an incredibly powerFul computer and any soFtware that's required is
Freely available.
u COMPUTER
Obviously youYe going to need a computer in order to learn how to program in
Python and to testyour code. You can use Windows (From XP onward) on either a 32
or 64-bit processor, an Apple Mac or Linux installed PC.
U AN IDE
An IDE (Integrated Developer Environment) is used to enterand exeeute Python
code. It enables you to inspect your program code and the values within the code, as
well as oFFering advanced Features. There are many difFerent IDEs available, so Find
the one that works For you and gives the best results.
. 'N*, i'
ps*»yitiOArof W -■m r
necessity. You can enter and exeeute code directly From the IDLE but a text editor,
such as Sublime Text or Notepad++, oFFers more advanced Features and colour coding
lOQltiflCj fdt 3 ftGWt?
when entering code.
IJJ
U INTERNET ACCESS
Python is an ever evolving environment and as such new versions oFten introduce
Lj* *vfeffw 4
v ne i a cHarsec="ntr-Bn> eFFicient language. Having access to the Internet will keep you up-to-date, help you
Nam* Ext. <cir-Ic.vTft)tcpad** Konc</zitIc?
. j Notfpidjpkfi
j N-step ie.ai ik_'A t-Ica
,h
,h
•■■rfl r.v-’” diisciriptinn'
?ta r-nz!*” ‘ kcyTaorrla11 c
c-anTPT:t:”,"Mcitiepf3!H-4: a tiriie :4<yurcift dodfi adito-r wlrich scq
izemt-"feIftcharger JjlnhepAd*# , Heitepadr desiminjid, free ac=-
out when you get stuck and give access to Python's immense number oF modules.
Notep3 djilHjs .cpp
'I Nntrp£d_piii i_iAi rcvp* .cpp
<liufc zel-"alternite" L. vte'11 jpp 11 u-jL!cn/rsn +iml” 121Ic-—"Follow Hotepi±(i++ wi Lli Rii
I NppEligSwileft .epp
- e 1- " a lyleabee t" typ*“ " fc/uXt/fK*" b re£m" /d.sset.3 /eaa/nj]p_c i. , esa " / >
JNppConnnrisnds ,cpp
<llnl[ 1e1="a lylfcsfree t" 1 , xe= "teit/asa" t:n*f="/aeseta/caa;/rciuta/tSmi(la«ti r. eaa"/;
jcmt
■clifiit rel= " sfrorttmt leoti" lutei*"bttp://Mtwad-itlDa-itlos,ara/asasts/lsa^/ravti
rtl=1,3cyl-eaf.0etT' type3* t*xt:/cfl 0 ■ tirer="/asser a/cs sJ 1 e6"J.
THE RASPBERRY Pl
Why use a Raspberry Pi? The Raspberry Pi is a tiny computer that's very cheap to purchase but offers the user a fantastic learning
platform. It's main operating system, Raspbian, comes preinstalled with the latest Python along with many Modules and extras.
RASPBERRY PI
The Raspberry Pi 3 is the latest version, incorporating a more
powerPul CPU, more memory, Wi-Fi and Bluetooth support.
You can pick up a Pi for around £32 or as a part of kit for £50+,
depending on the kityouYe interested in.
FUZE PROJECT
The FUZE is a learning environment built on the latest model
of the Raspberry Pi. You can purchase the workstations that
come with an electronics kit and even a robot arm for you to
build and program. You can find more information on the FUZE
atwww.fuze.co.uk.
BOOKS
We have several great Raspberry Pi tities available via www.
bdmpublications.com. Our Pi books cover how to buy your
First Raspberry Pi, set it up and use it; there are some great
RASPIAN step-by-step
project examples
The Raspberry Pi's main operating system is a Debian-based and guides to get
Linux distribution that comes with everything you need in the most from
a simple to use package. It’s streamlined for the Pi and is an the Raspberry
ideal platform for hardware and Software projects, Python Pi too.
programming and even as a desktop computer.
40743133
56gZ5304
423713053
Sone
»>
Getting to
Know Python
Python is the greatest computer programming language ever created. It enables
you to fully harness the power of a computer, in a language that's clean and easy
to understand.
WHAT IS PROGRAMMING?
It helps to understand what a programming language is bePore you try to learn one, and Python is no diFFerent. Let's take a
look at how Python came about and how it relates to other languages.
Programs are like recipes for computers. A 1 Put 100 grams of self-raising flour in a bowl.
A programming language recipe to bake a cake could go like this: 2 Add 100 grams of butter to the bowl.
3 Add 100 millilitres of milk.
is a list of instructions that
4 Bake for half an hour.
a computer follows. These Put 100 grams of self-raising flour in a bowl.
instructions can be as simple Add 100 grams of butter to the bowl.
as displaying your name Add 100 millilitres of milk.
or playing a music file, or Bake for half an hour.
as complex as building a
whole Virtual world. Python
is a programming language CODE l i^£ cake.py- C:\U&eri\lucyh\Dropbox\D_Actiori\cake.p1 (2.7,11}
File
::lass
Edit Format Run Options
Cake(object}:
'«Vrndow Help
PROGRAM COMMANDS
You might not understand some of the Python commands, like bowl.append and cake.cook(bowl).
The First is a list, the second an object; we'll look at both in this book. The main thing to know is
that it's easy to read commands in Python. Once you learn what the commands do, it's easy to
figure out how a program works.
T
laMHEI! •ime-
Dcuments/cake ov _ □
file Idit Shejl Debug Qptlons Windows Help File |dlt Firmat Bun Qptlcns Windows Help
bowl - []
flour - 100
butter - 50
milk - 100
bowl.append([flour» butter, milk])
Cake■cook(bowl)
Wikim-imA High-Ic vel progrumming language File Edit Shell Debug Qptions Windows Help
Ur J jl, LiU., ,
MOTI , |l-.« ..irbr^n-ujpedn
M»r, in o''■ ■■ hi jh !*. b I programming latiguag* 'n .1 | nip.i-m• • rj ••: r- i:ng |y. i l iri hnri dlv di 'nr. Of thi,* • >i In coihki * n 1b > w-h g iiwnlnfl-.ii ju.irji , ‘ ruij-u-■ ■ ur. '
Python 3.4.2 (defauit, Oct 19 2014. 13:31:11)
Ce*i@flts
Fivlirril. '•W-J
LiiKjijagi m e«w i» «w *■ ma* amomiiie «r h«i hH* ftimiwy i signAr^it jikh ar eampumg sysKir* («.3 fiWftwy 11 i.w u i^wimi) mikirii aw (humi m aevraprtQ .1 pragram ftinfUM m rtatt (GCC 4.9.1] on linux
Uu-nr-1 i.tr;
fariScm i^r"#
ui<Jci»l*'»J»ki« rtliHYstov sf-icd jngudgv. The amouitlgfdtbU«sl»n povwcti dcfli^k no» higii-kvcr
•«i !'Hf 19W» ■vgh*lpn?l pioyijniM -iigl.v flj.rjev«vng n M i'
1 pte-graminn^ Ia
«>P¥ rXTUrtiqrdy . .ilVU .njtBcmUiEjjmijIw gf juivwdi.1). •wv COBOL jud rcjrliul
Type "Copyright", "credits” or "licenseO" for more Information.
nivi.Hu Ia Whijwlii
TH£ Arsi BlglwftvJ projranmrg lin?JS]e devjre-; Tcf c-crptnerj yjs PlanUlkui «fwwd <emrad ;i^e J rwwessf rl w» «t Tip^rr^filM m fts Ime gnanU cng-nalsemtnbUiCiS WR (*» to Wortd Wgf II) large*/ >>> import this
.Vi.-f H-.l-H Litti.
imMlStVi Olfhi’1 ii,w,,kwnH.T«S! .r?nwjh UnfVjvii.tJ Hi-i,- Fitfi .■ ,i .-,i 'V^inflwg^ “Su4H.,i^lyn,J .inj lc whur tW Alggl' Thp llrvl iviily wft^.-jcHLvd high>lrvvl kwqvHigi'W» rMi'iiri. u iKjdlirK- The Zen of Python, by Tim Peters
dc.tftepmenl 4f IS M» c an» Au to. sy slffir* Al vi ■Senrnd m 1 &S0 and titS. tv EomMim of £u'op«an nd Anc^an corpuler accniltfj. antroiiuccd -«cui i ai vwll is irjles run^loni jnier leslcai «cpt* IC h-u
MiHn
al» L”il- ix. lanyjaae «Wi actai dis4inc:lKm visut und •■l* e-pa ai ■. .-rb a«S aht-f «11 fL“spcrKjiny xTti •‘n** Algol abo iftqduWd v.“i>jrrt jlrucluciJ piouiL- n njj tonoepts. suth as »h.- wdllt-do andlf-flKn-
AJ1&.1 ‘iV E \+- 1
Co^Trvnltf pwl» tf» coTilmcls and is ?> vrvmcr-viotwhubm
ur Ma a&riKlrn n 1 pmpfinmng langui^ iSf tIm lim n™
a lcmr-al mcinod dorkw-Jiaiur -rmn ■ bni- Dmng lough-v 'Nesamc nmd CotcH miroducctt tw •' au cMM Sfrucisl- and Lnp introduced 3 +-A grncrai Beautiful is better than ugly.
Explicit is better than implicit.
Cmhmh
I vM.
i-Vhil Ir.ki
1 lr-.;ifjn“,
Simple is better than complex.
n^!«4qd il'jir,T3 J Ab9tra™5B pfnRfly Complex is better than complieated.
LiplttJEt Kit 1 R«&ph mHnlng
IU*..:* filSAI 4 E" luiiliilliit JliLiilir. Piat is better than nested.
Fie marm iike
fciyo e.-tun.ilrai
4 t Hgh-ie-ielian^u^ecofniHHer weKlMLPe'
H Sr? Hbw
Sparse is better than dense.
WwdHauiro l'i RiaJilrfKir jik Readability counts.
CHSTtlU
Ff
7 tEMhUVUJ Hnld
Special cases aren't special enough to break the rules.
CreMe ■ Iwp*
Although practicality beats purity.
DmrfciJisW Fp^tlirP» [«Hj
(-•i]r4aP4 wifiijn
ngh icv«l langiiage*«rere-»me lugfw las-s: cf acsyacrjon fiom itucmk uairw iran aea>n}Mi(l> f«sten. aaaoo&s and ut suce, nign n« languages oeal »Rn vanab«« arrjy$.,-oc ^e,
Errors
**T
should
1 1
never pass
* i 1 ,1
silently.
ii __ _______
PYTHON 3 VS PYTHON 2
In a typical computing scenario, Python is complieated somewhat by the existence of two active versions of the language:
Python 2 and Python 3.
When you visit the Python In 2008 Python 3 arrived with several new
WORLD OF PYTHON PYTHON 3.X
_ W Download page you'll notice and enhanced features. These features
there are two buttons available: one for Python 3.6.2 and the other provide a more stable, effective and efficient programming
for Python 2.7.13; correct at the time of writing (remember Python is environment but sadly, most (if not all) of these new features are
frequently updated soyou may see different version numbers). not compatible with Python 2 Scripts, modules and tutorials. Whilst
not popular at First, Python 3 has since become the cutting edge of
Python programming.
Download
vV ■■ IV I & the
V I I Wtatti latest
& %■ Iu W. version
IV 8 wI I J for
I 'LJr I Windows
VI vp
PYTHON 2.X So why two? Well, Python 2 was originally Python 3's growing popularity has meant that
3.XWINS
launched in 2000 and has since then it's now prudent to start leaming to develop
adopted quite a large collection of modules, Scripts, users, tutorials with the new features
res and begin to phase out the previous version
and so on. Over the years Python 2 has fast become one of the first companies, such as SpaceX and NASA use
go to programming languages for beginners and experts to code Python 3 for snippets
its of important code.
in, which makes it an extremely valuable resource.
Python 3.4.2 Shell
[J Python 2.7.1 B Shell — [
File Edit SheU Debug Options Windows Help
File Edrt Shell Debug Options Amdow Help
Python 3*4*2 (defauit, Oct 19 2014, 13:31:11)
Pvthon ".7.13 fvl.7.13:a0£454blafal. Dec 17 3016. 30:42:591 fMSC v.1500 32 bit. ( *I [GCC 4,9*1] on linux
Type "Copyright", "credits" or "license()" for more Information
>>> print ("Python 3,x is AWESOME!”)
Python 3*x is Al/ESDME!
>>>
Howto SetUp
Python in Windows
Windows users can easily install the latest version of Python via the main Python
Downloads page. Whilst most seasoned Python developers may shun Windows as the
platform of choice for building their code, it's stili an ideal starting point for beginners.
STEP1 ^ Start by opening your web browser to www.python. Choosing the Customise option allowsyou to
STEP3
W org/downloads/. Look for the button detailing the speciFy certain parameters, and whilst you may
download link For Python 3.x.x (in our case this is Python 3.6.2 but as stay with the deFaults, it's a good habit to adopt as sometimes (not
mentioned you may see later versions oF 3). with Python, thankFully) installers can include unwanted additional
Features. On the First screen available, ensure all boxes are ticked
and click the Next button.
0 pip
Installs pip, which can download andl install other Python package;
Wondering which version to use?? M )out the differet
0 td/tk and IDLE
n Pvt installs tkinter and the IDLE development environment
Pl Python test suite
Looking for Python with a different OS? Python for Vi'v nc W «P,
Installs the Standard library test suite,
Unux/UNIX. Mac OS X. Other 0 py launcher 0 for all users (requires elevation)
Installs the globa! 'py' launcher to make it easier to start Python.
Want to help test development versions of Python? Vi s t
python
for
Windows Back Next Cancel
Click the download button For version 3.x, and The next page oF options include some interesting
STEP2 STEP4
save the File to your Downloads Folder. When the W additions to Python. Ensure the Associate File with
File is downloaded, double-click the executable and the Python Python, Create Shortcuts, Add Python to Environment Variables,
installation wizard will launch. From here you have two choices: Precompile Standard Library and Install For All Users options are
Install Now and Customise Installation. We recommend opting For ticked. These make using Python later much easier. Click Install when
the Customise Installation link. youTe ready to continue.
^ Customize installation
Choose locaticn and features Customize install location
C:\Program Files (x86)\Python36-32 Brov/se
python python
0 Install launcher for all users (reconnmended) for
for
Windows □ Add Python 3*6 to PATH Cancel Windows Back Install Cancel
You may need to conFirm the installation with the Clicking on the IDLE (Python 3.6 32-bit) link will
P5
Windows authentication notiFication. Simply dick launch the Python Shell, where you can begin
Yes and Python will begin to install. Once the installation is complete your Python programming journey. Don't worry iP your version
the Pinal Python wizard page will allow you to view the latest release is newer, as long as it's Python 3.x our code will work inside your
notes, and Pollow some online tutorials. Python 3 interPace.
python
for
Close
BePore you close the install wizard window, IPyou now click on the Windows Start button again,
STEP6 STEP9
_W however, it's best to click on the link next to the _W and this time type; CMD, you'll be presented with the
shield detailed Disable Path Length limit. This will allow Python Command Prompt link. Click it to get to the Windows command line
to bypass the Windows 260 character limitation, enabling you to environment. To enter Python within the command line, you need
execute Python programs stored in deep Polders arrangements. to type: python and press Enter.
Again, click Yes to authenticate the process; then you can Close the
installation window.
Close
P idle
If you're running an Apple Mac, then setting up Python is incredibly easy. In fact a
version of Python is already installed. However, you should make sure you're running
the latest version.
INSTALLING PYTHON
Apple's operating system comes with Python installed, so you don't need to install it separately. However, Apple doesn't
update Python very often and you're probably running an older version. So it makes sense to check and update First.
STEP1 Open a new Terminal window by clicking Go > STEP3 Click on the latest version oP Python 3.x, in our
_W Utilities, then double-click the Terminal icon. Now _ W case this is the download button For Python 3.6.2.
enter: python —version. You should see "Python 2.5.1" and This will automatically download the latest version oP Python and
even later, iP Apple has updated the OS and Python installation. depending on how youVe got your Mac conPigured, it automatically
Either way, it's best to check For the latest version. starts the installation wizard.
Continue i
* *
Open SaPari and head over to www.python.org/ With the Python installation wizard open, click on
STEP2 STEP4
W downloads. Just as with the Windows set up the Continue button to begin the installation. It's
procedure on the previous pages, you can see two yellow download worth taking a moment to read through the Important InPormation
buttons: one For Python 3.6.2, and the other For Python 2.7.13. section, in case it rePerences something that applies to your version
Note, that version numbers may be diPPerent due to the Prequent oP macOS. When ready, click Continue again.
releases oP Python.
Important Information
This package will install Python 3.6.2 for Mac OS X 10 6 or later for
i> Read
lntroti.uc.tion
me toiiowmg ardiiiecture(s): 1386, x66 64.
• UcenseB^I "NEW” For Python 3 .6, the python org website now provides only
one msialfer variam for download one that instails a 64-bit/32-bitIntel
Download I on Python capable of running on Mac OS X 10,6 (Snow Leopard) or
Ijier. This Read Me was installed with ne f£? 6 or later variani By
default, Python will automatically run m 64-b« mode if your system
supports it. The Python installed by this installer is biiilt with private
Wondering which version to use? H l
copias orso me ihi rd-party librarios not included with or newer Ihan
mose in OS X itseif. The list oi these iiDrahes is induded at the and oi
me License.rtf file.
HISTORYANP LICENSE “
1 Introduci ion lans-iMac^ ianosbornej pythoni —version
HISTORYOF THE SOFTWARE Python 3*6,2
f Read Mi
Ians-iHac;^ ianosbornel |
python was created m the eariy 19903 oy Guido van Rossum at
O License Stichting Maihematisch Centrum (CWl see hrtp jAflrww.cwijii) in the
Netherlartds as a successor ot a language called ABC. Guido
remams Pythoni pnnopai author aitnou ih it includes many
contributions from others,
In May 2000, Guido and the Python core deveiopmeni team moved to
BeOpon.com to lorm the BeOpen PythonLabs team. In October ot the
same year, the Pythonubs team moved to Digital Creations mow
Zope Corporation, see http/.Vywwjope com^. In 2001. the Python
Software Foundation (PSF. see httpYMww.python org/psffl was
formed. a non-protit organizabon created speaficaily to own Python-
related Intelledual Property.Zope Corporation is a sponsonng
member of the PSF.
Go Back ^ ( Continue 1
Finally youTe be presenbed wibh bhe amounb oF You need bo search in Finder For bhe Pybhon IDLE;
STEP6 STEP9
_W space Pybhon will bake up on your sysbem and an _W when you Ve Found ib, click it to launch and it
Insball bubbon, which you need bo click bo sbarb bhe acbual insballabion should look similar to that oF the Windows IDLE version shown on
oF Pybhon 3.x on bo your Mac. You may need bo enber your password the previous page. The only diFFerence being the Mac detected
bo aubhenbicabe bhe insballabion process. hardware platForm it's running on.
Standard In sta 11 on "Macintosh HD Python 3.6.0 <v3,6.0 414f79263allt Doc 22 2016, 17:23:13)
[GtC 4,2.1 (Apple Inc, build 5666) (dot 3}] on danin
1 Inuoduciion Type "Copyright', 'crediti ' or "liccnscO* for no r t i n f o rfna t1 on.
'>Read M Fhis will take 100 MB of space on your computer »>> A ARNING: The version of Tcl/Tk (8*5,9) in u se *ay be unstable
Click Install to perform a Standard installation of
t http ://wkwm, python org/downVood/moc/tcl tk f Or current infonMtion
this Software on the volume “Macintosh HD1h.
>> >
Custotnrze
STEP7 The installation shouldn't take too long; the older Older Mac versions may have trouble with the
STEP 10
_W Mac Mini we used in this section is a little slower newer versions oF Python, in which case you will
than more modern Mac machines and it only took around thirty need to revert to a previous Python 3.x build; as long as youTe using
seconds For the Installation SuccessFul prompt to be displayed. Python 3.x, the code in this book will work For you.
Howto SetUp
Python in Linux
Python version 2.x is already installed in most Linux distributions but as we're going
to be using Python 3.x, there's a little work we need to do First to get hold oF it.
ThankFully, it's not too diFFicult.
PYTHON PENGUIN
Linux is such a versatile operating system that it's oPten diPPicult to nail down just one way oP doing something. DiPPerent
distributions go about installing soPtware in diPPerent ways, so we will stick to Linux Mint 18.1 Por this particular tutorial.
STEP1 ^ First you need to ascertain which version oF Python Some Linux distros will automatically update
STEP3
_W is currently installed in your Linux system; as we _ W the installation oF Python to the latest versions
mentioned, we're going to be using Linux Mint 18.1 For this section. whenever the system is updated. To check, First do a system update
As with macOS, drop into a Terminal by pressing Ctrl+Atl+T. and upgrade with:
david@david-mint
File Edit View Search Terminal Help
davidgdavid-mint ~ s python --version
Python 2.7.12
david(adavid-mint sudo apt-get update && sudo apt-get upgrade
[sudo] password for david: |
STEP2 Next enter: python --version into the Terminal STEP4 “ Once the update and upgrade is complete, you
W screen. You should have the output relating to W may need to answer 'Y' to authorise any upgrades,
version 2.x oF Python in the display. Ours in this case iF Python enter: python3 --version to see iF Python 3.x is updated or even
2.7.12. installed. In the case oF Linux Mint, the version we have is Python
3.5.2, which is Fine For our purposes.
david@david-mint ~
File Edit View Search Terminal Help
david^david-irint - $ python --version
Python 2.7.12
david(sdauid-mint s |
However, ifyou want the Latest version, 3.6.2 as per Within the Python Polder, enter;
STEP8
W the Python website at the time of writing, you need
,/configure
to build Python from source. Start by entering these commands into
sudo make altinstall
the Terminal:
This could a little while depending on the speed oP your computer.
sudo apt-get install build-essential checkinstall
Once Pinished, enter: python3.6 —version to check the
sudo apt-get install libreadline-gplv2-dev
installed latest version.
libncursesw5-dev libssl-dev libsqlite3-dev tk-dev
libgdbm-dev libc6-dev libbz2-dev
davsd@david-mmt ^/Downloads/Python-3.6.2
File Edit View Search Terminal Help
david@david-mint - - -§- davidgdavid-mini -/Downloads Python-i.6 * 5 python3,6 -version
File Edit View Search Terminal Help Python 3.6.2
david@david-mint -/Downloads/Python*3.6.2 $ |
david@david-mint s sudo apt-get install build-essential checkinstall
Reading package lists... Done
Building dependency tree
Reading state information... Done
build-essential is already the newest version (12.Iubuntu2).
build-essential set to manually installed.
The following NEW packages will be installed
checkinstall
0 to upgrade, I to newly install, 0 to remove and 15 not to upgrade.
Need to get 121 kB of archives,
After this operation, 516 kB of additional disk space will be used.
Oo you want to continue? EY/n]
Open up your Linux web browser and go to For the CUI IDLE, you need to enter the following
STEP6 STEP 9
_W the Python download page: www.python.org/ W command into the Terminal:
downloads. Click on the Download Python 3.6.2 (or whichever
sudo apt-get install idle3
version it's on when you look) to download the source Python-
3.6.2.tar.xz Pile. The IDLE can then be started with the command: idle3. Note, that
IDLE runs a different version Prom the oneyou installed from source
o GO
david@david-mint -/Downloads/Python-3.6.2
File Edit View Search Terminal Help
Opening Python-3.6.2.tar.xz
About Downloads Documentation You have chosen to open:
david@david-mint -/Downloads/Python-3.6.2 $ sudo apt-get install idle3
Reading package lists... Done
uJ. Pyth on -3.6,2 -ta r joe
Building dependency tree
which is: xz archive (16,1 MR) Reading state information... Done
Download the latest source rele from: https://wvwj.python.org The following additional packages will be installed:
What should Firefox do with this file? idle-python3.5 python3-tk
Suggested packages:
Open with Archive Monager (default) tix python3-tk-dbg
Wondering which version to use? Heu e's more about the difft ® Save File The following NEW packages will be installed
Python 2 and 3. idle-python3.5 idle3 python3-tk
Do this aucomaticalfv foi files like this fron 0 to upgrade, 3 to newly install, 0 to remove and 15 not to upgrade.
Looking for Python with a different OS? Python for Windows
Need to get 68.4 kB of archives.
OSX, Gttier After this operation, 317 kB of additional disk space will be used.
Cancel OK Do you want to continue? tY/n] |
Warvtto help testdevelopmentversions of Python? Pre-relee
In the Terminal, go the Downloads Polder by ^ You also need PIP (Pip Installs Packages) which is a
STEP 7 STEP 10
_W entering: cd Downloads/. Then unzip the tool to help you install more modules and extras.
contents oP the downloaded Python source code with: tar -xvf Enter: sudo apt-get install python3-pip
Python-3.6.2. tar. xz. Now enter the newly unzipped Polder
PIP is then installed; check for the latest update with:
with cd Python-3.6.2/.
pip3 install --upgrade pip
File Edit View Search Terminal Help
Python-3. 6,2/Obj ects/accu.c When complete, close the Terminal and Python 3.x will be available
Python-3. 6.2/Obj ects/structseq,c
Py t hon - 3. 6.2/Obj ects/namespaceobj ect, c via the Programming section in your distro's menu.
Python-3. 6,2/Obj ects/typeslots.py
Python-3. 6.2/Obj ects/floatobject.c
Python-3. 6.2/0bj ects/clinic/ x
david@david-mint ■“/Downloads/Pythan -i h i
Python-3. 6.2/Obj ects/clinic/unicodeobj ect. e. h
Python-3, 6.2/Obj ects/climc/bytearrayobject. c. h File Edit View Search Terminal Help
Python-3. 6.2/Obj ects/clinic/bytesobj ect.c.h
david@david-miiit -/Downloads/Python-3.6.2 $ sudo apt-get install python3-pip
Python-3. 6.2/0bj ects/clinic/dictobjeot.c.b
Python - 3. 6.2/Obj ects/bytearrayobj ect„c «Reading package lists,.* Done
Python-3. 6,2/Obj ects/typeobject,c ;Building dependency tree
Python-3. 6,2/Obj ects/lnotabnotes.txt Reading state information... Done
Python-3. 6.2/Obj ects/methodobj ect.c The following additional packages will be installed:
Python-3, 6,2/Obj ects/tupleobject,c python-pip-whl
Python-3, 6,2/Obj ects/obmalloc,c jRecommended packages:
Python-3. 6.2/Obj ects/object.c python3-dev python3-setuptools python3-wheel
Python-3. 6.2/Obj ects/abstract.c The following NEW packages will be installed
Python-3, 6.2/Obj ects/listobject, c python-pip-whl python3-pip
Python-3, 6,2/Obj ects/bytes methods.c 0 to upgrade, 2 to newly install, 0 to remove and 15 not to upgrade.
Python-3. 6.2/Obj ects/dictnotes.txt Need to get 1,219 kB of archives.
Python-3. 6.2/Obj e c t s/1 yp eslo t s.in c After this operation, 1,789 kB of additional disk space will be used.
david@dav id-mint -/Downloads s cd Python-3.6.2/ Do you want to continue? [Y/nl |
david^dav id“mint /Downloads/Python-3.6.2 $ |
Installing a
Text Editor
lt's notentirely necessary (asyou can use the IDLE) buta text editor will help you
immensely when you're entering code. A normal word processor inserts its own unique
characters, paragraph settings and much more, so it's not a good platform for Python code.
SUBLIME CODE
Sublime Text is an excellent, cross-platForm text editor that's designed For entering code. It has a slick interFace, many
Features and perForms magniFicently. In short, it's an ideal starting point.
STEP1 LetJs begin by navigating to the Sublime Text Whichever version you choose, download the setup
STEP3
_ W webpage, to download the latest version for _W files and double-click them to begin the set up
whatever operating system you're currently running. You can find process. iFyouYe using Windows, which we are in this instance, then
the website atwww.sublimetext.com, together with a download you see the Standard installation wizard. The defaults will suffice, so
button for the detected OS that you're using. go ahead and install the program.
£0 4- ft Q £
Sublime Text
SuMmc Tertis a sophlstieated tert editarfcx code. markup and pras*
VouTflOve EheskktiierlnEWfAte, exEraCfftruryfeaturci^ndirrAan^; pedQrmaftte.
Welcome to the Sublime Text 3
Setup Wizard
This will install Sublime Text Buiid 3126 on your computer.
Cote Aliytfling tjn jlig bf tiHd to iftOw -t fanstlga Irt» gr wo*d wtflin j ni«_ * &/6 ►
Tfi* Egi alter r&T>* to on &*£££_
However, if you want to specify a particular When installed, Sublime defaults to a black
STEP2 STEP4
W operating system version, then click on the background and white text; whilst this is perfectly
Download link found in the top menu bar on the site. This will open fine for most users, it's not always the most comfortable viewing
a page with links for the latest version for OS X, Windows, Windows setup. Thankfully, there are countless themes you can apply by
64-bit and Linux machines. clicking Preferences > ColourScheme. We've opted for IDLE in
this screenshot.
Home Download Buy Blog Forum Support
pnnt i."Helio eveiyone!") * - Sublime Text fUNREGISTERED) □ X
Settings
Key Bindmgs
Sublime Text 3 is currently In beta. The latest buiid is 3126.
Font
o OS X 110.7 or later is requlred} Coler Scheme > AII iHallaw's E ve
o Windows - also available as a portable version
Amy
* Windows 64 bit- also available as a portable version
Slackboard
o Linux repo^ - also available as a 64 blt or 32 bit tarball
Ccbdft
Sublime Text may be downloaded and evaluated for free, however a iicense must be
purchased for continued use. There is currently no enforced time limit for the
evaluation.
Esp resso Libra
Sublime Text oFFers some excellent Features over Sublime isn't just For Python either. With ityou can
P5 STEP8
W that oF the Standard Python IDLE. For example, _ W build code For a number oF programming languages.
enter the Following: Click on Tools > Build System to see which languages youYe able to
build with in Sublime.
print (“Helio everyone!”)
W print ("Helio everyone'] * ■ Sublime Text [UNREGISTERED] □
This is an actual Python command, which will print the words File Edit Selection Find View Goto- Tools Project Preferences Help
Helio everyone! on the screen. Notice how Sublime automatically print f Helle everyone’]
-\ Command Palette.,. Ctri+Shift+P
Snippets...
recognises this as code and places the quotes and parentheses. print ("Helio everyone")
if True: Sui Id System > Automatic
print ("This is True!"j|
Build Ctrl+B
Ant
Build With.., Ctrl+Shrft+B
C+- +■ Single File
Cancel Build Ctrl* B rea k
Cargo
Build Re.su Et & >
D
v' Save Ali on Build
Erlang
Record Macro Ctrl+Q Haskdl
Soon, asyou become more Python-savvy, you'11 Find Sublime comes with a number oF preinstalled
STEP6 STEP9
_W that the Standard IDLE isn’t quite up to the task _W plugins For Python code, allowing you to experiment
oF keeping up with your code, alterations and injections oF code with your code in real-time. TheyYe probably a little bewildering at
mid-way through a long program. However, Sublime will keep you this point in time butyou will likely Find them useFul as your Python
updated and you can even utilise indents easily. skills increase.
API Reference
Sublime API
■ View
■ Regio nSet
1 print ("Helio everyone”) ■ Reumn
■ Edit
2 if True:
■ Window
3 print ("This is TrueE")
■ Settinqs
Base Classes
■ EventLi stener
■ Applicat io nCo m m and
■ Windo wCom mand
■ ~f extCommand
Lxample Plugins
Several p re-made plugins come with Sublime Text 2, you can fmd them in the F-a c k sg/ D-? f a'j 11 director/'
We're not going to get too heavily into the However, we recommend you use the IDLE For
STEP7 STEP 10
code right now but an indent is part oF Python this book. The Python IDLE isn't as advanced as
programming, where a statement indicates that the Following Sublime but it's a perFect base on which to build your skills; and you
indented commands must be run until a particular event has don't have to worry about any extra Features (as this is a Python
happened; aFter which the indents stop. Pressing Ctrl+] will indent a book, not a Sublime book). Python code can be saved though, in its
line oF code in Python. appropriate Format within Sublime.
•<.Th|
- >lr- /Mw
fmfK * ri
i'- Nuta
(ilL-l | Milii f rrii |-^iP I
*T-■ TliI" !r
GnKnvi
ua Tii>i
print ("Helio everyone”)
Onirirli
if True:
Ji
print ("This is True!”) V vwuln
| si-ieci
_ LKJl [W <£■'■
STARTING PYTHON
We worVt go into the details of getting the Raspberry Pi up and running, there's plenty of material already available on that
subject. However once you're ready, fire up your Pi and get ready for coding.
STEP1 With the Raspbian desktop loaded, click on the For example, in the Shell enter: 2+2
STEP3
Menu button followed by Programming > Python 3 _W After pressing Enter, the next line will display the
(IDLE). This will open the Python 3 Shell. Windows and Mac users can answer: 4. Basically, Python has taken the 'code' and produced the
Pind the Python 3 IDLE Shell From within the Windows Start button relevant output.
menu and via Finder.
Python 3 4 2 Shell - n
m*® fr* pythcn 34.2 shet
FtDqramrri r,g B-ueJ Java iDt Rle £dit Shell Qebug Qptions Help
GtS-iy Pncgrsmnws Edrrc*
Python 3.4.2 (default, Oct 19 2014, 13:31:11) T3 *
GreenAcol Java IDE
;|i
Scrstch 8 *»tegfawd dcvdcpmc^i enviraninerilor Python 3 »>l
SCfBtCh 2
SfRun Senae HAT Emulalor
jfj 3>mlftown
The Shell is where you can enter code and see the ^ The Python Shell acts very much like a calculator,
STEP2 STEP4
W responses and output of code youve programmed W since code is basically a series of mathematical
into Python. This is a kind of sandbox, where you're able to try out interactions with the system. Integers, which are the infinite
some simple code and processes. sequence of whole numbers can easily be added, subtracted,
multiplied and so on.
>>> 8+6 M
Eile £dit Shell fiebug Options Windows Help 14 Fonts/Tabs Highlighting Keys General
>>> 23453+64545522
64568975 Custom Highlighting Highlighting Theme
Python 3.4.2 (default, Oct 19 2014, 13:31:11) >>> 98778642342-12343 Seiect :
[GCC 4.9.1] on linox
Type "‘Copyright"*, '^credits'* or “license()** for more Information
98778629999
»> 1287437*43534
Choose Colour for ; • a Built-ln Theme U
2+2 56047282358
>>> print{ ‘Hei lc ev^r/une Norma! Te*t
4 Helio everyoneS
»> 8+6 IDLE Oassic
>>>
14 ■+ Foreground Background
»> 23453+64545522 qu can click here
64568975 #to choose items
def fune(param):
»> 98778642342* 12343 s ir ]np
98778629999 varO * ’strine’
>» 1287437*43534 vari =
56047282358 var2 - T found'
var3 = 1151( Jn • )
>» print("Hel Jio everyone!")
Helio everyone! error cursor |
>» shell stdout stderr
This is a little more like it, since youve just produced STEP9 Just like most programs available, regardless oP the
STEP6
_ W your Pirst bit oP code. The Print command is Pairly _ W operating system, there are numerous shorteut
self-explanatory, it prints things. Python 3 requires the brackets as keys available. We don't have room Por them all here but within the
well as quote marks in order to output content to the screen, in this Options > ConPigure IDLE and under the Keys tab, you can see a list
case the Helio everyone! bit. oP the current bindings.
Key Set
Highltghting Keys General
Ok Apply Cancel
STEP7 ^ You may have noticed the colour coding within ^ The Python IDLE is a power interPace, and one
STEP 10
_ W the Python IDLE. The colours represent different thatJs actually been written in Python using one
elements oP Python code. They are: oP the available GUI toolkits. IP you want to know the many ins and
outs Por the Shell, we recommend you take a few moments to view
Black - Data and Variables Blue-User Functions
www.docs.python.org/3/library/idle.html, which details many oP the
Green -Strings Dark Red - Comments
IDLE's Peatures.
Purple - Functions Light Red - Error Messages
Orange-Commands 25.5. IDLE
Sourcr code: L 1
Colour Use for Examples * multi vv iiUort' texi editor wilh rrmltipfe undu Fyltion uuloimny anarl mdunl tali lip& au Io comptetiofi and olher (saturas
* search wLhm an/ window, repiatc within editor Windows and searcti ihrc-jgh mulhpte Nos igrcpi
■ detsugg&r wrtu persislcn( bneakpointe sleppmg, and viewng cf g»ot>al and locai namospacos
. coniiguraton browsors and olher dialogs
Black Data & variables 23.6 area
25.5.1. Menus
Green Strings ,fHello World11 IDLE has two mam window t/pes in* Shell winduw and Ihe Editor wmdow It is possible lo have multiplo editor Windows simuttaneousiy Ouiljpul Windows, such as usod ror LdiL i Fnd m Fies are a subtype ot edil wmd
cunontfy navo the samo top menu as E Alor Windows but a diderent deFault titio <mU conteri rnen-j
Purple Functions len() print 0 IDLF's menus dynami..al y chanye baspcl on which w ndow is currenti/ selecled Facti ntenu ducumenled belc^r indicatas which wmdcnv lypa it rs usso:.lateti v, 111
Cless Browser
Show funrnnos and melnrwfs m Ihe mrcpnl Edrfnr hle m r rrpe slnirlurp In tnp =.hp.|| open r mediae hrst
r
www.bdmpublications.com The Python Manual 25
L
Getting Started with Python
Essentially, youVe already written your First piece oF code with the 'print("Hello
everyone!")' Function From the previous tutorial. However, let's expand thatand lookat
entering your code and playing around with some other Python examples.
STEP1 IF youVe closed Python 3 IDLE, reopen it in ^ You can see that instead oF the number 4, the
STEP3
whicheveroperating system version you preFer. in output is the 2+2 you asked to be printed to the
the Shell, enter the Familiar Following: screen. The quotation marks are deFining what's being outputted
to the IDLE Shell; to print the total oF 2+2 you need to remove
print(“Hello”)
the quotes:
print(2+2)
File Edit Shejl Debug Options Windows jHelp
• • # •
““ Just as predicted, the word Helio appears in the STEP4 You can continue as such, printing 2+2, 464+2343
STEP2
W Shell as blue text, indicating output From a string. W and so on to the Shell. An easier way is to use a
It's Fairly straightForward and doesn't require too much explanation variable, which is something we will cover in more depth later. For
Now try: now, enter:
print(“2+2”) a=2
b=2
1
The output oF the last step displays the current STEP 9 IF we were to apply the same routine as beFore,
STEP6
_ W values oF both a and b individually, as youve asked using the + symbol, the name wouldn't appear
them to be printed separately. IFyou want to add them up, you can correctly in the output in the Shell. Try it:
use the Following:
print(name+surname)
print(a+b)
You need a space between the two, deFining them as two separate
This code simply takes the values oF a and b, adds them together values and not something you mathematically play around with.
and outputs the resuit.
^ You can play around with diFFerent kinds oF variables In Python 3 you can separate the two variables
STEP 7 STEP io
_ W and the Print Function. For example, you could with a space using a comma:
assign variables Forsomeone's name:
print(name, surname)
name=”David”
Alternatively, you can add the space ourselves:
print(name)
print(name+” “+surname)
The use oF the comma is much neater, as you can see.
Congratulations, you've just taken your First steps into the wide
world oF Python.
Whilst working in the IDLE Shell is perfectly Pine Por small code snippets, it's not
designed Por entering longer program listings. In this section you're going to be
introduced to the IDLE Editor, where you will be working Prom now on.
EDITING CODE
You will eventually reach a point where you have to move on From inputting single lines of code into the Shell. Instead, the
IDLE Editor will allow you to save and execute your Python code.
STEP1 First, open the Python IDLE Shell and when it's up, You can see that the same colour coding is in place
STEP3
_W click on File > New File. This will open a new window _W in the IDLE Editor as it is in the Shell, enabling you
with Untitled as its name. This is the Python IDLE Editor and within it to better understand what's going on with your code. However, to
you can enter the code needed to create your Future programs. execute the code you need to First save it. Press F5 and you get a
Save..,Check box open.
file Edrt Shell Qebug Qptlons Windows Help Pale Edit Format Run Optio ns 31 1
Python 3.4.2 (default, Qct 19 2014, 13:31:11) File Edit SheFl Debug Qptlans Windows Help file Edit Format Run Optio ns Windows Help
[GCC 4.9,1] on linux
■
Type "Copyright", "credits" or "licenseO" for more j-nformation Python 3.4.2 (default, Oct 19 2014, 13:31:11) printCHe] Eo everyone!")
joce 4.9.1] on Linux
>” | Type "Copyright". "credits" or "licenset)” for mgre informet ior
>>>
OK Cancel
The IDLE Editor is, For all intents and purposes, a Click on the OK button in the Save box and select a
STEP2 STEP4
W simple text editor with Python Features, colour W destination where you'11 save all your Python code.
coding and so on; much in the same vein as Sublime. You enter The destination can be a dedicated Folder called Python oryou
code as you would within the Shell, so taking an example From the canjustdump it whereveryou like. Remember to keep a tidy drive
previous tutorial, enter: though, to help you out in the Future.
print(“Hello everyone!”) B -V # I B M 9 f*
Directory /home/pi/Documents J i
■- ■—1
4 ►
EP 5 Enter a name foryour code, 'print hello' for Let's extend the code and enter a few examples
W example, and click on the Save button. Once the from the previous tutorial:
Python code is saved it's executed and the output will be detailed in
a=2
the !DLE Shell. In this case, the words 'Hello everyone!'.
b=2
name=”David”
print helJo.py /home/pi.'Documenls, Python Coce p
FiIf Edit Format Run CJptipns Windows He:p surname=”Hayward”
Python 3.4 2 (default, Oct 19 2QT4, 13:31 ;T1) print("Hello everyone!")
ECCC 4.9.11 on linuK
Type "Copyright", "ciedits” or "1lcense()" for ffiore -Information,
»> 5"FAfi.T » = = = = = = =«-=.« = = == =.
print(name, surname)
>»
Hello everyone!
»> |
print (a+b)
If you press F5 nowyou'H be asked to save the file, again, as it's been
modified from before.
D %
E.>le Edit Sne! Qebug fiptia-ns ffindows He=p Filo gtb-t FurmuL Ru-, Optione Wi-iduw. Help
I
m saa
i ,■amRa@s»^i
QK Eh-TIE!
II
* *
This is how the vast majority of your Python code STEP9 If you click the OK button, the file will be
STEP6
_ W will be conducted. Enter it into the Editor, hit F5( overwritten with the new code entries, and
save the code and look at the output in the Shell. Sometimes things executed, with the output in the Shell. It's not a problem with just
will differ, depending on whetheryouVe requested a separate these few lines but if you were to edit a larger file, overwriting can
window, but essentially that's the process. It's the process we will become an issue. instead, use File > Save As from within the Editor
use throughout this book, unless otherwise stated. to create a backup.
DG*
L_,_■_1_■_. . print II
iHfgBIl
Elie Edit Shell Qebug Qptlons Uhndows Help 1 Fili Edit Format Run Options Windows H
Python 3.4.2 (default, Oct 19 2014, 13:31:11) — •V-VWVW
Save Ctrl+S
Save As... Ctrl+Slkft+S
Save Copy As... Alt+Shift+S
£lose Alt+F4
1 Ea* Ctrl+Q
STEP7 If you open the file location of the saved Python Now create a new file. Close the Editor, and open
STEP 10
code, you can see that it ends in a .py extension. a new instance (File > New File from the Shell).
This is the default Python file name. Any code you create will be Enter the following and save it as hello.py:
whatever.py and any code downloaded from the many internet
a=”Python”
Python resource sites will be .py. Just ensure that the code is written
b=”is”
for Python 3.
c=”cool!”
print(a, b, c)
You will use this code in the next tutorial.
STEP1 Python, in Linux, comes with two possible ways of STEP3 NowyouVe at the command line we can start
_ W executing code via the command line. One of the _W Python. For Python 3 you need to enter the
ways is with Python 2, whilst the other uses the Python 3 libraries command python3 and press Enter. This will put you into the
and so on. First though, drop into the command line or Terminal on command line version of the Shell, with the familiar three right-
your operating system. facing arrows as the cursor (»>).
fi cmd|
EP 5 Now enter: exit() to leave the command line Python ^ The resuit oF running Python 3 code From the
STEP8
session and return you back to the command Python 2 command line is quite obvious. Whilst it
prompt. Enter the Folder where you saved the code From the doesn't error out in any way, due to the diFferences between the
previous tutorial and list the available Files within; hopeFully you way Python 3 handles the Print command over Python 2, the resuit
should see the hello.py File. isn't as we expected. Using Sublime For the moment, open the
hello.py File.
File Edit Sdection Find Vtew Goto Tools Project Preferences Help
aPython”
c=JJcool!”
4 printfa, b3 c)
5 I
From within the same Folder as the code you're STEP9 Since Sublime Text isn't available For the Raspberry
STEP6
going to run, enter the Following into the _ W Pi, you're going to temporarily leave the Pi For the
command line: moment and use Sublime as an example that you don't necessarily
need to use the Python IDLE. With the hello.py File open, alter it to
python3 hello.py
include the Following:
This will execute the code we created, which to remind you is:
name=input(“What is your name? “)
a=”Python” print(“Hello,”, name)
b=”is”
c=”cool!”
print(a, b, c)
a=”PythonJJ
b=”is"
c=”cool!”
prin^a, b, c)
name=input("What is your nane? “)
print-("HelloJ t name)
STEP7 Naturally, since this is Python 3 code, using the Save the hello.py File and drop back to the
_ W syntax and layout that's unique to Python 3, it only command line. Now execute the newly saved
works when you use the python3 command. IFyou like, try the same code with:
with Python 2 by entering:
python3 hello.py
python hello.py
The resuit will be the original Python is cool! statement, together
with the added input command asking you Foryour name, and
displaying it in the command window.
STEP1 Open up the GUI version oP Python 3, as mentioned ^ You can use all the usual Mathematical operations:
STEP3
you can use either the Shell or the Editor. For the _ W divide, multiply, brackets and so on. Practise with a
time being, you're going to use the Shell just to warm our Maths Pew, Por example:
muscle, which we believe is a small gland located at the back oP the
1/2
brain (or not).
6/2
2+2*3
Python 3.4 2 Shell _ □ x
(l+2)+(3*4)
Eile £dit Shell £)ebug Qptions Windows Help
Python 3*4,2 {defauit, Oct 19 2014, 13:31:11}
[GCC 4,9.1] on linux
Type "Copyright", "credits” or ”license()" for more Information.
»>
In the Shell enter the Pollowing: You've no doubt noticed, division produces a
STEP2
W decimal number. In Python these are called Ploats,
2+2
or Ploating point arithmetic. However, iP you need an integer as
54356+34553245
opposed to a decimal answer, then you can use a double slash:
99867344*27344484221
1//2
You can see that Python can handle some quite large numbers.
6//2
And so on.
File Edit Shell Debug Options Windows Help
Python 3.4.2 (defauit, Oct 19 2014. 13:31:11) File Edit Shell Debug Options Windows Help
[GCC 4.9.1] on linux
Type "Copyright”, "credits" or "licenseO” for more Information. Python 3.4,2 (defauit, Oct 19 2014, 13:31:11)
>» 2+2 [GCC 4,9.1] on linux
4 Type “copyright"* Mcredits“ or "licenseO" for more Information,
»> 54356+34553245 >>> 2+2
34607601
»> 99867344*27344484221 >» 54356+34553245
2730821012201179024 34607601
»> »> 99867344*27344484221
2730821012201179024
»> 1/2
0,5
»> 6/2
3.0
»> 2+2*3
8
»> ( 1 + 2)+ (3*4)
15
»> 1//2
0
»> 6//2
3
You can also use an operation to see the remainder This will be displayed as 'Obi 1converting the
STEP8
lePt over Prom division. For example: _ W integer into binary and adding the prePix Ob to the
Pront. iPyou want to remove the Ob prePix, then you can use:
10/3
format(3, ‘b’)
Will display 3.333333333, which is oP course 3.3-recurring. IPyou
now enter: The Format command converts a value, the number 3, to a
Pormatted representation as controlled by the Pormat speciPication,
10963
the 'b' part.
TPiis will display 1, which is the remainder lePt over Prom dividing 10
>» 2+2*3
into 3. 8
»> ( 1 + 2 ) + (3* 4)
15
a
»> 1//2
2730821012201179024
0
>» 1/2
»> 6//2
0.5
3
>>> 6/2
»> 10/3
3.0
>» 2+2*3 3,3333333333333335
8
»> 10%3
I
4
Next up we have the power operator, or STEP9 A Boolean Expression is a logical statement that will
STEP6
exponentiation iPyou want to be technical. To work _ W either be true or Palse, We can use these to compare
out the power oP something you can use a double multiplication data and test to see iP it's equal to, less than or greater than. Try this
Symbol or double-star on the keyboard: in a New File:
2**3 a = 6
File Edit Format Run pptiom Wmdow
10**10 b - 7 a » 6
b = 7
print(l, o = 6) print(f, 3 -- 6)
Essentially, it's 2x2x2 but weTe sure you already know the basies print(2,
printf3„
a “ 7)
a == 6 mc b == 7]
print(2, o = print(4, a == 7 and b == 7)
behind Maths operators. This is how you would work it out in Python. □rintfS not a == 7 and b ■■ 7Ti
print(3, a = 6 and b
= 7) print(®,
pnnt(7.
a 7 or b =- 7)
a =»* 7 -r b 6)
print(8, not {a == 7 and b -- 6j>
>>> 6/2 print(4, a 7 and b
-== 7) print(9, not a == 7 and b — 6)
3.0 not a
>» 2+2*3 print(5, 7 and b 7) |
8
>>> (1+2)+(3*4) print(6, a 7 or b
== 7)
15
»> 1//2 print(7, a 7 or b
== 6)
0
>>> 6//2 print(8, not (a 7 and b - 6))
3
»> 10/3 print(9, not a == 7 and b == 6)
3.3333333333333335
>» 10%3
1
>>> 2**3
8
>>> 10**10
10000000000
>>>
STEP7 Numbers and expressions don't stop there. Python 1 Execute the code Prom Step 9, and you can see a
STEP 10
_ W has numerous built-in Punctions to work out sets series oPTrue or False statements, depending on
oP numbers, absolute values, complex numbers and a host oP the resuit oP the two dePining values: 6 and 7. It's an extension oP
mathematical expressions and Pythagorean tongue-twisters. For what youve looked at, and an important part oP programming.
example, to convert a number to binary, use:
bin(3)
»> 1/2
python 3.4,2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
0.5 Type "Copyright", "tredits" or ”license()Bt for more Information
>» 6/2 »> RESTART »««*««»*»»*»
3.0 >»
>>> 2+2*3
1 Truo
8 2 False
>>> (1 + 2)+(3*4)
3 True
15 4 False
>>> 1//2
5 True
0 6 True
>>> 6//2
7 false
3 8 True
>» 10/3
9 False
3.3333333333333335
>» 10%3 »>i
1
>>> 2**3
8
>» 10**10
10000000000
>>> bin(3)
"Obii1
>>>
#COMMENTS!
Programmers use a method of keeping their code readable by commenting on certain sections. If a variable is used, the
programmer comments on what it's supposed to do, for example. It's just good practise.
STEP1 Start by creating a new instance oP the !DLE Editor Resave the code and execute it. You can see that the
(File > New File) and create a simple variable and output in the IDLE Shell is stili the same as before,
print command: despite the extra lines being added. Simply put, the hash symbol (#)
denotes a line oP text the programmer can insert to inPorm them,
ei=10
and others, oP what's going on without the user being aware.
print(“The value of A is,”, a)
Save the Pile and execute the code. >y ,UI 1 3 4 2 ol
Pvthon Sheltru - □
E»le £dtt Shell fiebug Qptions ffimdows tleip
ik
Python 3*4*2 (default, Oct 19 2014* 13:31:11) □
[GCC 4,9.1] on lirnix
Type "Copyright", "credits** or "license()M for more Information.
>» ================================ RESTART ===================
»>
The value of A is* 10
»> ..RESTART
>»
The value of A isr 10
>»
• • # •
Running the code will return the line: The value oP A STEP4 ^ Let's assume that the variable A that we've created
STEP2
_ W is, 10 into the IDLE Shell window, which is what we _ W is the number oP lives in a game. Every time the
expected. Now, add some oP the types oP comments you'd normally player dies, the value is decreased by 1. The programmer could
see within code: inserta routine along the lines oP:
Essentially, the new code togetherwith comments The comment, the hash symbol, can also be used to
STEP6 STEP9
could look like: W comment out sections oP code you don't want to be
executed in your program. For instance, iPyou wanted to remove
# Set the start value of A to 10
the First print statement, you would use:
a=10
# Print the current value of A # print(“The value of A is,”, a)
print(“The value of A is,”, a)
# Player lost a life!
a=a-l
# Inform player, and display current value of A
(lives)
print(“You’ve just lost a life!”)
print(“You now have”, a, “lives left!”)
STEP7 ^ You can use comments in diFferent ways. For ^ You also use three single quotes to comment
STEP 10
_W example, Block Comments are a large section oP out a Block Comment or multi-line section oP
text that details what's going on in the code, such as telling the code comments. Place them bePore and aPter the areas you want to
reader what variablesyouYe planning on using: comment For them to work:
C > J
# This is the best game ever, and has been
developed by a crack squad of Python experts This is the best game ever, and has been developed
# who haven’t slept or washed in weeks. Despite by a crack squad of Python experts who haven’t
being very smelly, the code at least slept or washed in weeks. Despite being very
# works really well. smelly, the code at least works really well.
? y j
File Edit Format Run Options Windows Help File Edrt Format Run Options Windows Help
M This is the best game ever, and has been developed by a crack squad of Python experts
1
ff who haven*t slept or washed in weeks. Despite being very smelly, the code at least
works really well.
iiy «»11.1
# Set the start value of A to 10
a ~ 10
# Print the current value of A
print("The value of A is,", a)
w Set the start value of A to 10
a=1Q
# Player lost a life!
# Print the current value of A
a=a-1 # print ("The value of A is,1*, a)
$ Inform player, and display current value of A (lives) ff Player lost a life!
print(**You*ve just lost a lite!**) a-a-1
prmt( "You now have", a, "lives left1") # Inform player, and display current value of A (lives)
print(‘You’ve just lost a life!")
print( "You now have”, a, "lives left!”)
We've seen some examples of variables in our Python code already but it's always
worth going through the way they operate and how Python creates and assigns certain
values to a variable.
VARIOUS VARIABLES
Youll be working with the Python 3 IDLE Shell in this tutorial If you haven't already, open Python 3 or close down the previous
IDLE Shell to ciear up any old code.
STEP1 In some programming languagesyouYe required ^ You've seen previously that variables can be
STEP3
to use a dollar sign to denote a string, which is a W concatenated using the plus symbol between the
a
variable made up oP multiple characters, such as a name oP a person variable names. In our example we can use: print (name +
In Python this isn't necessary. For example, in the Shell enter: “ + title). The middle part between the quotationsallows us to
name=”David Hayward” (or use your own name, unlessyoure add a colon and a space, as variables are connected without spaces,
also called David Hayward). so we need to add them manually.
File Edit Shell Debug Optfons Windows Help File £dit Shell Debug Options Windows Help
Python 3.4,2 (default, Oct 19 2014, 13:31:11) Python 3*4*2 (defaultToct 19 2014, 13:31:11 )
[GCC 4.9.1] on linux [GCC 4,9.1] on linux
Type "Copyright", "credits" or "license()B1 for more Information. Type "Copyright", "credits" or "licenseO" for more Information,
>» name="David Hayward" >>> name="0av id Haywa rd"
»> print (name) >>> print (name)
David Hayward David Hayward
»> type (name)
<class 1str1>
>>> title-'Descended from Vikings"
>» print (name + ": M + title)
David Hayward: Descended from Vikings
>>>
^ You can check the type oP variable in use by P4 You can also f1
STEP2
_ W issuing the type () commancf, placing the name oP combine variables £ile Edrt Shell Qebug Qptlons Windows Help
Python 3,4.2 (default, Oct 19 2014. 13:31:1
the variable inside the brackets. In our example, this would be: within another variable. For [GCC 4,9,1 ] on linux
Type "Copyright", "credits’1 or lrlicen$e()”
type (name). Add a new string variable: title=”Descended example, to combine both name >>> name= . ard"
»> print (name)
from Vikings”. and title variables into a new David Hayward
»> type (name)
variable we use: <class ‘str*>
»> title»"Descended from Vikings"
»> print (name + " + title)
Python 3.4.2 Shell - □ x
character-name + “ + David Hayward: Descended from Vikings
»> character-name + M: + title
File Edit Shell Debug Options Windows Help >>> print (character)
Python 3.4.2 (default, Oct 19 2014, 13:31:11) n title David Hayward: Descended from Vikings
>>> age-44
[GCC 4,9.1] on linux
»> type (age)
Type "Copyright", "credits" or "licenseO" for more Information
>» name® 'David Hayward"
Then output the content oP the <class ’intr>
>>>
>>> prmt (name)
David Hayward new variable as:
>» type (name)
<class *str'>
>>> title="Descended from vikings" print (character)
>>>
age-44
Type (age)
Which are integers, as we know.
This is a process known as TypeCasting. The Python The use oFTypeCasting is also important when
STEP6 STEP9
code is: _W dealing with Ploating point arithmetic; remember:
numbers that have a decimal point in them. For example, enter:
print (character + “ is “ + str(age) + “ years
old.”) shirt=19.99
oryou can use: Now enter type(shirt) and you'11 see that Python has allocated
the number as a 'float', because the value contains a decimal point.
print (character, “is“, age, “years old.”)
Notice again that in the last example, you don't need the spaces , . / tj |£|]
between the words in quotes as the commas treat each argument
File Edit Shell £ebug Qptions Windows Help
to print separately.
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.t] on linux
>» print (name + age) Type "Copyright”, "credits" or "licenseO" for more information.
Traceback (most recervt -call last): »> shirt=19.99
File ‘'<pyshelltfi8>M, line t, in <:module> »> type(shirt)
print (name + age) <class ‘float’>
TypeError: Can‘t convert ’ int* object to str implicitiy
>» print (character + ” is ™ + str (age) + " years old.") >>>
STEP7 Another example oF TypeCasting is when you ask For When combining integers and Floats Python
STEP 10
input From the user, such as a name. For example, usually converts the integer to a Float, but should
enter: the reverse ever be applied it's worth remembering that Python
doesn't return the exact value. When converting a Float to an
age= input (“How old are you? “)
integer, Python will always round down to the nearest integer,
All data stored From the Input command is stored as a string called truncating; in our case instead oF 19.99 it becomes 19.
variable.
; jTw | sT- i i
Eile £dit Shell JQebug Qptions Windows Help
File Edit Shell Debug Options Windows Help
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
Python 3.4.2 (default, Oct 19 2014. 13:31:11) [GCC 4.9.1] on linux
[GCC 4.9.1] on linux Type "Copyright", "credits" or "licenseO" for more information.
Type “Copyright", "credits" or “licenseO" for more information. »> shirt=19.99
>>> age» input ("How old are you? ") »> type(shirt)
How old are you? 44 <class *float’>
>>> type(age) »> int(shirt)
<class 'str'> 19
>>> »> I
We've seen some basic user interaction with the code from a few of the examples
earlier, so now would be a good time to focus solely on howyou would get information
from the user then store and present it.
USER FRIENDLY
The type of inputyou want from the user will depend greatly on the type of program youTe coding. For example, a game may
ask for a character's name, whereas a database can ask for personal details.
^ IP it's not already, open the Python 3 IDLE Shell, Now that we have the user's name stored in a
STEP1 STEP3
and start a New File in the Editor. Let's begin with couple oP variables we can call them up whenever
something really simple, enter: we want:
printf"Hei Io")
flrstname-input( our first name )
print( "JThanks.)
file Edit format Run Options Windows Help surname*inputf"An what is your surname? )
pr int( Hwe lcoine". rstname . surname, . I >
printf"Helio' )
f i r s tn arne - inpu t ( ’ Wh at is o u r f i r s t nam e )
p rintf"Thanks*“)
surname-inputf"Ane tvhat is yojr surname? 1)
Save and execute the code, and as you already no Run the code and you can see a slight issue, the
STEP2 STEP4
doubt suspected, in the IDLE Shell the program will _ W Pull stop aPter the surname Pollows a blank space
ask Por your First name, storing it as the variable Pirstname, Pollowed To eliminate that we can add a plus sign instead oP the comma in
by your surname; also stored in its own variable (surname). the code:
"TJ
usennputpy- /home/pi/Docu
fU
=5
■ 1
in
o
i
7 i
Fjle Edi! Shell De huc 0ytions Windows Help £iie Edit Farmat B-un Qptions Windows Help
Python 3. <4.2 {default, Oct 19 2014, 13:31:11) print("halt ■ .<ho goes ther e*?")
[GCC 4.9.1] on linux name=inpoi;{)
Type "Copyright", "credits" or Hhc«nse( )" for more Information. : r" narae--"0.i : T' E
>» . RESTARI ... printt“weicorte, good sir, You ma;y pass,")
»> ■ 1r n *
Hait! Vitio goes there? printt"I -.novi you net. Prepare for battle")
David
Lielceme, good sir, You may pass.
>» —===—===—= RESTARI =================
>»
Haltl Viho goes there?
conan
I know you net. Prepare for battiel
The code from the previous step is often regarded Just as you learned previously, any input from a
STEP6 STEP 9
_ W as being a little neater than having a lengthy _ W user is automatically a string, so you need to apply a
amount of text in the input command, but it's not a rule that's set in TypeCast in order to turn it into something else. This creates some
stone, so do as you like in these situations. Expanding on the code, interesting additions to the input command. For example:
try this:
# Code to calculate rate and distance
print(“Halt! Who goes there?”) print(“Input a rate and a distance”)
name=inputO rate = float(input(“Rate: “))
lt's a good start to a text adventure game, perhaps? To finalise the rate and distance code, we can add:
STEP 7 STEPio
_ W Now you can expand on it and use the raw input
distance = float(input(“Distance: “))
from the user to flesh out the game a little:
print(“Time:”, (distance / rate))
if name==”David”:
Save and execute the code and enter some numbers. Using the
print(“Welcome, good sir, You may pass.”)
float(input element, we've told Python that anything entered is a
else:
floating point number rather than a string.
print(“I know you not. Prepare for battle!”)
i a-nicr
1LHJ i JV ' /! ts/Pvthon Co
File Edit Shell Debug Options Windows Help
— O X frle Edit Firmer Bun Qptions Windows HeSp
Python 3.J.2 (default, Oct 19 2014, 13:31:11) # Cade ta calculate rate and distan.ce
(GCC 4.9.1J on linux printf 'Input 3 rate and a distante")
Fjle £drt Format Run Qpticms Windows Help Type "Copyright", "eredits" or "lieensef)" for more informat ion, rate * float(input( Rate: ))
>» -------------------------------- R£START -------------------------------- distance ■ floettInput("Distance: “)>
>» BrintfTime:". (distance / rate))
Halti Who goes there?
David
we Itonie, good sir. You may pass.
»>
Haltf Who gces there?
Conan
I know you not. Prepare for battle1
-- RESTARI -----
»>
Input a rate and a distance
Rate: 12
nictante: 24
Time: 2.0
>» |
FUNKY FUNCTIONS
A function is a command thatyou enter into Python to do something. It's a little piece of self-contained code that takes data,
works on it and then returns the resuit.
lt's not just data that a Function works on. They can ^ You can pass variables through Functions in much
STEP 1 STEP 3
do ali manner oF useFul things in Python, such as _ W the same manner. Let's assume you want the
sort data, change items From one Format to another and check the number oF letters in a person's surname, you could use the Following
length or type oF items. Basically, a Function is a short word that's code (enter the text editor For this example):
Foilowed by brackets. For example, len(), list() or type().
name=input (“Enter your surname: “)
count=len(name)
print (“Your surname has“, count, “letters in
Python 3.4.2 (default. Oct 19 2014, 13:31:11>
it.”)
[GCC 4.9.1] on linux
Type "coiryr lght", "credits" or “licenseO” for more Information
»> len|[)(
Press F5 and save the code to execute it.
file Edit Shell E-ebug Sptians Windaws Help £i!e E-dit Farmst Bun apHons 'fiir.dows Help
Python 3-.4.2 (defjuit, Pct 19 2014, 13:31; 11) name-input ("Enter your sunu e: J
[GCC 4.9.1] an iinuK emunt- len{ rume]
Type “copyr“icredus-" or Hlie«nst<F for «or* informiticrn. print ("Vuu^i nane has”, count. "I■:-ct. it ")
^ Lrn( i ,ib I iifiHntAr uniMn1)
2»
»> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm RESTART
»>
Entflr ycur ,.grn,rni: iHayvuird
VtHJf
»> |
narif has ? letters ii.
STEP 2 A Function takes data, usually a variable, works on rEP Python has tens oF Functions built into it, Far too
4
_ W it depending on what the Function is programmed many to get into in the limited space available here.
to do and returns the end value. The data being worked on goes However, to view the list oF built-in Functions available to Python 3,
inside the brackets, so if you wanted to know how many letters navigate to www.docs.python.org/3/library/Functions.html. These
are in the word antidisestablishmentarianism, then you'd enter: are the predeFined Functions, butsince users have created many
len(“antidisestablishmentarianism”)and the number 28 more, theyfe not the only ones available.
would return.
»—* lyl
^ Additional Functions can be added to Python To use a Function From a module enter the name oF
STEP5 STEP6
_W through modules. Python has a vast range oF _ W the module Followed by a Full stop, then the name
modules available that can cover numerous programming duties. oF the Function. For instance, using the math module, since you've
They add Functions and can be imported as and when required. For just imported it into Python, you can utilise the square root Function
example, to use advanced Mathematics Functions enter: To do so, enter:
>»
Enter your surname: Hayward
Your name has 7 letters in it.
>>> import math
»> math*sqrt( 16)
4.0
»> 1
FORGING FUNCTIONS
There are many different functions you can import created by other Python programmers and you will undoubtedly come
across some excellent examples in the future; you can also create your own with the def command.
STEP1 Choose File > New File to enter the editor, let's STEP3 To modify it further, delete the Hello("David") line,
create a function called Helio, that greets a user. the last line in the script and press Ctrl+S to save
the new script. Close the Editor and create a new File (File > New
File). Enter the Following:
def HelloQ:
print (“Helio” from Helio import Helio
Hello(“David”)
ve and run the script. You can see Helio in the Shell, Press F5 to save and execute the code.
in HelloO and it returns the new Function.
on 3.4.2 Shell - a x testpy ■ /nome. pi/Documents/tes
£dt Shel £sebug £)ptions Windows Jje-lp Ei le |=dt Fgrmst Sun Qptions yfmdowE tdelp
Python 3.4 2 Shell _ D X
HeSIo.py ■ /horrie/pi/Documents/IH< python 3.4.2 (default, Oct 19 2014, I3:3l:llj 11 311 Helio uni 01 t Helio
File Edit Ehej Debug Oplions Windows Help Fife Edit Firmat Sun flptions Windows Jdelp [&CC 4.9.11 on linuK
Type '■Copyright1', "crediti^ or "licenseQ" for «ore informat ion. HelIo( Qa*id")
python 3.4.2 (defuit. oct 19 2014. 13= 3»:11 > def HelloQ:
[GCC 4.5.1} on limui print ( "Helio”) >>>
Type "copyrighc". "crediis" cr "iieensef)M foi «ore Information, Helio David
»> Trann7imDirmiiTTTBr7Ti:iTXTnir S T ARTiFTXBXixuBxxxnBFXi
Hello{)
»>
Helio
4
»> HelloQ
Helio
»> \
Let's now expand the Function to accept a STEP4 Whatyou've just done is import the Helio Function
STEP2
variable, the user’s name for example. Edit your From the saved Hello.py program and then used it
to read: to say hello to David. This is how modules and Functions work: you
W import the module then use the Function. Try this one, and modify
ef Hello(name):
it For extra credit:
rint (“Helio”, name)
Hello(“David”) , b):
resuit = a + b
This will now accept the variable name, otherwise it prints Helio
return resuit
David. In the Shell, enter: name=("Bob,,)) then: Hello(name). Your
r
www.bdmpublications.com The Python Manual 41
L
Getting Started with Python
Conditions and loops are what makes a program interesting; they can be simple or
rather complex. Howyou use them depends greatly on what the program is trying to
achieve; they could be the number of lives left in a game orjust displaying a countdown.
TRUE CONDITIONS
Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let's start then by checking
if something is TRUE, then doing something else if it isn't.
* *
LetJs create a new Python program that will ask Now you can use an iP statement to check iP the
STEP1 STEP3
the user to input a word, then check it to see iP it's wordjength variable is equal to Pour and print a
a Pour-letter word or not. Start with File > New File, and begin with Priendly conPormation iP it applies to the rule:
the input variable:
word=input(“Please enter a four-letter word: “)
word=input(“Please enter a four-letter word: “) word_length=len(word)
if word_length == 4:
File Edit Shell Debug Options
Python 3.4.2 Shei
Windows Help
_ C X
word=input("Please en
word_Iength*len(Aord)
Yvo rd_length == 4:
print (word, is
/
Ln: 4 Cdl: 4
# •
Now we can create a new variable, then use the len The colon at the end oP IF telis Python that iP this
STEP2
W Punction and pass the word variable through it to W statement is true do everything aPter the colon
get the total number oP letters the user has just entered: that's indented. Next, move the cursor back to the beginning oP
the Editor:
word=input(“Please enter a four-letter word: “)
word_length=len(word) word=input(“Please enter a four-letter word: “)
word_Length=len(word)
msu if word_length == 4:
File Edit Mormat Run Options Windows Help print (word, “is a four-letter word. Well
OU
word=input(“Pleas*i pnipr
word_length“len(word)
P i word: ")
done.”)
else:
print (word, “is not a four-letter word.”)
word=input(,,Please en d
wo rd_length^len(vsord)
if word_length == 4:
print (word, 'is ip rd. done. if}
i »i l,i" _ i I
'rJrfwMJrffjFjFJF
Let's start with a simple While statement. Like IF, The For
=or loop
op is an
onn another example. For is used to
STEP1 STEP3 YY j
C I UI IU
this will check to see iF something is TRUE, then run loop over a range oF data, usually a list stored as
m hrarkpK Fnrpxamnlp*
ifp
the indented code: ckets. For e>
1.^
ple:
//////
////.
x r, i ^///
Ix = X + 1 t / / J j? Jr Jr w f Jr j j J / wjr^jr
J jr j" . '
loopl py - /home/pi/Oocun
Si
*Untitled* Fiie £dft Shell Qehug fiptions Windows Help File Edr F^rmai fiyn £{ptbons Windows Help
Pythor. 3.4.2 (default, oct 19 2Q14, I3:3li11) words* rirCaf , ''Dog''* "Uniearn”]
Eile Edit firmat Rm SPfons Windows belp [GCC J.9.1) on linu*
Type “Copyright"t ^credits" or "iLcense(}" for more Information, fnr word 1 words:
================================ RESTART : print (word)
x»1 »>
1
.vh 1 i x<10:
3
2
print (x) 4
x=x+1 6
5
7
0
9
Cat
Oog
Unicom
>»
jr Jr f JF jjT
//j
STEP2 The diFFerence between iP and while is when while STEP4 The For loop can also be use
gets to the end oP the indented code, it goes back example by using the range
and checks the statement is stili true. In our example x is less than rYffjrJ
J* M' JF Jr .
/YY
for x in range (1, 10)
10. With each loop it prints the current value oP x, then adds one to WJF. Y Y Jr A
JF Y Y Jr Y
YYYYJ
print (x) y///////////
rYYYYj
J JJ 4
We've mentioned modules previously, (the Math module) but as modules are such a
large part of getting the most from Python, it's worth dedicating a little more time to
them. In this instance we're using the Windows version of Python 3.
MASTERING MODULES
Think of modules as an extension that's imported into your Python code to enhance and extend its capabilities, There are
countless modules available and as we've seen, you can even make your own.
STEP1 Although good, the built-in functions within Python The resuit is an error in the IDLE Shell, as the
STEP3
are limited The use of modules, however, allows us _ W pygame module isn't recognised or installed in
to make more sophisticated programs. As you are aware, modules Python. To install a module we can use PIP (Pip Installs Packages).
are Python Scripts that are imported, such as import math. Close down the IDLE Shell and drop into a command prompt or
Terminal session. At an elevated admin command prompt, enter:
Ll Python 3.6.2 Shell - □ )
file Edit Shell Debug Options VVindow Help pip install pygame
Python 3,6-2 (v3.6,2:5fd33b5, Jul 8 2017f 04:14:34) [MSC v.lSOO 32 bit (Intel)]
on win32
Type "Copyright"f "credits" or ttlicense()" for more information.
»> import math
»>
Some modules, especially on the Raspberry Pi, STEP4 The PIP installation requires an elevated status
STEP2
_ W are included by default, the math module being a _ W due it installing components at different locations.
prime example. Sadly, other modules aren't always available. A good Windows users can search for CMD via the Start button and right-
example on non-Pi platforms is the pygame module, which contains click the resuit then click Run as Administrator. Linux and Mac users
many functions to help create games. Try: import pygame. can use the Sudo command, with sudo pip install package.
Close the command prompt or Terminal and STEP8 Multiple modules can be imported within your code.
STEP5
_W relaunch the IDLE Shell. When you now enter: A To extend our example, use:
import pygame, the module will be imported into the code
import random
without any problems. You'll find that most code downloaded or
import math
copied From the internet will contain a module, mainstream of
unique, these are usually the source of errors in execution due to for I in range(5):
them being missing. printfrandom.randint(l, 25))
print(math.pi)
File Edit Shell Debug Options VVindow Help
Python 3 6.1 . (v3.€.2:5fd33b5r Jui 8 2GI7, 04:14:34) [MSC V.19G0 32 bit (Intel)]
on win32
File Edit Format Run Options Window Help
Type * Copyright14, ttcreditsn or "license () for more Information.
» > impor t p ygame impcrt random
print[math *pi)
The modules contain the extra code needed to STEP9 The resuit is a string of random numbers followed
STEP6
achieve a certain resuit within your own code, as _W by the value of Pi as pulled from the math module
weve previously experimented with. For example: using the print(math.pi) function. You can also pull in certain
functions from a module by using the from and import commands,
import random
such as:
Brings in the code from the random number generator module. You
from random import randint
can then use this module to create something like:
for i in range(5):
for i in range(10):
print(randint(i, 25))
print(random.randint(l, 25))
l*
\Jfc ‘Untitled' Edit r*
Kor mat Run
File Options Window Help
File Edit Format Run Options Window Help
random inr jzz randint
import random
i m range(5) :
for i ir. range(lG): print(randint(1, 25))
print(random.randint(1, 25))
STEP7 This code, when saved and executed, will display ten This helps create a more streamlined approach to
STEP 10
_ W random numbers from 1 to 25. You can play around programming. You can also use import module*,
with the code to display more or less, and from a great or lesser which will import everything defined within the named module.
range. For example: However, it's often regarded as a waste of resources but it works
nonetheless. Finally, modules can be imported as aliases:
import random
import math as m
for i in range(25):
print(random.randint(l, 100)) print(m.pi)
L* men ri. da'. i ents/ P^+h on/Rn d Ny mber, p\ Of course, adding comments helps to teli others what's going on.
File Edrt Shell Pebyg Options Wmdc-w Help F»le Edit Format Run Options- Window Help
... random
E-EST “.F.T i G: / Use r a / davi d/ Do c nt a / F ythcn/ Rzid Suinfce r . py
14
21
f•: i i rango (25) :
p r int (random. r an di!i t (1, i 0 0) )
L* *Rnd Number.py - G/Users/david/Documents/Python/Rnd Number.py (3.6.2)* — □ X
3
17 File Edit Format Run Options Window Help
4 import math as m
A
5
10 print(m.pi)
13
>»
----------- RESTART : C i /User s/dayid/DoctiiiMSlita/Fytlloo/Kfltd Nutnber . joy
26
11
17
65
37
52
37
35
59
54
42
48
96
28_
It goes without saying thatyou'll eventually come across an error in your code, where
Python declares it's not able to continue due to something being missed out, wrong or
simply unknown. Being able to identify these errors makes fora good programmer.
DEBUGGING
Errors in code are called bugs and are perfectly normal. They can often be easily rectified with a little patience. The important
thing is to keep looking, experimenting and testing. Eventually your code will be bug free.
• • * *
STEP1 Code isn't as Pluid as the written word, no matter ThankPully Python is helpful when it comes to
STEP3
_ W how good the programming language is. Python is displaying error messages. When you receive an
certainly easier than most languages but even it is prone to some error, in red text Prom the IDLE Shell, it will dePine the error itselP
annoying bugs. The most common are typos by the user and whilst along with the line number where the error has occurred. Whilst in
easy to Pind in simple dozen-line code, imagine having to debug the IDLE Editor this is a little daunting Por lots oP code; text editors
multi-thousand line code. help by including line numbering.
■
File fidit Shell Qebug Qptions Windows Help £ite £dit Firmat gun Jfltfndows HeJp
* # *
The most common oP errors is the typo, as we've STEP4 Syntax errors are probably the second most
STEP2
_ W mentioned. The typos are oPten at the command _ W common errors you'll come across as a programmer.
level: mistyping the print command Por example. However, they also Even iP the spelling is correct, the actual command itselP is wrong.
occur when you have numerous variables, ali oP which have lengthy In Python 3 this oPten occurs when Python 2 syntaxes are applied.
names. The best advice is to simply go through the code and check The most annoying oP these is the print Punction. In Python 3 we use
yourspelling. printl^ordO, whereas Python2 uses print "words".
=*A\ M .
* „ «T. Y * \ * **' v v, } * -I * l,«J , 1
r \ ,,'J LC J.J 1 -i' 'j f:A
■IhI
reference = { prlrtt "ij r.at a wai'd.";i
5:-5E4i fiir*
wWd
tdit code | Ljvl1 uiujjr.jiriin^ig wgrdLl*ngtH *
KWTld'
else:
There are thousands oF online Python resources, STEP9 Planning makes For good code. Whilst a little old
STEP6
_W code snippets and lengthy discussions across Forums _W school, it's a good habit to plan what your code
on how best to achieve something. Whilst 99 per cent oF it is good will do beFore sitting down to type it out. List the variables that wi
code, don't always be lured into copying and pasting random code be used and the modules too; then write out a script For any user
into your editor. More oFten than not, it won't work and the worst interaction oroutputs.
part is thatyou haven't learnt anything.
try:
some_code()
except x
cleanup()
The problem with a bare except is that \t will catch ait exceptions, including ones you really
dont want to be ignoring (like Keyboardlnterrupt and SystemExit). It would be much betxer if
true false
your except block only caught the speclfsc exception you expect, and let ali others bubble up
as normaI.
STEP7 Indents are a nasty part oF Python programming Purely out oF interest, the word debugging in
STEP 10
that a lot oF beginners Fall Foul oF. Recall the IF loop computing terms comes From Admiral Grace
From the Conditions and Loops section, where the colon means Hopper, who back in the '40s was working on a monolithic Harvard
everything indented Following the statement is to be executed as Mark II electromechanical computer. According to legend Hopper
long as it's true? Missing the indent, or having too much oF indent, Found a moth stuck in a relay, thus stopping the system From
will come back with an error. working. Removal oF the moth was hence called debugging.
55 IL
RlAjI
ns in ,e pa o ■K
■
M« h 71 iWl
PLAYING WITH Pl
For this example we're going to create a program that wiU calculate the value of Pi to a set number oP decimal places, as
described by the user. It combines much oP what weVe learnt, and a little more.
STEP1 Start by opening Python and creating a New File in STEP4 The previous step defines the rules that make
_ W the Editor. First we need to get hold of an equation _W up the algorithm and creates the string that will
that can accurately calculate Pi without rendering the computeds eventually display the value of Pi, according the Chudnovsky
CPU useless for several minutes. The recommended calculation brothers' algorithm. You have no doubt already surmised that it
used in such circumstances is the Chudnovsky Algorithm, you would be handy to actually output the value of Pi to the screen. To
can find more information about it at en.wikipedia.org/wiki/ rectify that you can add:
Chudnovskyalgorithm.
print(calc(l))
STEP3 Nowyou can insert the Pi calculation algorithm numberofdigits = int(input(“please enter the
_ W part of the code. This is a version of the number of decimal place to calculate Pi to: “))
Chudnovsky Algorithm: getcontextQ.prec = numberofdigits
def calc(n): £*t Firmat fluft Qpt«onj
—*
*CalcPi.
t = Decimal(0) -, i «lia un.il
deno = Decimal(0) k ;n r n) ;
X - (P4C il«t 1 < -1 ]*fhh . *«t&r 1 (Dtc Uh 1 ffl K) >* < 13591 40»+ 545 i 40t34+k J
duria ■ Siath. jatiariJllf 3+kJ* (Mth. fietar ial(k)++Dt-C i*al<3))+(64Cl32a*'*f.3*k) )
pi *- Deeima-Lft)/Decimal(deno)
numberofdigits = int(input("please entei th uvn I Icuiate ))
getcontextQ .pret = numberofdigits
k - 0
pi - pi * DecimaI{12)/Decimal(640320*+Decjjnal(1,5J>
pi = I/pi
r ■ n.r str(pij
pi = 1/pi
refurn str(pi)
EP 7 ^ You can execute the code now and it asks the user STEP9 Now we need to import the colorama module
W how many decimal places they want to calculate Pi (which will output text in different colours) along
to, outputting the resuit in the !DLE Shell. Try it with 1000 places with the Fore function (which dictates the foreground, ink, colour)
but don't go too high or else yourcomputer will be locked up in and the time module to start a Virtual stopwatch to see how long
calculating Pi. our calculations take:
import time
STEP8 Part of programming is import colorama
_W being able to modify code, from colorama import Fore
making it more presentable. Let's include ■i
13872723252284798186917184867353096708222303615292971732815423261495480206046405
35398750760139733285849996526642119020066783578725502635682724402886356888437352
88982506842338309905740013758327701784908891322958527973601013169595019458889349
44236412539394146530738483636665042264154387773376017707109142428744379717832620 File Edit Tabs Help
33721044052592738923786964883764463574460244839242316267458666952279157823643188 i*»ra: pber rypi: /DnriM^rit^/Pvthon 1 pytho n3 CalcPi.p
34956170648852260770217962185905198741140188951966612315753706167429421120955210 p r r n p number of decimal p 1 "h : 9 ■5 10 C alculate Pi
45317853525104446927986692358116127392886 py | j t/ UDD*•?UO»7*■
k/i i jPn /t r“ rv/\Q jT £" /“ “1
'265358973421 0940165
D[31m
17347469689 1 j? O* di O 0622310
Time taken: 5.99211573600769 178531253056! 1 54 E 102274587627; 1813 _p 17 iflon
_r _■._
>»
:41 129S80883 33661968071! 6926509'
'96061 4 70662 J4-)Z£.4D l 3 I -A — -ftiKJ193032786877!
“3 Qg nj TQ'17 1 1
__ D irotjoy 1559636358934008194713810116 8487 05 96257'
10
MMA 1./ QGC464G
Ln: 14 Coi: 4 T 8691 1096708222303615
h1 19020066783578 CPO ,0715
0194 ^3B89i34
0 • 1783262
■ j [gQ24 12 ■f ■T"7JT r j ~f f c
W#-- | I 3 / s -? / n *-! 4211 20955211
52 Lists
54 Tuples
56 Dictionaries
58 Splitting and Joining Strings
60
r
Formatting Strings
mipriiimiimiipmirriutmiBmiiriiJirmtmiirmirmitmi(riuprmif mtmiin iiipriurrrniriiiirriiir FiiirmiriiiiiriiiimiirMiirtiiirriiimiirrinrriii
STEP A list is a sequence of data values called items. You ^ You can also access, or indexr the last item in a list by
1 STEP 3
W create the name of your list followed by an equals using the minus sign before the item number [-1],
sign, then square brackets and the items separated by commas; or the second to last item with [-2] and so on. Trying to reference an
note that strings use quotes: item that isnt in the list, such as [10] will return an error:
• • i t t t
Once you've defined your list you can call each STEP Slicing is similar to indexing but you can retrieve
STEP 2 4
by referencing its name, followed by a number. Lists _ W multiple items in a list by separating item numbers
start the First item entry as 0, followed by 1,2, 3 and so on. with a colon. For example:
Forexample:
numbers[1:3]
numbers
Will output the 4 and 7, being item numbers 1 and 2. Note that the
To call up the entire contents of the list. returned values don't include the second index position (as you
would numbers[1:3] to return 4, 7 and 21).
numbers[3]
'|_ u wv i i j i i j vii Ji n iu n
Items can be added to a list by entering: STEP9 You also use the list Punction to break a string down
STEP6
into its components. For example:
numbers=numbers+[201]
list(“David”)
Or Porstrings:
Breaks the name David into 'D', 'a', V, T, 'd'. This can then be passed
mythi cal_creatres=mythical_creatures+[“Griffin”]
to a new list:
Or by using the append Punction:
name=list(“David Hayward”)
mythical_creatures.append(“Nessie”) name
numbers.append(278) age=[44]
user = name + age
>>> numbers = [1, 4, 7, 21, 98, 156]
»> mythical_creatures ■ ["Unicorn", "Balrog", "Vampire", "Dragon", "Minotaur"] user
>>> numbers
[1, 4, 7, 21, 98, 156]
>>> mythical_creatures “ *" ■* r”3 *r ' ** r
[‘Unicom* , 'Balrog*, 'Vampire', 'Dragon4, 'Minotaur'] Python 3.4.2 (default, Oct 19 2014, 13:31:11)
>>> numbers=nLiiibers+I20i} [GCC 4,9,1] on Iinux
>» numbers Type "Copyright", "credits" or "licenset)” for more information.
[1, 4, 7, 21, 98, 156, 201] »> list("Oavid")
>» mythical_creatures«riythical_creatures+ [ f,Grif in ] ror, fa\ 'v*, * i', 'd*]
>» mythical^creatures >>> name=lisT( Da Ha, ird )
['Unicom*, 1Balrog', 'Vampire1, 'Dragon*, 'Minotaur*, 'Griffin*] >>> name
>>> mythical_creatures,append( riessie") [* D‘, ‘a*, 'v1, 'iv, 'd*, * ‘H1, 'a', 'y', 'w*, 'a', 'r*, 'd']
>» mythical_creatures >» age* [44]
[‘Unicom*, ‘Balrog*, 'Vampire*, ‘Dragon*, 'Minotaur*, 'Griffin1, ‘Hessie*] >>> user = name ♦ age
>» numbers,append(278)
>>> user
>>> numbers
['D', *a\ v', 'i', *d'P * *, ‘H*, #ap, ‘y1, ‘w4, ‘a\ ‘r*, *d', 44]
[1, 4. 7, 21, 98, 156, 201, 278] >>>
>>>
STEP 7 ] Removal oP items can be done in two ways. The First Based on that, you can create a program to store
is by the item number: someoneJs name and age as a list:
Tuples are very much identical to lists. However, where lists can be updated, deleted or
changed in some way, a tuple remains a constant. This is called immutable and theyYe
perPect for storing fixed data items.
STEP1 A tuple is created the same way as a list but in this ^ You can create grouped tuples into lists that contain
STEP3
_W instance you use curved brackets instead oP square W multiple sets oP data. For instance, here is a tuple
brackets. For example: called NPC (Non-Playable Characters) containing the character name
and their combat rating Por an adventure game:
months=(“January”, “February”, “March”, “April”,
“May”, “June”) NPC=[(“Conan”, 100), (“Belit”, 80), (“Valeria”,
months 95)]
File Edit Shell Eebug Qptions Windows Help £ile £dit Shell Qebug Qptions Windows Help
Python 3*4*2 (default, Oct 19 2014* 13:31s11) Python 3.4.2 (default, Oct 19 2014. 13:31:11) n*
[GCC 4*9.1] on Linux [GCC 4.9.1) on linux
Type "Copyright", "credits" or "licensef)" for more Information* Type "Copyright”, "credits" or Mlicense()" for more information
»> months-C ** Janua ry’\ ‘'February*', "March“f "April"» "May**, "June1’) »> NPC=t("Conan",100), ("Belit". 80). ("Valeria-. 95)]
>» months >» |
('January1, ‘February1, 'March*, ‘April1, ‘May1, ‘June*)
»> I
Just as with lists, the items within a named tuple can P4 Each oP these data items can be accessed as a
STEP2
be indexed according to their position in the data whole by entering NPC into the Shell; or they can be
range, i.e.: indexed according to their position NPC[0]. You can also index the
individual tuples within the NPC list:
months[0]
months[5] NPC[0] [1]
However, any attempt at deleting or adding to the tuple will resuit Will display 100.
in an error in the Shell.
It's worth noting thatwhen referencing multiple Now unpack the tuple into two
W tuples within a List, the indexing is slightly different corresponding variables:
from the norm. You would expect the 95 combat rating of the
(name, combat_rating)-NPC
character Valeria to be NPC[4][5], but it's not. It's actually:
You can now check the values by entering name and combat_rating.
NPC[2] [1]
i 1 i
************************************************ • * *
This means of course that the indexing Follows thus: Remember, as with lists, you can also index tuples
STEP6 STEP9
using negative numbers which count backwards
0 i, i
from the end of the data list. For our example, using the tuple with
0, 0 2
multiple data items, you would reference the Valeria character with;
0, 1 2, 0
1 2,1 NPC[2][-0]
1, 0
? V. i r* * )•->
ii „
«Edil
Which as you can imagine, gets a little confusing when youve got a
File Edit Shell Debug Options Windows Help
lot of tuple data to deal with. Python 3,4*2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9*1] on linux
Type "copy right". Type "Copyright", "credits" or "licenseO” for more information*
>>> IIPC*l( "Conan" 100), ("Belit", 80). ( die 95)] »> IIPC-[("Conan1'V, 100), ("Belit", 80), ("Valeria", 95)]
»> IIPC[0 ] »> IIPC [2] [ -0]
(* Conan** 100) 1Valeria"
>» NPC[0] [0] »>
'Cor an"
>>> IIPC[0] [1]
100
>>> IIPC [ 1 ]
('8e lit*, 80)
>>> MPC[1 ] [0]
'Bel It1
>>> MPCfl] [1]
30
>» llPCf 2]
CVa leria1 , 95)
>>> IIPC [2] [0]
'Val er ia'
>>> IIPC [2] [1]
95
1
STEP7 Tuples though utilise a feature called unpacking, ^ You can use the max and min functions to find the
STEP 10
_ W where the data items stored within a tuple are highest and lowest values of a tuple composed of
assigned variables. First create the tuple with two items (name and numbers. For example:
combat rating):
numbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99)
NPC=C“Conan”> 100)
The numbers can be integers and floats. To output the highest and
lowest, use:
Ii
KEY PAIRS
A dictionary is Like a list but instead each data item comes as a pair, these are known as Key and Value. The Key part must be
unique and can either be a number or string whereas the Value can be any data item you like.
* *
STEP1 LetJs say you want to create a phonebook in Python As with lists and tuples, you can check the contents
STEP3
You would create the dictionary name and enter _W of a dictionary by giving the dictionary a name:
the data in curly brackets, separating the key and value by a colon Phonebook, in this example. This will display the data items you've
Key: Value. For example: entered in a similar Pashion to a list, which youYe no doubt Pamiliar
with by now.
phonebook={“Emma”: 1234, “Daniel”: 3456, “Hannah”:
6789}
File Edit Shell Debug Options Windows Help
Python 3,4.2 (default, Oct 19 2014, 13:31:11)
i
[GCC 4.9,1J on linux
Type "Copyright”. "credits" or "licenset)" for more Information
>» phonebook-{: 1234, "Daniel": 3456, ‘Hannah": 6789}
»> phonebook2*{"David": "0987 654 321“}
»> phonebook
{'Hannah*: 6789, *Enfima*: 1234, 'Daniel1: 3456)
»> i
• •
“ Just as with most lists, tuples and so on, strings STEP4 The benefit of using a dictionary is thatyou
STEP2
need be enclosed in quotes (single or double), can enter the key to index the value. Using the
whilst integers can be left open. Remember that the value can be phonebook example from the previous steps, you can enter:
either a string or an integer, you just need to enclose the relevant
phonebook[“Emma”]
one in quotes:
phonebook[“Hannah”]
phonebook2={“David”: “0987 654 321”}
■I . w , i _T _
Adding to a dictionary is easy too. You can include Next, you need to detine the user inputs and
STEP8
a new data item entry by adding the new key and _ W variables: one tor the person's name, the other
value items like: For their phone number (let's keep it simple to avoid lengthy
Python code):
phonebook[“David”] = “0987 654 321”
Phonebook name-input(“Enter name: “)
number=int(input(“Enter phone number: “))
phonebo0k={} 13
name*input(Enter name: )
nimber*int( input( Enter phone number : ))
You can also remove items trom a dictionary by STEP9 Note we've kept the number as an integer instead
STEP6
_ W issuing the dei command followed by the item's _W ot a string, even though the value can be both
key; the value will be removed as well, since both work as a pair ot an integer or a string. Nowyou need to add the user's inputted
data items: variables to the newly created blank dictionary. Using the same
process as in Step 5, you can enter:
dei phonebook[“David”]
Phonebook[name] = number
phonebCK>k={ >
name=input( E i er name: )
nimber® int( input( "Enter phone nimber; "))
phonebook[nane] - number
STEP 7 Taking this a step Further, how about creating a Now when you save and execute the code, Python
STEP 10
_ W piece oF code that will ask the user For the dictionary will ask For a name and a number. It will then insert
key and value items? Create a new Editor instance and start by those entries into the phonebook dictionary, which you can test by
coding in a new, blank dictionary: entering into the Shell:
phonebook={} phonebook
phonebook[“David”]
PvT ion c A _ ;^hei _ o X
File Edit Shejl Debug Options Windows Help File Edit Format Run IF the number needs to contain spaces you need to make it a string,
Python 3,4*2 (default, Oct \9 2014, 13:3iTiT)
|GOC 4.9.1} on linux
phonebook^{>
so remove the int part oF the input.
Type "Copyright", ■‘credits" or "licenseO" for more information,
>»
»>
Enter name: David
Enter phone number; 09S76
>» phonebook
{'David'; 9876}
>» phonebookl - . id"j
9876
>» =============================== restart ================
>»
Enter name:
!*» ... RESTART ...
»>
Enter name: Bob
Enter phone nunber: 0937 654 3321 3344
»> phonebook
i'0987 654 3321 3344’]}
»>
Splitting and
Joinina Strinas
When dealing with data in Python, especially from a useFs input, you will undoubtedly
come across long sets of strings. A useful skill to learn in Python programming is being
able to split those long strings for better readability.
STRING THEORIES
You've already looked at some list Punctions, using .insert, .remove, and .pop but there are also Punctions that can be applied
to strings.
STEP1 The main tool in the string Function arsenal is .split(). Note that the text.split part has the brackets,
STEP3
_W With ityouYe able to split apart a string of data, _W quotes, then a space followed by closing quotes
based on the argument within the brackets. For example, here's a and brackets. The space is the separator, indicating that each list
string with three items, each separated by a space: item entry is separated by a space. Likewise, CSV (Comma Separated
Value) content has a comma, so you'd use:
text-”Dcmiel Hannah Emma”
text=”January,February,March,April,May,June”
months=text.split(“,”)
months
* * * ***#*#■**•***** #*##**#*
STEP2 Now let's turn the string into a list and split the STEP4 YouVe previously seen how you can split a string
W content accordingly: into individual letters as a list, using a name:
names=text.split(“ “) name=list(“David”)
name
Then enter the name of the new list, names, to see the three items.
The returned value is 'D', 'a', V, 'i', 'd'. Whilst it may seem a little
useless under ordinary circumstances, it could be handy for creating
a spelling game for example.
Python 3*4.2 (default, Oct 19 2014, 13:31:1!)
[GCC 4,9*1) on linux
Type "copyrlght", “credits" or "license()" for more Information
»> text*”Daniel Hannah Emma '
>» names=text,split(M ) Eile Edit Shejl fiebug Qptions Windows Help
»> names
[1Ganiel* * 'Hannah** 'Emma*! Python 3,4.2 (default* Oct 19 2014* 13:31:11)
»> [GCC 4,9*1] on linux
Type "Copyright*1, "credits" or "licenseO" for more Information,
>>> nam*list( "Dav i )
>>> name
STEP6 You can thereFore apply .join to the separated name STEP 9 There's some interesting Functions you apply to a
you made in Step 4, combining the letters again to string, such as .capitalize and .title. Forexample:
Form the name;
title=”conan the cimmerian”
name=””.join(name) title.capitalizeQ
name title. titleQ
WeVejoined the string back together, and retained the listcalled
name, passing it through the .join Funetion. File Edrt Shell Debug Options Windows Help
STEP 7 A good example oF using the .join Funetion is when “ You can also use logic operators on strings,
STEP 10
you have a list oF words you want to combine into a with the 'in' and 'not in' Functions. These enable
sentence: you to check iF a string contains (or does not contain) a sequence
oFcharacters:
list=[“Conan”, “raised”, “his”, “mighty”, “sword”,
“and”, “struck”, “the”, “demon”] message-”Flave a nice day”
text=” “.join(list) “nice” in message
text
”bad” not in message
Note the space between the quotes beFore the .join Funetion (where “day” not in message
there were no quotes in Step 6's .join). “night” in message
£ile £dit Shell Qebug Qptions Windows Help File Edit She|l Debug Options Windows Help
Python 3.4.2 (default, Oct \9 2014, 13:31:11) Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4,9.1] on linux
Type "Copyright", '*credits,r or "licenseC)” for more Information, [GCC 4.9.1] on linux
»> list=["Conan", "raised'1, "his", 'Mighty", "sword", "and", "struck1", "the", "demon"] Type “Copyright", "credits" or "licenseC)” for more Information.
>» text-" '.join(list) »> message-‘Have a nice day"
»> text
'Conan raised his mighty sword and struck the demon* »> "nr e' in message
>» 1 T rue
»> "bad1 not in message
T rue
»> day1’ nor r message
False
»> "night" m message
False
»>
STRING FORMATTING
Since Python 3, string formatting has become a much neater process, using the .format function combined with curly brackets.
It's a more logical and better formed approach than previous versions.
STEP1 The basic Formatting in Python is to call each You can oF course also include integers into the mix:
STEP3
variable into the string using the curly brackets:
numbe r=10000
name=”Conan” print(“{} of {} was a skilled mercenary,
print(“The barbariem hero of the Hyborian Age is: and thief too. He once stole {} gold from a
{}”.format(name)) merchant.”.formatCname, place, number))
£ile £drt Shell Qebug Qptions Windows Help Python 3.4.2 (default7 Oct 19 2QT4. 13:31:11)
[GCC 4.9.11 on linux
Type "Copyright", "credits" or "license()" for more Information.
Python 3.4.2 {default, Oct 19 2014, 13:31:11)
>» name- ‘Conan"
[GCC 4*9.1] on linux
i
»> place-“X i-unet ia'k
Type "Copyright"’r "credits” or "license()” for more Information. >» print < ‘ ■! } i a i ed from the I- r t h ir a cold lat d kn ■ i as -! >■". format (naine, place))
Conan hailed from the Morth, in a cold land knorm as Cimmeria
»> name= 1 onan* »> number=10000
>>> print(*’The barbanan hero of the Hyborian Age is: {>"*format(nanie)) >» print("{} of {) was a skilled mercenary, and theif tgo, He once Stole {} gold from a merchant. forfiat (name. p
The barbanan hero of the Hyborian Age is: Conan lace, number))
Conan of Cimmeria was a skilled mercenary, and theif too. Ne once stole 10000 gold from a merchant.
»> |
>» |
Remember to close the print Function with two sets STEP4 There are many diFferent ways to apply string
STEP2
_W oF brackets, as you Ve encased the variable in one, _W Formatting, some are quite simple, as weVe shown
and the print Function in another. You can include multiple cases oF you here; others can be signiFicantly more complex. It all depends
string Formatting in a single print Function: on what you want From your program. A good place to reFerence
Frequently regarding string Formatting is the Python Docs webpage,
name=”ConanM
Found at www.docs.python.org/3.1/library/string.html. Here, you
place=MCimmeria”
will Find tonsoF help.
print(“{} hailed from the North, iii a cold land
known as {}”.formatCname, place)) |m Nrtp*y/rtw,
■ ™- ;. r: 11, j-mply colis- th* giQfcal fr ,■ bwiMr, 7hp mffthod i* provujfd » SUtldlMH cen Wffmde rt
Cwiv*rb vfrue (rtturnAd By a w$tgs» type(4$ m hesymed by ne methodi The deEfigfl vffston u-Klwstonds 'r (topf? 4rtd $ Cs<r>convefMJf
r>.. 3 i i t f .T *■ n^t- in nnr a i3.si.in -r Format 5ln?tgs comam ‘repiatspvpnt fietis surounded Evy curty braces u Anytofig Ihat s not comaiwd ir» braces iscowderefl iterat teU whch js copieti unchenoed lo the ousput H you need to mciude a brace cha^cter in ma
tiurolwn t can t» astaped bvttoit«h5 u And ::
[GCC 4.9.11 on linux
Type "Copyright”, "credits" or "licenseO" for more Information. The g-mmmiir far a noplacameot ft a? tatows
»
■
■
fi■
I
m^vrvl wv
n
The iiuki rtirntt ri^ell beK|im mlh MM llw: IS .nlhfir 4 ilunilbei W 4 huyurord ir 4 maiibe'. d leltrS to A fVMrorilri aniunmil 40d rf rt'S 4 jtuyiuxd I retof^ to 4 rumdd k^ywunj Amjijiiii+-iS :r fl4 Bluilwr*,idl 4nj niinitrti
m a tormal ^[-mg ora 0 12 in faq-iarca may Lar. ed ha orrutlact niul; pj^.1 «domi and tne fiumbari 0 t.i -.mII i* i»j(onia1iC4lly irt$#1ad m IhoE prdi( Tla» vft^nantft can tta fixicnvuil by any numbar of 'iffla or altnbgla
flJtprattioni AnesftfWiOnotlhalbffnglacia tna namsd affiriboC* Lfiang . whi* an aiipraa^on Iha fe)«n -[1^.1' dtnes an mdt* todcup uanig j.
cnflf lom1 jn veriajn 3 J. The posrtional arijumafli %pecir«fi canOeomuladiso-ti ir fi sqdiM lo--{-o- \ l j ■,
The cofwersion teid cbutcbs a type coernon bertore formati,ng ttormallp toejob oJ formabng a va'ue is dono by #io : . ■ method of If» value Isclf Howovai n sono cases 1 is dosvablo to floree a typo Io be Fonnattod as <t
fling ovemd-ng iis ovm deflinitKm ol tormatting EJy oonnaning the va%re lo a jlnng betore calllng , ffve narmfll IgmiAtHng Jpgt is Bypwwd
Ttinae convaisior’ (lays are curtenfUy suppOrted ■ * .■ whnih Callt jtr i on the ¥aluo ' r* whic.fi uiH c i i 4<id ■ -«' mrlich c j: Is ej :xi , i
EP 5 Interestingly you can reference a list using the string You can also print out the content oF a user's input
STEP8
W Formatting Function. You need to place an asterisk in in the same Fashion:
Front oF the list name:
name-input(“What,s your name? “)
numbers=l, 3, 45, 567546, 3425346345 print(“Hello {}. ”.format(name)
print(“Some numbers: {}, {}, {}, {}, {}”.
format(*numbers)) file Edt Shie^l Cebug ^pC=on&
■ liu i jtiTH if.
ij^nd&ws Help
KAfi ii
Ns £dit Farm at gun
tC£ln3
Qptjons
pv
Windows,
ornp
Halfi
TP5
Python .3. .1.2 (default. Det 19 2014. 13:31 i 11) nine-irpjtO ats your narat? )
IGCC 4.9,1] on 1-IPux pr int(" He 1 . f g nuat {narae))
Type "Copyright". ‘,kcredit&" pr "licen-sef)" for morp informatipn.
>» RESTART ===================
»>
Whafs your name? David
Helio
■ile £d(t Shell Qebug fiptions Windows tJelp >» l
Python 3*4*2 {default, Oct 19 2014, 13:31:11)
(GCC 4*9*1) on linux
Type "Copyright**, "credits" or wlicer»se()w for more Information
>» numbers=1* 3* 45. 567546, 3425346345
>>> print( Soine numbers: {}, {), {>, {} , {}".format{*numbers))
Some numbers: 1* 3* 45, 567546, 3425346345
>»
i Ln: B coi: 4
With indexing in lists, the same applies to calling a STEP9 You can extend this simple code example to display
STEP6
_ W list using string Formatting. You can index each item the First letter in a person's entered name:
according to its position (From 0 to however many are present):
name=input(“Whaf’s your name? “)
numbers=l, 4, 7, 9 print(“Hello {}. ”, format(name))
print(“More numbers: {3}, {0}, {2}, lname=list(name)
{1}.”.format(*numbers)) print(“The first letter of your name is a {0}”.
format(*lname))
_ □ X
File Edit Shell Debug Options Windows Help Fiif1 Edt Sheii Debug Optiom? Windows Help EU-e Edit Ffirmal Run options Windows H?!p
Python 3,4.2 {default. Oct 19 2014. 13:31:11) fian«=input( 'VJhafs you: nare? “)
Python 3.4.2 (default, Oct 19 2014, 13:31:11) [GCC 4.9.11 Drt linux pnnt( 1 . format£rame))
ln>3riie=l l •*■ £ (ri ane)
[GCC 4*9*1] on linux Type "Copyright", "credits" or "license()" for nere Information
>>> ■■*,» ■ ■ ■»» ■ ■ **-■■■**-»—*■■■ ■ ■ ■-*-»■ RESTART ■*■■■»■■■■■■■■■■■■ --------- ---- w m pnnt("The first letter of your oarne formati*Inane))
Type "Copyright1*, "credits" or " licensef)’" for more Information, >»
wtiatTs your nane? David
>>> numbers®t* 4, 7, 9 Heltg Cavid,
>>> ------------------------------ RESTART - —
>» print( ‘More numbers: {3} . { 0 } . {'} {I }, format (^numbers) ) >»
ti'hat's your nane? Conan
More numbers: 9, 1,7, 4* HcLLo Conan.
Ihp firsii letter pf ycur name ls .i C
>>>
STEP7 And as you probably suspect, you can mix strings ^ You can also call upon a pair oF lists and reFerence
STEP 10
and integers in a single list to be called in the them individually within the same print Function.
Format Function: Looking back the code From Step 7, you can alter it with:
r
www.bdmpublications.com The Python Manual 61
L
When working with data it's often handy to have access to the time. For example, you
may want to time-stamp an entry or see at what time a user logged into the system and
for how long. Luckily acquiring the date and time is easy, thanks to the Time module.
TIME LORDS
The time module contains functions that help you retrieve the current system time, reads the date from strings, formats the
time and date and much more.
* •
STEP1 First you need to import the time module. !t's one You can see the structure oP how time is presented
STEP3
that's built-in to Python 3 so you shouldn't need to by entering:
drop into a command prompt and pip install it. Once it's imported,
time.locat.time()
you can call the current time and date with a simple command:
The output is displayed as such: * time. struct_time(tm_
import time
year=2017, tm_mon=9, tm_mday=7, tm_hour=9,
time.asctimeQ
tm_min=6, tm_sec=13, tm_wday=3, tm_yday=250, tm_
isdst=0) ’; obviously dependent on your current time as opposed
to the time this book was written.
File Edit Shell Qebug Qptions Windows Help
• • i t * t
The time Punction is split into nine tuples, these are STEP4 There are numerous Punctions built into the time
STEP2
_ W divided up into indexed items, as with any other _ W module. One oP the most common oP these is
tuple, and shown in the screen shot below. .strPtimeQ. With it, youYe able to present a wide range oP arguments
as it converts the time tuple into a string. For example, to display the
current day oP the week you can use:
* * *
Note the Last two entries, with %H and %H%M, as STEP9 The output will look similar to the screenshot below.
STEP6
_ W you can see these are the hours and minutes and as _W The timer function needs to be either side oF the
the last entry indicates, entering them as %H%M doesn't display the input statement, as that's when the variable name is being created,
time correctly in the Shell. You can easily rectiFy this with: depending on how long the user took to login. The length oF time is
then displayed on the last line oF the code as the endtime variable.
time.strftime(“%H:%M”)
i v
STEP7 This means youYe going to be able to display ^ There’s a lot that can be done with the time
STEP 10
_ W either the current time or the time when s module; some oF it is quite complex too, such as
omething occurred, such as a user entering their name. Try this displaying the number oF seconds since January 1 st 1970. iFyou
ode in the Editor: want to drill down Further into the time module, then in the Shell
enter: help(time) to display the current Python version help File
import time
For the time module.
name=input(“Enter login name: “)
print(“Welcome”, name, “\d”)
. r '* -»1 j
print(“User:”, name, “logged in at”, time. Eile £dlt Shell Debug Qptions Windows Help
strftime(“%H:%M”)) Python 3.4.2 (default, Oct 19 2014, 13:31:1!)
[GGC 4.9.1] oni linux
Type "Copyright", "credits" or "Iicense()" for more Information.
„ p K
>>> import time
E,ie tdrt Shell Uebug Options Windows ttelp £ile £d(l Ffirmal Bun Qptldns aJndGmvfi yelp >» help(time)
Help on built-in module time:
NAME
time - This module provides various functions to manipulate time values.
DESCRIPTION
There are two Standard representations of time. One is the number
of seconds since the Epodi, in UTC (a.k,a * GMT), It may be an integer
or a floating point number (to represent fractions of seconds),
The Epoch is system-defined; on Unix, it is generally January Ist, 1970,
The actual value can be retneved by calling ^ntime(O).
* Start by entering some text into your systenrVs text IP you now enter poem into the Shell, you will get
STEP1 STEP3
editor. The text editor is best, not a word processor, some inPormation regarding the text Pile youVejust
as word processors include background formatting and other asked to be opened. You can now use the poem variable to read the
elements. In our example, we have the poem The Cimmerian, by contents oP the Pile:
Robert E Howard. You need to save the Pile as poem.txt.
poem. readQ
Save As - n
i Txt|
fhe Note than a /n entry in the text represents a new line, as you
| File Edit S&arch Qptions Help_
iV pi Do cu merus Create Foldef
11 renember used previously.
The dark woods, masking slopes of s<
The grey clouds.' leaden everlasting
The dusky streams that flowed withoi
And the Ione winds that whispered di
^ You use the open() Punction to pass the Pile into a ^ IP you enter poem.readQ a second time you will
STEP2 STEP4
_W variable as an object. You can name the Pile object _W notice that the text has been removed Prom the Pile
anything you like, but you will need to teli Python the name and You will need to enter: poem=open(“/home/pi/Documents/
location oP the text Pile you're opening: Poem.txt”) again to recreate the Pile.This time, however, enter:
poem=open(Vhome/pi/Documents/Poem. txt”) print(poem. readQ)
This time, the /n entries are removed in Pavour oP new lines and
Python 3.4.2 Shell
readable text.
File £dit Shell Qebug Qptions Windows Help
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux Python 3 4 2 Shell
Type ‘'Copyright'’, "credits" or ‘‘license( )*’ for more Information.
Ftle Edit Shdl Debug Options Windows Help
»> poeni=open( "/home/pi/Docunients/Poefn. txt")
»> »> poem,read()
i p
EP 5Just as with lists, tuples, dictionaries and so on, Extending this Further, you can use readlinesQ to
STEP8
W youYe abie to index individual characters oF the _ W grab ali the lines oF the text and store them as
text. For example: multiple lists. These can then be stored as a variable:
I ^1
on 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4,9.1] on linux
File Edit SheH Debug Gptions Windows Help Type "Copyright**, "credits" or "license()M for more Information,
»> poem-open( 'Vhome/pi/Docunents/Poefn, txt”)
Python 3*4*2 (default* Oct 19 2014, 13:31:11)
»> lines^poem,readlines()
[GCC 4.9-1] on linux
>>> UnestO]
Type "Copyright", "credits" or "licenseO4* for more Information 11 remember\n*
>» poem-open( ■ horne/f i Docunents/Poe ti. t* t' ) >>> lines[1]
»> poem.read(S) ‘The dark woods, masking slopes of sombre hilis;\n*
* I rem r >>> lines[2]
»> poem*read(5) "The grey clouds1 leaden everlasting arch:\n"
T efnber¥ »>
»> |
l I
Similarly, you can display one line oF text at a time by You can also use the For statement to read the lines
STEP6 STEP9
using the readlineQ Function. For example; W oF text back to us:
poem=open(“/home/pi/Documents/Poem. txt”) for lines in lines:
poem. readlineO print(lines)
Will display the First line oF the text with: Since this is Python, there are other ways to produce the same output:
poem.readline() poem-open(“/home/pi/Documents/Poem.txt”)
for lines in poem:
Displaying the next line oF text once more.
print(lines)
ni < r
ILcOv
1
^ You may have guessed that you can pass the Let's imagine that you want to print the text one
STEP7 STEP 10
_ W readlineO Function into a variable, thus allowing you character at a time, like an old dot matrix printer
to call it again when needed: would. You can use the time module mixed with what youve looked
at here. Try this:
poem=open(Vhome/pi/Documents/Poem.txt”)
line^poem. readlineO import time
line poem=open(“/home/pi/Documents/Poem.txt”)
lines=poem.read()
for lines in lines:
File Edit Shell Qebug Qptlons Windows Help
print(lines, end=””)
Python 3.4.2 (default, Oct 19 2014, 13:31:11) time.sleep(.15)
[GCC 4.9.1] on linux
Type "Copyright", "credits" or "licertseO" for more Information,
>>> poem=open( \ i s/Poem* t ) The output is Fun to view, and easily incorporated into your own code.
>» lme=poem, readline()
>>> Ime
*I remember\n* _ Q K tvj;.
»H FJe £di‘ S*reJI Qebug Windows H^p Fle £dit Formas Run fiptlons Wirdoi*-T; Help
'The
The
The
dark raxfds, itaskirlg, Slopes of Sombre flills:
grey clouds' leaden everlasting: arch;
dns-ky streams ihai Tl<mtd mithout a soiind.
I lines lines;
print Mines, end-
time.sle<ip(. 15 3
'J
II
Slope beyond slope. each haoded like its broThers,
J
■
/"W
I Working with Data
& /
The ability to read external files within Python is certainly handy but writing to a file is
better stili. Using the write() function, youYe able to output the results of a program to
a file, thatyou can then read() back into Python.
Start by opening IDLE and enter the Pollowing: However, the actual text file is stili blank (you can
STEP1 STEP3
W check by opening it up). This is because you've
t=open(“/home/pi/Documents/text.
written the line oP text to the Pile object but not committed it to the
txt” ”w”)
Pile itselP. Part oP the write() Punction is thatyou need to commit the
Change the destination Prom /home/pi/Documents to your own changes to the Pile; you can do this by entering:
system. This code will create a text Pile called text.txt in write mode
t.closeQ
using the variable 't'. IP there's no Pile oP that name in the location, it
will create one. IP one already exits, it will overwrite it, so be carePul.
• • # •
^ You can now write to the text Pile using the write() |p you now open the text file with a text editor,
STEP2 STEP4
W Punction. This works opposite to read(), writing lines _ W you can see that the line you created has been
instead oP reading them. Try this: written to the Pile. This gives us the Poundation Por some interesting
possibilities: perhaps the creation oPyour own log Pile or even the
t.write(“You awake in a small, square room. A
beginning oP an adventure game.
single table stands to one side, there is a locked
door in front of you.”)
f E
£ile £dit Shell Qebug Options Wjndgws Help
Fiie Edit Search Options Help
Note the 109. It's the number oP characters youVe entered. Python 3.4.2 (default, Oct 19 2014. ~3:3l:11)
(fou awake in a snall» square i
Type 'Copyright", "credits” or "licenseO” more information. there is a locked door in fror
>» t=open( n/h-f e/pi/Doc jments/texT • t' ,pV.‘r) -
I I
impoi math
* *
You can keep extending the text line by line, Now let's create a variable called pi and assign it the
STEP6 STEP9
_W ending each with a new line (\n). When you're W value oPPi:
done, Pinish the code with LcloseQ and open the Pile in a text
pi=math.pi
editor to see the results:
You also need to create a new Pile in which to write Pi to:
t.write(“The door is made of solid oak with iron
strips. It’s bolted from the outside, locking you t=open(“/home/pi/Documents/pi.txt”,”w”)
in. You are a prisoner!An”)
Remember to change your Pile location to your own particular
t. closeQ
system setup.
Python 2 4 2 £he! _ CJ x
EHe E1^ She| Qetiyg 2p?igrr% ]Wir dpws Hflip
Pythan 3.4.2 {defaull, Oct 19 2014. 13:31:11)
_ 1 File Edit Search Optiors Help
t(3-CC 4.9.1] on linux
type "Copyright". "credits" or "licenset)~ for more Information.
Jlfou awake in a small. square roora, A single table stands to one side,
>>> t-openi horne/Sacunent? (Here is a locked door in from of you.
y» t .ffntsl ”M }
1 £ile £dit Firmat Run Qptions Windows Help
>» t.writefVoti ^tarvd and survey your snrroundmgs. the You stand and survey your surroundirigs r On top of the rabie is sanie
neat, and a cup cf ^ster, mu”)
94 meat, and a cup of water. m oi’ math
»> t.writet' i^or is made ' iron strips. It's baltei! The door is made of solid oak with iron strips. tt's bolted from the
e njtside. locking you in iou afe a DrisMKr! .Mi1*] outside, locking you in. You are a prisoner!,
1 IS
e» t, ClfrSBi.>
»>
pr int( ” /a lue of Pi is: ,math,pi)
pi*math.pi
t*open( ‘V horne/pi/Doccinents
There are various types oP Pile access to consider To Pinish, you can use string Pormatting to call the
STEP7 STEP 10
using the open() Punction. Each depends on how the variable and write it to the Pile, then commit the
Pile is accessed and even the position oP the cursor. For example, r+ changes and close the Pile:
opens a Pile in read and write and places the cursor at the start oP
t.write(“Value of Pi is: {}”.format(pi))
the Pile.
t.close()
„ a x
I
Python 3.4.2 (default, Oct 19 201 4, 13:31:11) Adventure Ganie'
J&CC 4.9.1J on linux
Type *’copyr lghf. "credits" or "licenseQ" for more Information.
a Pile.
»> t-open("/hone/pi/Docur ents text.1: • t", "r- ”) You awake in a snnall, square roora, A single table s
>» t.writ*£"Aduentyrr> Gamfvn n ) there is a locked door in front of you +
17
>» t.ci0SE(>
»> r- j criOn ■3 4 snpj | _ e _ □ K
Vou stand and survey your surroundings, On top of tl File EdrE Shell Qebug fictoris ^nsJows Help
meat, and a cup of water. E»-* Edit Firmat Run fiptons WindQiwi Hq p
■ l math
—■—--
Python 3,4.2 {default. Oct 19 2914. 13;3 s: 11 > .
The door is made of solid oak with iron strips. It' |G« 4.9,1] Qn linuii
outside, locking you in. You are a prisoner!. Type ''Copyright*1, "crodits" or *‘license{ )" for more Information. printf "Value •: r pi rj; .rvath-pi)
>»------— RE5TAKT-—---
»> priot{"\nWriting to a file now,..")
Value of Pi i?; 3r 14159M53SS97&3
pl"math,pl
Writing to a file ™.. r
>» t-open{“/home / p i /Potune nts/p i.txi". ■>*}
t, wr i ■ f l i - f orrvs i (p i))
i t,close()
. .....M
Lfl: B -Coi: 4
l
EXCEPTIONAL OBJECTS
Rather than stop the flow ofyour code, Python includes exception objects which handle unexpected errors in the code. You
can combat errors by creating conditions where exceptions may occur.
^ You can create an exception error by simply trying ^ You can use the Punctions raise exception to create
STEP1 STEP3
to divide a number by zero. This will report back _ W our own error handling code within Python. Let's
with the ZeroDivisionError: Division by zero message, as seen in the assume your code has you warping around the cosmos, too much
screenshot. The ZeroDivisionError part is the exception class, oP however results in a warp core breach. To stop the game Prom
which there are many. exiting due to the warp core going supernova, you can create a
custom exception:
lUjl
raise Exception(“warp core breach”)
File Edit Shell Debug Options Windows Help
Ba aa Eec epticn
+— SysteF-Enit
Most exceptions To trap any errors in the code you can encase the
STEP2 +— Keyboariflntermpt
l— feneretoxEEit STEP4
_ W are raised +— Excepticii
+■— Scopi ree arieti
f StcpAsyn’: Ita rati en
_ W potential error within a try: block. This block consists
+-— Arit hjKticExxcr
1 JB. _ _ KsyError
ValueErzez
E ¥— UniccdaErrer
E -— Umicoti-eDecodeExror
E -UrdccdeEnccdeErrcr
E -UnicrdeTrenalaceErr
4- Karniog
E-tpr e c&t r iftiva raifig
4 — — FTid" ngDeptcCtttidnKalTjin
— Frnt tirieWa rn i ng
4-—
4-— SyntakWarning
UaerWaming
4—— Fu tur eW a r n in g
4™■— InportWarniiig
+— Uni co d eftar iiidg
4- F a a cu r ceKa r r. i. r,g
P5 For example, use the divide by zero error. You can Naturally, you can quickly Fix the issue by changing
STEP8
W create an exception where the code can handle the the "r" read only instance with a "w" For write. This,
error without Python quitting due to the problem: as you already know, will create the File and write the content then
commit the changes to the File. The end resuit will report a diFFerent
try:
set oF circumstances, in this case, a successFul execution oF the code.
a=int(input(“Enter the first number: “))
b=int(inputC‘Enter the second number: “)) _ □ K
File Edit Shell Debug Options Wind&ws Help gHe Edt fgmnat Run gpdons ffindows. yelp
printCa/b) Python 3.4.2 (default, Oct 19 2014. 13:31:11)
f&CC 4.&,1| on linux txt - OpOrtf" ■hOfr-./pi/Doeumenti/K! • tfile. E;<T". "V.”)
Type '"Copyright''. "credits" or "licensH )“ for more Information.
except ZeroDivisionError: »>
txt.write(
ercept IOError:
his i' i test ; -rmal servite • shorr
>»
else:
print(“You didiVt divide by zero. Well done!”) I
eptionl py (3.4.2 ^ d *
file Edrt 5heJI Debug Options Windows Help File Edit Format Hun Opllons Windows Help
>»
En ter tht f irst nufflh^r: 12
Enter the second nember: 0
To-u have tried to divide by sero!
|
* *
You can use exceptions to handle a variety oF useFul STEP9 You can also use a Finally: block, which works in a
STEP6
_W tasks. Using an example From our previous tutorials, _W similar Fashion but you can't use else with it. To use
let's assume you want to open a File and write to it: our example From Step 6:
try: try:
txt = open(“/home/pi/Documents/textfile .txt”, “r”) txt = open(“/home/pi/Documents/textfile.txt”, “r”)
txt.write(“This is a test. Normal Service will try:
shortly resume!”) txt.write(“This is a test. Normal Service will
except IOError: shortly resume!”J
print (“Error: unable to write the file. Check finally:
permissions”) print (“Content written to file successfully.
else: Have a nice day.”)
print (“Content written to file successfully. Have txt.close()
a nice day.”) except IOError:
txt .closeQ print (“Error: unable to write the file. Check
permissions”)
Eilp £dit ShvJI Qebug Sphcns Windows Heip
JGCC 4.9.1] an l*ngji tat * open("/horne file Edit Shell Debug Options Windows Help Fie EdA Format Run Optioni Windows Help
Type "copyr ]g+ii'H, "credita" or "ii censet )H for more informat ion, tut .write* This i (t wiL
Pythpn 3-4,2 (default. Qct 19 2014. 13 '31;lT >
IOError: |Q-CC 4.9.1J on linux txt ■ openf " home/pi/£loc(*ienEs/ textFile.t ■
i »> print ( "'Ei r®i ; wn Typo "Copyright". "orodUS™ or " 1tConso()" for m&r* Information.
; prr&rt
: »>
l^ (□ writo tht f il#, ch^ck pirisis-sions
print E "Coniem w
Ext .clo£e( )|
lo I >»
>»
mMMKMmMmM.MM.MMMMM.MMMMMMMMm.MMM.MM.Mm RESTARI
I « :ept IOError:
p r imt ( “Es r o t ; uri ab le i. o *■. i te the file. theC- pe i m i ion i”)
STEP 7 Obviously this won't work due to the File textFile. As beFore an error will occur as youVe used the
txt being opened as read only (the "r" part). So in "r" read-only permission. IFyou change it to a "w",
this case rather than Python telling you thatyouTe doing something then the code will exeeute without the error being displayed in the
wrong, you've created an exception using the IOError class IDLE Shell. Needless to say, it can be a tricky getting the exception
inForming the user that the permissions are incorrect. code right the First time. Practise though, and you will get the hang
oF it.
□ X
£d't Shell Qebug Sphon* Wirtd^wi Help £4& ttlit FifTnai; Buri Aptioris WiriddW? lp
GOING GRAPHICAL
You can draw simple graphics, lines, squares and so on, oryou can use one of the many Python modules available, to bring out
some spectacular effects.
STEP1 One oP the best graphical modules to begin learning The command turtle.circle(SO) is what draws the
STEP3
Python graphics is Turtle. The Turtle module is, as _ W circle on the screen, with 50 being the size. You
the name suggests, based on the turtle robots used in many schools, can play around with the sizes if you like, going up to 100,150 and
that can be programmed to draw something on a large piece beyond; you can draw an arc by entering: turtle. cl rcle(50,
oP paper on the Ploor. The Turtle module can be imported with: 180), where the size is 50, butyouTe telling Python to only draw
import turtle. 180° oPthe circle.
‘w1 J
' -.I-.
Lets begin by drawing a simple circle. Start a New STEP4 The last part oP the circle code telis Python to keep
STEP2
File, then enter the Pollowing code: _ W the window where the drawing is taking place to
remain open, so the user can click to close it Now, let's make a square:
import turtle
import turtle
turtle.circle(50)
turtle.getscreenC)._root.mainloopC) print(“Drawing a square...”)
As usual press F5 to save the code and execute it. A new window will for t in range(4):
now open up and the 'Turtle’ will draw a circle. turtle.forward(100)
turtle.left(90)
Or8p
turtle.getscreenC)._root,mainloopC)
L!il e py - /nomi-pti1 uoc
£il( Edit Ffirrnal Run SP^igns. Hfflp
ni| turtle You can see that weve inserted a loop to draw the sides oP the square.
turtle.tJ.rcl«(30)
T UrT -fipSS.G r¥$n ( ) ,_r PO l, mi in Ipflp ( )
py ■ py (3 4 2) - E X
f;t+ tdr ‘Ihi Qihu? "fHiii"™ i\ rvtwi
f-dri ciin-,ii Hun frrim K»-p
i' f! Iwi Act v» i J ■ 3 «•: 11 j.
f«« * », t J en |c • turtlr
irOt "cowfitfn- ■cr*dLTi" w "lutni+t r n-or*
... -------usTurt —— prsnTj, Lif*.inp, h ■ )
»s»
Eh jmiFiy_ £ vqtui p., _ t r.inpc(*j-
turt 1«. fcraard(IOP'3
Turi 14.
Su r C t*. | : . roct.ffinnlocfH 3
EP 5 You can add a new line to the square code to add Now let's get the code by importing the pygame module:
STEP8
some colour: a
import pygame
turtle.color(“Red”) pygame.init()
Then you can even change the character to an actual turtle by entering: img = pygame.image.load(“RPi.png”)
turtle.shape(“turtle”) white = (255, 255, 255)
w = 900 File Edit Format Run Options Windows Help
You can also use the command turtle. begin_fill(), and lunport pygame
h = 450 pygame, mit()
turtle. end_fill() to Fili in the square with the chosen colours;
screen = pygame.display. ung * pygame - image. load ("F Pi. pr g )
red outline, yellow Fili in this case. vtfilte - (255. 255. 255)
set_mode((w, h)) w = 900
h = 450
screen.fill((white)) screen = pygame.display.set_mode((w, h))
screen.fill((white})
screen.fill((white)}
screen.fill((white)) screen,blit(imgP(0.0))
pygame,display,flip()
screen.blit(img,(0,0))
a+i; Ie True:
pygame. di splay. flip() event in pygame.event+get():
:f event.type -- pygame,QUIT:
pygametquit()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
You can see that the Turtle module can draw out In the previous stepyou imported pygame, initiated
STEP6 STEP9
_ W some pretty good shapes and become a little _ W the pygame engine and asked it to import our saved
more complex as you begin to master the way it works. Enter this Raspberry Pi logo image, saved as RPi.png. Nextyou deFined the
example: background colour oF the window to display the image and the
window size as per the actual image dimensions. Finally you have a
from turtle import *
loop to close the window.
color(‘recP, ‘yellow’)
begin_fill() w - 900
while True:
h = 450
forward(200) screen ■ pygame.display .setjnode( (w, h))
left(170) screen* fill((white>)
if abs(pos()) < 1:
break screen,fill((white))
end_fill() screen.blitfimg, (0,0) )
done() File £dlt Fsrmat Run Sptions Windows Help pygame,display)
■ i turtle .iih ' ■ t *
color(Hred p 'yeilow')
lt's a diFFerent method, begin_fi11()
while True: wtiile True:
but very eFFective. forward{200)
left{170)
if abs(pos()) < 1:
for event in pygane.event.get():
break
end„fill{) -.f event,type == pygame,QUIT:
done()
pygame.quit()
Another way in which you can display graphics is Press F5 to save and exeeute the code and your
STEP7 STEP
_ W by using the Pygame module. There are numerous _ W image will be displayed in a new window. Have a
ways in which pygame can help you output graphics to the screen play around with the colours, sizes and so on and take time to look
but For now let's look at displaying a predeFined image. Start by up the many Functions within the pygame module too.
opening a browserand Finding an image, then save it to the Folder
where you save your Python code. Eile £dit FQjTnaT £un JlptKjns yimdows Help
l pygame
pygame.mitt)
screen.fill(£white))
scre&n.bJit( img, (0.0))
pygame.display.f1 ip( )
LOGGING IN
For this example, Let's look to a piece oP code that creates user logins and then allows them to Log into the system and write
the time they Logged in at. You can even include an option to quit the program by pressing 'q\
STEP1 Begin by importing the time module, creating STEP3 The global status statement separates a local
_W a new dictionary to handle the usernames and _ W variable Prom one that can be called throughout
passwords and creating a variable to evaluate the current status oP the code, this way you can use the q—quit element without it being
the program: changed inside the Punction. We've also rePerenced some newly
dePined Punctions: oldUser and newUser which well get to next.
import time
users = {} iof mainMenuO:
global status
status = status “ input("Do you have a login account? y/n? Or press q to quit.")
if status == "y":
oldUser()
1[ flK I elif status == “n":
newUser()
£ile £dit Ffirmat Sun Qptions Windows Help elif status == 'q :
inp t une quit()
users = {}
status *
def newUserC):
STEP2 Nextyou need to define some Punctions. You can createLogin = input(“Create a login name: “)
_W begin by creating the main menu, where ali users
if createLogin in users:
will return to aPter selecting the available options:
print (“\nLogin name already exists!\n”)
def mainMenuO: else:
global status createPassw = input(“Create password: “)
status = input(“Do you have a login account? users[createLogin] = createPassw
y/n? 0r press q to quit.”) print(“\nllser created!\n”)
if status == “y”: logins=open(“/home/pi/Documents/logins.txt”,
oldUserO “a”)
elif status == “n”: logins.write(“\n” + createLogin + “ “ +
newUserQ createPassw)
elif status == “q”: logins. closeQ
quitC) I
This creates a new user and password, and writes the entries into a
Pile called logins.txt.
File Firmat Sun Qptions Windows Help
quit()
inpcrt time
users * {> ief newUser{):
status - "Ti createLogin = input("Create a login name: ”)
EP 5 You will need to speciFy your own location For the Finally, you need to continually check that the 'q' key
STEP8
W logins.txt File, since we're using a Raspberry Pi. hasn’t been pressed to exit the program. We can do
Essentially, this adds the username and password inputs From the this with:
user to the existing users{} dictionary, so the key and value structure
while status !- “q”:
remains: each user is the key, the password is the value.
status = displayMenuQ
def newllser():
createLogin = input("Create a login name: ") •login py - /homepi/Document ; f . I- - O X
jet newllser{):
Now to create the oldUser Function:
STEP6 createLogin * input("Create a login n
if createLogin in users:
print ("\nlogin name already exis
else:
createPassw = input("Create passw
def oldUser(): usersfcreateLogin] - createPassw
print{"VnUser created!\n")
login = input(“Enter login name: “) logins*open(”/horne/pi/Document s/1 :xt", "a")
logins,write{ ' n' + createLogin +- createPassw)
passw = input(“Enter password: “) logins.close{)
def oldUser():
# check if user exists and login matches logm = input ( cniter login n^i
Fn*I | «Hi T" password
passw * input( t-1 )
password
ff check if user exists and login matches password
if login in users and users[login] == passw: f login :n users and userstlogin] == passw:
print ("VnLogin successfulf\n’)
print (“\nLogin successful!\n”) print ("User:", login, "accessed the system 01 , time,asctime()}
print (“User:”, login, “accessed the system print ("XnUser doe t n")
else:
print (“\nUser doesrTt exist or wrong
password!\n”)
STEP9 Although a seemingly minor two lines, the while
a e t ma i nMenu ():
giobal status
_ W loop is what keeps the program running. At the end
status * input( Do you have a login account? y/n? Or press q to quit.)
lf status == :
oF every Function it's checked against the current value oF status. IF
oldUser()
e 11f status == n :
that giobal value isn't 'q' then the program continues. IF it's equal to
newUser()
elif status == "q : 'q' then the program can quit.
quito
def newllser():
createLogin * input("Create a login name: )
if createLogin in users:
print ("\nLogin name already exists!\n')
itfhile status != "q":
else:
createPassw * input("Create password: ) status - displayHenu()
users[createLogin] - createPassw
print("\nUser created !VrT)
logins-open(“/home/pi/Docunents/logins.txt‘\ Ma")
logins,write( 'An" + createLogin + + createPassw)
logins.close{)
def oldUser(): ^ You can now create users, then login with their
logm = input( 'Enter login name: ' ) STEP 10
passw = input("Ente* password: ") names and passwords, with the logins.txt File
ff check if user exists and login matches password being created to store the login data and successFul logins being
if login in users nrd users[login] == passw:
print ("NnLiogin successful!\rT)
print ("User:**, login, 'accessed the system on:", time.asct une())
time-stamped. Now it's up to you to Further improve the code.
e Ise t
_ print ("\nUser doesn*t exist or wrong password!Xn")_
Perhaps you can import the list oF created users From a previous
session and display a graphic upon a successFul login?
and the time and date oF the login is outputted. IF they don't match, User created!
eldUseru
■ status — '
nfcriUstrO
Po yw h^ye a loRin ytnl Or pre^s q te quit.n f status »■ '
Create a login nime: Ji»
then you print an error and the process starts again. Create pasaveerd: RDMPdbs
User created!
quit(j
newU5»r( ):
createLogin * if
no jou have a leRin accwpjf' ytm cir press q te quit.y
En ter login name; Daviii
bnter pafi&nord; pas.iwDrd
Login successful!
def oldUser(): user: Oavid accessed tf? sjster qn- uqn £op n Hn t ?
login = input("Ente r login name: ') Do you have a logm accthiiU7 y/m Or press q to quii.
76 Calendar Module
78 OS Module
80 Random Module
82 Tkinter Module
84 Pygame Module
88 Using the Math Module
90 Create Your Own Modules
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.
^ You can see that the days oP September 2017 are STEP4 You could even Pashion that particular example into
STEP2
_ W displayed in a wall calendar Pashion. Naturally you a piece oPworking, userinteractive Python code:
can change the 2017, 9 part oP the second line to any year and
import calendar
month you want, a birthday Por example (1973, 6). The Pirst line
print(“»»»»»Leap Year
conPigures TextCalendar to start its weeks on a Sunday; you can opt
Calculator«««««\n”)yl=int(input(“Enter the
Por Monday iPyou prePer.
first year: “))
y2-int(input(“Enter the second year: “))
Python 3.4.2 Shell leaps=calendar,leapdays(yl, y2)
File Edit Shell Debug Options Windows Help print(“Number of leap years between”, yl, “and”,
Python 3*4*2 (default, Oct 19 20U, 13:31:11)
[GCC 4.9,1) On linux y2, “is:”, leaps)
Type " Copyright", "credits" or ,,license()" for more Information,
»> j ipor t calendar
>>> sep-calendar.TextCalendar(calendar»SUNDAY)
>» sep.prmonth(2017* 9) Elie Edit Shejl Qebug options Windows Help £4e Edrt 'imaT 6u-i Qpnons JjfirwJows he:p
September 2017 Python 3.4.2 (default. Oct 19 2014. 13:31:111 calendar
Su Mo Tu We Th Fr Sa |6CC 4,9.13 on linux printc»»»»: 1)
Type “Cdpyr 1 gjhl“. “erfrditi" er “licenseO" ^or mert infernatium. yl = int(inputf"£ irst ?>
1 2 ... RESTWRT- yj=5ftt(input("Ei “>)
10 11 12 13 14 15 16 ‘ErUer the first year: 1756 pnntj V1- d". y2. , leaps)
Enter the second year: 2D22
17 18 19 20 21 22 23 Number Of loap years l>v IvvOCn 1756 Ond 2022 IS: 65
24 25 26 27 28 29 30
»> birthday-calendar.TextCalendar(calendar.M0HDAY)
>» birthday,prmonth( 1973, 6)
June 1973
Mo Tu We Th Fr Sa Su
1 2 3
4 S 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30
>>>
*••***•*••*•***•••••***•••••***»•••*•**••**••••
You can also create a program that will display ali You're also able to print the individual months or
the days, weeks and months within a given year: days oP the week:
£i!< Edit Shep 2et3U9 Optans TVindciw- it! e £dit Fftrmsi gun Qption-E Windows (jelc.
le«P
1
En Tnr th*1 U-BBf to dtsplo y: 2017 0 i .i ■ calendar
2017 inputt "Enwr tlll yi ■ J1.J J
prm:<calendar .preaKyear) J
C2l' C*5
\
J ji TU ^ 1 Y E-i! brudlc7 March
UD Ty We lih Fr 53 5u MD Ty L-Jh Fr Sa 5U MD Tu We Th Fr Sa Su
1 1 2 3 4 5 1 2 3 * 5
2 3 4 S 6 7 V & 7 0 9 11 12 6 7 @9 10 11 12 File Edit Shell Debug Options Windows Help
9 10 n 12 13 14 15 13 14 13 10 17 1G 19 13 14 15 16 17 10 19
: 1 6 17 19 19 ?ct 21 22 20 2t 22 23 24 75 26 70 21 22 23 24 75 76
; 23 24 25 20 27 20 29
ID it
27 2S 27 23 29 30 31
Python 3,4.2 (default, Oct 19 2014, 13:31:11)
April ,!ay June
[GCC 4.9*1] on linux
.u& Tu U8 TU Fr 04
1
5U
2
Ug
1
Tu
2
uf
3
TF|
4
Fr
s
So
b
Sj
7
uo TU wa Th Fr
1 2
sa
3
Su
4
Type “Copyright’*, “credits** or “licenseO" for more Information.
4 S 6 7 C
,0 It 12 13 14 15
9
16
S
15
9
16
10
17
11
10
12
19
13
20
14
21
5 6 7 0 9
12 13 14 15 16
10
17
11
18
>>> impart calendar
17 10 19 2* 21 22
34 25 26 37 3S 29
23
30
22
29
20
30
24
31
35 26 27 2« 19 26 21 22 23
76 37 2B 79 30
24 25 >>> fo name in calendar.month_name:
Juli, 1 AuftjSt St p leniter
print(narne)
Tu Ne Th Fr Sa Su m Tu LJf Th Fr Sa Su Ug Tu We Th Fr 5a Su
i 2 1 2 3 4 s 6 i 2 i
3 4 S 0 7 e 9 7 0 9 10 It 12 13 4 5 6 7 8 9 10
i:. It 12 13 14 15 16 14 15 16 17 10 19 20 11 12 13 14 15 16 17
1 ■' 10 19 20 21 22 23 21 22 23 24 2$ 26 2,7 10 19 20 71 22 23 24
25 76 27 2S 29 W 20 29 30 31 75 26 27 78 29 30
Ji January
' • Ty WB Tb Fr Sa Su
No ventisr
MD Tu L',h Th Ff Sa Su
December
MD Tu We Th Fr Sa Su
February
2 3 4 L b 7 0
t 1 2 3
h 7 y 9 10
4
11
5
12 4 6 6 7 6
t 2
9
3
10
March
9 10 11 12 13 14 15
i! 17 10 19 20 21 22
13 14 15 16 17
20 21 22 23 24
10
25
19
26
11 12 13 14 15
1B 19 20 21 22
16
23
17
24
Apnl
:• : 24 23 2-fi 27 2B 29 27 20 29 30 25 26 27 2S 29 30 31 May
1 30 31
* *
STEP 6
Interestingly we can also list the number oP days in a
W month by using a simple Porloop:
STEP The calendar module also allows us to write the
9
calendar
-- i *
This code will create an HTML Pile called cal, open it with a browser
cal^calendar.Te* tCalendar(calendar.SUNDAY)
for i ]n cal * iternionthdays(2018, 6) :
and it displays the calendar Por January 2018.
print(i)
D cal.fitml x
E** Ed* Fjymat js-ji Qptions fci-ndewi yep
C © fite/r^hDme/pi/Docijnwfll-EJeal hrml tr ■ Qi s « CiiLf-nd.Tr
STEP “ You can see that code produced some zeros at the
7
OP course, you can modiPy that to display a given
_W beginning, this is due to the starting day oP the year as a web page calendar:
week, Sunday in this case, and overlapping days Prom the previous
import calendar
month. So the counting oP the days will start on Friday 1 st June
2018 and will total 30 as the output correctly displays. year=int(input(“Enter the year to display as a
webpage: “))
cal=open(Vhome/pi/Documents/cal.html”, “w”)
File Edit ShePI Debug Options Windows Help
cal.write(calendar.HTMLCalendar(calendar.M0NDAY).
[GCC 4,9*1] on linux formatyear(year))
Type “Copyright", “credits" or “licenseO" for more rmation
>» mmmmmmmmmmmmmmmmmmmm-mmmmmmmmmmmm RESTART ******* cal.close()
»>
0
0 This code asks the user Por a year, then creates the necessary
0
0 webpage. Remember to change your Pile destination.
0
•y * n h
3
-&tt4 IJhiu^ ii-rviiLioi h* <j E** fcat fa™it fljn iptm ]pidawi |jep
pjifwn 3.,.? {diffjult. oct Jei*. UcSlitli i 1 fc*‘ ■ f.ilirriir
[OCC 1.9.IJ «■' LkrwJ
Tjp, "Lup-fl 'cridltl' Bf ]“ r-jl KI4
4 1.1-4
HHH IHKIIIMIH HM.MIMIII KfiSl-UtT «»*>•< ***«.
I
I
if#4r*LPt( ii<*uif :l.i
Tif/1 - DO M Ulli i
’ •
I
Ji . .... . u r.. :i >>
7 5 caLhlml k
2016
janujry Pfbmiry March
MenrufeWedfhtjRISat SlmtMoaTu£ W a rfThuFrtSaiS,Lr*l&fiTuetfti ftdrnyfi' iSatSur
i i 3 4 $ $ 7 1234 l 2 i 4
0 « 10 11 1213 14 5 t 7 0 9 19 11 5 & 7 0 9 W 11
15 Ifr 17 10 1420 21 12 13 14 15 1017 10 12 13 14 13 1017 1«
22 23 24 23 2627 20 19 20 21 22 2374 25 19 20 21 22 2324 23
29 30 31 20 27 10 24 27 2H 29 3031
Azirf!
OS Module
The OS module allowsyou to internet directly with the built-in commands found in your
operating system. Commands vary depending on the OS you're running, as some will
work with Windows whereas others will work with Linux and macOS.
^ You can stant the OS module with some simple The Windows output is different as that's the
STEP1 STEP3
W Functions to see how it interacts with the operating _W current working directory of Python, as determined
system environment that Python is running on. If you're using Linux by the system; as you might suspect, the os.getcwdQ function is
or the Raspberry Pi, try this: asking Python to retrieve the Current Working Directory. Linux users
will see something along the same lines as the Raspberry Pi, as will
import os
macOS users.
home=os.getcwdC)
print(home)
Python 3.5-2Shell - + X
The returned resuit from printing the variable horne ^ Yet another interesting element to the OS module,
STEP2 STEP4
is the current user's horne folder on the system. _W is its ability to launch programs that are installed
In our example that's /home/pi; it will be different depending on in the host system. For instance, if you wanted to launch the
the user name you login 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-32.
import os
L£ Python 3.6.2 She!l - □ 3 browser-os.system(“/usr/bin/chromium-browser”)
File Edit Shell Debug Options Window Help
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)]
*Pylhon 3 4 2 Shels®
on win32 Edit Shell Qebug QpUons Smdows belp
Type "Copyright", "credita" or "license () Tt for more Information. Python 3.4,2 (default. Oct 15 2&14. 13:311 it)
(GCC l.S. 1) on linux
»> import os Typt "ccpyrighi", "cradits" er ''ittwsef)1' for mere inferat ion. '!' Apps For q uick access, place your bookmairiks here- on \ he bookma rfcs bar. I m port bc-okmai I
m[ 11 os
»> home~os . getcwd ()
»> print (horne)
>» brwrser-05.sysiem{ i : r -fc ' )
I I
C:\Program Files (x86)\Fytboii36-32
l
»>
.IrnOriifMl laihm-nntlnnB
ft Home
LA-^UwiI.U Shell*
© My
Fi(e £dii Shdl Debug Dptions ,V ido* Help
A Ttentfrig 9ye.hnn 3.fi.2 (V3.fi.2: S£d33i5. Jiil fi 2017, 04:HiS4S [H5C v.1900 32 bit ilnteHJ
n Sub#Cf*pttoM
LlfiftAftY
I
J Hletory
O Watch Later
siJHSCHiprmNS
a*™**
O 8KWS9 Chartrtd-S
veve
Taylorl hli Name Tl»e
vevo t»
Yandel ■ Como Antea {Dffielal
import os
os.rename(“NEW”, “OLD”)
To delete them:
For Step 5's example we used Windows, to show
STEP6
that the OS module works roughly the same across import os
all platForms. In that case, we opened YouTube's music Feed page, so os.rmdir(“OLD”)
it is thereFore possible to open speciFic pages:
v
view Scotoma
& ii
Typt “t,opyfigjixFi ■ti4diisJ of "license: J“ r&r nere irtfeiUfliiwi.
•3 O^wnloads
■ iMusic
-OOLD
! ► «Pictures
; >»
FH.I
?■>>> ? 341^irk!4l rrwici f»
i
t FKtOfv 'r*f
*l Poftnaids.
The random module is one you will likely come across many times in your Python
programming lifetime; as the name suggests, it's designed to create random numbers
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.
^ Just as with other modules you need to import However, the random module isn't used exclusively
STEP1 STEP4
_W random bePore you can use any oP the Punctions Por numbers. You can use it to select an entry Prom a
weTe going to look at in this tutorial. Let's begin by simply printing a list Prom random, and the list can contain anything:
random number Prom 1 to 5:
import random
import random random.choice([“Conan”, “Valeria”, “Belit”])
print(randomint(0,5))
This will display one oP the names oP our adventurers at random,
which is a great addition to a text adventure game.
File Edit Shell Debug Options Windows Help
n our example
STEP2 Python 3.
the number Pour File Edit Shell Debug Options Windows Help
Python 3,4.2 {defauit, Oct 19 2014, 13:31:
was returned. However, enter [GCC 4.9,1] on linux
Type "Copyright"-, "credits'* or "licenseO"
the print Punction a Pew more >» ii por+ random
»> print(random.randint(0,5))
times and it will display different 4
»> pnnt( random, randint(0,5))
integer values Prom the set oP 3
>» pnnt( random, randintfO ,5))
1
numbers given, zero to Pive. The >» print( random, randint(0,5))
2
overall ePPect, although pseudo- >» prmt(random,randmt(0,5))
5 You can extend the previous example somewhat by
random, is adequate Por the >» pr int{ random . randint(0,5))
4
STEP5
»> pnnt(random.randint(0,5)> _W having random.choice() select Prom a list oP mixed
average programmer to utilise in 4
»> pnnt(random.randint(0,5)) variables. For instance:
theircode. 5
>» print( random . r andint(Q ,5))
c:
j
»| import random
lst=[“David”, 44, “BDM Publications”, 3245.23,
“Pi”, True, 3.14, “Python”]
rnd=random.choice(lst)
For a bigger set oP numbers, including Ploating
STEP3 print(rnd)
point values, you can extend the range by using the
multiplication sign:
“ Interestingly, you can also use a Function within the Let's use an example piece oF code which Flips a
STEP6 STEP9
_W random module to shuFFle the itenns in the list, thus _ W Virtual coin ten thousand times and counts how
adding a little more randomness into the equation: many times it will land on heads or tails:
H*-jds 49?»
Tails 5061
import random
lst=[[i] for I in range(20)]
random. shuffle(l st) STEP 10 Here's an interesting piece oF code. Using a text
print(lst) File containing 466 thousand words, you can pluck
a user generated number oF words From the File (text File Found at;
Keep shuFFling the list and you can have a diFFerent selection oF
www.github.com/dwyl/english-words);
items From 0 to 20 every time.
import random
print(“»»»»»Random Word Finder«<<«««”)
File Edit Shell Qebug Options Windows Help
print(“\nl!sing a 466K English word text file I can
Python 3.4,2 (default, Oct 19 2014, 13:31:11)
[GCC 4,9,1] on linux pick any words at randomAn”)
Type “Copyright*', “credits” or **license( )" for more Information,
>» inipcj t random
>» lst= [ [i] for i in range(20)] wds=int(input(“\nHow many words shall I choose?
»> random.shuffle(Ist)
»> print(lst) “))
1111]. [12], [6]* [5], [13], [1], [15], [191, [3]* [2], [16], [10], [4], [8], [1
81, [17], [7], [91, [14], [01]
with open(“/home/pi/Downloads/words.txt”, “rt”) as
f:
words = f.readlines()
words = [w.rstripQ for w in words]
STEP8 You can also select a random number From a given print(“-”)
range in steps, using the start, stop, step loop:
for w in random.sample(words, wds):
import random print(w)
for i in range(10):
print(“-”)
print(random.randrange(0, 200, 7))
Results will vary but you get the general idea as to how it works. File £dit Shell Debug ^ptions Windows tjelp E,ile £dit
mdworcfs.py - /noirw^pi/DocumentE
Firmat Euo Qptions ^irvoows tSelp
Python 3.4.2 fdefault, Oct 19 2014. 13:31:11) impe i I rarvdwt
I0CC 4.S.1] on linux
Type "topyr teJlt” „ "Crediti" or ' 1 icens#()" for more Information pr int( ’»»
pririt£"\.mis
y»
. -v -
1 | 1 rf) | J. \.J i i. _r |T « | f I' I* _1 ,| ES fi) -y* < >»»»» >Rando<ri wo-rd ¥¥ds.= int( inpLii( iH
UJj.ng a -4-SfiH EEi“i£) )$h wprd fa le 1 CSn piCk ariy word$ at random.
154
119
7
7
161
168
168
182
126
175
»> j
Tkinter Module
Whilst running your code from the command line, or even in the Shell, is perfectly fine,
Python is capable of so much more. The Tkinter module enables the programmer to set
up a Graphical User Interface to internet 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.
Tkinter is usually built into Python 3. However, if it's The ideal approach is to add mainloop() into the
STEP1 STEP3
available when you enter: import tkinter, then _W code to contrai the Tkinter event loop, but weil
youneedtopip install tkinter from the command prompt get to that soon. YouVe just created a Tkinter widget and there are
We can start to import modules difFerently than before, to save on several more we can play around with:
typing and by importing all their contents:
btn=ButtonQ
import tkinter as tk btn.packO
from tkinter import * btn[“text”]=”Hello everyone!”
The First line focuses on the newly created window. Click back into
the Shell and continue the other lines.
File Edit Shell Debug Options Windows Help
Helio everyone!
import tkinter as tk
normally. Let's begin by creating a basic GU! window, enter:
from tkinter import *
wind=TkO btn=Button()
btn.packQ
This creates a small, basic window. There's not much else to do at
btn[“text”]=”HeVLo everyone!”
this point but click the X in the corner to close the window.
Then add some button interactions:
Python 3.4.2 Shell • □ X
def clickQ:
File Edit Shell Debug Options Windows Help
• •••••**•••*••*••*»*«•*•*•*•*•*•••*•*
Save and execute the code From Step 5 and a You can create radio buttons too. Try:
P5 STEP 8
W window appears with 'Helio everyone!' inside. iPyou
from tkinter import *
click the Helio everyone! button, the Shell will output the text 'You
just clicked me!'. It's simple but shows you what can be achieved root = TkQ
with a Few lines oP code.
v = IntVarQ
Python 3,4.2 (default, Oct 19 2014, 13:31:11)
fOCC 4.9,1] on Iinux Labelfroot, root,title(“0ptions”), text=”””Choose
Type "Copyright", "credita" or "licens e()" for more informat ion
»> ================================ RESTART =================== a preferred language:,
»>
>» You just clicked me! justify = LEFT, padx = 20).pack()
You just clicked mei
You just clicked me! Radiobutton(root,
text=”Python”,
padx = 20,
variable=v,
value=l).pack(anchor=W)
Radiobutton(root,
Helio everyone text=”C++”,
padx = 20,
variable=v,
You can also display both text and images within value=2).pack(anchor=W)
a Tkinter window. However, only GIF, PGM or PPM
mainloopO
Pormats are supported. So Pind an image and convert it bePore using
the code. Here's an example using the BDM Publishing logo:
You can also create check boxes, with buttons and
from tkinter import * STEP 9
output to the Shell:
root = Tk()
from tkinter import *
logo = PhotoImage(file=”/home/pi/Downloads/BDM_logo.
root = TkQ
gifM)
wl = Label(root, root,title(“BDM Publications”), def var_states():
image=logo).pack(side=”right”) print(“Warrior: %d,\nMage: %d” % (varl.getO,
content = From its humble beginnings in 2004, var2.getQ))
the BDM brand quickly grew from a single publication
LabelCroot, root,title(“Adventure Game”),
produced by a team of just two to one of the biggest
text=”»»»»»Your adventure role«<<«««”).
names in global bookazine publishing, for two simple
grid(row=0, sticky=N)
reasons. Our passion and commitment to deliver the
vari = IntVarQ
very best product each and every volume, While
Checkbutton(root, text-”Warrior”, variable=varl).
the company has grown with a portfolio of over 250
grid(row=l, sticky=W)
publications delivered by our International staff,
var2 = IntVarQ
the foundation that it has been built upon remains
CheckbuttonCroot, text=”Mage”, variable=var2).
the same, which is why we believe BDM isn’t just
gridCrow=2, sticky=W)
the first choice it’s the only choice for the smart
Button(root, text=’Quit*, command=root.destroy).
consumer.
grid(row-3, sticky=W, pady=4)
w2 = Label(root,
Button(root, text=,Show’, command=var_states),
justify=LEFT,
grid(row-3, sticky=E, pady=4)
padx = 10,
text=content).pack(side=”left”) mainloopQ
root .mainloopQ • * *«*•••#* * * » » • * • • * * * t • • t
* A*************************************************************
“ The code Prom Step 9 introduced some new
STEP 10
STEP 7 Filp £dit
tkintercQCi$2 py - ^ome/pi;'Docume. ython Code/tkintercode2 ,py (3.4.2)
Labe 1{ root.
'••rfJ.igc: • -
■gri4(rw*«o. sticky-H)
Mr4.|tl(9, var5.gotO>)
vari - IntVarfl
root,mainloop() tejct" ■ .r-
Prom the company Checkhuirbntrobt.
var2 - InTVartJ
Checfcbuitsnfroot. tesi-
variable*varl).gndtcsw»!, icicky»wi
, variabie»v*r2,>.grid(fOTH“2. sticky^wj
BDM Publications M n k var3 - InTVan[3
, stlckjf-W)
var5 ■ IntVar(J
Ch*cfcbuit*n(ir4^t. t*xt-"P.iL,i ifi'% var lablt-varS) .gridtcow-5, sticky^V)
obviously change the From it5 humble beg nnmgs in 2004,
the BDM brand quickly grew from a singje publicati on produced
by a toairi Of jU$t tWO to one Of the biggest names in global
bookacine publishing, for two simple reasons. 6.ittoni root, text^Oust , caiTrand-rost, destroyj, gnd( r wf7, sticky-W. padiy^i)
content, the root.title Our passion and commitment to deliver the very best product
each ana evory volume.
yvhile the company h»S grown with a portfolio of over
ma i n I aop{')
re^t- ' -‘n • . C(Hturand-var_iw)■ gc 1 d(f. sticky-fr
pmt Show
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.
Naturallyyou need to load up the Pygame modules Sadly you can't close the newly created Pygame
STEP1 STEP3
into memory bePore youVe able to utilise them. _W window without closing the Python IDLE Shell,
Once that's done Pygame requires the user to initialise it prior to which isnJt very practical. For this reason, you need to work in the
any oP the Punctions being used: editor (New > File) and create a True/False while loop:
gamewindow-pygame.display.set_mode((800,600))
pygame.display.set_caption(“Adventure Game”)
You can see that aPter the Pirst line is entered, you need to click back
into the IDLE Shell to continue entering code; also, you can change
the title oP the window to anything you like.
Python 2 Sh@l! _ □ H
iLn: &|Cnl: 4
■ II
iturp
I ~ Rflmp
V I I vT
File Edit Format Run Qptions Windows Help
pygame
om pygame.locals import *
pygame.init(>
runnmg=Tr ;
wrul running
ganewindow=pygame.display.set_mode((800,600))
pygame.display,set_caption("Adventure Game")
black-(0,0,0)
vrfute={255,255,255)
u^pyg3™*, image, load( h i")
de- sprite<x.y):
gamewindow,blit< ungf (x,y>)
x»(800*0♦45)
y=(600*0.8)
gamewin dow.f111(white)
sprite(x.y)
pygame.display.update{)
event i pygame.event.get():
if event,type==QUIT:
running* iY e
pygame.quit{)
J
Ii n: 1 f nl- H
^ LetJs quickly go through the code changes. We've downloaded image called spritel .png and allocated it to the
STEP6
_ W defined two colours, blackand white together variable img; and also defined a sprite function and the Blit function
with their respective RGB colour values. Next we've loaded the will allow us to eventually move the image.
■1 pygame
from pygame.locals import *
pygame. imt<)
runnmg=Tr ie
gamewindow^pygame.display.set_mode(< BOO.600))
pygame„disp1 ay.set_caption( d.enture Game1)
black={0 ,0,0)
white=(255,255,255)
img^pyganie. image. load( m D1 1 (. n
def sprite(x,y):
gamevvindow<blit( lmg, {xPy)>
x«(800*0.45)
y=(600*0.8)
xchange=0
imgspeed=G
running:
f event in pygame.event,get():
if event.type*«QUlT:
running»? alse
: f event.type == pygame.KEYDOWN:
if event,key=“pygame,KJIEFT:
xchange=-5
e 11f event.keyc“pygame,K_RIGHT:
xchange=5
if event * type^pygame.KEYUP;
if event.key—pygame,K_LEFT event.key==pygame.K_RIGHT:
xchange=0
x += xchange
gamewiridow. fill(white)
sprite(x,y)
pygame.display.update()
pygame,quit()
Copy the code down and using the lett and right arrow keys on the keyboard you can move your sprite across the bottom of
STEP8
the screen. Now, it looks like you have the makings of a classic arcade 2D scroller in the works.
running:
unpc i f pygame
* r event i i pygame.event.get():
from pygame.locals
if event,type==QUIT:
pygame.init{)
running=* ii •
running=T r ue
it event.type == pygame,KEY00V.tl:
gameAindOA^pygame.display.setjmode((800,600))
if event,key==pygame*K_LEFT:
pygame,display.set_oaption('Adventure Game") xchange--5
black~(0,0,0) elif event.keysspygame,K_RIGHT:
Atiite*{ 255 P 255,255) xchange=5
img=pygame. image. load( 'Vhofne/pi/Downloads/spT if event * type=-pygame.keyup:
if event.key==pygame.K_LEFT event.key^-pygame.K_RIGHT:
^ def sprite(x,y): xchange»0
gamevvindoWpblit( img. (x ,y))
x +- xchange
I x=(800*0.45)
I y=(600*0 »8) gamewindow. f ill(vrfiite)
spnte(x,y)
I xchange^O pygame.display.updatef)
ungspeed=0
pygame.quit()
STEP9 You can now implement a Pew additions and utilise pygame. di splay. fli p()
_W some previous tutorial code. The new elements are clock. ticl<(60)
the subprocess module, oP which one Punction allows us to launch a continue
second Python script Prom within another; and weTe going to create a break
New File called pygametxt.py:
pygame,quit()
import pygame
import time mmm „ - ~■ i—-——b nii«ni m— —■»——
>T*rniiiiT=!iTCfi
--- ——— ----■-——-——-— n a^m *
i iT*TiXi?+T*
«———ani» i i ■mrn -i—• f i n~. i_—„■ --
ju y4 hj
^*. _ m n n—i m—m - - —
def update(self):
if not self.done:
try: self.rendered = self.font. STEP10 When you run this code it will display a long,
render(next(self._gen), True, (0, 128, 0)) W narrow Pygame window with the intro text
except Stoplteration: scrolling to the right. APter a pause oP ten seconds, it then launches
self.done = True the main game Python script where you can move the warrior sprite
time.sleep(10) around. Overall the ePPect is quite good but there's always room
subprocess.Popen(“python3 /home/pi/Documents/ For improvement.
PythonX Code/pygamel.py 1”, shell=True)
def draw(self, screen):
screen.blit(self.rendered, self.pos)
text=(“A long time ago, a barbarian strode from the
frozen north. Sword in ihand...”)
message = DynamicText(font, text, (65, 120),
autoreset=True)
while True:
for event in pygame.event.get():
if event.type = pygame.QUIT: break
if event.type = pygame.USEREVENT: message.
updateO
else:
screen .fili (pygame. color. Color(4 black ’))
message.draw(screen)
E = MC 2
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.
STEP1 The math module is built in to Python 3, so there’s No doubt you are aware by now that if you know
STEP3
no need to PIP install it. Just like the other modules the name oP the individual Punctions within the
present, you can import the module's Punction by simply entering: module, you can speciPically import them. For instance, the Floor
1 mport math into the Shell, or as part of your code in the Editor. and Ceil Punctions round down and up a Ploat:
STEP2 Importing the math module givesyou access to the STEP4 The math module can also be renamed as you
module's code. From there you can call up any oP _ W import it, as with the other modules on offer within
the available Punctions within Math by using: math. Followed by the Python. This oPten saves time butdont Porget to make a comment
name oP the Punction in question. For example, enter: to show someone else looking at your code what youve done:
P5 Although it's not the usual way, it is possible to For Further accuracy when it comes to numbers, the
STEP8
W jmport Functions From a module and rename them. exp and expml Functions can be used to compute
In this example we imported Floor From Math and renamed it to F. precise values:
This process can quickly become conFusing though, where lengthy
from math import exp, expml
code is in use:
exp(le-5) - 1 # value accurate to 11 places
from math import floor as f expml(le-5) # resuit accurate to full precision
f(1.2)
/ I
y V File Edit Shell Debug Options Windows Help
File Edit Shell Debug Options Windows Help Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Python 3.4.2 (default, Oct 19 2014, 13:31:11) Type ■■copy^lght,'. “credits'* or “licenseO" for more Information.
[GCC 4.9.1] on linux >» from math import exp, expml
Type “oopyright", "credits" or "licenseO" for more Information. »> exp( 1e-5) - 1
>» from math import floor as f 1.0000050000Q69649e-05
»> f(1.2) >» expm1(1e-5)
1 1.0000050000166668e-05
»>
Importing all the Functions oF the math module can This level oF accuracy is really quite impressive but
STEP6 STEP9
be done by entering: _W quite niche For the most part. Probably the two
most used Function are e and Pi, where e is the numerical constant
from math import *
equal to 2.71828 (where the circumFerence oF a circle is divided by
While certainly handy, this is oFten Frowned upon by the developer its diameter):
community as it takes up unnecessary resources and isn't an
import math
eFficient way oF coding. Flowever, iF it works For you then go ahead.
print(math.e)
print(math.pi)
STEP7 Interestingly, some Functions within the math The wealth oF mathematical Functions available
STEP 10
W module are more accurate or to be more precise, are through the math module is vast and covers
designed to return a more accurate value, than others. For example: everything From Factors to inFinity, powers to trigonometry and
angular conversion to constants. Look up www.docs.python.org/3/
sum(^ ^«1-. . i, . i. * 1-. * i, . i * , 1- * . i, . i, * )
library/math.html# For a list oF available math module Functions.
Returns the value oF 0.999999999. Whereas: 9.2.4, Angular conversion
ma z. b. degrees(x)
fsum([.l, .1, .1, .1, .1, .1, .1, .1, .1, .1]) Conyort angie x Irom radians io degreos
math. acD£h(x)
»> sum([.1, .1, .1, .1, ,1, ,1, .1, .1, .1, .1]) Return the hyperbolic tanrjenl crf x
>>> The erf»:. function can t>:= usod to compute tradrtional stateslicai functionrs such as ifw cumolalive Standard normaf distributori:
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, thatyou save using a .py extension. These are then imported into Python using the
now familiar import command.
STEP1 LetJs start by creating a set of basic Mathematics Now you're going to take the Punction dePinitions
STEP3
Punctions. Multiply a number by two, three and out oP the program and into a separate Pile.
square or raise a number to an exponent (power). Create a New File Highlight the Punction dePinitions and choose Edit > Cut. Choose File
in the IDLE and enter: > New File and use Edit > Paste in the new window. You now have
two separate Piles, one with the Punction dePinitions, the other with
def timestwo(x):
the Punction calls.
return x * 2 File Edit Format Run Opttons Windows Help
def timesthree(x): ■ _ □ x
Ei te £dit Firmat Run Qptions Windows Help
return x * 3
iuli
print (timestwo(2))
rf timesthree(x)
Under the above code, enter Punctions to call the STEP4 IPyou now try and execute the basic_math.py code
STEP2
A code: again, the error 'NameError: name 'timestwo' is
not defined' will be displayed. This is due to the code no longer
print (timestwo(2))
having access to the Punction dePinitions.
print (timesthree(3))
print (squareC4)) Traceback (most recent call last):
File "/home/pi/Documents/Python Code/basic jnath.py". line 3. in <module>
print (power(5,3)) print (timestwo(2))
NameError: name 'timestwo’ is not defined
Save the program as basic_math.py and execute it to get the results.
Return to the
File Edit Format Run Qptions Windows Help
^=fT
STEP5
Met tinestwofx):
return x x ■>
newly created
aef timesthree(x):
window containing the Punction
Save As
return x * 3 dePinitions, and click File > Save
def square(x):
return x * x
As. Name this minimath.py
def povwr(xfy):
4Setterwd,py BooleantesLpy and save it in the same location
] Adventure,py (7 BoxesColours
return x ** y
|_| AJarmC]ock.pv r CalcPr.py as the original basic_math.
| Balls.py Calculato rpy
print
print
(tunestwo(2))
(timesthree(3)) |_| basitmath.py [_calervdaryear.py
py program. Now close the
print (square(4)>
print (power(5,3))
f ] bkup.py cards.py minimath.py window, so the
< J ►I basicmath.py window is lePt
ba$icjnath*py
File Qame: _ Save open.
Files of type: Python files (*.py, ipyw) Caneei
Back to the basic_math.py window: at the top oF the STEP9 Finally, you can now create a range oP iP statements
STEP6
code enter: _ W to determine what to do with the number and
utilise the newly created Function dePinitions:
from minimath import *
if choice == ‘1’:
This will import the Function dePinitions as a module. Press F5 to
print(timestwo(numl))
save and execute the program to see it in action.
elif choice == ‘2’:
print(timesthree(numl))
elif choice == ‘3*:
print(square(numl))
elif choice == ‘4’:
num2 = int(input(“Enter second number: “))
print(power(numl, num2))
else:
print(“Invalid input”)
print(“Select operationAn”)
print(“l.Times by two”)
print(“2.Times by Three”)
print(“3.Square”)
print(“4.Power of”)
choice = imput(“\nEnter choice (1/2/3/4):”)
from minimath import * Filt- £dil Sfrl*].l J>pbug £j..L ni WmcJ”.jra H-p
_ D X
pile Edrl
•testmath py -
Firmat 3ur. Options Windows Help
_ □ w
Select operationi.
1 .Times by two
2.Times by Three
2.Eqjare
S
4.Porter of
print(MSelect operationAn") Enier choice
print("3.Square")
print("4*Pawer of'")
[ a d L < H ' S } ! E x P n S VI L □ □ B n a B ta A S S
\B E " □ q □ N “i u n fi f 9J q n_R ' t 91 w/ 1
□ N u B S <u E W S a k p p f) Code Repository
1 E 'M' M- F SI G$ OJ G" i y ®
QJ i
W X R ' W u S S vi
4 i u «n S
%l B ■s i , □ & 3 E S K* ‘l S i et' S u ... «j rh eu
fi
# U □ «5 € J U y st i • ( T 19 1 9 * «J 1 b E fi 3J S Z E □
0 fi U fi □□ i a (* □ ... £1 n • is n w E eu w ni
WeVe included a vast Python code
repository for you to use freely in your
own programs. There#s plenty in here
to help you create a superb piece of
programming or extend your project ideas,
There's code for making backups of your
files and folders, number guessing games,
random number generators, Google
search code, game code, animation code,
graphics code, text adventure code and
even code that plays music stored on
your computer
This is an excellent resource that you won't
f ind in any other Python book, so use
it, take it apart and adapt it to your own
programs, and see what you can create.
w vi tu J L2J l/M
□□ /
v
ft K
.
C ™ 14
www.bdmpubUcations.com
□ * a V thon Manual
□ x
I—I
6) 0 Vi i» ai si 0‘ Zi
H # 0 m
v T man rogram aispia VI c FILEMAN.PY
t allow you to Q. 0 Copy the code below into a New > File and save it as FileMan.py.
A 0 read a file, write to a file/append to" U Once exeeuted it will display the program title, along with the
1 q current time and date and the available options.
a □ 70 Ta M
: si import shutil
import os
import time
u (5) A ~
^ in , ora import subprocess
4 1
7 x ® a def ReadQ:
path=input("Enter the file path to read:")
o File £ct 5hejl Eetuia aptipriE
Python j.j.2 (defiuiF. flet ifl 2QU. i3:3T:H>
[GCC. 4.9.1] (in J iny.
tje^p
Type 'Ldp jfr lghl“, "trediTi" at “litenifrj )" fdl" moi e inf*r»iliPn.
file £d.t Farmat 0un 2phon? ^Indi7»t Help
3 File Wan^erc^<i«cccc
EMdOl
patJh-inpiiT f “Entethe :
C print (file. read ())
File-c&er (p4th.' i )
The currunt tjjnif and dat-n ■l?" Frj, Sep 15 0S:15:41 J&f?
i
0 €
pjLlT.lriputt"EnEet Lhe pith af Ille
i d*.patii, 4* istsj p.ithj;
printrFile Found1 )
os.reflove(path)
p^Ullf 'Ftla hai bfrm delcled1!
:lldn:*l
a M jrrent t 4 J.
ai def Dirlist():
iJ 9 11]
II
C
0
1
i □ 7 R
y a m € e
Cl @
51 m u, □r
94 Black Dog i-
□
es - Volume 35 n v
□ Cl Cl A
r Python File Manager
if treedir==2:
1 .Re r ii
shutil. rmtree (path) f ll e
to a ile
print ('Directory Deleted') r@ 1Q
in □ d
if treedir==3: 0 y ] 5 % ei
7.11 ove file
exit{) jc ■
T i le
1 _
Cre a directory
10.Delete a directory
ll.Open a program
def OpenfileQ: 12, E x i T
path=input('Enter the path of program:')
Enter the path of the file to copy or rename:/home/pi/Documents/Poem.t
try: Enter the path to copy to:/home/pi /backuo
File copied
os. s tar tfile (path) 1, Retufn to nenu
2, Exit
except:
print ('File not found')
run=l
Imports
while (run==l): There are three modules to import here: Shutil, OS and
try:
Time. The First two deal with the operating system and File
os. system ('ciear')
management and manipulation; and the Time module simply
except OSError:
displays the current time and date.
os. system ('cis')
print ('\n»»»»»Python 3 File Manager«««««\n')
print ('The current time and date is:', time. asctime ()) Note how we've included a try and except block to check iF
print ('\nChoose the option number: \n') the user is running the code on a Linux system or Windows.
dec=int (input 1. Read a file Windows uses CLS to ciear the screen, while Linux uses ciear.
2. Write to a file The try block should work well enough but it's a point oF
3. Append text to a file possible improvement depending on your own system.
4. Delete a file
6 z
u 13 M n s
\
«21 7 _
NumberGuessing Game
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.
import random
>sw
/A
e e altered too C « A = 0
1 M n Sf 0 9 n M Name=input('Helio! What is your name? ')
fl number = random. randint(l, 30)
7 x print('Greetings, ' + Name + I\'m thinking of a
o a number between 1 and 30/)
W +
file £dit
mpo r t random
firmat Bun Qptions Windows Help
c while guessesUsed < 5:
bQ guessesUsed - 0
0 guess=int(input('Guess the number within 5 '»
riame=input(‘Helio! What is your nan + 1
4 h nunber * random*randint(1, 30)
print(' Greet ings. + Hame «■ + , I\’ if guess < number:
hile guessesUsed < 5:
guess=int(input( Guess rh- numt print('Too low, try again/)
guessesUsed * guessesUsed + 1
S
o/
j
a/ guess < mjnber: if guess > number:
prmt(’Too low, try agam. '
□
H guess =- number:
vi guessesUsed - str<guessesUsed)
prini('Wel 1 done. + Hame + * guessesUsed if guess == number:
s “ guess <
number
number:
■ str(number)
guessesUsed = str (guessesUsed)
print( if is + nunber) print('Well done, ' + Name + '!
□0
correctly in ' + guessesUsed +
M 4 if guess != number:
0 M number = str (number)
print('Sorry, out of guesses The number I was
<* D
°/ thinking of is ' + number)
0 '1
File £dit SheJI Debug Options Windows Help File £dit Firmat fiun Options Windows Help
□
G~ 51
°1
nJ
n vi
.< n
w 9
* 0
p| vl
c) 0
iJ 9
i □ Ln: 14 Coi; 4
0 @
□
96 Black Dog i-Te
C
□ a A
i—i
I
EI □
Lrsaracterbiats.pv n e,- ui
Filf3 Edit Shejl Dphug Optio ns Windows Help Eil-"' Edit Farmrrt Eun Optione Windows yelp
Endurance: 12
Conbat Rating: 16
Luck: 9
»>
vi
I di/
in- 28 Coi 4
*«+#** *#••*** + + #**•*•**+**+*•«*#** »»«** + ***** + **#*#*»*** + ****«*»* ***«*» + **»* ***«#***+*##»****4* + *e»*# ************ **** + *******#*
m
Code Improvements
Since this is such as simple scripb to apply to a sibuabion, bhere's For example, as per bhe screenshob provided, you could use
plenby of room bo mess around wibh ib and make ib more somebhing along bhe lines of:
inberesbing. Perhaps you can include an opbion bo bake score, bhe
besb oub of bhree rounds. Maybe an elaborabe way bo congrabulabe Endurance=0
bhe player for gebbing a 'hole in one' correcb guess on bheir firsb bry. CR=0
Luck=0
Endurance = random. randint(l, 15)
Moreover, bhe number guessing game code does offer some room
CR = random. randint(l, 20) EI
for implemenbing inbo your code in a differenb manner. Whab we
Luck - random. randint(l, 10)
mean by bhis is, bhe code can be used bo rebrieve a random number
Print ("Your characteres stats are as follows:\n")
bebween a range, which in burn can give you bhe sbarb of a characber Print ("Endurance: ", Endurance)
creabion defined funcbion wibhin an advenbure game. Print("Combat Rating:", CR) b
Print ("Luck:", Luck)
Imagine bhe sbarb of a bexb advenbure wribben in Pybhon, where
bhe player names bheir characber. The nexb sbep is bo roll bhe
virbual random dice bo decide whab bhab characbers combab
The player can bhen decide bo eibher sbick wibh bheir roll or bry again q
rabing, sbrengbh, endurance and luck values are. These can bhen be
for bhe hope of bebber values being picked. ThereJs ample ways in %
which bo implemenb bhis code inbo a basic advenbure game.
carried forward inbo bhe game under a seb of variables bhab can be
reduced or increased depending on bhe circumsbances bhe player's n
characber ends up in.
mi/
11
File Edit Shejl Debug Options Windows Help File Edit Format Run Gptions Windows
□
Python 3.4,2 (default, Oct 19 2014, 13:31:11) import randocn
[GCO 4.9.1] on linux
Type "Copyright*', "credits" or *'license()" for more Information Endurance^O
>>> RESTART CR-0
>»
Yuor character’s stats are as follows:
Luck=0
Endurance** r andom. r and int( 1, 15)
H
CR=random.randint(i, 20)
Luck=random.randint(1, 10)
u
Endurance: 4 print("Yuor character*s stats are a:
Combat Rating: S print( nEndurance: , Endurance)
Luck: 6 print("Combat Rating:", CR)
RESTART print( Luck:", Luck)
>>>
Yuor character*s tats are as follows R
Endurance: 2
Combat Rating: 20
Luck: 6
RESTART
Q
>»
Yuor character’s stats are as follows:
5
Endurance: 12
Combat Rating: 16
Luck: 9
>» vi
1
<
6
4
Ln: 28 Coi: 4 Ln; 13
qj
□
u #
FI
rw
Graphical Enhancements
There are several ways in which you can improve this code to make Forexample:
it more interesting. You can insert colours, perhaps a different
colour for every line. You can display a message inside the circle
and have the Turtle draw around it. Letyour imagination run wild
on this one.
Turtle's graphics can take a while to map out and draw, depending
on how big and how intricate an image it is youYe designing. Whilst
the effect can be quite stunning, it is Limited by the amount of
time it takes to display an image. Therefore itJs worth seeing if the
This will run through the code at the 'fastest' speed possible for
function turtle.speed() will quicken things up.
the Turtle. Itcertainly makes a difference and is worth considering
if youYe drawing Turtle images for games or presentations.
Turtle.speedQ comes in various values:
slow
File id it Firmet Bun ^ptions Windows Help
norma 1
|from turtle import *
from math import sin, cos, pi
| r=200
inc=2*piVt 00
t=0;n=1.5
You can experiment with the various speeds by adding the function for i in range{100):
in the for loop, just before the penup line. xi“r*sin(t>: yi=r*cos£t)
in(t+n); y2=r*cos£t-*-n)
speed(1fastest'}
penuipO; goto(Kl,y1)
pendown():goto(K2ry23
t+=inc
£ ‘ll
1 □ 0
9 l
c
7 R
n y a □ a m
f 51 m u □■
98
□
Black Dog i- es - Volume 35 n v
□ a a A
Polygon Circles/Random Number Generator
randint(nmbl , nmb2)
print ("\nThe random number between",nmbl,"and",nmb2/'is:\n")
print (x)
More Input
While an easy code to follow, itcould be more interesting ifyou For example, the code could be edited to this:
prompt the user For more input. Perhapsyou can provide them
with addition, subtraction, multiplication elements with their from random import *
numbers. iFyouYe Feeling elever, see iFyou can pass the code import turtle
through a Tkinter window or even the Ticker window that's
print ("\n»»»»»Random Turtle Image«««««\n")
available on Page 128.
nmbl=int {input ("Enter the start number: "))
nmb2=int (input ("Enter the second number: "))
Furthermore, the core of the code can be used in a text adventure nmb3=int (input ("Enter the third number: "))
game, where the character Fights something and their health, nmb4=int (input ("Enter the fourth number: "))
along with the enemy's, is reduced by a random number. This
can be mixed with the previous code From Page 90's Number
Guessing Game, where we defined the stats For the adventure turtle. forward(nmbl)
game's character. turtle. lef t(90)
turtle. forward(nmb2)
You can also introduce the Turtle module into the code and turtle. lef t(90)
turtle. forward(nmb3)
perhaps set some defined rules For drawing a shape, object or
turtle. lef t(90)
something based on a user inputted random value From a range
turtle. forward(nmb4)
of numbers. It takes a little working out but the effect is certainly turtle. lef t (90)
really interesting.
Whilst it's a little rough around the edges, you can easily make it
moresuitable.
Pvthon Turtle Grs phics ~ n x
1 /A □
TiPHnoniurTiD ljv * /nomp/ p Docu on Code/Turt o Hnd N um u DV{3 4
m
Python 3.4.2 (default, Oct 19 2014, 13:31:11) File £drt Fgrmat Run ^ptions Windows ijelp
[GCC 4.9.1) on linux f i um random jj pot t *
Type "Copyright", "credits" or "license()w for more Information, import turtle
>» ================================ restari ===================
»> pnnt(“ n: >>>>»>>Rai iGOfTi urt
nmb1“int(input(" HJ1
))
>»: ►>>>>>Random Turtle 5quare<<<<<<<<«
nmb2=inT(irput< Enter The second nunber "))
Enter the start nimber: 23
nmb3=iiH(input( Enter the third nimbe
nmb4=int< inpuT< "Ente the fourth nunb
))
Enter the second nunber: 21
Enter the third nimber: 45
Enter the fourth nunber: 33 turtle. forward{nmbl)
>>> ... RE START turtle.left(90)
»> turtle.f orwar d(nn b 2)
turtle.left(90)
>>>»»»>Rsndom Turtle Image<<««<«< turtle.forward(nmb3)
turtle.ieft(90)
Enter The start number: 86 turtle. fonvard(nmb4)
Enter the second nunber: 45
turtle.left(9G)
Enter the third nimber: 86
Enter the fourth nunber: 70 - randint(rmbl* nmb2)
>» i int("\nThe random number between" , nmbl, "and" ■ nmb2 is;\n,r)
Secure Passwords
There's plenty you can do to modiFy this code and improve it Adding a loop to prinb a password FiFty times is extremely easy, For
furbher. For one, you can increase bhe number oF characters the example:
generated password displays and perhapsyou can include special
characters boo, such as signs and symbols. TFien, you can oubpub
bhe chosen password bo a File, bhen securely compress ib using bhe
previous random number generabor as a File password and send ib
bo a user For bheir new password.
P9nL59li1FXLI bCql z
QfnQRj t5qf8pjdPT
mfDGBKIKcvOLilHR
Ri967mcVqChvoHdv
Ro LZWD N lq i CXT lK
znsSGooDsDL4TcVO
KvHKy616flJSdxHE This will oubpub FiFty random passwords based on the previous
$PSk77QPZnE20Cm7
SDWHFc u bPOXM 13 ll random selection oF characters.
UuCR5GhxFL4fWP50
BC yVkm a 09Q r p SMKc ■bbb^i
C2X7addOCsX6xOat O n A Q ^ c c11 'homo^ni/n f>inrio rD nrdt 1 O 'a—' ij V f W —r ■ _.J [J K^P | / (3 4 2) - c1 X
05FvZl5oCHApT7Bx
WYBbbzy3nPqHyTvlb £ile EcJft Firmat jn Qption s Windows Help
2PfTnUv3fzgllb8qH
H820ULLPkXbElL2u string
y57cKCE7IWX8kNHe random
tODdzlQDuSWYCSga
225Hpidc1tdLXP4v
TnJApwXOuiMILGEC Jef randompassword():
l,MnA0V/6HE8pql4fe
chars=string, ascn_uppercase + string. ascn_lowercase + string.digits
9zYtByYRgs0zS2dt
size- 4
2fl0xyped2O8a5ME8
return .join(random*choice(chars) for x ir range(size,20))
Fjd2145MIhwgKMTF
rTYH44thOxPOKJzO
13hM40ZqMcGs6L76 n=0
pntySQlVTRJfC7kll while n<50:
iazbaL45K1Yz9cSc print(randompassword())
s1hzoLLqG2I2kx2z n-n+1
TiLtPlJCzXedrYZS
onSV3wL OQn15KPXI
Random Password Generator/Keyboard Drawing Script
listen()
TheTurtle module is an excellent return "Done!"
resource for the Python programmer. if _ _ name main
msg = main{)
However, what makes it more print (msg)
mainloopO
interesting, is its ability to enable
the user to control the turtle on
the screen. This piece of code does File Edit Format Run Options Windows Help
- move backward
unleash their inner artist.
KEYBDRAW.PY
There are two modules in this script: Turtle and Tkinter. The
Turtle module is the main display, where the user Controls the
drawing, whereas Tkinter simply displays the user Controls.
ff rr
root = Tk()
Artwork
T = Text(root, root title ("Controls") ,height=8, width=60) Just as with ali code, there's always room for improvement
T.pack() somewhere. Here you could change the colours or ask the user
T. insert(END, "Right arrow key = move forward\ which colour they want to start with and then include a key in
nLeft arrow key = move backward\nr = turn right\nl the Controls to change the pen colour whilst drawing. ThereJs
= turn left\nu = pen up\nd = pen down\nh = go home\
also room to increase or decrease the speed oP the pen, again
nc = ciear")
that could be a user-dePined speed. You can also expand the
Controls thoroughly to include a lot more detail and options.
def main():
width(2)
speed(O)
pencolor ("blue")
onkey (up, "u" )
onkey (down, v'd")
onkey (ciear, "c")
Right arrow key = «ove forward
onkey (home, v'h") Left arrow key ■ move backward
r * turn right
onkey (lambda forward(5), "Right") 1 = turn left
onkey (lambda back (5), u * pen up
"Left") d " pen down
onkey (lambda left (5), "1") h * go hope
c s ciear
onkey (lambda right (5), "r")
yg amei
1 m + ■
dd
tains"
f 1 1 ■
lar
. 1
isc
EjTHfKpiKunVH
I Bfw II fli ilsl ■! nftH M i
wMv Wr
" i 'e « T . -V-- fM
b Here
/m g textw Pygame module. Each is ^
recogmsed he code# so you can pull it ^
duise it in \
import pygame
pygame. init()
The JoyOF Text
BLACK = (0, 0, 0) Here, you can see that we've started by dePining the colours
WHITE = (255, 255, 255)
but lePt the text black throughout the rest oP the code; then,
BLUE = (0, 0, 255)
also LePt the display window with a white background. The code
GREEN = (0, 255, 0)
RED = (255, 0, 0) itselP is Pairly easy to Pollow and you can improve it by using
diPPerent colours, changing the Pont Por each text example, and
PI = 3.141592653 | its size too.
size = (400, 500) Try using some oP the text examples individually in your code as
screen = pygame. display. se t mode (size) an introduction toyour program perhaps. Eitherwayyou use
it, it will help make it stand out a little more than the Standard
pygame.display.set caption("Text Examples") Python code you will likely come across during your time as
a programmer.
done = False
clock = pygame. time .Clock()
Black Dog i
Pygame Text Examples/Googie Search ScripL
rsj
print(' \join(format(ord(x), 'b') for x in text))
Fjle Edit Shell Debug Options Windows Help File Edrt Format Run Options Windows H
Python 3.4.2 (default, Oct 19 2014, 13:31:11) print{*t»»»»»Texf to Binary Conv
[GCC 4*9.1] on Linux
Type "copyright°* "credits** or "licen$e()w for more Information text= mput (
»> RESTART
>> print{ * join(format(ord(x),
■■v
"nter text to c
1000100 1100001 1110110 1101001 nooioo
_ iMk.
igraspberrypi:'/Dociaient S/P ython Cocte 1 |
■■
text=input( h l convert to Binary: "■)
printj , join(forniat(ord(x) ,
m u
h Series - Volume 35
* Q ‘i
H
M
Text to Binary Convertor </>
0
n
* * * * *
VI
10000101101001 11011101100001 1110010
1111001 <
$
The text to binary convertor does oPPer some room Por pygame. display. caption {"Binary Conversion")
improvement and enhancement. There are many uses: it could be
utilised in a password or secret word script, as part oP an adventure done = False
clock = pygame. time. Clock ()
game orjust a novel way to display someone's name.
With regards to rendering the outputted binary conversion to a for event in pygame.event.get():
Pygame window, complete with rotating text, you can use: if event.type == pygame.QUIT:
done = True
n
import pygame
.fili (WHITE)
pygame. init ()
font = pygame. f ont. Sy sFont (' , True, False)
BLACK = {0, 0, 0)
text = font.render(Binary, True, BLACK)
WHITE = (255, 255, 255)
text = pygame. transform. rotate (text, text
BLUE = (0, 0, 255)
GREEN = (0, 255,
+= 1 *
RED = (255, 0, 0)
screen.blit(text, [100, 50]) £1
pygame. di splay. flip ()
print ("»»»»»Text to Binary Convertor«««««\n")
| clock.tick(60) H
conversion=input("Enter text to convert to Binary: ")
b
pygame. quit()
(600, 400)
= pygame. display. mode (size)
print(' \join(format(ord(x), 'b') for x in conversion))
0
File Edit Format Run Options Windows Help
import pygame il
pygame*init() Q/
q/
BLACK (0t 0, O)
WHITE = (255* 255* 255
BLUE - (0, 0* 255)
b
GREEN - (0, 255, 0}
RED - (255* 0* 0}
u
screen.fill(WHITE)
font = pygame*font, SysFont( alifrn , 25* Tmi-, F^lse)
5
*
text * font.render(Binary, True, BLACK)
text * pygame.transform.rotate(text* text_rotate_degrees)
text_rotate_degrees += i
vi
screen*blit(text, [100* 50])
pygame.display*flip{) 1
clock.tick(60) <
pygame.quit()
■m-
m— v TT-j
e. 21
from tkinter import Tk
ta f\
_ O X
root = Tk()
File Edit Format JRun Options Windows Help £) root.title("File Browser")
t- ■••• tkinter import Tk
idlelib.TreeWidget
i m p -• i • os
i ' Scroi JiedCanvas, FileTreeltem,. TreeNode C
root - Tk() ai sc = ScrolledCanvas (root, bg="white",
root.title(
item - FileTreeltem(os.getcwdf)]
sc. frame .pack (expand=l, fill="both", side="left")
node = TreeHode(sc.canvas, n item)
node.expando
r-r
fi
root.mainloop(>
/
i* GoogleSerch.py
** KeybDraw.py t'*’ KeybDram.py
—^ Numbertju&ss.py
Mj iMumberGuess,py r* PolygtKiCirde-s.py
■ ^ PoJygonCtrcIes. py
■ ^ findMLtmfien.py
hello.py O
** leapyears.py
** login.py
^ logmtinne.py
namelist.py
:i pnnt hello.py
i
^ pygamel.py
J ovaafnetxt,o\ 0i
LI
*
VI
Advanced Filing
try: *
When executed, the code will display the current directory's *
with open(name,'r') as UseFile #
contents. If you want to see the contents oP another directory, you
print{UseFile.read{)) *
can run the code Prom a command line within the chosen directory;
just remember to call the code Prom where it's located on your print("No files opened") ■
system, as per the second screenshot. You can also double-click any *
oP the Pile names shown in the directory tree and rename them.
ff *
Title - root. title ( "File ) *
*
This is an interesting piece oP code and one that you can insert into label = ttk. Label (root,
your own programs. You can extend the code to include a user Open", foreground="red", font= {"Helvetica", *
# iH
speciPied directory to browse, perhapsyour own unique Pile icons label. packQ *
*
too. IFyouYe using Linux, create an alias to execute the code and
*
then you can run it Prom whereveryou are in the System. *
menu = Menu(root)
*
root. config (menu=menu) *
Windows users may have some trouble with the above code, an
#
* R
alternative can be achieved by using the Pollowing: file = Menu (menu)
Files","*.*")), H
lt's not quite the same but this code allows you to open Piles
title = "Choose a file,"
in your system via the Pamiliar Windows Explorer. It's worth
*
b
)
print (name)
experimenting with to see whatyou can do with it. *
*
L* □ *
*
File Edit Format Rui ion: ;□ He
from tkinter import *
from tkinter irnoort ttk
froir tkinter.filedialog askopenfilename
*
*
root Tk( }
:lef OpenFile () :
# D
ri
name = askopenfilename (mitialdir= C:
filetypes - ( V' rr
t
m * rt ),("All Files II
t
II M
' ")) , *
u
title = "Choos a rr
□
)
prine (name)
*
*
t" rv *
with open(name,1r1|
print(UseFile.read()}
as UseFile: *
* H
except;
print("No files opened")
#
* u
*
#
*
Title = root.title< "File Opene:;w)
label = ttk-Label (root f text =‘File Open", foreground="redn, font= (' THelvetica™, 16))
label.pack()
* fi
*
menu = Menu(root) *
root.config(menu=menu)
a
file = Menu(menu)
VI
root.mainloopI) 1
*
*
<
*
11
Ln: 11 Coi: 28
6
* * * * * * 4
OJt/
0 □ (51
def kl01():
4 h screen.onscreenclick(click _ handler)
£ile £dit
turtle
Firmat Sun £ptions Windows Help
Screen, Turtle
A
« j screen ■ 5creen() def click _ handler (x, y):
w c yertle = TurtleQ
screen. onscreenclick (None) # disable event inside
□ 5 k 101 f ):
event handler
screen.onscreenclick(cLickJrandIer)
0 € click_handler(x, y): yertle. setheading(yertle .towards (x, y))
screen.onscreenclick( Ione) # disable event inside event handler
Yi
1 I -1
AI yertle .setheading(yertle. towards(x, y)) yertle. goto (x, y)
yertle.goto(x* y)
screen.onscreenclick(clickJb3ndIer) # reenable event on event handler exit screen. onscreenclick (click _ handler) # reenable
5 ^
screen.onkey(klOl, > tt space turns on mouse drawxng event on event handler exit
□P
screen.listenf >
screen*mainioo P() screen. onkey (klOl, " ") # space turns on mouse drawing
H 4
screen. listen()
□
0 M
/ screen. mainloop ()
°/c
S *i
2nd Code Example:
U
@ shape ("circle")
pencolor ("blue ")
9 c ;\
width (2)
y U 1
E yi o
ondrag(goto)
m j listen()
B □
fjfe J~dit Firmat Bun fiptions Vfindows Heip
turtle
a shape("circi
□
pencolor("b1
mdth(2)
ondragC goto)
listenC) Ninja TurtleMouse
G~ 51 #Warning * This code can erash Python* so use it sparingly.l
iJ 9 B5 mi ■ ' 1 L JJ o
i
5
M C \\
1 □ a e
w ?1
9 7
r r
9 sm * '2 m
eo
I I f □
□
108 Black Dog i- ies - Volume 35 e\
□ n A
i—i
Mouse Controlled Turtle/Python Alarm Clock
teli the code how many minutes until print ("Interrupted by user")
sys.exit (1)
the alarm goes off.
Wakey Wakey
ALARMCLOCK.PY There's some good use of try and except blocks here, alongside
some other useful Loops that can help you get a firmer
This code is designed for use in the command prompt, be that
understanding of how they work in Python. The code itself
Windows, Linux or macOS. There are some instructions on how
can be used in a variety of ways: in a game where something
to use it in the main print section but essentially it's: python3
happens after a set amount of time or simply as a handy
AlarmClock.py 10 (to go off in ten minutes).
desktop alarm clock foryour tea break.
import sys
import string
Linux users, try making the alarm clock code into an alias, so
from time import sleep you can run a simple command to execute it. Then, why not
integrate a user input at the beginning to ask the user for the
sa = sys.argv length of time they want until the alarm goes off, rather than
lsa = len (sys.argv) having to include it in the command line.
if lsa != 2:
print ("Usage: [ python3 ] AlarmClock.py duration _
in _ minutes")
print ("Example: [ python3 ] AlarmClock.py 10")
print ("Use a value of 0 minutes for testing the
alarm immediately.")
print ("Beeps a few times after the duration is over.") c : VUsersAdavidVDociiaentEA Python >pythcn alar-B£locEc.py 10
kleeping for 10 minutes
try:
minutes = int(sa[l])
except ValueError:
gys.exit r)
I remember
The dark woods, masking slopes of sombre hilis;
latjL^
The grey clouds/ leaden everlasting arch;
t*xi IliC
The dusky streams that flowed without a sound,
And the Ione winds that whispered down the passes.
'".split('\n')
class Credits:
def _ _ init _ _ (self, screen _ rect, lst):
self .srect = screen _ rect
self. lst = lst
self.size = 16
self. color = (255,0,0)
self .buff _ centery = self .srect. height/2 + 5
self .buff _ lines = 50
self.timer = 0.0
self.delay = 0
self.make surfaces{)
while running:
Ln: 1 Coi: 0 I
for event in pg.event.getf):
if event.type == QUIT:
running = False
H
screen.fill((0,0,0))
u
cr ed. update () #
cred. render (screen) n
pg. display. update ()
r
clock. tick (60)
0
5
ALong Time Ago...
vi
The obvious main point oP enhancement is the actual text 1
itselP. Replace it with a list oP credits, or an equally epic opening
<
storyline to your Python game, and it will certainly hit the
mark with whoever plays it. Don't Porget to change the screen
resolution iP needed; we're currently running it at 800 x 600. 6
4
cu
^ t/
import time
import tkinter as tk
tick (timel=''):
# get the current time from the PC
time2 = time, s trft ime ('%H:%M:%S')
if time2 timel:
timel = time2
clock. config (text=time2)
| clock.after(200, tick)
root = tk.Tk()
clock = tk.Label(root, font=('arial', 20, 'bold'),
bg='green')
clock .pack (fill=' both', expand=l)
tick()
root.mainloopO
_ □ X
nQ
to\
«i
/fs X
u i y s_/ lock.py - /hoi 1 1P f i j 1 1/UIQwlOCK.DV l^ \JLi *- D
File Edit 1Firmat Run Option s Wir dows Help
inp n i
tkinter ■_ tk
clock.after(2G0f tick)
root * tk*Tk{)
clock * tk>Label(root, font={ 20 ). bg=
clock.pack(fill* both , expand-1)
tick()
root.mainloopt)
Python Digital Clock
Qclassmethod
Tick Tock def main(cls):
This is a piece of code we’ve used many times in the past to keep tkinter.NoDefaultRoot()
root = tkinter. Tk()
track oP time while working on multiple monitors and with just a
root. title ('Stop Watch')
quick glance to where we've placed it on the screen.
root.resizable(True, False)
root.grid _ columnconfigure(0, weight=l)
The Tkinter box can be moved around without aPPecting the time, padding = dict(padx=5, pady=5)
maximised or closed by the user at will. We haven't given the widget = StopWatch (root, **padding)
Tkinter clock window a title, so you can add to that easily enough widget. gr id (s ticky=tkinter. NSEW, **padding)
by snipping the code Prom other examples in this book. root.mainloopO
Another area oP improvement is to include this code when def _ _ init _ _ (self, master=None, cnf={}/ **kw):
Windows or Linux starts, so it automatically pops up on the padding = dict(padx=kw.pop('padx', 5), pady=kw.
pop('padyY 5))
desktop. See also, iPyouTe able to improve its Punctionality by
super(). _ _ init _ _ (master, cnf, **kw)
including diPPerent time zones: Rome, Paris, London, New York,
self .grid _ columnconfigure(l, weight=l)
Moscow and so on. self.grid _ rowconfigure(l, weight=l)
self. _ _ total = 0
self. _ _ label = tkinter.Label (self,
Rie Edit Format Run Qptions Windows Help
|| import tkinter G
text='Total Time:')
import time self. _ _ time = tkinter.StringVar(self, '0.000000')
lass StopWatchftkinter*Frame): self. _ _ display = tkinter. Label (self,
@ciassmethod Total Time: 2.259363 textvariable=self. _ _ time)
def main(cls):
| tkinter.MoDefauItRootC) stop | self. _ _ button - tkinter. Button (self,
root - tkinter.Tk()
root,title( ‘ Stop Watch') text='Start', command=self. _ _ click)
root,resizablefTrue* False) self._ _ label. grid (row=0, column^O,
root.grid_columnconfigure(0* weight=1)
padding 35 dict(padx«5P pady-5) sticky-tkinter.E, **padding)
widget = Stopv/atchf root, **padding)
widget ♦gnd(sticky-tkinter,NSEW, +*padding) self. _ _ display.grid(row=0, column=l,
root,mainloop()
sticky=tkinter.EW, ** padding)
det _init_(self, master=None, cnf={}, **kw>:
padding « dict(padx“kw.pop(’padx’, 5), pady®kw.pop(’padv‘, 5)) self. _ _ button.grid(row=l, column=0,
syperf)._init_(master( cnf,
self.grid_columnconfigure(1, weight-1) columnspan=2, sticky=tkinter,NSEW, **padding)
self,grid_rowconfiguret1, weight=1)
self._total ■ 0
self._label = tkinter.Label(self, text= Total Time: ) def_click (self):
self._time * tkinter.StringVar(selfr *0*000000+)
self,_display = tkinter.Labei(self* textvariable=self*,_time) if self. _ _button['text'] == 'Start':
self._button - tkinter.Button(selfr text-Start", oomnand-self._olick)
self._label.gnd(row=0, column=0, sticky=tkinter.E, **padding) self. _ _ button ['text'] = 'Stop'
self,_display.gridCrow-0, column-1 r sticky-tkinter.B/, **padding)
self,_button.grid(row=1, column=0. columnspan-2, self, _ _ start = time.clockO
stlcky-tkinter.NSEW, **padding) |J
self. _ _ counter = self. after _ idle (self. _ _ update)
def _click(self): I
if self._buttonr text1 ] « "Start*: j
else:
self._button[“te *t'] - Stop' self. _ _ button ['text'] = 'Start'
self._start = time.clockO I
self._counter - self,after_idle(self._update) self .af ter _ cancel(self. _ _ counter)
e Ise:
self._button[*text1] - ‘Start" I
self.after^cance1(self._counter) (j
|Ln= 12|Col: 22
def _ _ update (self):
now = time.clockO
Another example, expanding on the original code, could be a diff = now - self. _ _ start
digital stopwatch. For that you could use the following: self. _ _ start - now
self._ _ total += diff
import tkinter self. _ _ time.set('{: .6f}'. format (self. _ _ total))
import time self. _ _ counter = self .after _ idle (self. _ _ update)
Code Repository N u ? n s 0
er i u m 7
□ # U I
Gi Vi
\
if
V
The
. E r ^ («j B C MUSICPLAY.PY
The code is remarkably simple and can be played with very
a o <S U Few lines to clutteryouralready Fully-loaded program. Insert
this code and make sure you've either provided the Full path
i q
A □
er meara ruer w si to the MP3 or it's in the same directory as the Python File.
Forvthiswe e the pygame.
k a
import pygame, sys
ction, along wi G~ L*J
from pygame.locals import *
IU ^ mixer. A- pygame. init()
A I/Vl T ..
l ra
Ot
mus screen = pygame.display.set _ mode((640, 480))
7 x screen.fill((0, 0, 0, 255))
«
o Ca
_|_
a pygame.display.set _ caption("Pygame Music Player")
W
0
□ o m■
m
1
!ni
fi i
pygame. mixer. music. load("Superman .mp3")
□ I while True:
for event in pygame. event, get ():
E €
if event.type = pygame .QUIT:
vi Q pygame, quit()
sys. exit()
pygame .display .update ()
' VI □ Y h rsj
□.
0 4
0 M Just Play the Music and Dance...
of 9 There are a Pew extrasyou can apply here to make the music code You can also insert a small section oP the code into a previous
a little more interesting. For one, how about creating a list oP the example used: the Vertically Scrolling Text code Prom Page 108.
E *! available MP3s on the System, then oPPering the user the choice oP For example, you can have the bulk oP the code displaying the text
music to play via a simple list and input Punctions. itselP but then you can insert a couple oP lines to play some music
alongside the text. Making it an excellent opening to a Python
a " game or presentation:
@ File Edit Format Ruo Options Windows Help
y si ef make_surfaces(self):
self.text = [J
for i, line r enumerate(self.Ist):
1 s self,make_text(line)
m j l[l},y +- i+self.buff_lines
$ □
self.text.append(1)
def update(self>:
f pg.time.get_ticks()-self.tuier > self.delay
self.timer ~ pg. time.get_Utks()
a SI for text, rect in self*text;
□ i Insert these lines just bePore the While loop in the Vertically
rect.y -« 1
.e runmngt
f os event pg.event .getO:
if event.type ** QUIT:
runmng - Fa 3 se
screen.fili((0,0,0))
cred *update()
cred * render(screen)
pg.display.updatef)
clock,tick(6Q)
(^Pygame Music Play er/Python Image Slideshow Script
'/home/pi/Pictures/5.gif'
Displaying images in Python can be tricky ]
at times. Some modules work better than
x = 100
others at displaying certain image media y = 50
app = App(image _ files, x, y, delay)
types. Pygame is often the main choice app. show _ slides ()
but Tkinter can do a better job whilst app.run()
itertools 'i
Sliaeshowpy - /homs/pi/DQCurnenEs/^yChon Cods/Slidesndw.py
Firmat
• cycle
flun fiptions Windows Herp
• • App(tk.Tk):
"‘■Tk windaw/ label adjusts to size of image11'
tk.Tk. init_fself)
seif.geometry£ ■
se |f-<V «■ dslay
- .forma tc*. y))
Using Tkinter to display a series of images as a slideshow S*lf .plCIUTM = CyC l£( { tk . PhOIOlUl
image
self,pictuie_display = ik.Labeltself)
se H.p it t u r e_d ispla.- .patk()
£ f 3 1(j-image ).
image_f iles)
Unige)
img_obj*ct. - nextfttlf.pictures)
However, the images need to be saved as a .GIF. se If.p icture display .CDnf ig{ image--im&„Dbject)
class App(tk.Tk):
'"Tk window/label adjusts to size of image'"
def _ _ init _ _ (self, image _ files, x, y, delay):
Slideshowing Off
If you store your images in the same directory as the Python
tk.Tk. _ _ init _ _ (self) script is executed from, then you won't need to apply the full
path destination as defined in the image_files list; you simply
self.geometry('+{}+{}'. format(x, y))
name them 1 .gif, 2.gif and so on (or retain their full file names).
self .delay = delay
. App(tk.Tk);
■"tk nindomrlabe 1 adjusts to size of image’”
o• ■ ini t .<se If . image _f 11 es. x . y. delay);
tk.Tk._init,_fself)
img _ object, img _ name = next(self .pictures) solf-geoflmryf ■< ■ !• -< i1 .formatjx, y>)
self.delay - delay
self .picture _ display. config (image=img _ object) 34 lf. picturas * cyGl*(< tk rPhmoiniag4j; f il*™ image). image)
I image image_files)
self.picture_display - tk.Labelfself)
S4lf-pictur#_displjy-pack()
* - r ■ stio«v_s lid es t se 1 f) ;|
" ' "cycle rhrougri the images and display them' ' '
se 1 f. 111 le [ img_ri^ne )
self. after (self .delay, self.show _ slides) se L f. af te r (se t f . de 1 ay, self. shcrrt^s 11 des)
run(self);
self.mainloopE)
» set miliiseconds time between slides
def run(self): delay - 3500
ut g?t a series of g;F im^grr. you h^ve m the working f-ijlder
S ar use full path. or set directory tD insere the images are
t = 250
p = .50
trisi ac--j.Ti.di
t ime
FZJ3TAJITi C; /'tJiers^dttTsd/IJDcansentj/tTtliiaii/BHStn.pr
11C = 65
1C = 131
lDb = 139
ID = 147
lEb = 156
1E = 165
1F = 175
1Gb = 185
InS Cr C In: 7 Cnl
1G = 196
1 z U Q oCI
lAb = 208
■ irr IA = 220
;:\Usen\david\Doc ument s\Python>python Kusic.py lBb = 233
>achelbel's Canon in C«
1B = 247
Injoy
C = 262
Db = 277
>ress the Enter key to begln.
D = 294
Eb = 311
i. T i ITT
E = 330
L#r- luilt.py - Ci/Uiers/david/DotumtntVPytKon/ML sic.py (3.6.2) — D X
F = 349
File Edit Formet Run Qprions VYindow Hetf
1 lftipC
—nlP - r
r wir.sound
l t ijnt
A
Gb = 370
Lt (" Pacheibei" s Canor. 1:1 C." | G = 392
p : :: t (" nEn j c yv r.,r)
prirLt(" -.nh *5>
f. rirLt { ^ Frc-a a Cite Ehter tty to bcgi_n. ")| Ab = 415
' "p'„:Lt O
A = 440
t = 25Q
P = .50
Bb = 466
11C = 65
1C = 131
B = 494
lDb “ 133
ID = 14"
f lEb = 156
| IE ■=■ 165
1
= 175 hC = 523
1Gb « 185
1G = 156
| JLAfc = 108
hDb = 554
IX = 110
hD = 587
M
eo
n
lBb
II
13 - 147
hEb = 622
C = 161
Db = 277
D ~ 294
hE = 659
Eb = 311
1 E - 330 hF = 698
E = 345
Gb
G
=
=
370
392 hGb = 740
Ab - 415
A -
3b = 466
440
hG = 784
S - 494
hAb = 831
ht - 513
hDb = 554
hD = 55"
hA = 880
hEb - 622
hE
£F
=
-
655
638
hBb = 932
hGb = 740
hG = 7S4 hB = 988
hAb - 331
hA = S30
hBb - 932
hB = 5SS
m u ?
□. a
116 Black Dog i- es - Volume 35 \/
a t
H
3
153
n
Playing Music with the Winsound Module </>
2H
winsound .Beep ( G, t) *
winsound. Beep ( B, t) Naturally you can swap out the winsound.Beep Prequency and *
winsound. Beep ( hD, t) durations to suit your own particular music; or you can leave it as #
*
time. sleep (p) is and enjoy. Perhaps play around with the various methods to
*
make other music. *
vl
winsound. Beep ( IA, 2*t) *
*
winsound. Beep ( A, t) For example, players oP the Nintendo classic game, The Legend *
*
winsound. Beep ( hC, t)
oP Zelda: Ocarina oP Time, can enjoy the game’s titular musical
winsound .Beep ( hE, t)
intro by entering:
time.sleep(p)
(698, 500), *
(784, 250), *
winsound .Beep ( G, t)
(880, 500),
time, sleep (p)
(587, 500),
(523, 250),
winsound .Beep ( 1F, 2*t)
(659, 250), *
winsound .Beep ( F, t) *
(587,
winsound. Beep ( A, t) n
winsound .Beep { hC, t) ]
import time
cmd == “1
ragged()
def start():
f and ==
Volume 35
H ;
3'>
Rl "
Adventure Time EJ
This, as you can see, is just the beginning of the adventure and 'o
takes up a fair Pew lines oP code. When you expand it, and weave £dit Firmat Bun fiptions Windows tJelp H
the story along, you'll Pind thatyou can repeat certain instances
^ ‘-f \ ^ #
print(M\ir # 200) b;
such as a chance meeting with an enemy or the like. CR=0
Strength^O
Health=0
Luck*0
We've created each oP the two encounters as a dePined set nortih make for a htard iIlli&
■* rf
print(”The mountains ol [Q
)
pr iru( Press Enter to r 11 ne u ice and see ho■ VT Ii r nOc name* ls:*)
oP Punctions, along with a list oP possible choices under the input()
Strength=randcxn. randmtc U20)
cmdlist list, and cmd variable, oP which is also a dePined Punction. printtname, 1 I ar a St engtfi v Strength)
print(M\nlfs a hard life ind I northeners are born warnors. )
Expanding on this is quite easy, just map out each encounter and print("Press Enter to roll th l-J I * the Combat Rating for * name+
input()
choice and create a dePined Punction around it. Providing the user CR=random,randint(1, 30)
fi
print(name, ‘has a Comt ating CR)
doesn't enter quit into the adventure, they can keep playing. pnnt( n ur m#Health i? r Strength and Combat Rating, •)
print(*Pn s Ent name Health value.’)
input() t)
Health=Strength+CR
There's also room in the adventure Por a set oP variables designed print(name, 1 i is i 11 ~ i1 Ui? O HeaIth) u
pnnt("\r m ve r yoi needs .er r a i n am < int of luck to survive*”)
Por combat, luck, health, endurance and even an inventory or print( Press En id see how lucky", name* "is
%
□
input()
amount oP gold earned. Each successPul combat situation can Luck-random.randint{1, IS)
if Luck > 13:
reduce the main charactehs health but increase their combat skills prirxt(name, ig lud i d h ck value * Luck)
or endurance. Plus, they could loot the body and gain gold, or earn print(name, , Luck) H
gold through quests.
tune.sleep(5)
pnnt( ' \n" *200)
print("Here*s yo )
u
pnnt(name)
print( nConbat n? Ung = , CR)
#
Finally, how about introducing the random module. This will enable prmt( "Strength = ,,# Strength)
print("Health =" * Health)
print("Luck Luck)
n
you to include an element oP chance in the game. For example, in print("\n” *5) n
pnnt( ‘Press Ente ir adventur
combat, when you strike an enemy you will do a random amount mput()
J al
You could create a game oP dice in the inn, to see iPyou win or lose
A ragged looking man* and a pair rou' nK zuar
5
gold (again, improve the chances oP winning by working outyour
d^f start():
pr int {"\n .w)
*
printpOo you approach the,.,")
luck Pactor into the equation). printC^Vn")
vi
pnnt( 'i . Ragged looking man”)
print(n'2. Dangerous looking guards' )
1
Needless to say, your text adventure can grow exponentially
<
and prove to be a work oP wonder. Good luck, and have Pun with
your adventure.
6
4
ai
t/
root = tk.Tk()
canvas = tk.Canvas(root, root.title ("Ticker Code")/
height=80, width=60Q/ bg="yellow")
canvas .pack ()
£ont = ('courier'’, 48, 'bold')
text _width = 15
tHwittr ik
font=font)
dx = 1
dy = 0 # use horizontal movement only
i - s|'
# the pixel value depends on dx, font and length of text
LL, i i!! L Utk-f I '_[* ■ L !
J-rtT >
tr H, ^ p [ Q* . 15
Cinw.itiMpli. Ill
■ frVl.MJlilBUpC "i
pixels = 9000
7
a □
sck Dog i-Tec
□
Python Scrolling Ticker Script/Simple Python Calculator
Select operation,
1 ,Add
2,Subtract
3. MuItiply
4. Divide
Improved Calculations
The obvious contender for improvement here is using the
Create Your Own Modules route and extracting the function
definitions as a module. You can then call the module and focus
on the body of the code.
>W
board = ['"
cc
JJ
i^LJ »»»»»Hangman«««««
+-+
•ralvEE
r r r \r f
f ff \! f
/
r r f \FF
H
3
m
Hangman Game Script
dangerous entertainment exhausted impossible with open ("/home/pi /Downloads/words. tx t", "rt") as f: l
*
V s
VV ‘ ir -v - -
1-
1 - *■ a
SRv i v ' ’ -
S \v' *?s
i vvs'*. '
' '
!a-»
INSTALLING SCRATCH
Scratch can be run inside your web browser at scratch.mit.edu. You need to have Flash installed in your browser; if isn't already,
it can be installed from get.adobe.com/flashplayer. Sign up for an account with Scratch so you can save your programs.
STEP1 ' Scratch runs from inside the web browser. Click Let's take a look at Scratch Cat. Use click and drag
STEP3
_ W Create to open a new document. The Scratch _ W with the mouse to position him on the Stage. At
interface opens in the web browser, click the maximise button on the top, just above Scripts, youTl see two icons for Grow and Shrink.
your browser so you have plenty of space to view the window and Click one and click the cat to resize him. Shift-click on Scratch Cat
ali its contents. and choose Info to access rotation Controls. Click the blue back
re - Moxll:i Ufefny V □ LM «{() lK • i 0
button to get back to the Sprites pane.
+
4 U >nil ril) E? Q, * 6 ^ r * (s
Cieate Sapiar* C^Luii AbDui H±t|_. O
WiKi WcdnMdp.jp
Cb«n out ne n&n w Wedntwty
pejt. ■ new se-r** f ignligjung <Kf
Sonlch WHii'
3intiFl 'Sutyt/
*iaip ne ££reun Teera ir-a
'jiralch t
Fealured Projocts
STEP2 You can see the Scratch interface with a list of blue STEP4 Scratch Cat looks a little lonely on his white space,
items in the Block Palette, an empty Script Area W so Let's give him a background. Click the Stage icon
and a Stage. On the Stage will be an orange cartoon cat, known to the left of the Sprites Pane. The Script Area switches to Backdrop
as "Scratch Cat". This is the default sprite that comes with ali new Library displaying the available backgrounds. Click Music and Dance
projects; you will also see smaller versions of the sprite above the and choose spotlight-stage. Click OK.
Script Area and in the Sprites Panel.
* * • « • •
The background appears on the Stage and Scratch Dragtheturn [15] degrees block (with an
STEP5 STEP6
_W Cat looks a lot happier. Let's create a script that anti-clockwise symbol) Prom the Block Palette
moves him to the stage. Click Spritel in the Sprites Pane to select to the Script Area. Now drag the move [10] steps block and
the cat and click the Scripts tab to return to the Script Area. Now connect it to the bottom oP the Turn 15 Degrees block. They will
click the blue Motion tab at the top oP the Block Palette. snap together. Change the 10 in move [10] steps to 100. Our
UntitlEd-S on Scratch - Moiilla Firefox
program is now ready. Click the script (the two blocks) to see what it
UntitLed-S o ni Sera tch*
does. Scratch Cat will rotate and move towards the stage.
4» H ■ 8 ■ ■ h fi ©
x + ;; © tlntJtLcd-i on latr.ifeK- Moxltla F-Ire-fo* *)) i • O
|unrtrtlad-5 BcnpU
by ul .-hatLeraiev i JTshared ^r' UnlilkiJ SflivScrjtth *
^ H *« ■niLedu & £ * It £ © - a □ =
^Lrtpl-
S-OTt now U lutTfijllnn.li'Tf
tKismrsrm
ii .«-
av (ufmartttThfv ujmlwidj
ii
ii I
|P
im
ex
Ljir t» BSflUS*"P*JnE*J
x: 24$ y; i?q
I«CI tC PCI
Sprites New SDrite: ^ / m (3l sio yc r
stage I SprltP J
□
2 biZ .'irjp* r IbiHriiinfaf %
kSj
Uiv. biCrd'lip. I ia lucti1 cc-
A ,/iL\
Click File > Save Now to save your project. Enter Lots oP example Scratch Piles can
a nanrte in the New Filename box; we called ours MIT website by dicking Explore. \
cratch_Cat_On_Stage". As we mentioned in both Python and a huge range oP projects built by other users and
lix tutorials, it's important to avoid any special characters and able to share your own projects. Choose a projec
>aces in your filenames. Use underscoresinstead.
JntJtle-dvd on licrat-ch ■ MozJLLa. iJrefca
p P Str-aUh -
' ■ ■
ituttot
WSI Bowling
#.K 1
ffltl
I £cr*tth_CiUOn_H *
AbMUI He,'I|j
Scratch_Cai_OnSiage
Circle Recursion Fracta!
L. _i h m
Wf JL
1 iStf 1 Jh
viphi jjF
Ll 1 Li
■
1
/\
Ipt* lr F3k urjlpi
r W Ll ui Jvi- Lu 5K.-fcrt_li.-vJ lH
*- r#sg
P ii.kifu.ii i |- - r i.i iS ii I h- 'L t-.v l OVii-riji '
M — - —C, exteh (ani-.j -rw.yj
'■cnanfl# ceief efleci a
jWp nw5H! Jaar Bae: - De Qowm
#
«
VISUAL CODING
The scripts in Scratch are created by snapping together blocks. These blocks are similar to the code you find in more complex
programming languages, such as Python, but much easier to understand.
Click Create to start a new Scratch project and Click the Motion tab and drag the move [10]
STEP1
name it Dancing Cat. YouYe going to put your cat steps block and connect it beneath the when
and some other characters on a dance floor and get them to bust flag clicked block. A quick word about that [10]. When you write
some moves. Click Stage, then Music and Dance and choose party- a number or word inside those square brackets, that's the way of
room. Drag the Scratch Cat graphic around the Stage to find a good saying you can choose a value. It's the equivalent of a variable",
starting position. because it varies. We’ll teli you which number or selection we're
using but you can use any you want. Play around.
Click on Spritel in the Sprites Panes and click the lt's not much of a disco, so let's add some sound.
STEP2 STEP4
Scripts tab above the Scripts area. Now click Events _W Click the sound tab and drag play drum [8] for
in the Blocks Pane and drag the when flag clicked block into the [0.2] beats and connect it to the bottom of the stack of blocks.
Scripts area. This block represents the start of your program. It telis Click on the blocks and Scratch Cat will move and a sound will come
Scratch to run through the blocks below it when we click the Green fromyourspeaker.
Flag icon above the Stage window. UnUUed-S on Scratch - MozlLla FLrcfox
§ Untitted-Son Scratch x
♦ H
urtitled-s on Scratch
■1 A hLLpj /
*
mil.edu | ☆ ii © 4r fr e
Fffe-* rdit* Tlp* Aboul x+
w j Dancing_cat Scripts
rMeT EditT Tlps Abo-uL Save n 40 by luwhatttrstey (un&hared)
| MiJtl&n | E'mWU
Share
i'***
Sound
I 'introi
I' | apergEora
I | More tslocks
jc; iio y; w
Sprites New sprite: ^ / l«3
Steg
Lege Spritel
2 I. id di
Imn Lsicklii?fi
BS/£
BBt&P&Ck Baixf.nck
Dancing is a back and Forth aFFair, so let's get Scratch Scratch Cat only moves back and Forth once, which
STEP5 STEP6
Cat moving back. Drag another move [10] steps _ W isnt much oP a party. Click Control and drag the
block to the bottom oP the stack. Now click the 10 and change it to forever block to the Script Area. CareFully position it beneath the
-10 (minus 10). Entering minus Pigures moves the cat backwards. when [flag] clicked block but above the move [10] steps
Drag another play drum block to the bottom oP the script. Pick a block. The script should nest within the two prongs oP the forever
diPPerent drum sound. We chose 13. block. Click the Green Flag icon to start the disco. Click the red Stop
icon to end the program.
f//
r
www.bdmpublications.com The Python Manual 129
Learn Object Orientated Proqramming with Scratch & Python
Your Scratch Cat is now dancing back and Forth but wouldn't it be great if you could
control him. In this tutorial youVe going to look at creating keyboard interactions in
Scratch. Let's get our disco cat really grooving!
INTERACTIVE CONTROL
The only Control option weVe really looked at so far is the when [flag] clicked block, which starts the program. Once the program
is running it does its thing, right up until it finishes. YouVe going to use the other Control blocks to do something more interesting.
Open the Dancing Cat program From previous WeVe going to make Scratch Cat jump up and down
STEP1 STEP3
tutorials. Select Spritel and click on Events so you when we press the space bar. Click Motion and drag
can see the when [flag] clicked script. Now click Control in the change y by [10] and clip it to the when [space] key
Block Palette and drag the when [space] key pressed block to pressed block. What's with the "y"? This is what's known as
an empty part oF the Script Area. a "coordinate".
Untitkd-5 on Scratch - Mozilia FireFox
JT E- Untitled-5on Scratch *
a + :: ;;
Shar^ ■lA&taH
change y by feE?
ni (jur1
■ 1
|jy foir {
9
nurui: 1 $tep£
1
€E& h01 i 0,2
k y;
recs to sr
New sarite: ^ / {■) (2l
LCJ
Stage Spritel E*
2 b»ci(drops
rlbjcl ;roa:
H/<£ua
Q. - Q.
^ You can drag and rearrange the block Scripts to any The position oF each sprite on the stage is shown
STEP2 STEP4
_W part oF the Script Area. We like to have our when _W using two variables, x and y. These are reFerred
[flag] clicked Scripts in the top leFt but it really doesn't matter to as the "coordinates", The x is the sprites horizontal position
where they are. It's also worth spotting that we now have more than on the stage whilst the y coordinate is the vertical position. Click
one script For Spritel; you can have multiple Scripts For each sprite in and drag the sprite around the Stage and you'11 see the x and
your program. numbers change.
r+~[' i7:5& Untftled-5 on Scratch - Mozilla Firefox
W ■■ Untltled’5 on Scratch x v|i
,rti Qt Search
peditor V t) H ) ® fi https://scratch.miLedu C H
f±J lucyhattersley*
| Motion Events ©
| Lc oks | Control
| Sound 1 Sensing
1^
| Data
| Operat ors
| Mgr€ Rlocks
y: 25
move:
ID.
play dium
> Y- 16 -
Stage
2 b4clidr»pi
f ba(.«.droi5
ca /«i) a
The centre oF the Stage is x: 0 and y: 0. As you move What goes up must come back down. So drag
STEP5 STEP6
_ W the sprite up and to the right the numbers increase _ W another change y by [10] block and attach it
and as you move it leFt and down they decrease (going into negative to the bottom oF the when [space] key pressed script. Now
numbers). So when we use the change y by [10] block it says, change [10] to [-10]. Click the Green Flag and run the program.
take the current value oFy (the verticat position) and increase it by Now press the space bar and... oh no, nothing happens. We've just
10. That makes our catjump up. encountered our First "bug".
i. Iii.ii i y e y by
iO change y by
STEP1 The problem is that programs are super Fast and STEP3 Drag a block From the Blocks
highly visual programs like Scratch can move in Palette and insert it underneath the hange [y]
the blink of an eye and that's what is happening here. If you tap by 10 block. Now press the space bar on the key boa rd to see
the space bar repeatedly while the program is running youll see Scratch cat jump up, and then back down. Notice that you don't
Scratch Cat flickering as itjumps up and down. need to press the Green Flag icon to run the program; the Green
5%^
w Jr mr JFy M j
change y by
wait set s
change y by |
...
STEP2 The challenge is that our motion Controls move the STEP4. We think Scratch Cat stays in the air a bit too long.
cat instantly From one place to another, so Fast that We want a jump, not a levitation eFFect. Change
we can't see. Sometimes this is Fine, like our back and Forth dance, the wait [1] variable to IFfllsKll. This is a quarter oF a
but obviously we need to slow down the jump. Help is at hand. second and will give us a more Fun hop. Press the Green Flag to
Click the Motion tab to view the Motion blocks. start the script and tap the space bar whenever you want Scratch
x: 0
Cat tojump.
| Operatore y:-15
I Blocks
r
www.bdmpublications.com The Python Manual 131
Learn Object Orientated Programming with Scratch & Python
LOOK SPRITE
Sprites are 2D (flat) graphics drawn on top of a background. They are commonly used to display information in games such as
health bars, scores or lives. Older games are composed entirely of sprites, just like our Scratch project.
* *
We're going to add another sprite to our project and Ali the blocks on the Script Area have vanished. The
STEP1 STEP3
W a second character to the scene. Click the Choose _W scripts we built for Scratch Cat relate to that object,
Sprite From Library button, just above the Sprites pane. This opens not to our new sprite. Click on Sprite 1 in the Sprites pane to view
the Sprite Library that displays ali the different characters available. the Scratch Cat scripts again. Then click Ciga to return to your
Giga character.
Click on the Fantasy link in the sidebar and choose Now that we have more than one sprite, it's a
STEP2 STEP4
_W Giga. Click OK to add the character to the stage. good idea to name them. Click the "i" icon next to
Click and drag the sprite to reposition Giga to the right of Scratch Spritel. Change Spritel in the text box to Scratch Cat. Take a look at
Cat. Notice that a Giga icon has joined Spritel in the Sprites pane. the other options here. You can remove a sprite from the stage by
unticking the Show checkbox, without deleting it from the project.
UntitLed-5 on Scratch - MoziUa Fireftj*
Untitled-5 on Scratch x
1 Motio n l Evente
Contrai
| Sound | Sensi ng
| Pen | Operator5
| Drjf h J More- BiOCkfi
Scratch Ca!
** /i show: Yf
* * • «
^ Select Giga and choose Events. Drag a when WeYe quite sure you can see where this is going.
STEP5 STEP6
_W [space] key pressed and change [space] to W Press the Green Flag icon and our Scratch Cat object
[right arrow]. Add a change x by [10] blockbeneath. will start to dance and stili jumps with space, whilst our other
ShiPt-click the script and choose duplicate to create another. For the object, Giga, can be moved left and right using the arrow keys on
second script change the when [right arrow] key pressed to our keyboard.
[left arrow] and change x by [10] to [-10].
Unlille-d i on Scratch ■ MDjrillii F|rpfmi
Mu" i L>n.
II
4
E
M Itip-f
wlim leftarrnw key prcMctl whfii ■ jiv" nfrow kt?y |>t
t .
Mrhi»n luit j”u.v lir-y pr**i*rcl pAThi^n c-jhf VTft*
chaitge h by BM change x by ^*1
t honrjf k hy BfU j changij x by
m: ai? y: a«D
2
jS-5 J-!
hiillillfl
'j! i 41i
o
_3a*=J
ihicliriittip i
NVWbtfUfcW
Scratch P jia
Nmj IiuHM-flci
**/in
££E3S
q, = a
* = a.
CHANGING
Oar two objects, Giga and Scratch Cat don /e to look like the original characters. That's just the name wefve given to each
sprite. The visual appearance is a costume our objects can change their costume and look completely different.
R|?3B Select Giga in the Sprite Pane and dick the ■3ffaf3E^B Attach a ItfSffTSmMBMl block and inside it place
Costumes tab. The Scripts Area now displays the WmBmm \% H M i 1B35H5. Change l>ll to IISIUII. Click
costumes being used by Giga, including the current look. Choose Looks and drag a LlaVm4ejbV4ILiN block into the ijwiKwii block.
giga-c in the list on the sidebar; this gives our sprite a different Now Giga will switch to the next costume every half a second,
pose. Switch back to giga-a for now. creating an animation effect.
dntlcLed-i o.i Scratch. MisillW* I ircfax
I UnliUed P «
'
Impprt
cpral 4J5
1 1*1-1
■
ti.% \
Sputes
elutn^ w by
fhrinfjp v by d9
Dcrttch
MORE INTERACTION
Earlier we looked at how you could interact with scripts, using the keyboard to move the sprites but Scripts and sprites can
interact with each other, sending messages and responding to events.
Scripts can broadcast messages to each other. These The options For interaction between the sprites are
STEP1 STEP3
can be used to start other scripts or respond to _W Found in the Sensing part oF the Block Palette. The
events. YouYe going to get Scratch Cat to respond to the Giga and one we are looking For is touching, at the top. Notice that this is a
say "Watch Out!!!" iF the two sprites touch. Select Scratch Cat in the diFFerent shape to ones you are used to. It is designed to Fit in the
Sprites Pane so you can view its Script Area. siot next to our if block. Drag the touching block into the spare
UntltLedl-5 or. Scratch - MozlLla FErefox
slot in the if block.
^ i.Jntitte-cj-5 an Scratch X
H« Im
| Hh5 11«?'
thirik ICEErt
Hmffl..
| Hmr7,i
k; i?? y: -tw
Sprites New ■ prite: & / iU £1 switch backdrap to f jiit,- roorr
0
SLagt Scratch ■3 yi.
: h ickiirup i
*/&&
I i v* Liukei op
«r ■ rzm
r
..
Rjy-cKpj a rk BackDacK
^ You 've looked at 'iF' and 'else' in Python, so now The touching block responds to the condition
STEP2 P4
you need to look at them in Scratch. Programs work oF our sprite; in this case iF its touching another
around a Few simple terms and 'iF this then do that' is one oF them. On sprite. However, we need to teli it which one. Click the arrow in the
our stage, you want to say, "iF Giga touches Scratch then Scratch says touching block and choose Giga From the list. There are a couple oF
'Watch Out!!!'" Click Control and drag an i f block to the Script Area. deFault options, mouse pointerand edge. These are handy iFyouYe
UntitLed-5 on Scratch - MozlLU Fircfox
making games.
^ UntitEed-5 on Scratch
^ Unlitled-5 on Scratch
FUe* FdJt * Tjpc Abour F i
♦ II http&://sc rauh.mlt.edu ti * i
iQancing_Cat cripu iturnt und <
# File * Edit * TTps flb
❖
Stage Giga r(SEB
2 k ackdiaps
han batkflcp Stage | 5rrat
n r
riropj
Ml/Ufll i -
fa' buckilrap'
E3
wh»n t start u a cian*
MEl
T-.-_ IIP »1 —B—«■"
<ggnsp ■ eB
F^iCkpHtrk
We've got our i f, what we now need is a response. How do we get our 'if' script to run alongside the
EP 6
EP 5
W ClickLooksand drag a say [Helio!] for 2 W other Scripts? We could put the if block inside
secs block and insert it inside the if block. Change [Helio!] to when flag clicked but it would look big and ugly and do two
[Watch Out! ! ! ]. Try to run the program. Nothing happens! That's different things. We could add a second when [flag] clicked block to
because our if script isn't part of the when flag clicked script. the if block but that would only work if they were touching at the
Untitled-S un Stralch - Firt^n
start. The answer is to use a broadcast block.
j Unrihea-!; on Siratih
L “
Dancing_Cst
bv 'jucyti n/tl ■ rt I e v :un3l
BIBI
aanav 4 w w mitcdii/i i 11 5973T75/frrd G£©4#®©"I30 =
J-*
mi#al
L0Q&
v Ep
I
I
l h>il |l!H?nm
VvTTvlMi iur 0 tuta
thunyi- v by
(S)
es
jc: :^a y: -sia
□ iQj
ar
' hjLcbJri
—Mtfl! -E
Scnrtch
1 IalHi i 9 J - - - L!-
N W* ftwdfafep
9 ;
Backpack
4. = <K
e arrow in broadcast
U-ntltted-S Q-i ItriEchi ■ MozIEIa l Ire/ox dnEltLei-S on StnUh - Moiltla Flffcfes
?,j|ve nciHi
jr< | Sea p-rtHed page
Inr-HmU-rrsftry jiif.kurtli .m |ry kin^mlr- ■■ ■ ■ ■ •»
Lflfllrj
m
when i.)ltkc(l 1
(J1 llillk
_1
rhfinqp y hy
3li«tch
lULItllhirj ti.n.l
I Operatore
1 More Blocks
UntltLetf-i «n IcfaUh ■ Meillf* Hrtfox
; Unlilksf E nsn *
when
move (U steps
when bar.kdiap ^witih'
play drum 1
wtwn i i-
move step 1
Message Name: init rhaoyc y
Cancel
play drum 80 w*« CT3
when I receive
e * Sprite ptjy di Ltm
when I l eceive m
then
ou ve a
is
ate a dice game to help understand this
STEP1 YouYe going to leave the disco behind. Choose File > Click Make a variable and enter dicel into the ?
STEP3
_ W New. You start with a blank stage containing a single _ W window making sure that your variable starts with a
Scratch Cat sprite. Click Controland drag a when flag clicked lowercase letter. There are two options here: For all sprites
block to the Script Area. and For this sprite only. For all sprites allows every
sprite to use the dice; this is known as a global variable.
Untitled-i on scratch - MoiiUa Firefox
Untitled-5 on Scratch *
Make a List
New -variable
Sprites New sprite; For all sprites O For this spnte only
0
x: 240 y: -23
SpriLtii: New sprite: O/tfu& OK Carmel
Sta qe & prit«2
I baoktap '-*-
Fl £«y backdrou.
Stag e |S£rltt2
1 bdci.d-Qp
* 9
Uma i
File * Edit * lips About 41 H i B ■■•cr, mit.edu ☆ gD O #
rmrt Untsrled-5
hBHj I ___ _ Scnpt& Costum es SoundE FilrT p4j«T Tip^ AWul K 5! ©
„442. by I ucyhattersl ey (unsh are d)
i | Events | tJrrtitle d-5 Scnpts
l | Control
by lutyhaitersley(jr>iha'adi
I
i ■mimi | Sansing
| Operators
I
(
Data | More Blocks I I
when elide e d I wlleli cllt ked
Make a Variable Make a Vanable
New variabit
x: anu y: -ibo
New sprite ^
St d 3* , Sprrfce j
3 bickdrep
b+cixtop
Staqc
1 bdf imp
• • •
A whole bunch oF blocks appears in the Block Both the dicel and dice2 variables are currently
STEP5 STEP6
Palette. We can now use our dicel variable but empty. They could be anything we wanted, but
we want two dice, so click Make a variable again and this time we want them to be a random number between 1 and 6. Drag the
enterdice2. Remember to choose For this sprite onlyand set [dicel] to [0] block and click it underneath the when
click OK. flag clicked block. Drag another set [dicel] to [0] block
Jntitled-S on Scratch - Mozillfl Firefox
underneath and change the [dicel] setting to [dice2].
J S untltled sonscratdi x
UntltLed-5 an Sc.ratc.lh - MoziL(a F ire Fax
ii -a https://stratch mILedu I!
Untitted-&or>ScratcK *
r-r: > f\
“nAI
r—n |Untrtled-S
File'* Edit» Ups Ab a ut Y® Ja
4 «i ■ A http: dscraiit mited-u i 'iiS5B2SJi/)?edit( * m © 'I
Lv4«l:
"" by lUcyHattersIey {urrahared)
■U
SprfteZ: dicel i |untitted-5 rriptS
hpriteZ: diccl 1 .i r by lueyhatt lunshared)
Sprite./: dire L
r ol
5pflt£2i dir r2
Data
Maks a List
Mace s Liat
_x: ho y. -h
Sorites New sprite: ^ fl
Stagc
L luc-di ii p
SLitgH
L b ickdrap
fUvi
Ni4i bidtuop
£/&m
V/j
r/A,//A
//////>
ar; you v
rs/.
o eve
y/j
.
variable. Adda pick random [1] to [10] m block to dice 2 and 1 Untitled-Son Scrgtch
4 Ai A
*
Sprite?: diff-l
dir el r dice? thefl
5prlte2: dlc*2
operaiora
wh^n - In k.‘,l
t+alce a usi
sei dicel tn pkk random *: aro y: -ss
i-
spnt NSW Sprite: ^ w (3
set dicel' to pick random {
5tiJ* ^ SpnttS
L b«-=L.ilr4|>
Miw hKictcp:
/V7
4*
r* _
4" H ' i' A bttps://scrstch. mtLedu/p rojects/115982 531/ fred itor e Search ☆ £ fWI
L™J
|Untitled-
by lucyhattersley (unshar i
itums: LinuF
hpriheZ: dic^l
I ooks
r_1
L™J
| Untitled-5
by ~^
lucyhattersl^y (un^hsred) h• Sc n pt & . c Btum e e iounds SpfltcZ: dke2
S —*
I Conerol i Win!!!
Sprlt*2: dlctz
|Saund | Senslng
IP€f1
|Data
Operators
| Mors Blocks
■i ^ 'f IjJjjHi fir! 0 i iri
m
m x: 24D y: -ar n
_je i» y: ibb
New sprite iS* / ^ tfl
QSS3SS
: p rite: New sprite O/dia
m yj y/y.
V r (SfL- ■nKjH ■ , p. •
iSImKQJI ili itJ i Ili® IMIS uMH UliMiMrji
DOUBLE TROUBLE
We're going to start with the dice game from the previous tutorial, but create a second character. The Fancy OOP word for this
is "instantiation": creating an instance of something - in this case another instance of Scratch Cat.
STEP1 LetJs add a second character to the Stage. ShiFtclick You can check this out by clicking the Green Flag
STEP3
_W on Scratch Cat on the stage and choose Duplicate. _ W icon. Vic and Bob will both roll dicel and dice2 but
Click OK. Rearrange the two characters on the stage so theyYe each gets its own random resuit (shown in the Stage). WeVe going
stood side by side. Use the Sprite InFo Window to give them names: to change the game to one where the two dice are added together
"Vic" and "Bob". (highest score wins). Disconnect the IF block From the script and drag
it to the Block Palette.
|untitletl-5
by lucyhattersley (unstwad) P• Sc npt s
| MDtion
costum&s
tvents
seunds
Data
Gperators
More Blacks
Vi e: dice?
Boh: dkeL
I
|p=n
iens ina
| Gparetorl
]Cf no, I lose!!! Ddt j I More BIqc
pob: dkc?
when
pick randoni to
H -I n Maky u variable
set Jicel to plck random
H yi ri I pick random 0 to
then
swrtch CDityme Ite cpjtunn
st: 2+d y: ws *
Sprite1: Ne tot sprite; *>/&& mwrtcfi mi 24-z y: -m Make a List
backdrop to bdckdrtpl
ettect to 'O
Sfcpgp Vit
1 kickdrpp
Stage Vic I Bsb
New bedsdrcp' L bd d d'D|i
rIsti b*ckdrop
•.:<oE
Select Bob and click Data in the Script Palette and We need two new variables: one For Vic's total, and
STEP2 STEP4
W you'll see dicel and dice2. Bob received his own W one For Bob's. Click Make a variable and enter
set oF dice when we duplicated him but he doesn't share dicel and vic_total. This time choose For ali sprites then click OK.
dice2 with Vic. Place checks in the boxes next to dicel and dice2 so With Vic stili selected, click Make a variable again and enter
you can see them on the Stage. bobtotal. Click OK.
iiU
r—1 | Untitled-5
by lucylnattersley ^unsharad) f* • Scripts
I ■jtlon I tuent!
SQund | Untitled-5
by lucyhattarsLey funshar&d}
I ipL5
) Motton
Vic: dicel BOB
I oks |cc„,rol
Vic: dicel
Ii»*» I Central
vic: dicti
Bob: dicel
|sDund
|p,n
| Sensi rg
| Operatori
I'
i Win!!i oh no, i lose”!
Data
oh no , i lose!!! nata 1 More Block
Bob: diceZ | More Bloc Bob: dit-e?
when
Make s Variable Variable
to pick random
to pick random
New Vari ab e
Imagine both characters writing their totals on a Drag set [dice2] to [0] Prom the block
STEP5 STEP6
_ W blackboard that they share, but each has its own _ W palette and connect it to the script. Change dice2
pair oP dice. The totals are global and shared across both characters; to vic_total. Now click Operators and drag the + block to the
the dice are local to each object. [0]. Click Data and drag dicel to the lePt side oP the + block and
dice2 to the right side. This adds up the dicel and dice2 variables,
mit.edu . •
File* Edit* Tip? About and stores the combined value in vic total.
rwf |ontitled-5_ Scnp-ts Costurm
L.i by lucyhattersl ey (un-s h a re d i
I Metlon | Event S
vici dkel W
| CcnEroI
Vir: dkr?
I iou* | Sensinq
tJ 'j b. dkel | Operat ors
Oh no, I loseiS!
Bob: diceJ | More Blocks
—
Make a Variabis
V
s
XI :R4 y: -L43
Stage
L
rien baikdrop
Si/tidA
GREATERTHAN
The sprite with the highest score is going to win our game. This is decided using the greater than Symbol >. This sits between
two numbers, i.e. 3 > 2 and lets you know if the number on the leFt is bigger than the one on the right.
STEP1 Both sprites are going to announce their score and STEP3 Bob needs to run the same script, only with bob_
W the one with the highest score will say, "I win!". W total in place oF cat_totaL We could write Bob with
Click Looks and drag kMMKTSIIFABATi—Now click Data the same code but the point of objects is that you can stamp out
and dragB^BHJEDt0 replace iTEUril. The First part of the copies. Shift-click Bob and choose Delete. Now Shift-click Vic and
game is ready, weTe going to use an iF block with operator choose Duplicate. Click the InFo icon and rename Vic2 as Bob
For the next part oF the game.
|Looka | Coptrol
| Solirid Q SebBlng
|pen | ClperatorB. lAthan
| Senslng
| operators I Data 1 More Blocks E«t ^li- • | ta pfcLc i andon, •O' to E?
n •j-jr lcrt-*l
thinfc
Staga
set Cultor
1 iikd^Dp
Nem badedrep
say [hello!]
[I win!]
So-unda
.i f- by lucyhatterslEy ( umbhars.!1
| Motlon Events
| OpereLors
| Icok-s
|Mors Blocks
I Saun ti | Sensing
| Operators.
whers !ett arrow k I Mors Blocks
|t '■
change x by vFc total
Maks Vanable
fi 1 to pfck random
x: 24' y: -lm
II bi ...id ■ a st tiie: iigtJ and waifc 1 5prit;es New sprite / jjfc Pi
SCRATCH THAT
OOP can be hard to explain, but makes sense when you start using it. If you've used Scratch then you already have an idea of
what an object looks like, it looks like a sprite. This is why we detoured into Scratch. It's great for learning OOP.
In this tutorial we're going to open the dice_game In OOP we don't design objects. Instead we design
STEP1 STEP3
program that we created earlier in Scratch. Resize _W a blueprint Porour object, called a "Class". Think oP
the window and place Scratch on the lePt-hand side oP the screen. it like a blueprint or stamp. Vic and Bob are both dice-rolling cats, so
Next we're going to recreate this game in Python using objects, so we create a blueprint Por a dice-rolling animal. We then stamp out
you can see how objects are similar to Scratch sprites. two identical objects Prom that blueprint. One called "Vic" the other
Untltled-5 on Scratch - MozILIa Fircfoit
called "Bob". We’re going to need the random number module, so
Untitted-5on Scratch *
fi
enter this line:
£1 ■ U mit.edu •
E)oli: ditel | Operatore ■ dke „ * f»rn F.py - yho (np/luf y/fl»qjnrif.ri. PyTh»n/dltf. gainf.py [7.7,n*]»
lauti dk«£ | Data | More Blocks k«4 d"C<3 1 -U pUlc r iH.JlUl. I EJ 0 y U.fMie:-S ci". Scratch * £..- £dit Ffrrnrfl. JJjjn ^pLiuiv. H--*
randaim i randintj
vi t loi ol- Ht i«L*- to plck randiMn 0 to 0 * « A miT.rfu
IfilflV-l tn
LOj vLv|i i.
b obtotil s*. vic ivcjl to <iic«l 4- tEceii Hlt» fcdit * !.{.* ftbcut 1 i* SC ll m
;ar fm © iec-s
L4 teSJT
H h„
■jt .iiicwr s ii 'ur.tr i i*d
atnpti ililttlf;! 'm v Jl -«i 01
Motfun 1 |M.
■ vlt. t.jtal > -b i>l> total th*r. Vnr dlucl
VIlF
II ii
puni LiiwaiJt mausi^alnfiRi Ujb. i
vk_(u.*l ■
b-nli 11, l .il 1
VI 1
hi mtutf-fi
«r aio y: lsc 4
'SfBW 5 «/de stes to »1
31
L biciuli-o:-
ts, e >n> y: |ns _ _
L-
M<w sarta. ^ / if.
«i/&m
3 ^Ktdnp
M wm
n/£a
r
BaCkpack CE
Open Python 2 and choose File > New Window. Now let's dePine our class, which we're going to call
STEP2 STEP4
_W Resize the Editor window to the right-hand size oP DiceAnimal. Enter:
the screen. Choose File > Save As and name it dice_game. Now let's
class DiceAnimal():
have a look at the objects in Scratch. We have two: Vic and Bob.
dicel = 0
Each has three variables (two dice and a total); both pick random
dice2 = 0
numbers between 1 and 6 and check to see iP their total is bigger
total = 0
than the other.
Notice the Punny capitalisation oP DiceAnimal. This is known as
y UntLtletf-Ji on Scratch * CamelCase and class dePinitions should be named in this Pashion
f fl ■ fi. - -r mitedu * m o # » =
II
MotJon
Vic: dicti
ic™ fando* a npo r t randint
! Vic: dicti * ^ mi£.«du ID O 4 » —
M-nvn
Bub. di l rl
Bob: dic r?
II Wm
iMoreB
j DiceAn iranl {J
dic#l - 0
dic*a * o
vkicil.il
lucmiHiri #•. LLrAir.aridi tflc*3 - flj
Hfrtlon
Vk;dkel
ijc.li lota.
VirriJi.r?
Save As
dtjitti H-»h: Hirr i
OiircLcry: /hDmB/lucy,iflBginiitir5_Py?hon
ctMjntdanin.py L vk_iiiiJ M
^ .gHWjgte/equest H d3ta_ir:fro py [“1 he l-.b irrfjH
U,l M Iu ,'ll L, M«Hsnnatics [3 iouM«tef_*ord.py Q hi
□ppmcinJCc.py J funcEaari&.p/ | i lis.' [
fc.ask^nmth py [”] get_^mjgie py H
-blasti py Q hello.py ~\ pc
x: 24a y: iao A »
•glid# 0 ucc t-fj
Spfites 'Je.\ ■- prce: ^ / CA fi f.io oume bce_gsmej 5.a*e
L_ R-.S ti jhii y; | ■
L L a-cbarip
■jAJ- O i 0 r' O
N««rtprl» ^/^1
Man
] kK>dnrp
Pl n litUv
trt rctatic-b rtvh
o
Now we're going to deFine a Function that rolls both Look at Scratch, and you'11 see this is the same as
STEP5 STEP6
_ W dice, and adds the two together to create the total. _ W the set dicel to pick random 1 to 6 block. But what
Inside the class, indented Four lines to line up with dice 1 ( dice2 and are those selP bits about? Remember that Vic and Bob have their
total, enter this: own dice. Vic's dice are going to be accessed use vic.dicel and vic.
dice2 and Bob's using bob.dicel and bob.dice2. But the class doesn't
def rolldice(self):
know what we're going to call each object; instead it uses "selF" as a
self.dicel random.randint(l, 6)
placeholder. This works no matter what name each object has.
self.dice2 random.randint(l} 6)
self.total self.dicel + self.dice2 Ldice_garTe.py . /hem i fiu cy/Etrg ln,n c-n_kyt bon./dke_g ary lt.py <2.7.1
■dk a gamr -py - /tiiHii(/tuc^«g)np«h pyttien/d k e ga<n» pv (z.7.i i*3*
¥ U 0 lljM 4 0} toti
1I »***
A mlt.cdu 10 Q 4 $r-
m WWW
••A..Aii
GB
ii DLCft)lniMl(]:
dIcel - 0
Ilrtruir»
rdld S c fi < s e-t f):
dicel - r&ndlntll. t)
=tlf.di£e2 = randinlfli 6)
Ini
i1
Mottan II D
dU*2 - 0
ll 1 C F 3 - 0
I
I I self.total = seU ,dicel + stl l.dit&J
rief ralldlu(i»K);
self.dicel = idridmul. 6]
r-j
Ujh: &:C*4
ii c* i
1I self.dice? r«ndinr(1 * 6]
self.total = self,dicel -*r setl.dice4 Hu J: iSW
/4a
U»L- LvLai
i£J
53
eas 5H1
k ZK' y; i»
N«« Eprlte
jfif 31
I ■ ■ =■ d>ip
S f / yy / / / y/ / /
4 / / //, * // 'A
// / //. // / A
□rfi iy
n. w s vf f d * . 2 r
A r // * - J *
irr.iiBiillrdhiia
yy/W/r/r/A ■ §■ one ‘bob
Tj
•....
. //////A
M Creating an object in OOP has a big fancy
Pancy name: STEP Now we're going to use dot notation to access
"instantiation”. Don't be impressed by the the values inside both the cat and lobster. Enter • ui ilw j
. •
?, ali it means is creating an instance oPyour class. And this iV/
IHilB bob.dice2 m
%vv
////
There, that wasn't hard at ait. Finally, we're going to use if, eliP and else statements to create
■3 ci_g«nierpy ■ /h^mi/Eucy/Beglnneirj-HyEhorvdlcc.-ganc.py u-
the game.
‘dr-c* i^Fun^.pif -/hiOm^/Luf v/Sf-giFin^rt Python/dir* (jwie.py <2,7,11
vic = DicE-Aninal | )
i- t^tmJ k h<r* 1 -t J lti»n tot ■ niceAnin^l|3
jrffif S t^ripE»
MgMc-n
!<lt,lll I 0 pfDjia frJU.J ■■ dice? • fi
dlc*3 » 0
£||| E>li: It nll 2itiLi|
1 1S:12‘24)
£Jlt Fyn-.ll £uri fljjtiorr'.
n rando* ■r f randint
i±^P
1 3
V I r , r ijl L H j c (■- |
>>S l
Vic W L II b i
self.dicel * randint(1. 63
aelf.dice? = randintll, 63
K^X! H1
14|
vir 1 •-■1 %■ hofr 1 -4 ■i lh»n J Dn&-rolldlceii 3|
vic p DiceAnlssll)
self.total i= self dicel 4 self,dice?
W.
/ \
Asyou start to create advanced projects in Python, you'll need more advanced code.
You could type it in by hand and often you'll find code on developer's websites but
increasingly it's being housed on GitHub.
Git enables you to clone code created by other ^ Open a web browser and enter github.com. Click
STEP1 STEP3
developers on your laptop or Raspberry Pi. So W Sign Up and create an account. Now open a terminal
it's a vital tool to have on all your systems. You install Git in Linux window and enter git config —global user.name “John
using APT. First enter sudo apt-get upgrade to get the latest Doe” (repladng John Doe with your name). Next enter git config
package lists and sudo apt-get install git to install the latest version —global user.email [email protected] the
of Git. Follow the instructions at github.com for macOS and email address with the same one you used to sign up to Github.
Windows systems.
Enter git --version to make sure it's installed Now weYe going to clone a project frorn Github to
correctly. You should have the latest version W our computer. In the web browser enter github.
installed (ours is 1.7.10.4). You can enter git -h to get quick help com/lucyhattersley/fizzbuzz. This is a repository fve created
or man git to read the manual but Git is pretty complex at First so on Git that contalns a program called FizzBuzz. A repository is like
its better to follow our guide. YouYe going to use the desktop to an online folder that contains the code. You will see links to the files
take a look at Github next so enter startx. contained in the project: README.md and fizzbuzz.py but don't click
LaJ
on these.
Me: iu i^/GitHub [pi<®raspberrypi:. -]
[pi{5& raspberryp i -]
O https / github com fi f* lucyhattersley/frzzbuzz
Dt scrfption WtLsilfc
■MDt c>n of ri We-beb* for th is repo sit ory u lon Save ur mcel t> Coda
CD ISBLIQS
i 2 ommii l- 1 branch 0 IBIG39SS 1 C1 ME I I Ul< I VVastebasket
n Pulli UG 'J. i File Edit Tabs Help
Bi ■ i l. masler * fizzbuzz i +
ED Wiki
pi^raspberrypi c i fizzbui
pi®raspberrypi fizzbuzz $ \
Firr?1 commit fir“bu“r.py README.md
p i -j r jspbeiTypi filllill i i hon fi
- ' lucyhane ratey auHiored Sep 1.2015 lntast Luium i 2i28f456af [=1 -V- Pul^Jt!
O Setlings
m READf lE.md
httpsi "-J-LL--L -- ^
fizzbuzz You can e |
Back
pr Forwand
ri~i c Relosd
Add Bookmark..
■ lucyhnT1or*lav -
button. Enter reverse string
import sys Gi&at r^posiioiy name-siire eFiqti and me ruo rabie. Need inepiration? Howatoui I aquae
Press Control-0 and then Enter to save the code. Press Control-X option. Click Create repository Privata
You choose who can see and commit m thrs repository
to exit. to make the File. Next you need \-A Initialize this repushory with a README
to copy the text From the HTTP's T Ns w ll tei you l-mmedlaiely clone tuo repository to your computer Sklp this sk>p if you'ro
STEP2 You can test the program by entering python STEP4 You've now linked the local directory to the Git
iMay/aiiwaMataJj|t)B>|yYou should repository and can sync changes From one place
see dlorW olleH returned on the command line. YouYe going to another. Enter I*Mj^I iMIto track the
to put this program on your Github but First it needs to be a Git python File. Now enter t
Folder, enter git init. This initialises the directory as a git repository. Git you want to send "commit" the File to your Git space. Finally
It creates a hidden File called .git to the Folder. You can see this enter rtiwMicffl and enter your username and password to send
using Is -lah the Files. YouTl now see them on github.com. This is only a really
rough introduction to Git. Head over to codeschool.com/courses/
• > /y ng . try-git to Find an online course.
□ □□
File Edit Tabs Help
. pi@>raspberrypi: ~/reverse_string
File Edit Tabs Help
*■ __
lflrasf3ber rypi Q T "L ^ lJ d
rever se_stnn 9‘Py
m
iberrvoi % qit co mmit -n i l Jl 1 9 L Commit
ma s t ei ommi t} ' c6]qF:irst Com
1 fibi changed , 4 ins<= rtio
l m JPH|
0644 re1v e r s e _stn nq. py
iQrasf iberrypi $ git pu sh
* . i
isernaine for ■ mm H , .
h L LpS -r / / (_[i tnu D , C O |T i1 :
Build a CamJam
EduKitRobot
The CamJam EduKit 3 is a fantastic robot kit that enables you to build a fully
functioning robot with ultrasonic and line following sensors forjust £17. All you need is
a chassis and we'll show you how to turn an old tin box into an amazing robot.
CAMJAM
The Cambridge Raspberry Jam (camjam.me) teaches children of all ages how to build electronics projects and the kits are sold to
everyone via the Pi Hut. The CamJam EduKit #3 has everything you need to build a robot (thepihuLcom/collections/camjam-edukit).
STEP1 The CamJam EduKit 3 includes wheels, motors, a Flip the box upside down and make a hole in it in the
STEP3
_W battery box, an EduKit ControLler Board and two _ W middle, at one end. WeYe using a metal drill to drill a
sensors. You also get a breadboard, wires and resistors to bring it hole through the tin box but if your box is made From plastic or card
all together, along with some double-sided you could cut a hole using scissors. It doesn't need to be large, just
tape. We suggest you get a USB battery big enough to fit the wires from the servo motors.
charger, the type used to recharge
phones and a Wi-Fi dongle.
You'll need a chassis foryour robot. WeYe using a tin ^ Attach the two plastic wheels to the yellow servo
STEP2 STEP4
W box, the type you often get to keep knick-knacks in. W motors making sure theyYe on opposite sides. Now
You can use any flat surface as a chassis, so long as you can fix the servos to the underside of the box, making sure theyYe near
mount the wheels but using a Container makes the hole you created. You can use the double-sided tape to mount
it easier to hold all the bits inside. the wheels but it's a good idea to use Blu-Tack First to make sure the
You could also use a plastic design works.
Tupperware box or
even the box
that the kit
comes in.
• *
Place Four AA batteries inside the battery box and Place the robot Front away From you and attach
STEP5 STEP6
_W make sure it is set to Off. Use a small screwdriver to _ W the red and black wires From the right wheel to the
loosen the two Central screws in the EduKit Controller Board. Place block marked Motor A. It doesn't matter which way round. Take the
the black wire From the battery box in the GND and the red wire wires From the leFt wheel and attach them to Motor B with the wires
in VIN (Voltage). Take a look at Worksheet 1 (camjam.me/?page_ the opposite way round From Motor A (see picture).
id=1035#worksheets) For more inFo.
STEP1 Install a Fresh build oF Raspbian Jessie on an SD STEP3 Charge up a portable USB charger, the type
Card. Use and sudo normally use For mobile phones and make sure
ppt-Qetupgrode
_to get the latest builds for all your soFtware. it's got plenty oFjuice. Shut down your Raspberry Pi and plug
Now use sudo apt to install in the portable charger and make sure it can boot and run your
VNC soFtware. EnterHfTgBMSTSfnPIgflaMSand add Raspberry Pi.
to the end ofyour bash File so it starts at boot time.
STEP2 Connect a Wi-Fi dongle to your Raspberry STEP4 Check that the VNC connection is working From
_click on the Wi-Fi icon in the top right of tl XcFc
oF the another computer. On a Mac press Control-K and
desktop interFace; enter H33S3SI iF vouTe not in the deskt enter the vnc://192.168.0.[x]:5901 (with x the number From ifconfig
environment. Choose your network and enter the Wi-Fi pi in Step 2). Click Connect and you should see the XFce desktop. Your
Open the terminal and enterhlAMKifSl Make a note oF yo Raspberry Pi is now ready to work remotely inside the robot.
network address.
nii C€ « -ai “
2
miKiimMlM
w >* * *■ JC
«tiji* *> ^ t
un „ * tin
1J * * » *
u s
■ a L i c i1
Z Cii* A czntzi; tH
. c: tv
l - h
«i ““““
~IH35~3 fi
i csj3lt,*rr,r
„ M -I Villi —
T* ^ ^ Homi UIQI f o-fffo . CJf
t I i • <itll
1 T
■*k ’ r
+: ii n ii .w «i . —
With all the motor parts in place, it's now time to hook everything up and start testing
outyour robot. Once the motor control unit is attached to the Raspberry Pi and it is all
powered up, you're ready to start testing its movement in code.
READY TO ROLL
Our robot stili has a way to go to be complete but with the servos and wheels attached to the motor control unit and the
power in place, it's ready to start rolling around.
^ You should have all six wires attached to the EduKit Open the CamJam website (camjam.me/?page_
STEP1 STEP3
Controller Board unit. Double check that the black id=1035#worksheets) and download Worksheet 2 -
wire From the battery is going to GND and the red wire to VIN and Running the motors. Open a text editor on your computer and type
that the black and red wires to Motor A and Motor B are the mirror out the code for the 2-motors.py program. You can cut and paste it
opposite way around (as shown in this photo). Gently push the to your text editor but we think it makes more sense to type it line
motor control unit into the GPIO pins on the left side. by line so you understand what it's doing.
i' ilii T-rit v-rr. fir-.vch uo h.hJir.:uF V, nMv. *! ^ He'p # $ * B ■:j* ta
• • 9 m J-nflMctprv
X. ■
i liWrtJi ! hiiM ic t:itil i *. m I
*jb*b(TW i * t 'C amigra i FduKtt- 3 • - ■ Rol&afi cs-
CUMJJUK - ■ J-' HotQr ■ Tr*,t-Cedi-
«0 ElijKi!
J*n -B^nb* cM Mtom
u
3' Roset ■the‘{iPl0‘pln£- Ctoros -off ■ Ttotors ■ too)
GPIO.cleitupO
Now it s time to power up your robot and see if it Open a FTP program such as FileZilla and choose
STEP2 STEP4
_W moves. Attach the battery pack to the Raspberry Pi File > Site Manager. Enter the !P address in the
and swttch on the battery box. Give the Raspberry Pi thirty seconds Host field, "pi" in the User field and your password ("raspberry" by
to go through the boot process and connect to it from a computer default). Right-click on pi under Remote Site and choose Create
using VNC to make sure it is responding. Directory, name it "EduKitRobotics". Now transfer the 2-motors.py
file to the EduKit directory on your robot.
to ii-dlt Vlew Trar*?fri jjcirn Ikiut.Tiiils Wrndai* ilnv Mrs.i> • a«i- ibel htolfi V © f*. 'B >$, iQ fidi ■. M
4 □ □ 0 V' e * 4 fc ■ «r A
bHIHf 1 nam
BKvn <it
SKi Mirug*r
p#?»
(H^Ul
Uiiiwd tfWKl^r SKTinflfi 'faiiai
itirr
towifi
P4SK Psn;
V.L-:
# #
DRIVING CODE
Now that our robot is up and moving, it's time to give it better control functionality. This code enables you to move the robot
forward, backwards and rotate left and right. It also makes it easy to give the robot multiple directions in order.
Head back to the CamJam website (camjam. Take a good Wirafclw #! f» ^ 9 Help
STEP1 # • •
1" » P||« P*(hT ; ^flf tOpyS-Or^ng.pv
i-driving.py
Worksheet 3 - Driving and Turning. Type in the First block oP code Python code to see how it GPIO. setupCpinMQtQrBForwards^ GPIO.OUT)
GPIO. setupfpirHQtQrBBackwards,, GPID.0UT)-i
and save it as 3-driving.py in the EduKitRobotics Polder. Make sure creates Function deFinitions For 23
2* t
Turn'allrinotors ■ oH^f-
dflf ■ StopMotors (): -»
25 ■ ■ GPIO.OLtputipinrtotorAFonwards* ■ B)-
you enter the code Prom the section Moving the Robot at the end oP Forwardsf), BackwardsQ and 2G ■ GPIO.outputCpinMotflrABackwards.j b&)-
GPIO.outputtpinMotorBForwardSj■B)
W**fl 1*11itie1 ffldt f Vi nor tC'ut |V ;r. «('ut r. rt* r e-m ti.e ir it e-Mnjvt c*«m. an
GP10. ictwsrrlr^s (t-j l-ic)
Now add the LeFt() and RightQ 39 - GPIO.octputtpinrtotorAForwards,
"T »7i>71+-«- cw^r- bv rairiMitceib:N?-cc IviiH ura~i»nin(l 3-drivin|.nf * &eL vari^tlfrs -^cr t he - &P10 ■ «tolor ■ p inS- ■ ■ GPlO.outpuf (pinMotorABackwardSj. b1)-
pi nKo^tirAFdrw-a rd i - ;a-
11
id
pin^diorAtacd^ards -
pi nwotorSForwiFOi■*
Functions From the worksheet •i-;
-
GPIO.output(pinMotorBForwardsJ ■ B)-
GPIO.output(pinMotDrBBackwards,■1)
pin^otQr-ftEiir^ardi ■ m -i
45 f
#’Turn- le-Ft-t
def Left{);-
OPIO. ittuptpll■.‘,OEO'BABat kMrJij OPIO. OUT) 46 ■■ GPIO.outpirttpinktotorAForwards,‘B)-
GPI tl. FVt □ ■>!*rdjG? 10, GL?T >
OPIO b ii‘l u K0 Ir.yti £0 "BEblt kh Jr ili, OPIO. OUT] 47 ■ ■ ■ 'GPIO.output(pinHotorAfiackward&J ‘1)-.
Moulnjt the Robot ‘■fi GPIO.outputfpinktatarBForwards., ■ i)-i
i • T Lirp- ■ dll ■ rtetliH-i ■ pH-1
To milor W»t cabct. kIm-v "ic-if- rtted En -rtl E’t coit i(j'\ fi nwt 5hc lim ss 49 - GPIO.outpiJ;t(pinMotorBBackward5# ■ 6) -
brfcH* |-e lin nc 'VE6. clnnup^I tltf StOpftDt&rsOl •
PVMfOlI >
ts^r. l-j-pnui;],!
i*tfcw*rdsO
: GPI0.cui(i4it(plnHQtcirtfDruandE, ■/)
CPIO.oytDottplnHotortBsckwarhiJs, W) ■
50
si
m
^-Turn-ftight-*
t lao-tlas^ (].) OPIO. ti-ilput (p inKctorSF oritJ Fd ij J
iiopftjicrtiJ 52 t dflf ■ Right O
GPIO. outoot f p inhtotorB35c k>, s ros, B:
Iijn ITit j n (Jf (y>ni IfW ls...lunin^ inlg The !H«um! * flLkitf,
Pjrllwil 3'drlvliti.FY si ■■•-GPIO.output(pinMotorAForwardsf'l)~
a - Tum' both ■'soto^i •#Dn«i'd*-
Itl t l.-i-r yCur 'ob« m -iiik taf*il j ■» flfir -,v. ilfld, hiitai > •«> to' irr IICV4 tnrt IHp 54 ■ GPl0.output(pinflotorABackwards/BE')-
d?f F#rtiary)S();
Left and R_i£b_t OPIO.ftitpwbfpiniflstorftffirwirdib } GPI0.output(pinMotorBForward5,-B)-
fhn ml ilcp :■(mdf jrM|lt-M hjKMIAt. IfUI n-lll.rnEhr rnbcil k’ltM r*»K IU I ?ht luUi- jhiip EjPltl, pJtJVtfpinPIgtOFftftpclWPrtlij, :} 56 - GPIO.output(pinMotorBBackwardsJ -1)i
lyjr ii the ioi^wl"i («h obc» tfir curnre ni-iw 'u^cE^m Emi EbKoiir Ihkf code ydu «dt-J i" dir OPIO.ouIpul:(Pi.otteter&Forwii‘^!. .j
RtbnT. tJPlO,flJtpvC(pinhtatpn(6aFl™ar4i, ({} 57 |**
t r. I... i *lfc„ 'hi rt£hl mgl-w ■■ lurnad hp.= lha li*l Kpnd aw lurrik h*c-i*iirEL. Br> t jn n§hl. 5B #’GPIO’Cleartup^
Ihalf^ l-jr-- ii *i.r- r:l 5n inUdif umsnf l.-rn hit* b*. i * -■ m Tiint-botlh ■ notori
* Turn le-Tt 59 GPIOideanupO
tof dt i EJii L h iJd T4I b ( 3 ;
CR]Q. outgiii (pln^aEonii■nrabirn-v, fll QPlO .outpuC (pioMotar*F ornjr USj )-
r.^:0 uyEUii^tpipihiEinridjchwhrHT. I)
t?wUul f . ll OPIO. ajtfHic (p lomtorASac Iwards, 13 IPvBko t ur.xi-ileliJTF-si i UHtaflJI i I rf11 L«t cjni-j go;Di^oi5. iZ:5iaa I D
Window ^ # Q Help
| P # <9_|jj] JkdriwflQbpy_|
STEP2 The worksheet advises using nano to create code Add the T Fllfl a«h W : -dr vir^ oj
I 3-dr;vihjj.p? t (ho synibu s« ePlcdl t
31 *
J*. Tu rn- both ■ motor s- forwards-»
def■ Forwards():-
GPI0.output{pinHotorAForward5i bI)i
it makes more sense to type it out on your computer and transFer instructions to the very end
32
33 ■ ■ -GPIO.outputtpinMotorABackwards, 0)-.
ia •GPlQ.output{pinlwtotor&Forwardsi, ■ i)-,
it using FTP. Use VNC to connect to your Raspberry Pi and run the oF the code and save the ii *-
^ “■
GPIO.outputtpinMotDrBBackwardSj ■ 6)i
4£
47
»
- ■ GPIO.output(pirtMQtorAFcirwards, ■ e)-
GPlO.outputtpinMotorABackwardSj. ■ 1)-
sa fl-novement■instructions-
and then stop. 59 Forwards()-
time. sleep(I) ■ *t Pause Bfor '1b second^
H Left()-i
time. 5leep(B.5) ■# Pause-for half-a ■ second-
i&3 Forwards ()^
64 time. sTeep( 1) -
ts Right ()-
es tifnetsleep(0.5)»’
6? Backwards () ■
63 tinie.5leep(&,5)-
ea StopMotorsf
70 -1
Now that your robot is built and moving around, it's time to give it some smarts. The
two sensors can be used by the robot to react to its surroundings; either following a
line or avoiding obstacles.
Open the CamJam website (camjam.me/?page_ Use a regular male-male jumper cable and place it
STEP1 STEP3
id=1035#worksheets) and download Worksheet 4 _W next to the jumper in the breadboard in the same
and Worksheet 5. Worksheet 4 is just For the Line Detector, while column, FiFth row. Connect the other end to the GND oF the EduKit
worksheet 5 is For both sensors. Make sure you take a good look at Controller Board. Now take another Female-male jumper wire and
the Building the Circuit diagram in Worksheet 5 and keep it with you connect it From the VCC pin on the Line Detector to the 3V3 (3.3
during this tutorial. volts) pin on the EduKit Controller Board.
Make sure that the robot isn't currently powered. Next take a third Female-male jumper cable and
STEP2 STEP4
IF it is use VNC and shutdown the Raspberry Pi and _W connect it to the OUT pin oF the Line Detector.
disconnect the power to the Raspberry Pi. Locate one oF the Female- Connect the other
male jumper wires and connect the Female end to the GND pin on end to pin 25 on the
the Line Detector. Connect the other end to the breadboard in the EduKit Controller
eighth column, Fourth row (as shown here). Board. This pin is used
as the input pin to get
a reading From the
Line Detector. Note
that the colours oF
your wires may not
match the ones in the
Worksheet diagram
and it doesn't matter
which colouryou use.
EP 5 Now it's time For the Ultrasonic Sensor. Take it Take a good look at the resistors in the tutorial.
STEP 6
W out of its packaging and siot it gently into the _ W You need a 3300 resistor. This should be orange-
breadboard. Make sure the GND pin is in a hole in the same column orange-brown-gold orOrange, Orange, Black, Black, Brown. Bend
as the GND pins From Step 2 (as shown in this photo). The Echo, Trig both pins to Form a U-shape and insert one end in same column
and VCC pins should be in the breadboard holes to the right. as the Echo pin on the sensor. The other end goes into an unused
column on the leFt.
Now youVe going to use a 4700 resistor, which With everything wired up, take the double-sided
STEP 1 STEP 3
_ W should be yellow-purple-brown or Yellow, Violet, _ tape oFF the bottom oF the breadboard and attach it
Black, Black, Brown. One end goes in the same column as the GND to the top oF your robot, with the sensor Facing outwards. Use some
pin on the sensor, the other into the same column next to 3300 oF the double-sided tape that's spare and connect the Line Detector
resistor From Step 6. to the bottom oFyour robot making sure the lens Faces down.
Next take a jumper cable and place one end in the Now create the 5-distance.py code and place it
STEP 2 STEP 4
_ W same column as the two resistors. Place the other _ W in your EduKitRobotics directory. Use python3
end in Pin 18 oF the EduKit Controller Board. Use a second jumper 5-distance.py to run the code and you will see distances appear on
to connect the VCC connection to the EduKit Controller Board's 5v the screen. Place your hand in Front oF the sensor and watch how it
socket. A third jumper connects the Trig column to Pin 17. adjusts accordingly. Now use the movement code with the sensor
code to make your robot smart. Happy robotics.
SBES
/ r
Vi h, 1ijrt3
f p^■ * li.7l^ini^ j £
.
□□□
File Edit abs
n ■
J / 4 e.,
ri^r
J
Distanee ; _7/4 1
Distanc^ 2
Distanee : 9
.
Distance ; 12, T
Distance : 95. 4
Distance : 5E Q
Distanc® : 97 0
Distanoe ; 96.
Distance : Q o
O
Distance : 95 6
Amazing Robotics
Projects to Try
Building a robotics project is one of the most rewarding things you can do with Python
and few things are cooler than a proper working robot. Here are some of the best
robotics projects you can find.
The PiTank is a web controlled tank that Pires SPYTANK While the PiTank Pires guns, the Spy Tank is
PiTAN K
_W ping-pong balls. The Piring mechanism is based on a _ W designed to roll around and provide video
spud gun and it's controlled using a web browser that displays real- Peedback. It uses a Pully 3D printed case and the Raspberry Pi
time video streaming. It’s powered by a Raspberry Pi and Arduino communicates over WiFi. A GoPiGo board is used to control the two
and uses the Raspberry Pi Camera and AdaPruit Servo Board. motors that move the Spy Tank around. The Raspberry Pi Camera
Module is used to bounce video over the network to where you are
More info: bit.ly/1 PMqdlY
monitoring it.
ROBOT - RECOGNITION FROM VOICE^ iPyouYe looking Pora robot kit that is
DIDDYBORG
relatively easy to assemble and supremely
Thanks to Siri and OK Google, voice control is Pairly commonplace in powerPul, then the DiddyBoarg is the one to go Por. The DiddyBorg
consumer gadgets. So what could be kit comes with a laser cut chassis, six motors, a PicoBorg Revers
cooler than creating a voice controlled motor controller and Pull build instructions. All you need to add is
robot. Alexis Ospitia has created this the Raspberry Pi board
Pabulous looking robot that walks
More info: bit.ly/1 PMqs6T
in response to voice commands,
and it speaks back.
«i
DRONE PROJECTS
Building a drone is not a task to be taken tightly. Drones, especially quadcopters, are the most compelling robotics project of
our time but it's not easy to control a flying robot carefully and safely.
llrMniSl
DRONE Pi Drone Pi is a project currently underway ZEPPALOON
WJJJiiMWW Notall
that combines a Multiwii (multiwii.com) with drones
a Raspberry Pi. The Multiwii looks after the four motors and have to be quadcopters and
the Raspberry Pi collects information and communicates with there's a lot to be said for
a smartphone. The phone is used to monitor footage from the creating a different project such
camera and control the drone. as this Zeppaloon. Kongsberg
is an international technology
More info: bit.ly/1 RHjlgy
Corporation that was created
to teach students all about the
technology they use to operate
offshore vessels. It uses a
Navio2 flight controller.
CARDBOARD QUADCOPTER The cardboard RPAS DRONE ^ A great drone project to try is the
quadcopterisan RPAS Drone. This uses a Navio2 flight
autonomous drone with the frame built out of cardboard. It controller and Raspberry Pi 2 combination with a remote control
was built by four students at Olin College of engineering for a aircraft. The resuit is a remote control aircraft that sends video
stream over a 4G network. This means it can be flown remotely,
or set on autopilot, while the video stream is monitored from the
the details have been ground.
put online. It uses a
More info: bit.ly/1 RHkmuz
HobbyKing Multi-Rotor
Control Board V2.1 to
control the four motors
More info: bit.ly/1 RHjR3N
The Raspberry Pi is a great device for emulating old arcade machines and consoles; its
GPIO pins make it easy to embed inside arcade machine cabinets and cases. It's a fun
projectand one that's extremely entertaining.
BOX BUILDING
The big challenge with most arcade cabinets isn't the electronics but the cabinet Big, heavy and mostly wooden they are a real
project to get stuck into. You can buy cabinets though and just concentrate on building the circuits.
• • • «
LAPTOP PROJECTS
Building a laptop is another great project, as it enables you to create and test Python code on the move on your own hardware.
There are a few laptop kits and projects to choose from. Here are our favourites.
I4K1JIS The Pi-Top is one of the most famous Raspberry NETB00K Most laptops are slender and light but this
WKKMMW Pi laptop projects. It combines a 3D printed case is a real sturdy option made from a recycled
with a 13.3-inch LCD screen and keyboard. You can 3D print the aluminium case. Fitted in the case is a 7-inch LCD panel with a logic
Creating devices enablesyou to track, monitor and getalerts with the best coding
projects; including the stealthiest spy gadgets and serious home security; there’s
bound to be something here thatyou'll find useful.
This cracking
TWITTER RASPBERRY Pi PHOTO LIVE SIMPLE TIME-LAPSE CAMERA
A time-lapse camera
This project uses a Waveshare Night Vision camera (waveshare.com/ project places a Raspberry Pi inside a coFFee tin to build a time-lapse
rpi-camera-F.htm) to capture images in the dark and then shares camera that can be LeFt outdoors For an extended period oF time. Illy
them directly to Twitter. Whilst it's a good security project, it's ideal coFFee tins are Fairly
For keeping an eye on pets or wildliFe at night too. The script that robust, reasonably
makes use oF the Twitter API is especially worth getting to know. watertight and can
hold a microcomputer,
More info:
Camera Module
http://www.
and battery pack. A
instructables.com/
simple script is used to
id/Twitter-Photo-
capture images on a
Live-Feed/
regular basis.
More info:
instructables.com/
id/Simple-timelapse-
camera-using-
Raspberry-Pi-and-a-c/
DIGITAL MEDIA
Media storage and playback is a classic use of homemade hardware and there is no shortage of unique projects to try out Here
we've found four of our favourite media related projects.
■n
id/Roberts-747-DIY-
Raspberry-Pi-internet-
radiostreame/
Well done for making it this far. With what you've learned you can conf idently start to
create engaging Python code. Don'tstop now though, there's plenty more to learn to
help you achieve great things.
LEARNING CODE
Learning to code any language, from absolute beginner to industry professional, is possible using nothing but free Online resources.
Some sites offer video tutorials, others offer interactive learning and there are hundreds of great books and websites to read.
wav khsnBcademy.org/
1 vw cottecademy com/leairPchoiceHanguaije
Icodelcademy
□M JS
Learn Python The Hard Way “ Once you've started to get the hang
LEARN THE HARD WAY PROJECT EULER
(learnpythonthehardway. _W oP the basies, you’ll be in need oP a
org/book) is a well-established online course that's Pree to Pew projects to try out. There's nothing worse than trying to come
take; although you can pay to get additional materials like code up with ideas Por things to do with code. A good practice area is
downloads and videos. It’s somewhat controversial and gets pretty ProjectEuler (projecteuler.net/archives). This table lists an archive
tough towards the end but it really does take you through the nuts oP programming problems. It’s ideal Por Plexing your programming
and bolts oP computer programming. muscles.
■hardway.org/book/
^ Menu ^ iVj^iArchived Problems - .
1 FARM PYTHON
LLHnii
|i- |U
r v i nun <
JfcS • < £ https V/pre-jecteuler net/archi ves
Projeci Euier
Welcome io ihe 3rd Edit ion of Learn Python the Kard Way. You can visit the companionsite to the boc-k at hnp le n ~>pyi honthehard w ay orqj
where you can purchase digtlal downloads and paper versionsof the book. The free HTML version of the bookis avatlable at
htlp://[earnpyt h o nt h e hard way. org/boo k/ . Problems Archives
(►) The problems arehrver table shows problems 1 to 507. if you wguld I ke to tackle the 10 most recently published probi-
Table Of Contents problems
■>
Cllok the descriptlon/btle of the problem to Mew J^tails and cubmltyour answer
* p,efac*
Inlroduclion. The Hard Way fs Easicr
4
irvxHjs j7 ; 2
BBBBB B
■
Ht ■ Co lo Problem:
lyndo.com
m**1 WiUCKHiOvi-r jy,
— Hrnwt* itii' llfciiwy
Fittp jValacka wllo w ewvitv-viorti/aiiaSffih/175 m
! «q pii
Ratum lo R «visioni
Meifi-Llili
vtoMotei FTc*gr^Taring
Ali memberships include GmglhlH Pr^gru-mmlng
PROFESSIONAL LEARNING
MOOCS (Massive Open Online are a fantastic way to learn computer programming. These modern courses are often run
by world class universities like , MIT and Harvard and offer you the chance to learn from the top experts in the world.
CS50 Harvard's CS50: Introduction to Computer Science MATHEMATICS FOR COMPUTER SCIENCE
(edx.org) is the best place to start. This online course
can be covered at your own pace and offers a comprehensive If youre going to get serious about computer Science you need to
introduction to the art of computer Science and programming. get a good understanding of the mathematics involved. Use Khan
It's designed for Harvard students with little or no knowledge of Academy to catch up on any basies, then follow MITs Mathematics
computing and you can get a verified certificate from it. for Computer Science (ocw.mit.edu/courses/electrical-engineering
» o v CS50 T'.lr«k.<i::£ni!d J«l L Tyrrell
and-computer-science/6-042j-mathematics-for-computer-science-
■ ripa •Hr,-* crg •:<xirs«-,"'>uodyciior CLmauwi sc-nhc tinvmd!< esSC-| * Fl O fall-2010/).
NOW IT WORKS COURSfS 5CHQOL5 Ea FARTNERS
MIT 6.00 Alongside Harvard's CS50 course lies a selection MIT, STANFORD & BERKLEY If you are truly
of videos from MIT. The lectures From MIT 6.00 dedicated, you can
Introduction to Computer Science and Programming can ali be pick up the equivalent oP a Bachelobs Level Computer Science
watched on YouTube (youtube.com/watch?v=k6U-i4gXkLM). Program using nothing but Pree online courses. There is a huge
Prof. Eric Grimson and Prof. John Guttag will walk you all the range available at MIT, StanPord and Berkley. Take a look at this
way from being a newcomer to having a deep understanding of web page for a suggestion of courses to follow: http://blog.
programming concepts. agupieware.com/2014/05/online-learning-bachelors-level.html.
Glossary ofTerms
Just like most technology, Python contains many conFusing words and acronyms. Here
then, Foryour own sanity, is a handy glossary to help you keep on top oF what's being
said when the conversation turns to Python programming.
Argument Expression
The detaiied extra Information used by Python to perForm more Essentially, Python code that produces a value of something.
detailed commands. Can also be used in the command prompt to
specify a certain runtime event. Float
An immutable floating point number used in Python.
Block
Used to describe a section or sections of code that are Function
grouped together. Used in Python to define a sequence of statements that can be
called or referenced at any time by the programmer.
Break
A command that can be used to exit a for or while loop. For example, GitHub
if a key is pressed to quit the program, Break will exit the loop. A web-based version control and collaboration portal designed for
Software developers to better manage source code.
Class
A class provides a means of bundling data and functionality together. Global Variable
They are used to encapsulate variables and functions into a single entity. A variable that is useable anywhere in the program.
Comments Graphics
A comment is a section of real world wording inserted by the The use of visual interaction with a program, game or operating
programmer to help document what's going on in the code. They system. Designed to make it easier for the user to manage the
can be single line or multi-line and are defined by a # or program in question.
Debian GUI
A Linux-based distro or distribution that forms the Debian Project. Graphical User Interface. The interface which most modern
This environment offers the user a friendly and stable GUI to operating systems use to enable the user to internet with the
internet with along with Terminal commands and other forms of core programming of the system. A friendly, easy to use graphical
system level administration. desktop environment.
Dictionaries IDLE
A dictionary in Python is a data structure that consists of key and Stands for Integrated Development Environment or Integrated
value pairs. Development and Learning Environment.
Distro Immutable
Also Distribution, an operating system that uses the Linux Kernel as its Something that cannot be changed after it is created.
core but offers something different in its presentation to the end user.
Import
Editor Used in Python to include modules together with all the
An individual program, or a part of the graphical version of Python, accompanying code, functions and variables they contain.
that enables the user to enter code ready for exeeution.
Indentation
Exceptions Python uses indentation to delimit blocks of code. The indents are
Used as a means of breaking from the normal flow of a code block in four spaces apart, and are often created automatically after a colon
order to handle any potential errors or exceptional conditions within is used in the code.
the program.
Integer Python
A number data type that must be a whole number and not An awesome programming language that's easy to learn and use,
a decimal. whilst stili being powerPul enough to enjoy.
Kernel Range
The core oP an operating system, which handles data Processing, A Punction that used to return a list oP integers, dePined by the
memory allocation, input and output, and processes inPormation arguments passed through it.
between the hardware and programs.
Root
Linux The bottom level user account used by the system itselP. Root is the
An open source operating system that's modelled on UNIX. overall system administrator and can go anywhere, and do anything,
Developed in 1991 by Finnish student Linus Torvalds. on the system.
Lists Sets
A Python data type that contains collections oP values, which can be Sets are a collection oP unordered but unique data types.
oP any type and can readily be modiPied.
Strings
Loca l Varia ble Strings can store characters that can be modiPied. The contents oP
A variable thatJs dePined inside a Punction and is only useable inside a string are alphanumerical and can be enclosed by either single or
that Punction. double quote marks.
Loop Terminal
A piece oP code that repeats itselP until a certain condition is met. Also Console or Shell. The command line interPace to the operating
Loops can encase the entire code or just sections oP it. system, namely Linux, but also available in macOS. From there you
can execute code and navigate the Pilesystem.
Module
A Python File that contains various Punctions that can be used within Tkinter
another program to Purtherextend the ePfectiveness oP the code. A Python module designed to internet with the graphical
environment, speciPically the tk-GUI (Tool Kit Graphical User
Operating System InterPace).
Also OS. The program that's loaded into the computer aPter the
initial boot sequence has completed. The OS manages all the other Try
programs, graphical user interPace (GUI), input and output and A try block allows exceptions to be raised, so any errors can be
physical hardware interactions with the user. caught and handled according to the programmer's instructions.
Output Tuples
Data that is sent Prom the program to a screen, printer or other An immutable Python data type that contains an ordered set oP
external peripheral. either letters or numbers.
PIP UNIX
Pip Instatis Packages. A package management system used to install A multitasking, multiuser operating system designed in the '70s at
and manage modules and other soPtware written in Python. the Bell Labs Research Centre. Written in C and assembly language
Print Variables
A Punction used to display the output oP something to the screen. A data item that has been assigned a storage location in the
computer's memory.
Prompt
The element oP Python, or the Command Line, where the user
enters their commands. In Python it's represented as »> in the Also X11 or X-windows. The graphical desktop used in Linux-based
interactive shell. Systems, combining visual enhancements and tools to manage the
core operating system.
Pygame
A Python module that's designed Por writing games. It includes Zen oF Python
graphics and sound libraries and was First developed in When you enter: import this into the IDLE, the Zen oP Python
October 2000. is displayed.
The SAMSUNG
Galaxy
Guidebook#
iswrt hov\ taget r hc masi fkxn your Samsufflj &j kxy
ass
•,<**
4
baliUSapph
lrn'irrijlri
pcrfonTintr
-1 IRum»
•^n^ntVlr.syva
'f™fi Up ■‘in.
' LHWI "TLISjl 1^
m i*ii-
Oii- * *Kf*U,
**■*. Mivijrrfrij*
PLUS
P' y
m, 9
Special Deals and
*
Bonus Content
ultimatephotoshop.com Sign up to our monthly newsletter
Buy our Photoshop guides and download and get the latest updates, offers
tutorial images for free! and news from BDM. We are here
Simply sign-up and get Creative. to help you Master Your Tech!
Discover more of our complete
manuals on Readly today...
^ The Complete ^ The Complete pr The Complete The Complete
iPhoneX® HPhone X® Max iPhoneX®
to imprOY
yOUT
l-UCMi INDbRbNUbN I I0U1. NI.' L -'Ur-i .)Lh I J NIJ bDllIU-M HHPi INUbPlNU-bNI
BDWs :ju"v-!:ivit. ^iss iPhotit IVldcBfioki - IPad * Mac deiklopi * [Pod tokich * *Waieh * «TV BCWi EstcMiril Cvick-1(5 rin&dd
II iPhone MacBook
iOS 12 Manual JHEw!
*TV+
Muri lEApplpsrwuTV wn^rp’
tiitorials
to improve
yovir *News+ txpert
iciv vo.i subscribe i.o tutoria!*
:#iK> n"^KJjinr:.
TAKf h fBIT FHQT0 5 WITH -05 & BtatOE
r:l \ I r i' toimpto^
Ntrtfl l>: pne. Vd c
your skllls
Photos like
the Pfos i
Leam how to take and edit your photos
wfthyouriPhone, iPad and Macs
Revievuedl
GoPro
txpert
tutorii
toltnprove
yOU* SklMS
tutoTiaH c;
tounpTQve
^oU-ir
r
Easy to follow g vides and tu tona Is FREE Gift worth £5.99! FREE Gift worth £5.99!
11
‘ij-V I • «di-' .V.T llW.-tft
M FREE Gift worth £5.99! FREE Gift worth £5
3sM minfe fox-dmik
Internet
For Seniors For Seniors For Seniors For Seniors
Speciai
Large Print
For Seniors
Edition Speciai
Large Print
Ed ition
Speciai
Large Print Speciai Spedal
Large Print Urge Print
Edition Edition Edition
1011^ INDbHbNUbm IQMfclNBEPSNDBHT IMOEPENiJErjl IW^.MJbHbNO^r
FREE Gift worth £5.99! FREE Gift worth £5.99! Easy to foffow gvidos and tutoriafs
Speciai
rge Print
Edition
Becoming a Programmer
Regardless of whether you're a student, computer
enthusiast or just curious as to how programming
works, ourtutorials will helpyou discover how Python
works and how you can use it to interact with other
users. What's more, you can start to learn how to think
like a computer programmer, and how to apply your
knowledge to tackle computing problems.
Python has proved itself to be a The Python Manual has been written to help you get
into Python from the ground up. Learn where to go to
flexible, easy to learn and powerfu!
download the latest and up-to-date version of Python
programming languageforthe and install and launch it from Windows, macOS, Linux
computers and even the Raspberry Pi.
modern computer user and developer.
p-by-step Tutorials
Python code can be found on the The tutorials in this book have been written to help you
build confidence in using Python. With simple code to
desktop, in server rooms, on the begin with, you can soon easily create a Python program
that can ask the user's name, store information in a
Internet and working in conjunction
database-like setting, manipulate lists of data as well as
with many loT devices. write to files in your system.
nd The Code
We look at how you can use Linux to create your Python
situation such as creating a game, code, as well as object oriented programming with
Scratch; there are some great projects involving robots,
coding an essential backup script or sensors and creating an arcade machine too.
Becoming a Python programmer is morethan simply
creating a random password generator
knowing the language, it's how to apply that knowledge
that you can use at horne or at work. and get the most from the code.