0% found this document useful (0 votes)
49 views164 pages

The Complete Python Manual - Volume 35 2019 Text

The document is a promotional manual for learning Python programming, highlighting its accessibility and versatility across various operating systems. It emphasizes Python's ease of use, the vibrant community supporting it, and its applications in creating games and utilities. The manual includes tutorials on setting up Python and coding basics, making it suitable for beginners and enthusiasts alike.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views164 pages

The Complete Python Manual - Volume 35 2019 Text

The document is a promotional manual for learning Python programming, highlighting its accessibility and versatility across various operating systems. It emphasizes Python's ease of use, the vibrant community supporting it, and its applications in creating games and utilities. The manual includes tutorials on setting up Python and coding basics, making it suitable for beginners and enthusiasts alike.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 164

FREE Code Black Dog

N EW! Python 31 Raspberry Pi I Linux Download i-Tech Series


The Python Manual

£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

The Complete The Complete


Raspberry Pi Linux Mint
Manual Manual

Eupert
uitor^
to impfove
you r

Vii- uiTif ?17 loo;-: INDEPENDENI laffvtujffEsMnt

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+

Il:l ysu subsmbetL'


Q.vr &3.\ mafjTjinct.

S8""'™0™5"'"""... J IK *£* and A ArcvKif- ir. likr


rdetfli* for games. 'fit:
llyou si! sUouTtnerv

Photos like iPadAir,


iPad mini

the Pros
and i Mac
inside

Learn how to take and edityour photos


withyouriPhone* iPadand Macs
Win! RetfiewfrdJ Stop-by-itep Tutoria LiL
An amnii ng EiranJIF-SljWPtwtoPriirter GtttDRiiiwwtb
setof W« nuunt FVfoe*l ini I |4w£m( Ptwlijp^pHy =>nd
M4 JM Hru&htlTMkj 0 jC Hiiildili J.l vililiii|; uii ifliAm-'. - F'
PtantroriKS. STA^AitbfluisheneliVtlsTA 7 jmlyaurH>:wich . j
spdrtscarbuds!' 2nd Edi?icn 100^» INOEPEN DENT
vdLnwAs i»5* ikOfKNOtm

m>
-M
Welcome to Python, the worlcTs best programming language

Python is one oF the most successFul programming languages in the world.


It's easy to use, Free to download and install and can create spectacular
games and handy Utilities that help make your computing liFe easier. It's
available on all the major operating Systems and can be used on the most
powerFul Windows 10 PC to the latest version oF the Raspberry Pi, in the
horne and at work. You can even Find Python code being run in outerspace
on board the International Space Station. lFit'sgood enough For NASA, then
it's good enough For the rest oF us!

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?

Let's get Python programming!

@bdmpubs E I BDM Publications www.bdmpublications.com


Contents

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
■■■■■■■■.....

100 Random Password Generator

Working with Data 101 Keyboard Drawing Script


so
•j 102 Pygame Text Examples
52 Lists 103 Google Search Script
54 Tuples 104 Text to Binary Convertor
56 Dictionaries 106 Basic GUI File Browser
58 Splitting and Joining Strings 108 Mouse Controlled Turtle

Black Dog i-Tech Series - Volume 35


Contents

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

J24) Learn Object Orientated Programming with Scratch and Python

126 Getting Started with Scratch 134 Sensing and Broadcast


128 Creating Scripts in Scratch 136 Objectsand Local Variables
130 Interaction in Scratch 138 Global Variables and a Dice Game
132 Using Sprites in Scratch 140 Classes and Objects

142 Robots, Drones and Cool Python Projects *


144 Using GitHub 154 Arcade Machine Projects
146 Build a CamJam EduKit Robot 156 Security Projects
148 Controlling Your Robot 158 Becoming a Coder
150 Add Sensors to the Robot 160 Glossary of Terms
152 Amazing Robotics Projects to Try

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

www.bdmpublications.com The Python Manual


6 Black Dog i-Tech Series - Volume 35
(^Say Helio to Python

There are many different programming


languages available to learn and use.
Some are vastly complex and incredibly
powerful and some are extremely
basic and used as minor Utilities for the
operating system. Python sits somewhere
in the middle, combining ease of use with
a generous helping of power to allow the
user to create a range of minor Utilities,
some excellent games and performance
heavy computational tasks too.
However, there's more to Python than
simply being another programming
language. It has a vibrant and lively
community behind it that shares
knowledge, code and project ideas, as
well as bug fixes for future releases.
It's thanks to this community that the
language has grown and thrived. Now ifs r
your turn to take the plunge and learn
how to program in Python.
Read on and let's see how to start you of f
on your Python Adventure.

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

The Python Manual


I Say Helio to Python

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

C++ is usually reserved for more complex


programs, operating Systems, games and so on.

8 Black Dog i-Tech Series - Volume 35


environment or users. Operating Systems, such as Windows, macOS Python was created over twenty six years ago and has evolved to
and such are usually a combination oF C++, C#, assembly and some become an ideal beginnehs language For learning how to program a
Form oF visual-based language. Games generally use C++ whilst web computer. It's perFect For the hobbyist, enthusiast, student, teacher
pages can use a plethora oF available ianguages such as HTML, Java, and those who simply need to create their own unique interaction
Python and so on. between either themselves or a piece oF external hardware and the
computer itselF.
More general-purpose programming is used to create programs,
apps, soFtware or whatever else you want to call them. TheyTe Python is Free to download, install and use and is available For Linux,
widely used across ali hardware platForms and suit virtually every Windows, macOS, MS-DOS, OS/2, BeOS, IBM i-series machines, and
conceivable application. Some operate Faster than others and some even RISC OS. It has been voted one oF the top Five programming
are easier to learn and use than others. Python is one such general- Ianguages in the world and is continually evolving ahead oF the
purpose language. hardware and Internet development curve.

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

print(r,You have already guessed that letter. Please try again.”)


continue
else:
pass

guessed_letters. append(player_gijess)

for letter in range(len(chosen_word)):


if player_guess == chosen_word[letter]:
word_guessed^letter] = playerguess he

if player guess not in chosen_word:

Python is a more modern take on BASIC, it's easy to learn


and makes for an ideal beginner's programming language

www.bdmpublications.com The Python Manual 9


I Say Helio to Python

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.

WHAT WE'RE USING


ThankFully, Python is a multi-platForm programming language available For Windows, macOS, Linux, Raspberry Pi and more. IF
you have one oF those systems, then you can easily start using Python.

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.

|_| PYTHON SOFTWARE


macOS and Linux already come with Python preinstalled as part oF the operating
System, as does the Raspberry Pi. However, you need to ensure thatyouTe running
the latest version oF Python. Windows users need to download and install Python,
which weYl covershortly.

Download the lates* verslon for Windows


□ TEXT EDITOR
rf >«ntniMitM' .!• ‘r . n> rt«ul irlw•••■<
Whilst a text editor is an ideal environment to enter code into, it's not an absolute
iKTnttll IMhJfli /na 1.

LflCi IPfi W FVItV.n *|r. ,|

. '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

Fil« £dft Scjfdi


+

5ftew Erxoding L-jnguBge Scftmgj M*au Ruti Plugiris iVotJrw


new concepts or change existing commands and code structure to make it a more
Si .*dil Jr n
i o
iCcc Swfllcht:
^ a

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.

_ TIME AND PATIENCE


new 4 < • - - l±r Ixe IE
3l Notfjiad.p^-s-vpp- rfv... ■cpp <lj.nfc //plTis.^-oogle , cofli/11 reL™"|ja&.l isfccr" />
,LOG
Jsvrtag ,log ^lH 1 >T f~ " trat/jjivtj* nr e pt" >
wzr.ccif._gcfg * {long: 1 * r. J-:
" J functi an 4)
[7I f vir p4 = riOfcument.-reattELiir.ent (
pci-Lyj]* ■=".■-■ . . . i
......
fd.aaybe =
) :
fc±"Ue;pt.ars = . q uoq _* . C2CL- ‘ 2?: p..
Despite what other books may lead you to believe, you won't become a programmer
vai s - docuMcuc .gteElftineH.cjByT-aiflfN-affia (' I-’]
in 24-hours. Learning to code in Python takes time, and patience. You may become
t
s .parer.tJTfde asfore (p-o., 3J ;
■Illi;

Cdcripx rVT]rtV7i35er 1 pt”

cype"ri text/ jiavascript'1' sja/n,pp nl. 3jsri>€/sc:rip£:i-


]qn«ry.c™/Jqgcryl . ? rlin r]?11^
stuck at times and other times the code will Flow like water. Understand youYe learning
<jcript typr-'1 tei t/ji^aicripL' a ; c—^https : //apia .goagle: . ccizi/ 1 a/ plu-focie . ja^X/^ci
something entirely new, and you will get there.

T K J Black Dog i-Tech Series - Volume 35


Equipment You Will Need

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.

s#© Python 3 4 2 Shell - / main py- /horne/pi/ piigNraspbenypi -

ril? Edit t-jjnr.gt gun Aptioris H“ p

i 6ivih it SCffrirt 6t i#> teget S rahgli^g lh Ydiur fr i*n 0 u W


* indicate wher- ono of ehem n-as be-en- beforg-,

Python 3 -i 2 sh4:1 - /horne/pi/Dacunwiis/tn^in.py [2| .; 7] _ □ K M - 5QQQD0DQQ t qjy Si2e Ol IntE-gEt


N ■ SOOO0 * nupb-er of irvts ini the strean
Eile Edt 5:hej Detsug Cptlons Windows fciele
rantfw'cesi >
Python 3.4.3 (default . Oct 1« JDH , 13:31:11] seH\*set( )
TCiCC 4.3.1] «1 Linux
Typo "tepyF Jgtit". "credjtV gr for npre |nformatign. dtf d* jaVu(io)i: * the rfiquir-ud f unet ion
--—-- RESTART --—— ir n . seen:
»> ratum Tru*
3124BSW3
igt59?1*Jl siirv.add(n) * not ir«n bafar» u ldri rn ;tt
469667237
Z735M832
73253230

40743133
56gZ5304
423713053
Sone
»>

vpe 'Htlp' : r ed latiofi-

www.bdmpublications.com The Python Manual 11


Say Helio to Python

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.

PYTHON PROGRAMMING RECIPES B


File
C:\U5er5\lucyh\Dropbox\C_Action\rec1pe.txt - Sublime Text (UNREGISTERED)
Edit Selection Find View Goto Tools Project Preferences Help

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

conceived in the late 1980s def init (self):


Just like a recipe, a program consists of instructions that you follow self.ingredients = []
by Guido van Rossum def cook(self,ingredients);
in order. A program that describes a cake might run like this: prxnt "Baking cake . "
at Centrum Wiskunde &
cake = Cake()
Informatica (CWI) in the bowl = []
bowl — []
Netherlands as a successor to flour = 100 flour = 100
butter = 50
the ABC language, butter = 50 milk = 100
bowl*append([flour,butter,milk] )
milk = 100
cake,cook{bowl)
Guido van Rossum, the bowl. append( [flour, butter, milk] )
Father oF Python. cake.cook(bowl)

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

Python 3.4.2 (defluit. Qct 19 20t4» 13:31:11) class Cakefobject>:


[GCC 4.9.1] on limix lef );
Type "Copyright"» rtcreditsTt or "license()w for more Information self.ingredients * []
»> ============================= RESTART ================== tef cook(self, ingredients);
»> print {"Baking cake,..")
Baking cake,..
»> cake=Cake()

bowl - []
flour - 100
butter - 50
milk - 100
bowl.append([flour» butter, milk])

Cake■cook(bowl)

12 Black Dog i-Tech Series - Volume 35


Getting to Know Python

HIGH-LEVEL LANGUAGES ZENOF PYTHON


Computer languages that are easy to read are known as "high-Level". Python lets you access ali the power of a computer in a language
This is because they fly high above the hardware (also rePerred to as that humans can understand. Behind all this is an ethos called "The
"the metal"). Languages that "fly close to the metal," like Assembly, Zen of Python." This is a collection of 20 Software principies that
are known as "low-level". Low-level languages commands read a bit influences the design of the language. Principies include "Beautiful
like this: msg db ,0xa len equ $ - msg. is better than ugly" and "Simple is better than complex." Type
n Mgh Imvl arogr^nniir» > tj - a x import this into Python and it will display all the principies.
y Hhilupfdli-.yrj Ul ☆ | ^ X A .
^ NrijigyiMl m E ,ii ► r ni|,_J>iiwhrF I !n iM .si; Ei|Fti I it; III I

Hv-jd r ilii *‘kT lir-Tiry S-l! cb 0,

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 3.6.1 Shell — □ X


I 3.6.2
on File Edit Shell Debug Options Wmdow Help
Python 3.6,1 (v3„6.IiSScOdbS, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)]
Wondering which version to use? IA i 1 11 'L on win32
Type f,copyrxghtlff "credits" or "licenseO" tor more Information.
II £— u 1 >»

Lookingfor Python with a different OS? Python for


m *J In

Want to help test development versions of Python? F

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!
>>>

www.bdmpublications.com The Python Manual 13


Say Helio to Python

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.

INSTALLING PYTHON 3.X


Microsoft Windows doesnJt come with Python preinstalled as Standard, so youfre going to have to install it yourself manually.
Thankfully, it's an easy process to follow.

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.

Download the latest version for Windo ws Optional Features


0 Documentation
Installs the Python documentation file.

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.

Install Python 3.6.2 (32-bit) Advanced Options


Select Install Now to install Python with default settings, or choose 0 Install for all users
Customize to enable or disable features. 0 Associate files with Python [requires the py launcher)
0 Create shortcuts w tnstalled applications
0 Add Python to environment variables
0 Precompile Standard library
0 Download debugging symbols

□ Download debug binaries (requires VS 2015 or later)

^ 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

14 Black Dog i-Tech Series - Volume 35


w
( Howto SetUp Python in Windows

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.

L-& Python 3.62 Shell - □ 3


Setup was successful File Edit Shell Debug Options Window Help
Python 3.6,1 (v3,6,2:5fd33b5, Jul 3 2017, 04;13:34) ;[MSC v.1900 32 b it (Intel)]
on win32
Special thanks to Mark Hammond, without whose years of
Type "Copyrightnt "credits" or "license £) ri for more Information*
freely shared Windows expertise, Python for Windows wouid
stiil be Python for DOS.

New to Python? Stari with the online tutc nal and


documentation.

See vha:’s ne/, in this release.

CJisdo 0 oatn iqth hmit


Changes your machine configuration to allow programs, includrng Pythi n tc
bvoass the 260 character "MAX PATH mi itation.

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.

W Disable path length limit


Changesyour machine ccnfiguration to allow programs, including Python, to
bypass the 260 character "MAX_PATH" [Imitatio-n.

Close

^ The command line version oF Python works in


STEP7 D @ Filters S/ STEP 10
_W much the same way as the Shell you opened in
Best match
Windows 10 users will now Step 8; note the three leFt-Facing arrows (»>). Whilst it's a perFectly
IDLE (Python 3.6 32-bit)
Find the installed Python 0C ictOD 31 p.
Fine environment, it’s not too user-Friendly, so leave the command
3.x within the Start button line For now. Enter: exitO to leave and close the Command
Search suggestions
Recently Added section. The Prompt window.
idle - See web results
First link, Python 3.6 (32-bit)
will launch the command
Microsoft Windows Version 10,0.15063]
line version oF Python when (c) 2817 Microsoft Corporation. Ali rights reserved.

clicked (more on that in a C:\Users\david>python


Python 3,6,2 (vB,6.2:SfdBBbS, 3ul 8 2017, 04:14:34) [MSC v,1900 32 bit (Intel)] on win32
moment).To open the IDLE, Type "help", "Copyright", "credits or "license" for more Information.
>>> exit()
type IDLE into Windows
C:\Users\david>
start.

P idle

www.bdmpublications.com The Python Manual 15


Say Helio to Python

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.

e» python ^ install Python

Welcome to the Python Instatler


About
This package will install Python 3.6.2 for Mac OS X 10.6 or later
tj imroducUon
Python for Mac OS X eonsisftolihe Python programmmg languafle
• Re a d Mi interpreter, plus a setol pro ara ms ta aJlaw easy aece 55 Jd Lt for Mac OS X
Pi 1 A I BA I jTfb ■ users mciudlng an mtegraled devfclopmeni efwiTonmeni IDLE,
• Lice n se
NEW: There are importante ha n-g es n Ihis release recardina netwerh
secunty and trusi «itHUcate*. Pfoase see ttia ReadMe ior more datatis.
ad Pyt
Download
IMPORTANT: IDIE andolher programs usmg Ehe tkint&r graphica! user
interfate loolhil require specifk: versions otthe TctTk plitfcrm
Wonderifig wh independeni wmdewi teoikit. Visit hitosyAvvvw.pvtnon.oraftfowriload^
macitcTW for curre ni informabo n on supponed and recommended
versions of Tel/Tk tgr this ve rsion of Python an d Mac OS X.

Looking for Pyt

Want to help te_

Continue i

Looking for a spetific


Pyt hon reieases by version number

* *

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

Download the latest version for Mac OS X •

i> Read
lntroti.uc.tion
me toiiowmg ardiiiecture(s): 1386, x66 64.

Which Inslflller variant should I use?

• 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.

Certificate verifieation and QpanSSL


Looking for Python with a different OS? Python for W
"NEW1* This vanani ot Python 3 6 now includes its own private ccpy
of OpenSSL 1,0.2. Unlike previous releases, the deprecaled Apple
K. Othe supplied OpenSSL litoranes are no longer used. This also means that
me trusi certificaies in system and user keychains managed by ihe
Keychain Access applicatiori and the security command line utility are
Want to hclp test devclopmcnt versions of Python? no longer used as defaults by the Python mal module. For 3.6.0, a
■ mm. »-v r-J - '-"fini irx ifn< ■ *4 - «-»■

Co Back ' ‘ Continue 1

Black Dog i-Tech Series - Volume 35


EP 5 The nextsection details the SoFtware License There's nobhing much else leFb bo do in bhe Pybhon
STEP8
W Agreement, and whilst not particularly interesting _ W insballabion wizard so you can click bhe Close bubbon.
to mosb Folks, it's probably worth a read. When you're ready, click on iFyou now drop back inbo a Terminal session and re-enber bhe
bhe Conbinue bubbon once again. command: python3 --version, you can see bhe new version is
now lisbed. To enber bhe command line version oF Pybhon, you need
«nn InstaII Python
bo enber: python3. To exib, ib's: exitO-
Software License Agreement

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 1995 Guido continued his work on Pyinon at the Corporation for


National Research Initiatives (CNRI, sea hapJ/A/ww.cnri reslonmusJ
m Reston-. Virginia where ne re lea sed severa I versi ons of the
Software,

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.

ft f\Q, Python Shell


Python 3.1.2 (r312:79360M, Mar 24 2010, 01:33:18)
[GCC 4.0.1 (Apple Inc, build 5493)] on darwin
Type "Copyright", "credits" or "licenseO" for mo
re information.
»>

www.bdmpublications.com The Python Manual


Say Helio to Python

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:

sudo apt-get update && sudo apt-get upgrade


Enter your password and let the system do any updates.

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 |

18 Black Dog i-Tech Series - Volume 35


How to Set Up Python in Linux

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 $ |

www.bdmpublications.com The Python Manual 19


Say Helio to Python

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 £

Hom» n^wnlawl Hui\ Rtcij Fqtqth Suppent

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.

It is recomtnended that you dose all other applications before


continuing.

Click Next to continue, or Cancel to exit Setup.

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 &*£££_

Sublime Tpi( I, h.Jkj jni&fribtf

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

Sublime Text 3 File Edit Selection Find View

pnnt C Hei Io ev e ryo ner)


print (''Helio everyonel
*
Goto Took Project Preferences Help
Browse Packagei ..

Settings

Settings - Syntax Specific


Download Settings-Distractior Free

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

For notification about new versions, follow sublimehq on twrtter. ^ IDLE


i P Iastie
Even more bleeding-edge versions are available in the dev builds. LA2V

Sublime Text 2 is also stili available. Mac Classic


MagicWB (Amiga)

20 Black Dog i-Tech Series - Volume 35


Installing a Text Editor

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

i print ("") Playback Macro Ctri+Shift+Q JavaC


Save Macro... Lua
Macros > Wake
* Python
Develo per > L
R
Insta II Package ControL.
Ruby
Rust
Syntax Tests

New Build System

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/'

■ PflcfcagM/DerBuiT/aeie^MQEd.py Deletes a word to the tett or nght ot the cursor


• pecka«/Derauic/aupiicaM_iine,py Duplicates the current line
■ paeieafle*/Derauit/QOM_iine.pY Frompts the userfor input, then updates the selection
■ Paefcaffej/Dersiilt/ront.py Shows hOW tO WOCk With seTTlfigS

■ paein.tfeVDerauic/narie,py Uses add^regionsO to add an icon to The gutter


■ Pndcag-ea/De f au lt /1 rim_trail ino_whi t eapa ce. n y MOdifiCS & bUffer jllSt bfifOTC ttS S3Vt(J

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 <£■'■

www.bdmpublications.com The Python Manual 21


Black Dog i-Tech Series - Volume 35
Getting started with Python may seem a
little daunting at First but the language
has been designed with simplicity in mind.
Like most things, you need to start slow,
learn how to get a resuit and see how you
can get whatyou want From the code.
In this section we cover variables, number
and expressions, user input, conditions
and loops and the types oF errors you will
undoubtedly come across in your time
with Python. Let's start and see how to
get coding.

24 Starting Python for the First Time


26 Your First Code
28 Saving and Executing Your Code
30 Executing Code from the Command Line
32 Numbers and Expressions
34 Using Comments
36 Working with Variables
38 User Input
40 Creating Functions
42 Conditions and Loops
44 Python Modules
46 Python Errors
48 Combining What You Know

The Python Manual


Getting Started with Python

Starting Python for


the First Time
As previously mentioned we're using the Raspberry Pi as our Python hardware
platform. The latest version of Raspbian comes preinstalled with Python 3 (version
3.4.2); so as long as you have a version 3 Shell, all our code will work.

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

A Mathematica [GCC 4.9.1] on linux


Type "Copyright", "credits" or "licenseO" for more information.
Python 1 (IDLE! »> 2+2
, Ed i
4
ffi Hro fc 1 J_

;|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.

E ile Edit She|l Qebug fiptions Windows Help


Python 3,4,2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9,1] on Imux
Type ''Copyright’*, ''credits'* or '*Ixcense()” for more Information
»> 2+2
4
>» 8+6
14
»> 23453+64545522
64568975
>» 98778642342“ 12343
98778629999
»> 1287437*43534
56047282358
»> 1

24 Black Dog i-Tech Series - Volume 35


then you can always change them via Options > ConPigure IDLE and
print(“Hello everyone!”)
clicking on the Highlighting tab. However, we don't recommend that
As per the code we entered in Sublime in the Installing a Text Editor as you won't be seeing the same as our screenshots.
section oP this book.
Python .
3 4.2 (default, Oct 19 2014 , :
13 31 11 : )
[GCC 4.9.1] on iinux
Type “Copyright", “credits" or “licensef)" for more Information.
»> 2+2

>>> 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

Save as New Custom The me

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.

>» print("Helio everyone!")


Helio everyone! Fonts/Tabs

Key Set
Highltghting Keys General

>» I * Use a Built-in Key Set IDLE CIassie Windows

Save as New Custom Key Set

Custom Key Bindings


Aetion - KeyCs)
beginntng-oMine - <Key-Home>
center-msert - <Control-Key-l> <Controt-Key-L>
change-in dentwidth cAit-Key-u> cMeta-KeyHJ> cA!t-Key-U:
check-module - <AltHCey-x>
c Io se-ali-Windows - <Control-Key-g> <tontra!-Key-Q>
elose-window - <Alt-Key~F4> <Meta-Key-F4>
comment-region - <rAlt-Key-3=- ^Meta-Key-3>
copy - <Control-Key<> <Control-Key-C>
cut - <ControFKey-x> <Control-Key-X>
dedent-region - <Controi-Key-bracketfeft>
fcJ T

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

IDLE ts Pyttwr»'s iniegrated Developnwnt and Leavmng Environment.

IDLE Colour Coding IDLE the fpficnving Eeetrjrrjfj

* coded m 100% pur&Pyihon, using the tuint^r GUI tooflut


. w^rte; mpidly Ihe on WmLfews, Uni* and Mac 0S X
■ P/lhm sEieQ wrtdow (irrferadivR inlerprelei) wrOn ralori/ing a! code mput, nutpul and error messages

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

25.5.1.1. File menu (Shell and Editor)


Orange Commands if for else
Ne^i' Fite
Croale a oew flle edhing window
Blue User functions get_area() Oue^t
Open an existing file wlti an Open dialog

Dark red Comments iRemember VAT Recenl Files


Open a hs! of recent fites Chdr one lo open it
Opon Module.
Light red Error messages SyntaxError: Open an existmg module (seerches sys path}

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.

PLAYING WITH PYTHON


With most languages, computer or human, it's alL about remembering and applying the right words to the right situation.
You're not born knowing these words, so you need to learn them.
* *

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

Python 3.4.2 (default, Oct t9 2014, 13:31:11)


[GCC 4.9.1] on linux Python 3.4.2 Shell _ n x
Type “Copyright'*, "credits*' or "license()*' for more Information.
File Edit Shell Debug Options Windows Help
»> print( "Helio")
Helio Python 3.4.2 (default, Oct 19 2014. 13:31:11)
»> I [GCC 4.9+1) on linux
Type "Copyright", "credits" or "licenseO" for mori Information
»> printf "Helio' )
Helio
»> printf”2+2*)
2+2
»> print(2+2)
4

»>

• • # •

““ 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

File Edit Shell Debug Options Windows Help

Python 3.4.2 (default, Oct 19 2014, 13:31:11)


[GCC 4.9.1] on linux
Type "Copyright", "credits" or "licenseO" for more Information. Python 3.4.2 (default, Oct 19 2014, 13:31:11)
»> print( 'Helio' ) [GCC 4.94!] on linux
Helio Type "Copyright", "credits" or "licenseO" for more Information
>» pr int( ”2+2 ” ) >>> print("Helio’ )
2+2 Helio
»>
>» print( "2+2**)
2+2
>>> print(2+2)
4
>>>
>» a-2
>>> b»2
»> 1

Black Dog i-Tech Series - Volume 35


Whatyou have done here is assign the letters a Now let's add a surname:
STEP8
W and b two values: 2 and 2. These are now variables,
surname-”Hayward”
which can be called upon by Python to output, add, subtract, divide
print(surname)
and so on for as long as their numbers stay the same. Try this:
You now have two variables containing a First name and a surname
print(a)
and you can print them independently.
print(b)

File Edit Shell Debug Options Windows Help


Python 3.4*2 (default, Oct 19 2014, 13:31:11)
[GCC 4,9.1] on linux
Type *'copyr ight'\ "credita" or •* Licenset )" for more Information.
»> name® Divid”
»> print(name)
David
>>> surname= 'Hayvsard'
»> print(surname)
Hayward
U>>? 1

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.

File Edit Shejl Debug Options Windows Help

Python 3^2 (default, Oct 19 2014 13;31™11)


[GCC 4.9.1] on linux
Type ''Copyright1*, "credits” or Mlicense()" for more Information.
»> nacne^ David"
»> print(name)
David
>» surname* Hayv\ard"
»> print(surname)
Hayward
>» print(name*surname)
DavidHayward
>>>

^ 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.

Python 3,4*2 (default, Oct 19 2014, 13:31:11)


[GCC 4,9,1] on linux
Type "Copyright”, "credits" or "licenseO" for more Information.
>>> name-"'David"
>>> print(name)
David
»> surname* Hay.vard'
»> print (surname)
Hayward
>» pfint(name+surname)
DavidHayward
»> print(name, surname)
David Hayward
>>> print(name+ +surname)
David Hayward
1 »> i

www.bdmpublications.com The Python Manual


Getting Started with 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
>>>

Source Must Be Saved


OK to Save?

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*

print("Hello everyone! '*)

£|l«- edit Shei Eobug Sptkjns wndflmrt Help


3.4 (dpfjLih, Oct 19 SUM. 13;?1; 11)
[GCC 4.5.1J On liou*
Type ^Copyright", "credits” or "1lcense()“ for more information,
;■»

Directory /home/pi/Documents J i
■- ■—1

PQ _pycache_ cake.py loopl.py


j~] BlueJ Projects Circi e. py main.py
l~) Greenfoot Projects _) graphics.py namecount.py
□ Python Code Hello. py Square.py
Fl Scratch Projects img.py [2 test.py
Addition.py imgtest.py wordgame.py

4 ►

File name: print hello Save


u
L-t: l\ Coi J
Files of type: Pvthon files (TpvAdyw) Cancel

Black Dog i-Tech Series - Volume 35


Saving and Executing Your Code

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

Python 3.4,2 {default. cct 19 2014, 15:31:11} print(“Helle everyenel")


(G« 4,9. 1J on linux a-2
type “topyrightH. "credits” or "litenseO" for more in format ion. b-J
.■:o----PlEStAftT- | nam.."fi.!. ld"
>» surn ane- H a ,■ •. a c
Hello everyone! * pr mt{name , aurnaat)
j» print ce+b)

I
m saa
i ,■amRa@s»^i

Sourre MLjst Be Savesi


o OK to Save?

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

[GCC 4.9.1] on linux


“ " " “ 1
£jew File Ctrl+N
Type "Copyright", "credits" or "licenseQ" for more information, Qpen...
>» ================================ RESTART =================== Ctrl+O
>» Recent Files
Hello everyone! Open Module,,. AfUM
>» | Class Browser Alt+C
Path Browser

Save Ctrl+S
Save As... Ctrl+Slkft+S
Save Copy As... Alt+Shift+S

Prini Window Ctrl+P

£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.

www.bdmpublications.com The Python Manual


Getting Started with Python

Executing Code From


the Command Line
Although we're working from the GUI IDLE throughout this book, it's worth taking
a look at Python's command line handling. We already know there's a command line
version of Python but it’s also used to execute code.

COMMAND THE CODE


Using the code we created in the previous tutorial, the one we named hello.py, let's see how you can run code that was made
in the GUI at the command Line LeveL.

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 (»>).

STEP2 Just as before, D @ Filter:


STEP4] From here youVe able to enter the code you've
W we're using a Best match
looked at previously, such as:
Raspberry Pi: Windows users will
Command Prompt q=2
need to click the Start button and LWSKCOD aoi
print(a)
search for CMD, then click the Search suggestions
Command Line returned search; fi cmd - See we □ resui ts
You can see that it works exactly the same.
and macOS users can get access
to their command line by clicking
Go > Utilities > Terminal.

fi cmd|

Black Dog i-Tech Series - Volume 35


Executing Code from the Command Line

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.

M C:\Users\david\Document5\Python\heilo.py - Sublime Text (UNREGISTERED)

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.

File Edit Tabs Help

www.bdmpublications.com The Python Manual


■ Getting Started with Python

sic mathematical expressions with Python, simple addition and the


nd on that now and see just how powerPul Python is as a calculator. You
within the IDLE Shell or in the Editor, whicheveryou like.

ITS ALL MATHS, MAN


You can get some really impressive results with the mathematical powers of Python; as with most, if not ali, programming
languages, Maths is the driving force behind the code.

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.
»>

Python 3,4,2 {defauit, Oct 19 2014, 13:31:11)


[GCC 4.9.1] on linux
Type “Copyright1*, “credits1* or “license()“ for more Information
»> 2+2
4
i »> 54356+34553245
34607601
»> 99867344*27344484221
2730821012201179024
»> 1/2
0,5
»> 6/2
3*0
>» 2+2*3
8
>» { 1 + 2}+ (3*4)
15
»> |

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

Black Dog i-Tech Series - Volume 35


Numbers and Expressions

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

»> (1 + 2)+ (3*4) »> 2**3


15
>» 1//2 8
»> 10**10
0
>» 6//2 10000000000
3 »> bin(3)
»> 10/3 •obii’
3.3333333333333335 »> format(3,‘b )
>>> 10963
1 »>

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
>>>

www.bdmpublications.com The Python Manual


When writing your code, the flow oP it, what each variable does, how the overall
program will operate and so on is ali inside your head. Another programmer could
follow the code line by line but over time, it can become difficult to read.

#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:

# Set the start value of A to 10 a=a-l


a=10 print(“You’ve just lost a life!”)
# Print the current value of A print(“You now have”, a, “lives left!”)
print(“The value of A is,”, a)

*Comments.py-/honne/pi/Docume,.,Pytfion Code/Commems.py (3.4.2)* - □ x


File Edit Format Run Options Windows Help

34 Black Dog i-Tech Series - Volume 35


a
P5 Whilst we know that the variable A is lives, and ^ Inline comments are comments that Follow a section
STEP8
W that the player has just lost one, a casual viewer or _W oP code. Take our examples Prom above, instead oP
someone checking the code may not know. Imagine for a moment inserting the code on a separate line, we could use:
that the code is twenty thousand lines long, instead oFjust our
a-10 # Set the start value of A to 10
seven. You can see how handy comments are.
print(“The value of A is,”, a) # Print the current
value of A
j*4
a=a-l # Player lost a life!
£ile £dit Shell Qebug fiptions Windows Help
Python 3*4*2 {default, Oct 19 2014, 13:31:11)
print(“You’ve just lost a life!”)
[GCC 4*9*1] on linux
Type "copyright"# "eredits" or "Iieense()" for more Information.
print(“You now have”, a, “lives left!”) # Inform

>>>
restart player, and display current value of A (lives)
The value of A is* 10
>>> -------------------------------- RESTART ----------------------------
»>
The value of A is, 10
»> RESTART
>>>
The value of A is* 10
You * ve just lost a life!
You now have 9 lives left!

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!”)

File Edrt Format Run Options Windows Help


# Set the start value of A to 10
a=10
# Print the current value of A
print("The value of A is,", a)
# Player lost a life*
a*a*1
# Inform player. and display current value of A (lives)
print("Youfve just lost a life!")
print(">ou now nave1', 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!”)

www.bdmpublications.com The Python Manual


Getting Started with Python

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)
>>>

Numbers are stored as diPPerent


variables:

age-44
Type (age)
Which are integers, as we know.

Black Dog i-Tech Series - Volume 35


Working with Variables

EP 5 However,youeantcombine bothstringsand This presents a bit oF a problem when you want to


STEP8
W integer type variables in the same command, as you work with a number that's been inputted by the
would a set oF similar variables. You need to either turn one into the user, as age + 10 won't work due to being a string variable and an
other or vice versa. When you do try to combine both, you get an integer. lnstead,you need to enter:
error message:
int(age) + 10
print (name + age)
This will TypeCast the age string into an integer that can be
Python 3,4,2 (default, Oct 19 2014* 13:31:11) worked with.
(GCC 4,9.1] on linux
Type "Copyright", "credits" or ftlicense()" for more Information
»> n ame = 1 [ a v i d h a y w a rd"
>>> print (name)
David Hayward
>>> type (name)
<class 'str*>
>>> title*'Deicended froni Vikings"
»> print (name + ": " ♦ title)
David Hayward: Descended from Vikings
>» character=name + + title
>>> print (character)
David Hayward: Descended from Vikings
>>> age-44
»> type (age)
<class 1int*>
>» print (name+age)
Traceback (most recent call last):
File "<pyshell#9>f,* line 1, in <module>
print (name+age)
Typegrror: Can#t convert ’int‘ object to str implicitiy
»> |

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.") >>>

David Hayward: Descended from Vikings is 44 years old,


»> print (character, ''is1', age, 'years old,’)
David Hayward: Descended from Vikings is 44 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

www.bdmpublications.com The Python Manual


Getting Started with Python

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:

print(“Hello”) print(“Welcome”, firstname, surname, I hope


firstname=input(“What is your first name? “) youJre well today.”)
print(“Thanks.”)
surname=input(“And what is your surname? “) *userinput.py - /hom
£ile Edit Format Run Options Windows Help

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:

print(“Welcome”, firstname, surname+“. I hope


File Edit She|l Debug Options Windows Help
you’re well today.”)
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9*1] on linux
Type ^Copyright1’, "credita" or "licensef )" for more Information*

>>> File Edit Format Run Options Windows Heip


J
Helio printf HeLlo,+)
What is your first name? David firstname*inputf' hat is your first name? )
Thanks. printf "Thanks.“)
And what is your surname? Hayward surname-inputf nd what is you: surname? )
>>> |
printfMWelcomel,( firstname, surname+"* I hope you*re well today.")

Black Dog i-Tech Series - Volume 35


You dorftalways have to include quoted textwithin What youve created here is a condition, which we
STEP8
the input command. Forexample, you can ask the _W will cover soon. In short, we're using the input From
user their name, and have the input in the line below: the user and measuring it against a condition. So, if the user enters
David as their name, the guard will allow them to pass unhindered.
print(“Hello. What’s your name?”)
Else, it they enter a name other than David, the guard challenges
name=input()
them to a fight.

"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: “))

£ile Edit Ffirmat Bun Qptions Jglndows Help


# Code to calculate rate and distance
print(“Input a rate and a distance11)
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
>» |

www.bdmpublications.com The Python Manual 39


Now thatyou've mastered the use of variables and user input, the next step is to tackle
Functions. You've already used a few functions, such as the print command but Python
enables you to def ine your own functions.

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)

»> 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

File Edit Shell Debug Options Windows Help

Python 3*4,2 (default, Oct 19 2014, 13:31:11)


File Edit She|l Debug Options Windows Help [GCC 4.9*1] on linux
Type "Copyright", "credits" or "licenseO" for more Information.
Python 3,4,2 (default, Oct 19 2014, 13:31:11) »> len( "arrfcidisestablishiiientarianism )
[GCC 4,9*11 on linux
Type "Copyright", “credits" or "licenseO** for more Information,
RESTART
»> len( antidisestablishmentarianisin )
>>>
28
Enter your surnafne: Hayward
»> i Your name has 7 letters in it*
»> import math
>>>

Black Dog i-Tech Series - Volume 35


Creating Functions

^ 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:

import math math.sqrt(16)


Once entered, you have access to all the Math module Functions. You can see that the code is presented as module.Function(data)

File Edit Shell Debug Options Windows Help


Python 3.4.2 (default, Oct 19 20t4f 13:31:11)
[GCC 4*9*1] on linux
Type "Copyright”* "credits'1 or "licenseO" for more Information.
>>> len("antidisestablishmentarianism")
28


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

File Edit Format Rufi OptjOfVS Windows


*umitled*
Help
print (word, “is a four-letter word. Well done ”)
Python 3.4.2 (default. Oct 19 2014. 13:31:11> word=input t "P leass ?nrei viQru:
[GCC 4.9.1J on linux
Type “Copyright4*, "credits” or "licenseO" for more informat ion,

The double equal sign (==) means check iP something is equal to
something else.

File Edit Format Run Options Windows Help

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.”)

File Edit Format Run Options Windows Help

word=input(,,Please en d
wo rd_length^len(vsord)
if word_length == 4:
print (word, 'is ip rd. done. if}

print (word, 'i.s ju r rd.")


i

Black Dog i-Tech Series - Volume 35


I *
IV
Conditionsand Loops mj
wl ili
w
jM

Press F5 and save the code to execute it. Enter


EP 5 Now expand the code to include another conditions
STEP6
W a Four-letter word in the Shell to begin with, you Eventually, it could become quite complex. We've
should have the returned message that it's the word is Four letters. added a condition For three-letter words:
Now press F5 again and rerun the program but this time enter a
word=input(“Please enter a four-letter word: “)
five-letter word. The Shell will display that it's not a Four-letter word
word_length=len(word)
wisLdiHnBi wordgame py - /home/pi/Doc if word_length == 4:
File Edit She-ll pebug ^ptions Windavts Help

python 3.4,2 (defauli, oct 19 2014. I3:3l:lt)


Ftle Edit Format
word=mput( "Please em
fjun Optrons
ri r
Windows
-■ lj r
Help
Ierrer word; }
print (word, “is a four-letter word. Well
[GtC 4.9.1] on iinujt word„length*len(word)
Type “Copyright", "crediti" or "licenseO" for more informationi.
»> ....-............-...... RF5TART

if w£>rd_length == 4:
print (wOrd, “ss
I tp;
ir-letter i well dene."j done.”)
Pleas? enter a four-letter word: ^rd
Word is a four-letter word. WeJl done.
>>> ■»!■■■ ■ ■ »!■■« ** RESTART .
print (word, "i' r i four-Iet rrd. "]
elif word_length == 3:
>>>
Please enter a four-letter word; Frost
Frost is not a four-letter word. print (word, “is a three-letter word. Try again ”)
»>1
else:
print (word, “is not a four-letter word.”)

Python 3 4 2 Shell -’0r‘.tgamepy - nome/ pi,dqc _ n k



Fle Edit SheM Cebuq Optiens Wjnduwv Htlp £Ma £diC Fannat Eun Qptions Windows be:C
Python 3,4,2 (detuuli. oci 19 2014, I3:3i:li) wo r d= i npu t:(“01ease
( - em
enter a foorjfitifiuffl ■>
(GCC 4.9. 11 on limis
type "copynghT", "credits" or " JieenseC)" for more Information
»> 11 iti 11« ■Illi I| ■tln Ulli r 11 ■ mu .. RESTAfit —
fi '
word_length-1en(wo r d1
if W0f0l_un^(h == 4;
prini (word. is b letter word. Well dc-nc-.r!J
>» ■ ■ . 1 ■ word_len£th «w
Pleas* i?rit*i * four-letter word: Word prLtil (word, "ts :■ -letter wrd, fry again"}
Word is s four-letter wrd. Vie 11 done.
J»------RESTART----- prini (wordr ouP-Irttcr wetd.“)

Please enter a four- letter word3 Frost


Frost is not a four-letter word.
>;>* --F.ESTAR.T-■■-

Olease enter a four-letter word: Ega
is a thrtt-Itttti worel. Try ag^iri
>>> |

i »i l,i" _ i I

A loop looks quite similar to a condition but they are so


block of code a number oF times, usually with the suppor
y/y//
rY
.

'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 ^///

hile x < 10: YY/YYY/YYj


m &E3
print (x)| /A /////,
print (word) TrYYYYY* //Y/

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

that value. When x does eventually equal 10 it stops. YYYYYYYYYYYYi


rYYYYYYYYYYYY
r,YYYYYYYYY.^^rj

Thex=x+1 part isn't needed here because the range Punction


e/Df/Oi
creates a list between the Pirst and last numbers used.
Ette Edlit fflrmat Qptlons Windows He

Python 3.4.2 (default, Oct 19 2014, !3:3f:11)


[GCC 4 .9,1} on lirujx I xclO:
Type " Copyright', "credits” or "licensen” for more Information, print (x)
Python 3.4 2 Shell - □ x loopl py - /home/pi/Oocumer
>>> «■ RESTARI X-K+l
>» Elie £dit She[l flebug Qptions Windows JHelp EHe Edit Fflrmat Eun fiptlons a^lndo^ Help
1
Python 3.4.2 (default, Oct 19 2014, 13:31:11) ' ir x in rang,e (1, 10}:
2
[GCC 4.9.1} on linux print (k)
3 Type "Copyright", "credits" or ,rlicense()M for more Information,
4 »> ====================_==_= restart =======_===_===
5 >>>
6 1
7 2
8 3
9 4
>>> | 5
6
7
e
9
>»--—.. RESTART ---—-
>>>
Cat
DSg
Unicom
»> ======= = ======================== restari ===================
>>>
J_

www.bdmpublications.com The Python Manual 43


Getting Started with Python

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.

File Edit Shell Debug Options Window Help


Python 3*6,2 (v3* 6 * 2:5fd33b5, Jul 3 2017, 04:14:34) [MSC v.1500 32 bit (Intel)]
on win32
'Type "Copyright11, "credita" or "license () " for more Information,
1 »> import math

>» empore pygamie


1 Tracebacfc (most recent call last) :
File "<py3hell#l>w, Ime 1, in <module>
Import pygame
ModuleNotFoundError: No module named 'pygame'
II »>

Black Dog i-Tech Series - Volume 35


Python Modules

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

»> import math

for i ir. range £5) :


print(random*randint(1, 25))

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_

www.bdmpublications.com The Python Manual


Getting Started with Python

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

Python 3.4.2 tdefault» Oct 19 2014. 13:31:11)


(GCC 4.9.1] on linux
Type "Copyright1', “credits" or "licenseO" for more Information. £ draw the white backgrouiid onto the surface
>>> ..................... RESTART ------------------------
»> windowSurface.fill(WHITE)
(most recent c»ll lest);
File ‘Vhcme/pi/Oocunents/graphics.py", line 83, in <ntodule>
fgjhpy^Gne.dirsw, eliipsefwindowSurface, RED, (300, 250, 40, 80), 1 )
NameError: name 'fghpygame' is not defined # draw a green polygon onto the surface
»>
pygame. dra*v,polygon(mncEwsurface , GREEH. ((146. 0).

#f draw some blue lines onto the surface

pygaifte.draw. line(windowSurface, BLUE, (60, 60), (120,

pygame, draw. line(windowSur face , BLUE, (120, 60), (60r

pygame.draff.line(windowSurface, BLUE, (60, 120), (120

# draw a blue circle onto the surface

pygame.drwv.circleCwindowSurface, BLUE, (3D0, 50), 20

# draw a red ellipse onto the surface

# . >pygame,dra'A.ellipse(windowSurface, RED, (300, 250,

ft draw the background rectangle onto the surfai

pygame, draw, rectCftindowSur face. R.ED, (textROct, lef t -


__y
Ln: Coi 4

* # *

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

File Edit Shell Debug Options Windows


Python 3,4,2 {default, Oct 19 2014, 13:31:11)
Help Eile Edit $he]l Debug Dpttons
Python 3.4.2 (default, Oct 19 2014, 13:31:ll)
Windows Help
J
[GCC 4.9 * 1J on linux [GCC 4*9* 1J on linux
Type "Copyright", "credits" or "licenseO" for more Information. Type "Copyright", "credits" or "licenseO" for more Information,
>» apples^lO »> print "Helio vorld M
»> pirntfapples) SyntaxExror: invalid syntax
Traceback (most recent call last): >>>
File "<pyshell#1, line 1, in <tnodule>
pirnt(apples)
NameError: name *pirnt* is not defined
»>i

EM Black Dog i-Tech Series - Volume 35


at www.pythontutor.com/visualize.html#mode=edit. Simply
print(balanced_check(inputO))
paste your code into the editor and click the Visualise Execution
Remember that For every'(' there must be an equal number oF button to run the code line-by-line. This helps to ciear bugs and
any misunderstandings.
import sys
♦ '•"> v ■ pyfhiirttijter.MFTi

SlEart leum Test your Pyihor


def balanced check(data): v *■ ii i r i iiiMiJ debugging sMIIs!
% stack = I] 2C m riute teil NCTON.

characters = list data Pyttan 3.S-


fUMt f-C«r t f&ii-J-tfttx UOta: £'«+
i gr.td a £ tvii-l-ott®* wd< H i i? * iotr-itn*! QHM*
“ard_ 1-e-nqf i kfixi :>
for character in characters: if word_ 1 *it^rth —“ t:
print ['ford, * foui*litttr WDri. dQT!P.Hl
i-ilrn*! GfejiC»

■IhI
reference = { prlrtt "ij r.at a wai'd.";i
5:-5E4i fiir*

wWd
tdit code | Ljvl1 uiujjr.jiriin^ig wgrdLl*ngtH *

KWTld'

} ■ c >,f!r ■: fc»fi pKb*gr*r‘ termina M.1 ’

if character in reference.keys{): Vi|V**l*0 W*"B i .rl'~r _ i_i . ‘Jj [fi . L‘

stack.append(character) uf rf|£r*v* 'hic t}Gi by cUtanC Wt'W

i fWl de^ffril at> A nrljnrirtiTi ulng'


yOu l*Sm swwcrinf

1 ]uH ftfcid i huci «V C-arfe!

elif character in reference.values() and len(stack) > 0: 4<w(!( per^s--?r irU


char = stack.pop{}
if reference.get{char) != character:
return "NO" ffrtuJ

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.

You have a bare except clause, i e.,

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.

A few other generaI comments on your code:


irue false
• In line 200( you have this constructi on:

for letter in range(len(cho5en_ward));


if player_guess — ehosenword[letter]:
word_guessed[letter] = player_guess
/ smail numbe
sente nce
7 / edium number
sentence
large number
sentence
7
YouYe looping over the index variable, but also usmg the list element. It would be better to £
write: end
for idx,, letter in enumerate(chosen_word) :
if player guess =— letter:

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.

www.bdmpublications.com The Python Manual 47


r-^ Getting Started with Python

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))

STEP2 You can utilise the Chudnovsky Algorithm to create


STEP 5 You can save and exeeute the code at this point if
_ your own Python script based on the calculation.
_ W you like. The output will print the value of Pi to 27
Begin by importing some important modules and functions within
decimal places: 3.141592653589734207668453591. Whilst pretty
the modules:
impressive on its own, you want some user interaction, to ask the
from decimal import Decimal, getcontext user as to how many places Pi should be calculated.
import math
This uses the decimal and getcontext functions from the decimal STEP 6 You can insert an input line before the Pi calculation
module, both of which deal with large decimal place numbers and _W Def command. It needs to be an integer, as it will
naturally the math module. otherwise default to a string. We can call it numberofdigits and use
the getcontext function:

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

• < :■■■ • math


it DtcuuL, pc-tcantcxt
File Edit Firmat Run Qptlons Windows Help
ter c-alcfr)-:
■"■'cur* decimal import Decimal, getcontext
pi = Decimal(0) t ■ DecuiaKo.)
pjl * DecimaltO}
dene - DecimaitP) i porx math
k = 0

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

for k in range(n): calc(n):


t - Decimal(O)
pi = Decima 1(0)
t = (Decimal(-l)**k)*(math.factorial deno - Decimal(O)
k = 0
(Decimal(6)*k))*(13591409 +545140134*k) for k in range(n):
t = (Decimal( -i )*#k)*(math.factonalCDeciiTiaI{6)*k))*(i359i409-*'545i40i34*k)
deno = math.factorial(3*k)*(math. deno - math,factorial(3*k)*(math.factor ial(k)**0ecima 1(3)}*(64Q320**(3*k)j
p i +*= Dec ima 1 (t) /Dec ima 1 (deno)
factorial(k)**Decimal(3))*(640320**(3*k)) pi - pi * DecimalC 12)/Decimal{64O320**Decimal( 1.5))
pi = 1/pi
retui n str(pi)
pi += Decimal(t)/Decimal(deno)
pi = pi * Decimal(12)/Decimal(640320**Decimal(l 5)) pr int(calc( 1)}

pi = 1/pi
refurn str(pi)

Black Dog i-Tech Series - Volume 35


Combining What You Know So Far

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

iHiuberofdigitS - int(ing>Ut( 'please ente! the nurber of decimal places ia ileulate Pi to i -»


an element that times how long it takes our getcontextf).prec = numberofdigits

computer to calculate the Pi decimal places def calc(n)i


t = Decima 1(0)

and present the information in a different pi * Decima1(0)


deno = Deciinal(O)
k - 0
colour. For this, drop into the command line for k i range(n):
t - (Decimal(-1)#+k)*(math*factorial(Decima 1(6)*k)) + (13591409+54514Q134*k)
deno = math.f actor ial(3*k)*(math.factGrial(k)**Decijnal(3))*(640320**(3*k))
and import the colorama module (RPi users pi + «• OecimaL{t}/Dec imaI(deno)
pi = pi * Decimal{ 12)/Decuriale 640320** Decimal*1.5))
pi ■ 1/pi
already have it installed): return str(pi)

pip install colorama pr mt{calc( 1))

STEP10 To finish our code, we need to initialise the t = Decimal(0)


_W colorama module and start the time function at pi = Decimal(0)
the point where the calculation starts, and when it finishes. The end deno = Decimal(0)
resuit is a coloured ink displaying how long the process took (in the k = 0
Terminal or command line): for k in range(n):
t - (Decimal(-1 )**k)*(math.
from decimal import Decimal, getcontext
factorial(Decimal(6)*k) )*(13591409+545140134*k)
import math
deno = math.factorial(3*k)*(math.
import time
factorial(k)**Decimal(3))*(640320**(3*k))
import colorama
pi += Decimal(t)/Decimal(deno)
from colorama import Fore
pi = pi * Decimal(12)/
colorama.initQ
Decimal(640320**Decirnal(l. 5))
numberofdigits = int(input(“please enter the number pi = 1/pi
of decimal places to calculate Pi to: “)) return str(pi)
getcontextQ.prec = numberofdigits
print(calc(l))
start_time = time.timeQ print(Fore.RED + “\nTime taken:”, time.time() -
def calc(n): start_time)

fj Python 3,4 2 Shefl sd. CalcPi py - /horne-pi pi@raspberrypi ~/D,

O l i f n a n j 7i n iSh@2l CalcPi py - / h o m c/p i / D o<cuments/Python Cotj0,> CalcPi ov (3 4 2) _ a x


m n x
£ile §dit Ffirmat fiun Qptions v/mdows £|elp
File Edit Shell Debug Options Windows Help
“ “ -— t**^
decimal irt Decimal, getcontext
Python 3.1.2 (defajlt, Oct 19 2014. 13:31:11)
it math
[GCC 4.9.1) on linux
imps rt time
Type 1’copyngfit,\ "credits" or " license()" for more Information,
i' ! colorama
fr i colorama impar t Fore

colorama,initf)
please enter the number of decimal places to calculate Pi to: 10QD
3.141592653569734207668453591570293340762233260915706590894145498737666209401659
1QEG6611734746960975779B16037965556627803580134599593513286173176615982806223108
numberofdigits * intcirtput("please entei
0441973785312S30565152115747085933S317744154596022745876277128465914181337399228
getcontextO ,prec * numberofdigits
5953578411298808837824212679468963352921667694733661968Q7151593493G958426926509Q
80187699606147066217003750206017344284513142480930327868775560407147230694298134
start_tine - time.time()
45787466657726444985596290919860559636358984008947138101161111956856848705962570
def calc(n):
13S72723252284798186917184867353096708222303615292971732815423261495480206046405
t = Decimal(O)
35398750760139733285849996526642119020066783578725502635682724402886356888437352
pi s Decimal(Q)
88982506842338309905740013758327701784908891322958527973601013169595019458889349
deno * Decimal(O)
44236412539394146530738483636665042264154387773376017707109142428744379717832620
k - 0
33721044052592738923786964883764463574460244839242316267458666952279157823643188
for k m range(n):
3495617064885226077021796218590519874114018895196B61231575370616742942112095521D
t - (Decimal(-l)**k)+(!inaTh,factorial(Decimal(6)*k))*( 13591409+545140134+k)
45317853525104446927986692358116127392886
deno - math. factorial(3*k)*{math. f actonal(k)**Decunal<3) )*(640320**(3*k))
»> RE START
pi *= Dec imal( t)/Decima 1( deno)

pi * pi * DecimaK i2)/0eciJiial(640320**0ecimal( i ,5))
please enter the number of decimal places to calculate Pi to: 1000
pi - 1/pi
3.141592653589734207668453591578295340762233260915706590894145498737666209401659
r eturn str(pi)
10806611734746968975779816037965556627803580134599593513286173176615982806223108 I
04419737853125305651521157470859338317744154596022745876277128465914181337399228
595357841129B8QB8378242126794689633529216676947336619680715159349309584269265090
pnnt(calc( 1))
30187699606147066217003750206017344284513142480930327868775560407147230694298134
45787466657726444985596290919B60559636358984008947138101!61111956856848705962570
print(Fore.RED une takei f time.timeo - start_tii»e)

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

www.bdmpublications.com The Python Manual


Data is everything. With ityou can
display, control, add, remove, create
and manipulate Python toyour every
demand. Over these coming pages we
look at howyou can create lists, tu ples,
dictionaries, multi-dimensional lists and
how you can use them to Porge exciting
and usePul programs.
You can also learn how to use date and
time Punctions, write to Piles in your
system and even create graphical user
interPaces that will take your coding skills
to new levels and into new project ideas.

52 Lists
54 Tuples
56 Dictionaries
58 Splitting and Joining Strings
60
r
Formatting Strings
mipriiimiimiipmirriutmiBmiiriiJirmtmiirmirmitmi(riuprmif mtmiin iiipriurrrniriiiirriiir FiiirmiriiiiiriiiimiirMiirtiiirriiimiirrinrriii

62 Date and Time


64 Opening Files
66 Writing to Files
68 Exceptions
70 Python Graphics
72 Combining What You Know So Far

The Python Manual 51


Lists are one of the most common types of data structuresyou will comes across in
Python. A list is simply a collection of items, or data if you prefer, that can be accessed
as a whole, or individually if wanted.

WORKING WITH LISTS


Lists are extremely handy in Python. A list can be strings, integers and also variables. You can even include functions in lists,
and lists within lists.
* *

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:

numbers = [1, 4, 7, 21, 98, 156] numbers[-1]


mythical„creatures - [“Unicom”, “Balrog”, mythical„creatures[-4]
“Vampire”, “Dragon”, “Minotaur”]
\SSimu P* AJ I
File Edit Shell Options Windows Help

Python 3.4.2 (default, Oct 19 2014r 13:31:11)


File Edrt Shell Debug Optra ns Windows HeJp [GCC 4.9.1] on Linux
Python 3.4.2 (default, Oct 19 2014, 13:31:11) Type "Copyright”, "credits" or "IicenseO" for more Information.
>>> numbers - [1. 4, 7. 21, 98, 156]
[GCC 4.9.1] on Linux
Type "Copyright", "credits" or "license()" for more Information. »> mythicai_creatures = [ i ■ "Balroe ramoire min
>» numbers * [1, 4, 7, 21, 98, 156]
>» mythical_creatures = [ "Unicom" i 'Balrog", H Vamp •«u IH' SU "1
>>> numbers
(1. 4, 7, 21. 98, 156| I
>» I »> numbers[3]
±51I
»>> mythical_creatures
[“ Unicom* ( “Balrog', ‘Vampire1, 'Dragon', Minotaur']
>» mythical_creatures[3J
'Dragon*
»> numbers E * i ]
156
»> numbersE-2]
98
>>> mythical_creatures[-1]
'Minotaur1
»> rnythical_creatures[-4]
'Balrog'
>>>

• • 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

Type "Copyright", "credlts” or "LicenseO1* for more Information.


To call the third from zero item in the list (21 in this case). >» numbers * [1, 4, 7, 21, 98, 156]
>» mythical_c reatu res = [“Unicom1*, “Balrog", "Vampire", uvagon "Minotaur']
>>> numbers
II, 4, 7, 21, 98, 156]
>» numbers[3]
1 ,*• ,.u. ;1-, i25
Y 'i ;* ._
v-p- [I: ^ l ES jt',’ ’ 21
>>> mythicaL_creatures
Eile Edit: Shell Debug Qptions Windows Help
['Unicom*, *Balrog*, 'Vampire*, 'Dragon*, 'Minotaur*]
Python 3.4.2 (default, Oct 19 2014, 13:31:11) >>> mythical_creatures[3]
[GCC 4.9.1] on linux 'Dragon'
Type "Copyright", "credits" or "licenseO” for more Information. >>> numbers[-1]
>>> numbers - [1, 4, 7, 21, 98, 156] 156
>» mythical_creatures = [ ic V oBTl P d! inotau >» numbers[-2]
>» numbers 98
[1, 4, 7, 21, 98. 156] >>> fnythicai_creatures[ * 1 ]
»> numbers[3] 'Minotaur'
21 »> mythicaL_creatures[-4]
>>> mythicaL_creatures 'Balrog'
["Unicom', 'Balrog*, * Vampire* 'Dragon*, 'Minotaur'] »> numbersE1 :3]
>» mythical^creatures[3] 14, 7]
'Dragon* »> numbersE0:4]
»> | II, 4, 7, 21]
»> numbers[3:5]
(21, 98]
>>> numbersE1 i]
E4, 7, 21, 98, 156]
>>> |

52 Black Dog i-Tech Series - Volume 35


You can update items within an existing List, remove You can view what can be done with lists by entering
STEP8
W items and even join lists together. For example, to _ W dir(list) into the Shell. The output is the available
join two lists you can use: Functions, For example, insert and pop are used to add and remove
items at certain positions. To insert the number 62 at item index 4:
everything = numbers + mythical_creatures
numbers.insert(4, 62)
Then view the combined list with:
To remove it:
everything
numbers.pop(4)
:*■, i i ype copyngnt'* creans or ncense^j’ ror more Information.
»> dir(list)
Frfe Edit SheJI Debug Options Windows Help
[‘_add_*, class _* . *_contains_\_delattr_*, *_de litem._/ , *_dir_*
Python 3.4,2 (default, Det 19 2014, 13:31:11) , *_doc_1_eq_V, *_format_/, ‘_ge *. *_getattribute_1_getitem„'
[GCC 4.9,1] on Iinux , *_gt_*, \_hash * . *_iadd_', *_imul_*_init_4, p iter_* , \_le_4
Type "Copyright"* "credits" or "IicenseO" for more informat ion. , *_len_* . It_1 p _mul_1, *_ne *. 1_new * , *_reduce_1 , *__reducere
>» numbers * [1. 4, 7, 21 . 98* 156] x_\_repr_p( ■_reversed_' , *_rmul_* , * setattr / , 1 setitem ’ s
»> mythical_creatures = ["Unicom", "Balrog", "Vampire", "Dragon", "Minotaur"] izeof . * str *. * subclasshook_1 , ‘append1, ‘ciear4, 'copy“* 'count*, 4ex
>>> everything = nunbers + mythical_creatures tend', 4 index*, 'insert*, 'pop*. 'remove', * reverse't 'sort*]
»> everything »> numbers = fi, 4, 7* 21. 98, 156]
[1* 4, 7, 21, 98* 156. 'Unicom*, 'Balrog', 'Vampire1, 'Dragon1, 'Minotaur'] >» numbers
>» [1, 4, 7* 21, 98, 156}
>» numbers.insert(4, 62)
>>> numbers
[1, 4, 7, 21, 62, 98, 156]
#
>» numbers,pop(4)
62
>» numbers
[1, 4* 7, 21, 98, 156]
t
************************************* * ■ *

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:

dei numbers[7] name=input(“What’s your name? “)


lname=list(name)
Alternatively, by item name:
age=int(input(“How old are you: “))
mythical_creatures.remove(“Nessie”) lage=[age]
»> mythical_creatures ■ ["Unicorn"', "Balrog”, "Vampir
»> numbers
u aeor ? * inotaur1]
user = Iname + Tage
[1, 4, 7, 21, 98, 156]
>>> mythical_ereatures
[‘Unicom*, ‘Balrog*, 'Vampire4, 'Dragon', 'Minotaur']
The combined name and age list is called user, which can be called
>>> numbers=numbers+[201]
>>> numbers
by entering user into the Shell. Experiment and see what you can do.
[1, 4, 7, 21, 98, 156, 201)
»> mythica l_creatures“myth ioal_creatu res* [ "Griffin"]
>>> mythical_creatures 4 _ O X
[‘Unicom** 'Balrog*, 'Vampire4, 'Dragon', Minotaur*, 'Griffin'] Fi;le Edit Shell Debug Optioni Windows Help £lle td;t Firmat Pun Qpilons Windows
>>> mythical_creatures.append( Messie ) Python 3.4.2 {default, Gct 19 2014. 13:31:11> r
>>> mythical_creatures name*input(' ut vo )
[GCC 4.9,1] on linua lname-listtnarie)
['Unicom', ‘Balrog*. 'Vampire'. 'Dragon', Minotaur*. 'Griffin*, *Nessie*] Type “Copyright11, “credns" or "licenseO" for more Information,
>>> RESTART
age-int(input( H oid are ))
>>> numbers.append(278) »>
>» numbers V.liafs yojr n^me7 Conan of Cimmeria user - Iname + lajH
[1, 4, 7, 21, 98, 156, 201, 278] How old are you; 44
»> user
>>> dei numbers[7) ['t% 1 o' , 'n', ‘a*p ‘n'r ‘ ‘o*. ‘f. ■ ‘, ‘C\ ‘i*. , ‘m*. me\ *rm i'.
>>> numbers ’a'* 441
»>
[1, 4, 7f 21, 98, 156, 201]
>>> mythical_creatures.removef lessi^')
>>> mythical^creatures
[‘Unicom', ‘Balrog*, 'Vampire' , 'Dragon', 'Minotaur1, ‘Griffin*]
»> [

www.bdmpublications.com The Python Manual 53


Working with Data

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.

THE IMMUTABLE TUPLE


Reasons for having tuples vary depending on what the program is intended to do. Normally, a tuple is reserved for something
special but theyYe also used for example, in an adventure game, where non-playing character names are stored.

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)]

f "" ~.~. .“ .' .~ ~ .^ -~jF'

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.

£ile £dit Shell Qebug fiptions Windows fctetp


Python 3,4#2 (default, Oct 19 2014, 13:31:11)
[GCC 4*9,1] on linux
Type "Copyright”, "credits" or *"license()" for more Information.
>» months=(“January", "February“P "March", "April", "May", "June'')
»> months
('January'p ‘February*, ‘March*. ‘April** *May*. ‘June‘)
»> months [0]
* January'
»> months [5]
‘June1
»> months.appendt Jul, )
Traceback (most recent call last):
File "<pyshell#4>,*p line 1, in <module>
months.append("July")
AttributeError: 'tuple* object has no attribute *append*
»> |

54 Black Dog i-Tech Series - Volume 35


• *******

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]

£ife £dil Shell Qebug Qplions 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 "Copyright1*, “credits" or "licenseO" for more Information, »> NPC=("Conan", 100)
>» npc-[("Conan", 100), ("Belit", 80), ( "Valeria V, 95)] >» (name, combat_rating)&HPC
»> NPC[2) [1] »> name
95 ■Con an *
»> combat_rating
100
>>>

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:

£ile £dit Shell fiebug Qptions Windows Help print(max(numbers))


Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
print(min(numbers))
Type "Copyright", "credits" or “licenseO” for more Information.
>» |IPC=( “Conan", 100)
>» I
File Edit Shell Debug Options Windows Help
Python 3.4*2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "Copyright", "credits" or "licenseO” for more Information,
»> numbers-(10.3, 23, 45.2, 109*3, 6*1, 56-7, 99)
>» print(max(numbers))
109.3
>» prmt(min( numbers))
6.1
>» |

Ii

www.bdmpublications.com The Python Manual 55


Lists are extremely useful but dictionaries in Python are by far the more technical way
of dealing with data items. They can be tricky to get to grips with at First but you'll soon
be able to apply them to your own code.

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 _

File Edit Shell IDebug Options Windows Help


Python 3,4,2 (default, Oct 19 2014, 13:31:11}
File Edit Shell Oebug fiptions Windows Help (GCC 4.9.i I on linux
Python 3,4.2 (default, Oct 19 2014- 13:31:11) Type "Copyright", "credits" or "1icense()" for more Information
(GCC 4.9.1) on linux >» phonebook“{"Emma": 1234, "Daniel": 3456, "Hannah": 6789}
Type "Copyright”, "credris" or "licenseO" for more Information, >» phonebook2-{"David": "0987 654 321"}
»> phonebook={ E mia": 1234, DanieT’: 3456* "Hannah": 6789} »> phonebook
>» phonebook2={ Dnv c 1: "0987 654 371 } CHannah': 6789. ‘Emma*: 1234, ‘Daniel1: 3456}
»> f >» phonebook[ Enma )
1234
»> phonebook( Hannah"]
6789
>>>

Black Dog i-Tech Series - Volume 35


Dictionaries

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: “))

File Edit Format Run Options Windows Help

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

■ TaajTjy i£j j » j a y ^ ■jf J ■\T JfCjrj


. • ' 4 (| - [ym lui

File Edit Format Run Options Windows Help

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,

£ile Edit Shell Qebug Options Windows fcjelp


Python 3*4.2 (default. Oct 19 2014, 13:31; 11)
[Gtt 4.9.1] cn liniix
Type "■Copyright''j "credits" or ,rIicense()" 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’]}
»>

www.bdmpublications.com The Python Manual 57


Working with Data

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

File Edrt Shejl Debug Optlons Windows Help

Python 3^4.2 (default, Gct 19 2014* 13:31 MI)


[GCC 4*9.1] on linux
Type "Copyright**, "credits" or “*license()" for more Information,
»> text*"January,F#foruary,March,April,May June"
>>> months=text*split(*,")
>>> months
January’, 'February*, *March*# ‘April1. 'May*. ‘June*]
>» i
>>>

* * * ***#*#■**•***** #*##**#*

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

58 Black Dog i-Tech Series - Volume 35


them ali together to Form a word or just a combination oF items, stop, a hyphen or whatever you like:
depending on the program yoiTre writing. For instance:
colours=[“Red”, “Green”, “Blue”]
alphabet =””.join([“a”,”b”,”c”,”d”,”e”]) coi =”,”.join(colours)
alphabet coi
This will display 'abcde' in the Shell.
0le Edat She[l Qebug Options Windows Help

Python 3.4*2 (default, Oct 19 2014, 13:31:11)


[GCC 4*9.1] on linux
Type "Copyright**, “credits" or "licensetfor more informatxon,
File Edit SheJI Debug Options Windows Help »> list=["Conan“i “raised", *his", "mighty*", "sword”# "and**, "struck", "the*1, "demon"]
»> text* . join(list)
>» text
Python 3.4,2 (default, Oct 19 2014, 13:31:11) 'Conari raised his mighty sword and struck the demon*
[GCC 4,9.1] on linux »> colours^["Red", "Green", "Blue")
Type "Copyright", "credits" or "licenseO" for more Information. »> coi* ‘.join(colours)
»> alphabet*1’”. jpin( [ a", "b”, ”c", "d* , “e"]) »> coi
' Red,Green*Blue r
»> alphabet »>
r abcde1
»>

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

Python 3,4.2 (default, Oct 19 2014, 13:31:11)


[GCC 4.9,1] on linux
Type "Copyright", "credits" or “license()“ for more Information
Ede £dit Shell fiebug Qptions Windows Help >>> title- 'conan the cimmerian'
>>> title.capitalizeQ
Python 3,4*2 (default, Oct 19 2014, 13:31:11) *Conan the cimmerian*
[GCC 4,9,1) on linux >>> title,title()
Type "Copyright”. "credits" or '*license{ )w for more Information, * Conan The Cimmerian*
»> name=l ist( "David") »> i
»> name
'a\ ’v\ ‘i\ 1 d#]
»> narae= .join(name)
»> name
* David1

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
»>

www.bdmpublications.com The Python Manual 59


When you work with data, creating lists, dictionaries and objects you may often want
to print out the results. Merging strings with data is easy especially with Python 3, as
earlier versions of Python tended to complicate matters.

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))

Python 3.4 2 Shell


Pyihon 3 4 2 She I £ile £dit Shell Qebug Sptions Windows Hetp

£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,

for-w.* fl*X4(vaFue farmeJ


i ^tiwyrtrtm9.f1* ^1 O C S+eft* ^ fi ^ ft 9 9 Q —

■ ™- ;. 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

7.1.3. Format String Syntax


File £dit She|) Qebug Qptions Windows jjelp The. - - , ir-tflnoc md llit • r»..- - cia« bia1* :he sarr»? synlHj (di isimal«.!; ings >h :neuqn ,n !ne r.«e of ?• -t..- -..t Crin tiefire ths.i «sn icrnHi slfing s*n‘.isxji

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

>>> name= an ■ VlKMuC ILald Lj* [i-laiuj . t*l” Lunnu.1 f* ™ J ■*

»> place* Cinsuej ia” 11* *[3_E.pn* ’nrw t r [" .;


ira.MH fel* 114pn* kl lef ' lalwnirii
iji
»> pnnt( {} hailed from the Horth. in a cold land t no, n as {}",format(nane, place))
ittrrbcCt ruute i'icn.un<T
■t ^ ndu T2* Lr. rt^r | ulMi ilfiirg
1 ni»n*liptT-r>Ki rl» r*ft¥ iDnrn ?MTlrter evenit "3 t
Conan hailed from the Horth, in a cold land knowi as Cimmeria r i ■■

»


fi■
I

m^vrvl wv
n

feTmat_ip*ie 15■ cOf^^rLP^I ii aere


>>>
tfl 1*U TOfmtll J*rmv. m* ru^>l»-r uniuiM fiu!i:l ^t®r1 wdh n ther tpOCifmi lh* obect whOW wtkjfr iS to sr«J riMitvd Alio rrm eu^M iiswed (1( !h* f*p*K*m*nt rw:o T?14 IV 0p1cn*!hr TotfiSiMKl b¥ (l
CpnuwiiOrt rntsd nrfiich i* pn*cijh^jr<J Ijy w ««cKmikM pomi ' i,, and « JScuT!ii#r„ip*c, whtch 14 t)y e K»ai < i ■ Thaw # noo-dt^uit breiM for m* i upItiCvftMrvi v*ilihj

S« et» tuo >. • ri.fr Mu» i a/nju,tijcr

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 ■,

Some simple tormat stnnfl examoies

"firr., ctc- j-gtuis zq t fizsz peritz&n*! izTV&eut


"Stim *** * n" 4" refwfji^i fjri:
“Ptop (i » uB 11 i* *trm t* m*
‘H; a tJ L 1J 3 ITU S" # IIbTK.1 «Lufi i*^V'UUl Mf Ji-±.B2.L 'Jatt* ?
JLJi. Lijiai * U mV#1qF.L : " I ‘ i Tl^jAC “ J LUdl^Et Sif LliC f >.«..1 iJ*;
"DH-tt I’pifeVfrt1 j 1 *■ «i I |LJ~i * W mK.W~ C k+i/Vlfr-* rpJrl]/Vfiff P fi

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

60 Black Dog i-Tech Series - Volume 35


Formatting Strings

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:

characters=[“Conan”, “Belit”, “Valeria”, 19, 27, names=[“Conan”, “Belit”, “Valeria”]


20] ages=[25, 21, 22]|
print (“{0} is {3} years old. Whereas {1} is {4}
Creating two lists. Now you can call each list, and individual items:
years old.”.format(*characters))
print(“{0[0]} is {1[0]} years old. Whereas {0[1]}
is {![!]} years old.”.format(names, ages))
£ile Edit Shell Qebug Options Windows tjelp
Python 3.4.Y (defaultT 0ct~19 201*7 13:31M1)
[GCC 4.9.1] on linux
Type "Copyright", "credits" or "litense()" for more Information,
»> characters=["Conan”* "Belit", "Valeria", 19, 27, 20) Eile Edit SheJI Debug Qptions Windows Uelp
»> print (”(0) is {3} years old. Whereas {1} is {4} years old.".format(*characters))
Conan is 19 years old, whereas Belit is 27 years old. Python 3.4*2 (default, Oct 19 2014, 13:31:11)
>>>
[GCC 4,9.1] on linux
Type "Copyright", "credits" or "license()” for more information.
»> names=[ Conan , "Belit", Valeria )
>>> ages*[25, 21, 22]
>» prmt{4,{0[0] > is {1[0]> years old. Whereas {011]} is {1 [ 1 ] } years oU«w.form
atfnames, ages))
Conan is 25 years old. Whereas Belit is 21 years old.
»> |

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

Python 3.4.2 (default, Oet 19 2014 r 13:31:11)


[GCC 4.9.1] on linux
Type "Copyright"* "credits" or "licenseO" for more Information.
>» import time
»> time.asctimeO
'Thu Sep 7 08:44:24 20171
>» |
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCt 4.9.1) on linux
Type "Copyright", "credits"1 or "licenseO" for more Information,
»> impc t time
>>> time.localtime()
t ime. strue t^t ime (tm_y ea r=2017, tmjnon-9, titijnday-7, t»_hoiir»9, tm_min=6 tm sec=
13, tm_wday=3, tm_yday=25Q. tm_isdst=0)
>>> l

• • 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:

Index Field Values time.strftime(4)


0 4-digit year 2016

1 Month 1 to 12 File Edit Shell Debug Options Windows Help


Python 3.4,2 (default, Oct 19 2014, 13:31:11)
2 Day 1 to 31 [GCC 4.9.1] on linux
Type ‘'Copyright”, "credits" or "licenseO" for more Information.
>>> import time
3 Hour 0 to 23 »> time.strftime{ ,A )
'Thursday1
»>
4 Minute 0 to 59

5 Second 0 to 61 (60 or 61 are leap-seconds)

6 Day of Week 0 to 6 (0 is Monday)

7 Day of year 1 to 366 (Julian day)

8 Daylight savings -1, 0, 1, -1 means library determines DST

62 Black Dog i-Tech Series - Volume 35


This naturally means you can incorporate various You saw at the end oF the previous section, in the
STEP8
Functions into your own code, such as: _W code to calculate Pi to however many decimal places
the users wanted, you can time a particular event in Python. Take
time.strftime(“%a”)
the code From above and alter it slightly by including:
time.strftime(“%B”)
time.strftime(“%b”) start_time=time.time()
time.strftime(“%H”)
Then there's:
time. strftime(“%H%M”)
endtime=time. timeO-start_time

File Edit 3he|I Debug Qpttons Windows Help


Python 3.4.2 (default , Oct 119 2014, 13:31:11)
[GCC 4,9,1] on linux
Type "Copyright", "credits" or "licenseO" for more Information.
>» i? i )ui l time
»> t ime. strf time ( ")
'Thu'
>» t une. strft une(
'September'
>>> t une.strft une(" : ‘)
f Sep *
>» t une .strft une( 1 H
'09*
»> t une. strf time ( 4 •j ■)
'09411
»> 1

* * *

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

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)
Python 3,4,2 (default, Oct 19 2G14, 13:31:11) I6CC 4.9,1] on linux
tGCC 4.9,1] on linux Type "Copyright*’, "credits" or "litense()" for more Information
Type "Copyright", "credits’* or "licenseO'* for more Information, >» RESTART ■■■■■■■■■■■■■*■■■■«
»> impoi t time >»
»> time.strftime('■ a > Enter login name: David
'ThuF Welcome David \d
>>> time.strftime( ) User: David logged in at 09:52
fSeptember * It took David 5.311823129653931 to login to their account.
>>> time.strftime(". r ) »> |
'3epf
»> t ime . strft ime{ ' H )
»09*
»> time .strftime{ y H^jr )
109411
»> time .strftime{ -H: -JJ")
'09:43'

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).

The other representation is a tuple of 9 integers giving local time.


The tuple items are:
year (including century, e.g. 1998)
month f1-121_

www.bdmpublications.com The Python Manual 63


In Python you can read text and binary files in your programs. You can also write to file,
which is something we will look at next. Reading and writing to files enables you to
output and store data from your programs.

OPEN, READ AND WRITE


In Python you create a file object, similar to creating a variable, only pass in the file using the open() function. Files are usually
categorised as text or binary.

* 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

_1 Scratch Pipjects 21/06/17


m Additi on py 52 bytes 18/08/17 Vista on vista roarching., hilis on h £ile Edit Shell £)ebug Qptions Windows Help
Slope beyond slope, each dark with :
i cakepy 251 bytes 25/08/17 Our gaunt land lay. So when a man c! Python 3.4.2 (default, Oct 19 2014. 13:31:11)
A rugged peak and gazed, his shaded [GCC 4.9.1] on linux
5 Circle py 1 50 bytes 21/08/17 Saw but the endless vista - hili on Type "Copyright1', '*creditsM or "licenseo*' for more Information.
il graphicspy 19 kB Friday Slope beyond slope, each hooded liki »> poetn=oper( home/pi l ocumenTs Poee tvf')
»> poem
1 Helio py 45 bytes 18/03/17
<_io.TextiOWrapper nafiie= VhQme/pi/Bocuiiients/Poefn.txt1 mode^r' encoding=’tfTF-8’ >
21/03/17 It was a gloomy land that seemed to »> poem,read()
S img.py 61 bytes
Ali winds and clouds and dreams tha
+,X rememberXnThe dark woods, masking slopes of sombre hillsAnThe grey clouds1 leaden everlasting
§ imgtest py 350 bytes 21/03/17 With bare boughs rattling jn the loi
arch;YnThe dusky streams that flowed without a sound,\nAnd the Ione winds that whispered down the
And the dark woodlands brooding ovei
M loopl py 43 bytes 18/08/17 Not even lightened by the rare dim :
passesAn\n\nVista on vista marching, hilis on hilis AnSlope beyond slope, each dark with sullerc t
Which made squat shadows out of men reesAnoyr gaunt land lay, 50 when a man climbed upYnA rugged peak and gazed, his shaded eyexnSaw
M ruai n py 175 bytes 15/08/1? but the endless vista - hili on hi 11,YnSlope beyond slope, each hooded like its brothersAnYnYnlt
Cimmeria, land of Darkness and deep
H namecourct py 101 bytes 18/03/17 was a gloomy land that seemed to holdVnAll winds and clouds and dreams that shun the sun.YnWith ba
re boughs rattling in the lonesome winds AnAnd the dark woodlands brooding over allAnNot even lig
RPi.png 42.2 kfi 21/08/17 It was so long ago and far away htened by the rare dim sun\nWhieh made squat shadows out of men: they called itXriCimmeria, land of
i Square.py 155 bytes 21.08/17 I have forgot the very name men cal' Darkness and deep Night AnYnYnlt was so long ago and far away\nl have forgot the very name men cal
The axe and flint-tipped spear are led me.YnThe axe and flint-tipped spear are like a dream,YnAnd hunts and wars are shadows* I recal
1 test.py 40 bytes 18/00/17 And hunts and wars are shadows. I n lYnQnly the stillness of that socnbre landAnThe clouds that piled forever on the hilisAnThe dim ne
Only the stillness of that sombre L ss of the everlasting woods.YnCimmeria. land of Darkness and the riight.\n\n\nGh, soul of mine, bor
J The&mmenan Poem 14 kB 11.07
The clouds that piled forever on th n out of shadowed hilisAnTo clouds and winds and ghosts that shun the sunAnHow many deaths shall
'T wordgame.py 287 bytes 18/06/17 The dimness of the everlasting wood: serve to break at lastYnThis heritage which wraps me in the greyXnApparel of ghosts? I search my h
eart and findYnCammeria. land of Darkness and the MigjhtA
Character Codin g Current Locale (UTF-8J >» I

^ 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

»> poem*open{ 'Vhcpme/pi/Docunients/Poem. txt")


>» prmtCpoem.readf))
I remember
The dark woods, masking slopes of sombre hilis;
The grey clouds* leaden everlasting arch;
The dusky streams that flowed without a sound.
And the Ione winds that whispered down the passes.

Vista on vista marching, hilis on hilis,


Slope beyond slope, each dark with sullen trees*
Our gaunt land lay, So when a man clunbed up
A rugged peak and gazed, his shaded eye
Saw but the endless vista - hili on hili,
Slope beyond sloper each hooded like its brothers.

It was a gloomy land that seeroed to hold


Ali winds and clouds and dreams that shun the sun,
With bare boughs rattling in the lonesome winds,
And the dark woodlands brooding over ali,
Hot even lightened by the rare dim sun
Which made spuat shadows out of men; they called it
Cimmeria, land of Darkness and deep Night,

64 Black Dog i-Tech Series - Volume 35


Opening Files

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:

poem.read(5) poem=open(“/home/pi/Documents/Poem txt”)


lines=poem.readlines()
Displays the First Five characters, whilst again entering:
lines[0]
poem.read(5) lines[l]
lines[2]
WilL display the next Five. Entering (1) will display one character at
a time.

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

Rle Edit Shell Qebug Qptions Windows Help


£ile gdit She[l fiebug Qptions Windows £(e3p
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 "Copyright"* "credits" or ”Iicense()" for more Information. [GCC 4.9.1] on linux
»> poem=open("/home/pi/Documents/Poein*txt") Type "Copyright", "credits” or Mlicense()” for more Information.
>>> poem,readline() »> poem=open{'/home/pi^Documents/Poan. txt“)
'I rememberVn' »> for lines m poem:
>>> poem.readline() print{lines)
*The dark woods, masking slopes of sombre hilis;\n*
»> |
1 remember

The dark woods, masking slopes of sombre hilis:

The grey clouds* leaden everlasting arch;

^ 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

Python 3. A.2 (default Oct 19 i0'4. 13:31:11} linipMr r tune


[GCC -1.9.13 linux
Type “cepy riEfiC1. "crediEs" or "licenset)“ For i*0re ir forma Cion. ‘ t-i--..’ i '‘DOCuHenc:
>» --- RESTART ..«r.......™.,,
;>1>>r er.err b e ■ lines^-poe*.re-acK)

'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

And ttie Ione «irids that whispered dows the passes.

Vista m vista marchin^, Fui Is hilis,


'Jloae beyond slape. each dark with suilen Trees.
Our gaubt Iand lay. So rthen a «an cliirtbed up
A rjgged peak and gazed. his shaded eye
5a* but tbe tndless vista - hili on hili.

II
Slope beyond slope. each haoded like its broThers,

www.bdmpublications.com The Python Manual


■_!_ k

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.

WRITE AND CLOSE


The write() function is slightly more complex than read(). Along with the filename you must also include an access mode which
determines whether the file in question is in read or write mode.
* *

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.

£ile Edit Shell Debug Options Windows Help


Python 3 4 2 Shell
Python 3.4.2 (default. 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 informat
Python 3*4*2 {default, Oct 19 2014, 13:31:11) t=open( M/horne/ 1 iJ L. i_11 | 9 rr 1 | S. j |_ r1 Xt * 1
[GCC 4.9*1] on linux t,write( rou ciwakc luare room* A sinigle table stands to one sid
Type “Copyright", "credits" or “license{)n for more rmat ion here is a Ioch fioor in frnn t 01E you.")
»> t=open{"/home/pi/Docupients/text,txt","w") 109
»> »> t.closeO
»>

• • # •

^ 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) -

»> t.rtrite( ": tu a ake in - snall4 square dc . a. single table s


t. there is a locked door in t ront of you. 1)
109
»> t.closef)
»> [
File £dit Shell Qebug Options Windows Help
Python 3.4,2 (default, Oct 19 2014, 13:31:11)
(GCC 4.9.1] on linux
Tjt
Type "Copyright", "credits" or "licenseO" for more Information
>>> t-open( ’ honie p i /Documents text. t * t1 , a" )
»> t. write ("You awake in a small» square room. A single table i 1JL ri
U

e* there is a locked door in front of you.")


109
>>>

I I

66 Black Dog i-Tech Series - Volume 35


To expand this code, you can reopen the Pile using You can pass variables to a Pile thatyouVe created
STEP8
W 'a', Por access or append mode. This will add any text _ W in Python. Perhaps you want the value oP Pi to be
at the end oP the original line instead oP wiping the Pile and creating written to a Pile. You can call Pi Prom the math module, create a new
a new one. For example: Pile and pass the output oP Pi into the new Pile:

t=open(“/home/pi/Documents/text.txt”,”a”) import math


t.write(“\n”) print(“Value of Pi is: “,math.pi)
t.write(“ You stand and survey your surroundings. print(“\nWriting to a file now...”)
On top of the table is some meat, and a cup of
water An”)
File £dlt Ffirmat Run Qotions Windows Help

impoi math

print( "Value Pi is: w,math.pi)

printt"XnVfritirig to a file now_')

* *

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)

print( AnWriting to a file now...")

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

Eile Edit Shell Qebup Qotions ^ndows Help


File Edit Saaich Qptiona Help_
text txt
You can see Prom the results that youfe able to pass any variable to
7!

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

www.bdmpublications.com The Python Manual


When coding, you'll naturally come across some issues that are out oFyour control.
Let's assume you ask a user to divide two numbers and they try to divide by zero. This
will create an error and break your code.

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

Python 3.4.2 (default, Oct 19 2014, 13:31:11)


[GCC 4.9.1] on linux
Type "Copyright’', "credits" or "licenseO" for more rmation
»> 1/0
Traceback (most recent call last):
File ”<pyshell#0>", line 1, in <module> Rte Edit Shell Oebug Options Windows Help
1/0 Python 3.4.2 (defaultt Oct 19 2014, 13:31:11)
ZeroDivisionError: division by 2ero [GCC 4.9.1] on linux
»> I Type "Copyright”, Mcredits" or "licenseO" for more Information.
>» raise Exceptionf *warp core breach1')
Traceback (most recent call last):
File '■<pyshell#0>,p, line 1, in <module>
raise Exception("warp core breach*4)
Exception: warp core breach
»> [

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

automatically when Python l +- FI c at ir. gF ui " 11 r r or


4-— Cve r f lcw£ nor
oP try, except, else, where the code is held within try:, then iP there's
t +■— Zs-rcDi visiciiExrc r
comes across something that's +—- AaaerLictiflrrcr
+— At t rifciit eir ror
an exception do something, else do something else.
Buff erError
inherently wrong with the code. -1- EDFE rrer
H- Icrpc rtErxor
+— Ko dcl e: ic lF oimdErr or
However, you can create your +— LociupError
+— IndexErrcr
Ia"

1 JB. _ _ KsyError

own exceptions that are designed ■1- Keuic ryError


+- Name Error
£ite Ed>t Firmat Buri aptioris Windows hdeip
HnbotmdLcca lErr c r
to contain the potential error and +--
1!
rcr
BidtkingIOErrCr Insert your operatlons here ->
1 CM ldProce 3 b Er rc r
pt Exception 1:
react to it, as opposed to letting E
t
+— Conr.e cti onE rro r
i -— ErolenPipeError If there i an exepetion do this ->
t t -Co une cx. i o nAb o r te dE r
t* • t pt Exception 2:
the code Pail. II
E
i
t
t— CoMectionRelusfriSEr
+-- CoautctiDnJaftaecErro, If there another exception do this ->
E fi 1eEs's 13 Er^cr
l 4—— FilsKdcF ctmdErr c r
1 4-— InterrnptedError If there i no exception, then do this->j
1 4— — IaADirecrcr vErrcr
E 4- i-5 2 L ADire croryEri ei
E +— FirmisalenEtror
1 F roce 33 Lpc-JrupE rrol
E +— TimeoutError
-l-— fofn renceError
4- Runt ireE^cr
I +— Hat Iir:_pL 1 ena nte g£ r z c r
E +— RtcLirsiccErrcr
+ -- Synt flHEtrQr
( 4-—-— TTifJentsticrjError
I 4— TabErrcr
H- Syst eirZrrcr
- TypeError
T

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

68 Black Dog i-Tech Series - Volume 35


Exceptions

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

print ("Error: unable to write ~he file, Chsck permissions1)


resure

frror; un^b 1p to write the fiLe, the-ck perrrusSions ieiset

print(“You have tried to divide by zero!”) >» ================================ RESTAflT ■=——w——:

Content wntter to file ■su.ccessf ully. Navo e nice- day,


print ("Coment wntten to file succ&ssfully. ttave e nice day
tst,cloie()


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

Python 3.4,3 {default, Oct 19 2014, 13:31:11) [: •• v:


J y rt 4,9.1) on linux a“int(input("Enter :h^ first number:
Typ* "Copyright", "ertdits" ar "liC#ns#0" f&r !*or* inforaation. b-^intf inputf ‘Er • ? ■ Ihe - , r ,: nia»hei
...................lui......... RESTART pr jnt(a/b)
>» 2eroDivisionError:
Fnter the first nunber: 12 pr inc( "Vou hxve tfJfid rn dividr by ,ve ror>
En ter the second nunber r fi 'else;
7-0 prmK-yeij didn t divide by sere, lici i done1")
Vou didn‘t divide by zero. Well donel


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

Pytho iT3.4.2 (dofault» Ott 19 2014,13:31:11)


J File Edi! Foime1: Run Dptlons Wlndowi H^lp

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

Errort unable to write the file. Check permissions


«.■■■■■■■■■■■ = ■ = ■■■■ txt, write ("This is a test, Normal Service will shortly resunet")
t L11 Hi 1 ; V :
print {"Content written to file successfully. Have a nice day.")
>» txt,close()

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

Python 3.4.2 (default, Oct 19 2&14. 11:31:11)


[occ 4,9,11 on linux ttl * Opcn( . jp• II1 Dl-f.iFicn ' -1, i 11 Lr • ! "r • )
Typo “copyriEfit", "credits" or "licensefj" for more irfonration.
>» .... RESTARI.---- txt.wricef"Fhis is a test, Hemtal Service will Shortly resme!")
»> f VR0 4 I y r
Error: unable to write the file, Check permissions print ("Content written to file successfully. Have a nice day. )
J.» ============================ RESTARI =================== int.closeo
»1 h*•. ^p: IOError:
Certent written ta file successfully, Have a nice day. print ("Error: unable to write the f:Le, Chedk permissions")

www.bdmpublications.com The Python Manual 69


Whilst dealing with text on the screen, either as a game or in a program, is great, there
will come a time when a bit oP graphical representation wouldn't go amiss. Python 3
has numerous ways in which to include graphics and they're surprisingly powerPul too.

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-.

tvi [ Python Turde Graphics i»i

£lle Edit Shell Oebug Options Windows Help


Python 3.4,2 (default, Oct 19 2014* 13:31:11} ie|
2
[GCC 4,9.1] on Linux 4 turtle.eircle(50. 180)
Type "copyright", "credits" or "license()" for more information, turtle.getscreenC) F.root .maieloopKj
>>> import turtle
>>>

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

Black Dog i-Tech Series - Volume 35


Python Graphics

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)

img ‘ pygame-amage .leaii(


white * (255. 255. 255)
Q raspberry pi loge i wy 21 900
h - 450
screen = pygame,display.set_mede((w, h))
C fi Secure htlps duckduckgo oorn sc reen.fi11((white])

screen.fill(£white))
scre&n.bJit( img, (0.0))
pygame.display.f1 ip( )

eveni i > pygane eveni.get():


lf event „typ.e ■■ pygame, OUn":
pyJJJme . £|lj II ( }

www.bdmpublications.com The Python Manual 71


Based on what you've looked at over this section, let's combine it ali and come up with
a piece of code that can easily be applied intoa real-world situation; orat the very
least, something whichyou can incorporate intoyour programs.

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 *

STEP4 The newUser Punction is next:

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: ”)

def mainMenu(): if createLogin in users:


glol a 1 status print ( \nLogin name already existsSVn”)
status * input("Do you have a login account? y/n? 0r press q to quit.")
if status == "y"1: createPassw * input( 'Create password: )
oldUserf) users[createLogin! - createPassw
elif status ■» #,n": print{,l\nUser created! n' )
newtiser() logins*open( "/honie/p i/Docunents/logins .txt" * "a”)
elif status ** "q": logins *wr i te ( r * createLogin ♦ ’ * createPassw)
quit() logins. close( )|

72 Black Dog i-Tech Series - Volume 35


Combining What You Know So Far

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

File Edft Format Run Options Windows Help


lf createLogin in users:
print ("\nLogin name already exists!\n‘) unpo t time
users - {)
status =
createPassw = input( Create password: 1 )
usersfcreateLogin] = createPassw ief mainMenu():
print( ‘VnUser created!\n’) giobal status
status = input( >o you have a login a
logins*open(”/home/pi/Doctments/logins.txt", "a") if status “ v':
logins.wnte(' \n" + createLogin + " ♦ createPassw) oldUser()
logins.close() elif status **= "n":
nevrtJser{)
eli‘ status “■ q":
• # quit()

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")

on:”, time.asctimeO) • e status !=


status * displayMenu()
q :

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?

STEP7 There's a Fair bit happening here. There are login


£iie Edit Sheji Hebug Gptions Windows H.e!p File fdn Firmat 5un flptkjns ^hdovn. Help
and passw variables, which are then matched to the Python 5.T.2
[CiCC a.9.1| on Linux
tS 2014. TjTiTTTTll r>u t time
users * ()
Type "Copyright"t "crediti" or "licenseQ" for more infornet status “
----— RESTART --■■-■■■■■■■■
users dictionary. IF there's a match, then you have a successFul login >»
Oo you hsoe a logih
Create a login -n^ne: Da via
y/m Or pres^ q to quit-J»
displayfclflWOi
r i.»5 statvs
status - inputC
Cra,t, [:■.i1 o ■ ii: passwar^ i i status "y'

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.

passw “ input("Ente r p3sswc rd: ")

# check if user exists and login mate hes password


if login in users a rd users [login} == passw:
print ( AnLogin success fui!\n )
print ( "User:’ . logm. "accessed the system on:', time.asctimeO)
else:
print ("XnUser doesn* t exist or w rong password!Xn ‘)

www.bdmpublications.com The Python Manual 73


74 Black Dog i-Tech Series - Volume 35
Using Modules

A Python module is simply a Python


created source File which contains the
necessary code For classes, Functions
and global variables. You can bind
and reFerence modules to extend
Functionality and create even more
spectacula r Python programs.
Want to see how to better use these
modules to add a little something
extra to your code? Then read on and
learn how they can be used to Fashion
Fantastic code.

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

The Python Manual 75


Using 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.

WORKING WITH DATES


The calendar module is built into Python 3. However, if for some reason it's not installed you can add it using pip install
calendar as a Windows administrator or sudo pip install calendar for Linux and macOS.

STEP1 Launch Python 3 and enter: import calendar to


STEP3 There are numerous functions within the calendar
call up the module and its inherent functions. Once W module that may be of interest to you when
it's loaded into memory, start by entering: Porming your own code. For example, you can display the number oP
leap years between two speciPic years:
$ep=calendar.TextCalendar(calendar.SUNDAY)
sep.prmonth(2017, 9) leaps=calendar.leapdays(1900, 2018)
print(leaps)
EESEEEED The resuit is 29, starting Prom 1904 onward.
File Edit Shejl Debug fiptions Windows Help

Python 3,4*2 (default, Oct 19 2014* 13:31:11)


[GCC 4.9,1] on linux
Type "copyrigjht**, "credits" or '*license( )M for more Information
>» ir por t calendar file £dit Shell Debug Options Windows £ielp
»> sep=calendar.TextCalendar(calendar,SUNDAY)
>» sep.prmonth(2017f 9) Python 3.4.2 (default, Oct 19 2014, 13:31:11)
September 2017 [GCC 4.9.1| on linux
5u Mo Ty We Th Fr Sa Type "copyr ightM, "credits** 1 or ”license<)" for more informat ion,
1 2 »> import calendar
3 4 5 6 7 8 9 >» leaps*calendar,leapdays(1900, 2018)
10 11 12 13 14 15 16 >» pnnt(leaps)
17 18 19 20 21 22 23 29
24 25 26 27 28 29 30 »>
»> |
>>>

^ 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 “>)

3 4 5 6 7 8 9 »»»»»Leap Year Celculatar<4<«<«« leaps-coiendar.1eapdays(y9. y2)

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

>>>

76 Black Dog i-Tech Series - Volume 35


f Calendar Module

*••***•*••*•***•••••***•••••***»•••*•**••**••••

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:

import calendar import calendar


year=int(input(“Enter the year to display: “) for name in calendar,month_name:
print(calendar.prcal(year)) print(name)
We're sure youll agree that's quite a handy bit oP code to have import calendar
to hand. for name in calendar.day_name:
print(name)
Pylhc n 3 4.2 Shei! . C i 1

£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

_W Punctions in HTML, so that you can display it on a


website. Let's start by creating a new Pile:
import calendar
cal=calendar.TextCalendar(calendar.SUNDAY) import calendar
for i in cal.itermonthdays(2018, 6): cal=open(Vhome/pi/Documents/cal.html”, “w”)
print(i) c=calendar.HTMLCalendar(calendar.SUNDAY)
cal,write(c.formatmonth(2018, 1))
r / ■ /hom6/Di/DDCunriSi.ythoi
davsinmonth.Dv
/ r J
) Loae/aavsinmorith Dv (3 4 2 - a x cal .closeQ
File Edit Format Run Options Windows Help

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

january 2013 "/ hnmn/p i ■tmiiiw.i r-V.i: .html".


SunMonT ucW udThuFriSat
c - calendar.HTULCaiflndjrfcaleTvdar^SLPiOATj
1 2 3 4 5 6 cal. nT i tfl (c, ft>r.atrTflflTh( 2JJ18. n J >
76 5 10 11 1213 cal ,cioM( j
14 15 16 17 18 1920
21 22 23 24 25 2627
28 29 30 31

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 >>

ii b .mf a. HTH^Ci 3 *r. UCW&AY \ . f fervat t*ir: v+ii1 J J


5 v* vr*< i JOH
... ................................ urvriflT ..... ............. ..............

6 fcTlti? Wi+ IfW Tfr SiipLpy 1 3C1K

7 5 caLhlml k

C ijj iH^.r-,,1 il Wn*

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!

www.bdmpublications.com The Python Manual 77


Using Modules

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.

INTO THE SYSTEM


One of the primary features of the OS module is the ability to list, move, create, delete and otherwise interact with files
stored on the system, making it the perfect module for backup code.

^ 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

File Edit Shejl Bebug Qptions Window Help


--—1—--
,
Python 3 5,2 (default, Nov 17 2016, 17;05;23)
IGCC 5.4.0 201606091 on Unux
Type "Copyright1', "credits" or "licenseU" for more Information
>» import os
>» home=os. getcwdU
>» printfhorne)
/home/david
»> |

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
»>

78 Black Dog i-Tech Series - Volume 35


OS Module

The os.systemQ function is what allows interaction


EP 5 The ability to manipulate directories, or Folders iF
STEP 8
W with external programs; you can even cali up _W you preFer, is one oF the OS module's best Features.
previous Python programs using this method. You will obviously For example, to create a new directory you can use:
need to know the full path and program Pile name for it to work
import os
successfully. However, you can use the Following:
os,mkdir(“NEW”)
import os
This creates a new directory within the Current Working Directory,
os.system(‘start chrome “https://www.youtube.com/
named according to the object in the mkdir Function.
feed/music”’)
Ne* Tui; Hotmt ^ VeyTyfre se En? Isto JJefcug aptisf-i y?ip
Pytho* 2.4.2 ({rttjult. Ott i( 20». 12:21:111
G £r ■■ "w, y Qu tu trt. M 11 ■ |GCC 4.0-. 1 ] cn iirrus
Type “copyngfit". “creifits" or icensetl" Ter nor* InfflfimtlSrt.
*>>■ • gs
gs.rpkdiri •: >
= OYpuTube Search O, t O 0 »>

.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

You can also rename any directories youve created


fl
STEP 9
H**- **
4
a
J, by entering:
0 SP0^

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:

import os V* Edr Eh«U CaOug flstlons ujfide*'.


Python 3, *,2 {default, OCC 1» 2QU.
[KC 4.9.1] gn linuH
b*ifl
13:31:11)
J File EtJrt

v
view Scotoma

& ii
Typt “t,opyfigjixFi ■ti4diisJ of "license: J“ r&r nere irtfeiUfliiwi.

os.system(4 chromium-browser “http:// >> > l -if o* t e-?


>>» na.renane|
>>> 01. rrndjr^HI^I
, )
Oinecrary ~ree

bdmpublications.com/”’) i fsS &esklc^p

•3 O^wnloads

■ iMusic
-OOLD

! ► «Pictures

Another module that goes together with OS is


STEP 10
shutil. You can use the shutil module together
with OS and time to create a time-stamped backup directory, and
copy Files into it:

import os, shutil, time


root_src_dir = rVhome/pi/Documents’
root_dst_dir = Vhome/pi/backup/’ + time.asctimeO
for src_dir, dirs, files in os.walk(root„src__dir):
dst_dir = src_dir.replace(root_src_dir, root_
STEP 7 Note in the previous step's example the use oF dst„dir, 1)
single and double-quotes. The single quotes encase if not os.path.exists(dst_dir):
the entire command and launching Chromium, whereas the double os.makedirs(dst_dir)
quotes open the speciFied page. You can even use variables to ca for file_ in files:
multiple tabs in the same browser: src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
import os
if os.path.exists(dst_file):
a=(4chromium-browser “http://bdmpublications.
os. remove (dst_fil e)
com/”’)
shutil. copy(src_file, dst_dir)
b=(4 chromium-browser “http://www.google.co.uk”’)
os.system(a + b) printf Backup complete
y. 1

Jrte L4-1 i-ief ieUyi tftb

' Pylhon l.i.J itfeiauJl. Oit in MU 11:11:11)


4.1.1] Hk lUMt
fjf#+ "tBpyF ■ . "«rMil*- #r “1 k«*M*: >' fs<- «1«-|'4 ;n1>™* t I0«i.

; >»

FH.I
?■>>> ? 341^irk!4l rrwici f»
i

t FKtOfv 'r*f

-lr Ed+ Fgirr-* flun dpHini W*idnv.i h^F


.ir ,-.rp
*i. ihnil. TO"r ’4’ 13-
r o B- C _i r t_ [J i r th Ld IJi* ieui lu diini.to' y
rus L_di l_dLi I '.<l '■/vi. 0 no e.BiLtiiwO * 'ji i L* L' e U4L>.Up J.
g',c_diT. diri. fiiea i
■fcL_dif ■ irt_dirLrpptjLeuno[_a>rt_air. > jiii_d?.t_di! ■ 'I
«k. p jih. t.. lui. dk l_ J l i j;
n^rfdirsrfliT tfir:
fele, files:
in_Ti1* ■ jmntu L_dji . 1lI*_S
dir_TLli - oi-itiiLi.;ai i_dir . fili.i
fl* F-iT> k'llTi:dBT Fl!*)!
Di. reagvr|dst_f llej
SlhiL t k .< up, ( i I <Lwf L I r . J'. [_li L I j MI
er:nT{ ) 51

*l Poftnaids.

www.bdmpublications.com The Python Manual 79


Using Modules

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

Python 3.4.2 (default, Oct 19 2014, 13:31:11)


[GCC 4,9.1] on linux Rle £dit She|l Oebug Options Windows H^P
Type "Copyright**, "credits*' or ,4license( )*' for more Information,
>» import random Python 3,4,2 (default, Oct 19 2014. 13:31:11) r
>>> pnnt(random,randint<0»5)) [GCC 4.9.1] on linux
4 Type “Copyright", "credits" or Mlicense()" for more Information
>>> >>> import random
»> random.choice( [ ‘Conan", "Valeria". "Belu"])
'Conan*
»>i

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:

import random File Edit Shell Qebug Options Windows Help

print(random.randomQ *100) Python 3,4,2 (default, Oct 19 2014, 13:31:11)


[GCC 4.9.1] on linux
Type “Copyright1*, "credits" or "licenseO" for more Information.
Will display a Ploating point number between 0 and 100, to the tune »> imp F random
>» lst» [ "David** „ 44. "BDM 3245.23, Pi% Trur, 3*14,
oParound PiPteen decimal points. >>> rnd=random,choice(Ist)
»> pnnt(rrid)
3245,23
»>

Black Dog i-Tech Series - Volume 35


Random Module

“ 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:

random. shuffle(lst) import random


print(lst) output^^Heads” :0, “Tails” :0}
coin=list(output.keys())
This way, you can keep shuFFling the list beFore displaying a random
item From it. for i in range(10000):
output[random.choice(coin)]+=l
print(“Heads:”, output[“Heads”])
File £dit SheN Debug Qptions Windows Help print(“Tails:”, output[“Tails”])
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4,9.1) on linux
Type "Copyright", ‘'credits'1 or "licenseO" for more informat ion *
»> impar t random headstsi>s py - horne 'p•' jot jments f'yThon C ijde/h&aostai s py (3
'■ 4 2 ;■ - c x
»> lst»|"David“, 44, MBDM Publications", 3245.23, True, 3,14, "Python"! ille tdrt 5he;l ^ebug Qptions Mflndows yelp E'le Edil Farniai Pun Qptiorrs ftindews y«lp

»> md-random.choice( lst) .


Py Ehon 3 4.2 (default. &ct 13 2QM. 13 ; 31: tl 3 < F.irntr*-.
[GCC 4 .3.1] on linuji
»> print(rnd) Typ* ' c<W¥0$hi“r “GrcdLts“ w “lictns^K)“ for fliftr* Information.
»> «i .. restart ■*■*■»■»■■■■■■■■■»■
output-'!"H-.-j-. :Q„ Tails":!))

3245.23 H i*. i-:- 4393 c 0 in*11st(out put.keys()J

»> random*shuffle(Ist) Tails


>>>
5007
RfSTART
* ■.vn^C 10000);
outputlrandwi.ehdica(CCHrt)]+=1
>» print(Ist) »>
Heeds 5090 pr Wlt("n. ■ ouiputl ‘H-ad-5 ])
[3245,23, 44, 'DavidA ‘Python*F *Pi*, True, 3,14* 'BDM Publications* I Tails
>■>> .i
4950 pnnt<" • • . output C Tai "s ])
RE5TART
»> random.shuffle(Ist)
Heads tu i y
»> print(lst) Tails 49S1
■» i •> . i
■python** 3.14, 'David*J
RESTART
[44, 4BDM Publications', True, 3245.23, ‘Pi* >»
Heads 492D
Tails 5090
»> -j RESTART
>>>
Heads 4912
Tails 5096
-. RESTART

H*-jds 49?»
Tails 5061

Using shuFFle, you can create an entirely random list


STEP7
oF numbers. For example, within a given range:
Ln; Z0 CdI Ul: 11 Co! 32

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

. -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.

File £dit Shejll J2ebug fiptions Windows Help wards = f.raadlirt&st)


how many words shsll 1 choow? i2 wprds - [ft . rstnpO 1 w words)
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux • ~ vt i random. sample(words r wds)
Type ‘'Copyright4', "credits4* or ”license()“ for more Information. pnnt(H)
»> import random
>>> for i in range<10);
print{random.randrangefO, 200, 7))

154
119
7
7
161
168
168
182
126
175
»> j

www.bdmpublications.com The Python Manual 81


Using Modules

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

Python 3.4.2 (default, Oct 19 2014, 13:31:11)


[GCC 4-9.1] on linux
Type "Copyright", "credits" or "licenseC )** for more informat ion, File £dit Shell Eebug gptions Windows Help
>» import tkinter as tk
>>> from tkinter import * Python 3.4.2 (default, Oct 19 2014, 13:31:11)
>>> [GCC 4*9*1] on linux
Type "Copyright", "credits" or Mlicense{)" for more Information.
»> import tkinter i tk
»> fiun tkinter import *
»> btn=Button()
»> btn.packO
»> btn[ te -1 ]-"Hp1!c everyone ! "
>>>

Helio everyone!

It's not recommended to import everything from a


STEP2 STEP 4 J You can combine the above into a New File:
module using the asterisk but it won't do any harm 1 ■ - a * - ■ I

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

Python 3.4.2 (default, Oct 19 2014, 13:31:11)


- print(“You just clicked me!”)
[GCC 4.9.1] on linux
Type "Copyright", "credits" or "license()M for more Information,
btn [“command”] =clicl<
>» impor t tkinter as tk
>» from tkinter impor t *
>» wind-Tk()
»> I tkintercodel .py - /hoinne/pi/Docum0...ython Code/tkintercodel py (3.4.2) -axi
File Edit Format Run Options Windows Help

82 Black Dog i-Tech Series - Volume 35


Tkinter Module

• •••••**•••*••*••*»*«•*•*•*•*•*•••*•*

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)

Farm at ftijn Qptibns WmdoviiS yelp


- n *

I _W geometry elements into Tkinter. Note the


n tkinter
sticky=N, E and W arguments. These describe the locations oP the
root = Tk< J
logo ► Photolmage(file-
The previous code is lorac/p-ij11 DoHnloads/fiDW_lotgo,gif')
h1 = Labelfroot, root.titiet"BDM Publications*)* iinage=logo).packtside='r vghl ■“>
content - " .ts humb ie beginnings in Z004,
check boxes and buttons (North, East, South and West). The row
rh a p n ;ly grert from a single publication produced

quite weighty, mostly Of lUSt mo to one of the biggest nanes in global


; j uu l . n i' ig, for two simple reasons,
argument places them on separate rows. Have a play around and
i a s 5 .i no mtraenT to deliver the very best product

due to the content each and every volurne.


While the company has grown with a portfolio of over
250 publications delivered by our interna non ai staff.
see what you get.
the foundation that it has been built upon remains the sane,
variable holding a part which is why we believe BDM isnlt just the first choice itls
iht only choice for the smart consoner. """r
w2 = Labe1(root, def vjr„statest):
11 ~ - n k ■ ■ r :
oPBDM’sAboutpage justify^LEFT,
padk ■ 10.
taxt*conf*nrt).packfside* eft")
prlnt(' WriOf

Labe 1{ root.
'••rfJ.igc: • -

“Advctiiuro Sm"), text»


d nEtarbit i

■ > *■■ •>


lodari Vd" K, (viri

-^nui ,i :. rr-,r ji i- <olir -<<<‘.


rtrZ.get().

■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

website. You can CfieckbuiTftnfrebt.


var4 - IntVarfJ
CheckbilUbrvfirfldt.
t#xl« F >

tfrii- El.irbrtri n . v d r ub lffv*r4 >, gr i-d t


rftur-S. StlCky»W>

, 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

230 publications delrvered by our internatio nal staff,


and the image to suit the foundation that it has been built jpon remains the same,
whnh h why we believe 3DM isn't just the first chcice Ht'f,
gdventur1'

the only choice For the smart consumer, Warridr

your needs. Mage


Ranger
i_l i. £.± L.UI. JL Sarbanan
Paladm

pmt Show

www.bdmpublications.com The Python Manual 83


Using Modules

Pygame Module
We've had a brieF look at the Pygame module already but there's a lot more to it that
needs exploring. Pygame was developed to help Python programmers create either
graphical or text-based games.

PYGAMING
Pygame isn't an inherent module to Python but those using the Raspberry Pi will already have it installed. Everyone else will
need to use: pip install pygame from the command prompt.

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:

import pygame import pygame


pygame. initQ from pygame.locals import *
pygame. initQ
gamewindow=pygame.display.set_mode((800,600))
File Edit She|l Debug Options Windows Help
pygame.display.set__caption(“Adventure Game”)
Python 3*4*2 (default, Oct 19 2014, 13:31:11)
[GCC 4*9.11 on linux
Type "Copyright", "credits" or "licenseC)" for more information.
»> unport pygame
running=True
»> pygame. inite)
(6, 0) while running:
»>
for event in pygame.event.get():
if event.type==QUIT:
running=False
pygame.quitC)

Let's create a simple game ready window, and give


STEP2
it a title:

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

Eile £dit Sh•eP Cebug QptJoni Help

python 3.4,2 «tefautl. Qct 19 2014. 13;?1411J


j ISCC 4.9.1J on 1 ]r.u>
Typfr "copjri' igtit", "«reditS" or for more info/mar *o*l.
>» _ ' t pygame
pygame. in i t £ >
te. oj
ganfrftiind&m-pygame .dlis-p Jay . se£_Bade( ( EOO , ECO})
>» pygane, display.set_capti-on{' •• I•-*- -r• > G ■ j

iLn: &|Cnl: 4

Black Dog i-Tech Series - Volume 35


Pygame Module

STEP4 IP the Pygame window stili worYt


_W close dontworry, it's justa
discrepancy between the IDLE (which is written
with Tkinter) and the Pygame module. IP you
run your code via the command line, it closes
perPectly well.

P5 YouYe going to shiPt the code around a bit now, img=pygame.image.load(“/home/pi/Downloads/


W running the main Pygame code within a while loop; spritel.png”)
it makes it neater and easier to Pollow. We've downloaded a graphic
def sprite(x,y):
to use and we need to set some parameters Por pygame:
gamewindow.blit(img, (x,y))
import pygame
x=(800*0.45)
pygame.
y=(600*0.8)
running=True
gamewindow.fill(white)
while running: sprite(x,y)
pygame.display.update()
gamewindow=pygame.display.set_mode((800,600))
pygame.display.set_caption(“Adventure Game”) for event in pygame.event.get():
black=(0,0,0) if event.type==pygame.QUIT:
white=(255,255,255) running=False

■ 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.

|import pygane x=(500*0.45)


from pygame.locals import *
pygame.init{ >
game^indciw, f 111 < wh ite)
running=T rue sprite(x,y)
pygame,displaytypdate()
while- running:

gamewiridQW=pygame. disp lay,set_mode( f SOQ ,600) }


pygame.display.set_caption( ‘Adventure Game')
black=(Q,0,0) for event in pygame.event.get():
white=(255,255,255) if event*type==QiUIT;
ing=pygame. image. Ioad( Vhome/pi/DovsrLGad-s/spr i r> runn ing*1"a Ise
pygametqu*T{)
def spriteCx.y);
gamewindow„bIit(img, (x,y))

www.bdmpublications.com The Python Manual


Using Modules

EP 7 Now we can change the code around again, this imgspeed=0


W time containing a movement option within the
while running:
while loop, and adding the variables needed to move the sprite
for event in pygame.event,get():
around the screen:
if event.type=-QUIT:
import pygame running=False
from pygame.locals import *
if event.type == pygame.KEYDOWN:
pygame.initC)
if event.key==pygame.K_LEFT:
running=True xchange=-5
elif event.key==pygame.K_RIGHT:
gamewindow=pygame.display,set_mode((800,600))
xchange=5
pygame.display.set_caption(“Adventure Game”)
if event.type-=pygame.KEYUP:
blacl<-(0,0,0)
if event. key—pygame .KLLEFT or event
white=(255,255,255)
|<ey==pygame. K_RIGHT:
img=pygame.image.load(“/home/pi/Downloads/spritel.
xchange=0
png”)
x += xchange
def sprite(x,y):
gamewindow.blit(img, (x,y)) gamewindow,fill(white)
sprite(x,y)
x=(800*0.45)
pygame.display.update()
y=(600*0.8)
pygame.quitC)
xchange=0

file fdit Fgrmat Run Options Windows Help

■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()

Black Dog i-Tech Series - Volume 35


Pygame Module

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 - - —

£ile Edit Firmat Run Qptlons Windows


import subprocess
import pygame
pygame.initC) import time
import subprocess
screen = pygame.display.set_mode((800, 250)) pygame. imt()
screen - pygame.display,set_mode((800, 250})
clock - pygame.time.Clock() clock = pygame.t une.Clockf)

font s pygame,font,Font( 25)


font = pygame.font.Font(None, 25) pygame. t ime, set_t ime r (pygame. USEREVEffT P 200)

pygame.time.set_timer(pygame.USEREVENT, 200) def text_generator(text):


tmp ■
fer letter xn text:
def text_generator(text): trap += letter
lf letter !« * *:
y:eld tmp
tmp = ‘’
x d: DynaftiicText(object):
for letter in text: f __init_(self, font, text, pos, autoreset=F Ise):
self.done = Fo1
tmp += letter self*font “ font
self,text = text
if letter != ‘ 4: self._gen « text_generator(se!f.text)
self.pos - pos
yield tmp self.autoreset = autoreset
self,update()

class DynamicText(object): t reset(self):


self,_gen - text_generator(self,text)
def _init_(self, font, text, pos, self.done = F.iise
self.update()
autoreset=False):
f update(self):
self.done = False if not self.done:
trv: self.rendered * self«font,render(next(self._gen), , (0t 128, 0))
self.font = font except StopIteration:
self,done - Ti ue
self.text = text time.sleep(10)
subprocess.Popen("python3 /hoi»e/pi/Oocuments/Pytho ani , shell®n je)
self._gen = text_generator(self.text)
self.pos = pos dpt d r aw( self, sc reen):
screen.blit(self.rendered, self.pos)
self.autoreset = autoreset text=( une a: n n.

self .updateO message * DynamicText(font, text, (65, 120), autoreset-

def reset(self): event ir pygame,event.get():


x■ event,type -- pygame,QUIT; : -
self._gen = text_generator(self.text) if event.type == pygame,USEREVENT message.update()
k *
■ ■

self.done = False screen. f i 1 Upygame,color. Color(


f w- ,*■ ■« A #» r» \
ick' ))
m A I" ^ r- Lfl
self .updateO Ln: 19 Coh 0

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)

www.bdmpublications.com The Python Manual 87


Using Modules

Using the Math Module


One of the more used modules you will come across is the math module. We have
mentioned previously in this book that mathematics is the backbone of programming
and there's an incredible number of uses the math module can have in your code.

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:

from math import floor, ceil


floor(1.2) # returns 1
Elie Edit Shejt Qebug fiptions Windows Help ceil(1.2) # returns 2
Python 3.4.2 (default. Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type 'Copyright", "credits" or "licenseO" for more Information
»> import math
>>> * File Edit She|l Debug Options Windows Help
Python 3.4.2 (default, Oct 19 2014. 13:31:11)
[GCC 4.9.1] on linux
Type ‘‘Copyright", “credits" or “licenseO" for more Information
»> from math import floor, ceil
>» floor( 1.2)
1
»> ceil( 1.2)
1
>>>

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:

math.sin(2) import math as m


m.trunc(123.45) # Truncate removes the fraction
This displays the sine oP 2.

£(le £drt Shell Debug Options Windows Help


£ils Edrt Shell £ebug Qptions Windows tlelp
Python 3.4.2 (default. Oct 19 2014, 13:31:11)
Python 3.4.2 (d-efault, Oct 19 2014, 13:31:11) (GCC 4.9.11 on linux
EGCC 4.9,1] on linux Type "Copyright”, "credits" or "licenseO" for more Information
Type ■'capyright", "credits” or "licenseO1- for more informat ion. >>> import math as m
>>> import math »> m.trunc( 123.45)
>>> rnath.sin(2) 123
0.9092 9 7426 S 2561317 >>>
»» I

88 Black Dog i-Tech Series - Volume 35


Using the Math Module

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)

File Edit Shell Debug Options Windows Help

Python 3.4.2 (default, Oct 19 2014, 13:31:11)


[GCC 4.9.1] on linux
Type “Copyright", “credits" or “licenseO" for more Information.
»> import math
»> print(math.e)
2.718281828459045
>» print(math.pi)
3. 141592653589793

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

m*th. radians ix]


Convad a-iyi* x Irom dagrees io fadans

Returns the value oF 1.0. 9.2.5, Hyperbolic functions


I iyperbolic functians ara a;iii<jy* of hiyoiiomylnc rumiiions hal are based on hyperbeias inslead ot tirdes

math. acD£h(x)

Relurn the snvEr!» hyperbolic rasirie at x


i iTiTiivCMSj
math , asinhfx)
Return the rnwerse hyperbolic sine of x
File Edit Shell Debug Options Windows Help math. atanb(x)
Return the mvdfse hyperbolic tangent of

Python 3.4.2 (default, Oct 19 2014, 13:31:11) m*ch. coshiij

[GCC 4.9,1] on linux Return the hyperbolic cosme of t

Type "Copyright", “credits" or "licenseO" for more Information. math. sinhfx)


Return the hyperbolir: uine or *

»> from math import * math , tub(jrj

»> sum([.1, .1, .1, .1, ,1, ,1, .1, .1, .1, .1]) Return the hyperbolic tanrjenl crf x

0.9999999999999999 9.2.6, Spedal functions


»> fsum((.1. .1, .1, .1, .1, .1. .1, .1, .1, .1]) math, ftrf (X)

1.0 Return the error hmction at x

>>> The erf»:. function can t>:= usod to compute tradrtional stateslicai functionrs such as ifw cumolalive Standard normaf distributori:

cLet phi ■; >: I :


*Cumulative diatribution function for the ataomard sonui d£sttLbut. o ji*
ratum (1,0 + etf / sqrt (2 . P|) ) f £.0

www.bdmpublications.com The Python Manual 89


Using Modules

Large programs can be much easier to manage if you break them up into smaller parts
and import the parts you need as modules. Learning to build your own modules also
makes it easier to understand how they work.

BUILDING MODULES
Modules are Python files, containing code, 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))

def square(x): print (tirnesthree{3))


print (square(4))
File Edit Format Run Optiorts Windows Help
print (power<5,3)) f timestwo(x):
return x * x return x * 2

rf timesthree(x)

def power(x,y): square(x)■


return x * x
return x ** y f power(x,y)i
A *

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.

1 basic_math. py - /home/pi/Docume...Python Code/bastc_mathpy (3.4.2) - □ x

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

90 Black Dog i-Tech Series - Volume 35


Create Your Own Modules

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”)

File Edit Format Run Options Windows Help

^ You can now use the code Purther to make the


STEP7
program a little more advanced, utilising the newly
created module to its Pull. Include some user interaction. Start by
creating a basic menu the user can choose From:

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):”)

£tle Edit Format Run Options Windows Help


1 'i i munimath unp r i *

print(,cSelect operat ion.\nt">


print( ‘1.T unes by i^o")
print C :r2 .Tumes by Three"')
print( "3.Square*')
i printC”4.Power of"}

choice - input("VnEnter choice (1/2/3/4

Now we can add the user input to get the number


STEP8
the code will work on:

numl = int(input(“\nEnter number: “))


This will save the user-entered number as the variable numl.
Note that For the last available options, the Power
STEP10
_W oP choice, we've added a second variable, num2.
This passes a second number through the Function dePinition called
File Edit Format Run Options Windows Help power. Save and execute the program to see it in action.

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

yrint("l Aiines by ) Ffiter rnjrnhee; 3


9

»>
irint( "2 .T imes by ^hree") Seleet *p&raiion.

print("3.Square")
print("4*Pawer of'")

choice = input(fi,\nEnter choice (1/2/3/4):")

ncril = int(irputC"\nEnter number: "))

www.bdmpublications.com The Python Manual 91


SHARE YOUR CODE!
The code listed within this section can be downloaded
as Python files, so you don't have to type it out. Simply

the code is available as a compressed file for you to


download and execute.
Also, if you've written something amazing, and you
want to show it off, then why not send it in and we'11
add it to the Code Portal as well as mention it via our
social media accounts.
Teli us what the code does, how it works (don't forget
to include comments in the code), and what platform
to run it on.
Send it in to: enquiriesrbdmpublicati com. We look
forward to seeing whatyouVe done

Black Docti Series - Volume 35


<v
QJ
v
i
J ] Vi eu fi E i @ □ 3* Co

—f) b <00^0 n U < B /


□□
* [ fi

[ 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.

Python File Manager


Number Guessing Game
Polygon Circles
Random Number Generator
100 Random Password Generator
Keyboard Drawing Script
102 Pygame Text Examples
103 Google Search Script
104 Text to Binary Convertor
106 Basic GUI File Browser
108 Mouse Controlled Turde
109 Python Alarm Clock
110 Vertically Scrolling Text
112 Python Digital Clock
114 Pygame Music Player
115 Python Image Slideshow Script
116 Playing Music with the Winsound Module
V <f*. i k >»’»** *.’•%* cy 118 Text Adventure Script
120 Python Scrolling Ticker Script
Simple Python Calculator
122 Hangman Game Script

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

D file=open (path/'r ")


W + >»
3 3 3 3 3 S'Z-S'= = = — I7i: 3 C 3 C C 333 IESITZ 33 fcESTAftl S5X3EETIS 3 ZZI3ZIZII

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?

Chooss thfl opTion nurober:


Pr:nts fila,r«ad[})
input('PreE5 Enrer...')
f ile.clMfl() ai input{'Press Enter../)
0 ? i.Resd 4 filv
7 -Wr j t p- |<j n file WritelJT file.closeQ
4 h 3. ApperaJ tt<t to a file
4. Delet* a, fila
5. List f(lm in j
fi.-Cherk fil* ««■Kt^nri*
7.Move 3 file
e.Cc-py 4 file
dir^tory
path-iflpirttXncef the 031*1 sT r;je
oi. path . i-jf ile{paTh):
pr|nf( 'firhujJdjriE tlxi AKiifing

pFintt 'Creaiing The w file']


takt^mpuK‘Em?■ u l ‘J
9.Create a itiregtpry f: ]e=c::en(pa.th. • J
in.Palatp a dirartory
11. Opan a program
def Write ():
QJ
q/
1 12. Eait **!(>:
path^i^iutt■> • thi fil
t*nt“|n(n»tt"Frirer thp t«t ta add:'
f ile-:jser (pach.
fllt.nr"iie(
)
n +teit)
;•• ith ]
path=input("Enter the path of file to write or create:")
if os .path. isfile (path):

Delere*! J:

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

print('Rebuilding the existing file')


prjnt('File poe
else:
PlriliitO:
*□ Lrt: 6 Coi: 0 Lr' 21 Ce
print('Creating the new file')
SI f + text=input("Enter text:")
file=open (path, "w")
P rU file .write (text)
□ 0 >»»>»»python h File Hanager<<«<<<«<
0 4 I he current time and date is: Fn Sep 15 08:22:^2 2017 def Add():
0 M Choose the option number: path=input("Enter the file path:")
text=input("Enter the text to add:")
c* 9 ).Read a file
2*V/rite to a file
3. Append text to a file file=open (path, "a")
4. Delete a file file .write ('\n'+text)
5. List files in a directory
6*Check file e>istence
0 'i 7,Move a file
8*Copy a file
9,Create a directory
def Delete ():
10*Delete a directory path=input("Enter the path of file for deletion:")
11.Open a program
12.Exit if os .path.exists (path):
0 ^
@ print ('File Found')

9 c os. remove (path)

0 print ('File has been deleted')


y si else:
m j File Edit Sheji Qebug fltPl|C>ns W>ndows Help
print ('File Does not exist')
B C ’p-?r P v t bon 3 A MAllAi
i

a M jrrent t 4 J.
ai def Dirlist():

□ i Choose the optien numberi path=input("Enter the Directory path to display:")


1. Read a file sortlist=sorted(os .listdir (path))
G~ f| 2. Write to a file
3_Append text to a file i=0
1 4*Delete a file
5-List files in a directory
6.Cheek file existence
while (i<len (sortlist)):

cal 74Move a file


8«Copy a file
print (sortlist [i] +' \n')
i+=l
n vi 9. Create a directory
10. Delete a directory
11.Open a program
R

.< C1 12.Exit 1 def CheckQ:


w 9 Enter the Directory path to display:/home/pi/Docuinents
Addition > py
0) fp-int(input('Check existence of \nl.File \n2.
Directory\n'))
BlueJ Projects
if fp==l:
0 vl Circle.py
path=input("Enter the file path:")
e) 0 Greenfoof Projec K b
os .path. isfile (path)

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 os.path.isfile(path)==True: 5. List files in a directory


print('File Found') 6. Check file existence
else: 7. Move a file
print ('File not found') 8. Copy a file
if fp==2: 9. Create a directory
path=input{ "Enter the directory path:") 10. Delete a directory
os. path. isdir (path) ll.Open a program
if os. path. isdir (path)==Fal se: 12. Exit
print ('Directory Found')
else:
print ('Directory Not Found') if dec==l:
Read()
def Move{): if dec==2:
pathl=input('Enter the source path of file to move:') Write ()
mr=int(input('l.Rename \n2.Move \n')) if dec==3:
if mr==l: Add()
path2=input('Enter the destination path and file name:') if dec==4:
shutil .move (pathl ,path2) Delete ()
print ('File renamed') if dec==5:
if mr==2: Dirlist()
path2=input('Enter the path to move:') if dec==6:
shutil .move (pathl ,path2) Check()
print ('File moved') if dec==7:
Move()
def Copy(): if dec==8:
pathl=input('Enter the path of the file to copy or rename:') Copy()
path2=input{'Enter the path to copy to:') if dec==9:
shutil. copy (pathl rpath2) Makedir()
print ('File copied') if dec==10:
Removedir()
def Makedir(): if dec==ll:
path=input ("Enter the directory name with path to make Openfile()
\neg. C:\\Hello\\Newdir \nWhere Newdir is new if dec==12:
directory:") exit()
os. makedirs (path) run=int(input("l.Return to menu\n2.Exit \n"))
print('Directory Created') if run==2:
exit()
def Removedir():
path=input{'Enter the path of Directory:') * e * *

treedir=int (input ('l.Deleted Directory \n2.Delete


| Directory Tree \n3.Exit \n'))
bs He
if treedir==l:
ent ime an : Mor 25 07:57:28 2017
os. rmdir (path)
11 IO n
n Pi
ni

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

www.bdmpublications.com The Python Manual ■ 95


w
V i
v J 0 ] VI
□□ / a
V

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. '

□ 5 print('Too high, try again/)


guess > nunber:
print( Too high, try again,
+ guess == number: if guess == number:


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

a " Python 3.4,2 (default, Oct 19 2014t 13:31:11)


[GCC 4*9.1] on linux
random

@ Type ”copyright‘\ “credits*' or "license{)“ for more Information guessesUsed c


Hame»input{*Helio! What is your r
9 c Helio! What is your name? David
nitfnber - random/randint(T, 30)
print(1Greet;ngs. + Hame + , I
y Greetirgs. David. I"m thinking of a number iP fWPef -
the number within 5 gt i esse s 26
1 ** while guessesUsed < 5:
guess=int(mput("Guess the ni
m j Too highr try again.
Guess the number within 5 guesses*«.20
guessesUsed & guessesUsed + 1
t guess < nunber:

B n Too highr try agam.


Guess the number within 5 guesses..#15
Well done, David! You guessed correctly in 3 guesses
print( Too low, try agair
:t guess > nunber:
print(*Too high, try agai
a 0 »> | f guess == number:


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

NumberGuessing Game </>

EI □
Lrsaracterbiats.pv n e,- ui

Filf3 Edit Shejl Dphug Optio ns Windows Help Eil-"' Edit Farmrrt Eun Optione Windows yelp

Python 3*4.2 (default. Oct 19 20U. 13:31:11J 1 ■ t randcxn


|&CC 4.9.1J m linux
Type “copyria^t“P “creitiTs" or “UcenseO" for mere information. Endurance=0
ftvviftftiivflivi
pi@raspberrypi: Docments/Python Code S python3 NunherGuess.py »>
CR=0
Uick=o
Helio! What is your name? David Yuor character’s stats are 35 follows: Endurance=random.randintf1, 15)
CR=rand«n,randintc1. 20)
Greetings, David. I*m thinking of a number between 1 and 30. Luck^randont, randintf 1, 10)
print['lYgor characteres stats an- as follows:\n”)
Guess the number within 5 guesses.,.25 Endurance: 4
Cantat Rating: 5 printt ' nEnduranc?: . Endurance)
Too low, try agam. Luck: 6
>» RESTART
print(”Co»bat Rating:". CR)
print("Luclk: ”, Luck)
Guess the number mthin 5 euesses...27
o »>
Yuor character"s stats are as followsr
,/011 done, David! You guessed correctly m 2 guesses.
pi@raspherrypi: '/Doonefits/Python Code $ | Endurance: 2
Conbat Rating: 20
Luck: 6
>>> WH1KV KWn-KVS Kna-3 VH a-KK KWI -3rTT- = D = = RESTART 33ir==^ = 3= = n3rTTT = n = =3TI=II=IE =
»>
Yuor character'5 stats are as follows:

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

www.bdmpubtications.com The Python Manual


POLYGONCIRCLES.PY
There's lots of Mathematics used here along with some
intricate coordinate manipulation with the Turtle module.
Enter the code and execute it to see how it turns out.

from turtle import*


of strai from math import sin, cos, pi
r=200
inc=2*pi/100
t=0;n=1.5
for i in range(lOO):
xl=r*sin (t); yl=r*cos(t)
x2=r*sin(t+n) ;y2=r*cos (t+n)
penup (); goto (xl,yl)
pendown (); goto (x2 ,y2)
t+=inc

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

User input and the ability to RNDNUMGEN.PY


manipulate that input are important It might be simple but this little piece of code will ask the user
for two sets of numbers, a start and a finish. The code will then
elements with any programming pluck out a random number between the two sets and display it.
language. It's what separa tes a good
from random import *
program from a great program, one
that allows the user to interact and print ("\n»»»»»Random Number Gene rator«««««\n")
nmbl=int (input ("Enter the start number: "))
see the results of that interaction. nmb2=int(input("Enter the last number: "))

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

£ile Edit Shell Qebug Qptions Windows yeCp


_ X

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)

www.bdmpublications.com The Python Manual


RNDPASSWORD.PY
Copy the code and run it; each time you'll get a random string
oF characters that can easily be used as a secure password
which will be incredibly difFicult For a password cracker to hack.

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.

An inberesbing aspecb bo bhis code is bhe abiliby bo inbroduce a loop


and prinb any number oF random passwords. Leb's assume you have
a lisb oF 50 users For a company and you're in charge oF generabing
a random password For bhem each monbh.

File £dit Shell Eebug fiptions Windows Help


RESTARI

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

exactly that, allowing the user to AII movements ar 1 f_j UT


= move forward
LlHlC T CHTlGn i

- 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

Ali movements and turns are by incrementa of 5.


Right arrow key = move forward
Left arrow key = move backward
r = turn right
1 = turn left
u — pen up
d = pen down
h = go home
c = ciear
u ffff

from tkinter import *


from turtle import *

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")

www.bdmpublications.com The Python Manual


ne ^ i

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()

text rotate degrees = 0

while not done:


\xq\ UMOp apisdp
for event in pygame.event.getO:
if event.type == pygame.QUIT: yjbbeq jgxi
done = True

screen. fili (WHITE)

pygame.draw.line (screen, BLACK, [100,50],


[200, 50])
pygame.draw.line (screen, BLACK, [100,50], \
[100, 150])

font = pygame.font.SysFont('Calibri', 25,


True, False)
text = font. render ("Sid<aways text", True, BLACK)
text = pygame. trans for m. rotate(text, 90)
screen.blit(text, [0, 0>])

Black Dog i
Pygame Text Examples/Googie Search ScripL

Using the OS and Urllib modules, this GOOGLESEARCH.PY


small snippet of code will display a You will need to pip install the urllib module, unless it's already
window for the user's input, then pass installed. It also uses Zenity, which is a Linux-based (GNOME)
tool for creating dialog boxes.
the input to a Google search in their
import os
browser. It's really quite a handy script import urllib.parse
and one that's easily introduced into google = os .popen(' zenity —entry —text="Enter your
Google search: " —title="Google Search"7).read()
yourown code. google = urllib .parse. quote (google)
os. system('chromium-browser http://www.google.com/
search?q=%s' % (google))

Searching For More


Here weve used the Zenity command to create the dialog box, The last two For Chrome and Internet Explorer respectively.
which as we mentioned is only available to Linux machines (such as
Ubuntu, Raspberry Pi, Linux Mint and so on). 1Fyou want to execute There is a Zenity For Windows project available on GitHub at www.
it in Windows you have a couple oF possibilities: you can Find a github.com/kvaps/zenity-windows. It's a good working version
Windows version oF Zenity and pass the usebs query through it; or but you do need to install it to a Folder on your system where you
you can create a Tkinter dialog box to pass the inFormation. won't require administrator access to be able to run the Zenity
program. When you have Zenity installed, you can modiFy the
You can see that this particular code uses the Chromium browser Windows version oF this code in Python to read:
which comes preinstalled on the Raspberry Pi, and some versions
oF Linux. To use your Favourite browser in Windows, For example,
you will need to change the command in the last line oF the code import urllib.parse
to read FireFox, or whateveryou use, together with the Start
google = os. popen('start c:\Temp\ZenityWbin\
command. So essentially, one oF the Following:
zenity —entry —text="Enter your Google search: "
—title="Google Search"7). read()
google = urllib.parse. quote (google)
os. system ('start firefox http://www.google.com/
search?q=%s' % (google))

os. system ('start iexplore http://www.google.com/


search?q=%s' % (google))

[ GocgleSearch.py - G/Users/david/Documents/Python/GoogleSearch.py (3.6.2)

File Edit Format Run Options Window Help


XHipOXt- 03
ljtt jit urllib.parse

google = os.popen(*start c;\Temp\Zenity\\bin\zenity —entry —text=wEnt< Search* p).read()


google = urllib.parse _ quote(google}
os.system(1start firefox http://www*google,com/search?q=ls1 % (google) )|

www.bdmpublications.com The Python Manual 103


TXT2BIN.PY
Naturally we're using the format function to convert the
user's entered text string into its binary equivalent. If you
want to check its accuracy, you can plug the binary into an
online convertor.

text=input("Enter text to convert to Binary: ")

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),

En ter text to convert to Binary Oavid


10Q0100 1100001 1110110 1101001 1100100
>» |

■■v

hdit Tabs Help


jm j n.
i@raspberrypi Code I pyt,hon3 TxtSBin.py
>> b jnve <<

"nter text to c
1000100 1100001 1110110 1101001 nooioo
_ iMk.
igraspberrypi:'/Dociaient S/P ython Cocte 1 |

File Edit Format Run Options Windows Help

t>rirvt{ *»>Text <«< DI


>

■■
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.

text _ rotate _ degrees - 0


With regards to improvements, you could display the binary
conversion in a Pygame window, using the animated text options Binary=(' \join (format (ord(x), 'b') x in
Prom page 100. You could also ask the user iP they wanted to have conversion)) vT
another go, or even ask iP they wanted the binary output to be
saved to a Pile. while not done:

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

print{ >>>>>>>>Text to 8mary Convertor<<<<<<<<^<\n" )

conversion=input("Enter text to convert to Bmary: "}



H
size - (600* 400)
screen = pygame.display.set_mode(size) u
pygame.display.set_captlon( E inary Conver ;:or )
#
done = False
clock * pygame* time *Clock() n
text_rotate_degrees - 0 R
Binary-( .join(format(ord(x)* b) for x in conversion))

while not done:

for event in pygame.event.get():


0
f event.Type == pygame.QUIT:
done * True

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()

print( .join(format(ord(x)* 'b ) for x in conversion)) 6


4
fu

www.bdmpublications.com The Python Manual l


\.K
§ Lira l^pJ i i

■m-
m— v TT-j

Here' sa hielp;)ifui~ anc i intere FILEBROWSER.PY


•^ . i; ■ r a i
^tgt] iiW*X< HI 1 ilJffsi ii^i< m m » 0 Tkinter is the main module in use here but we're also using
0 0 <x U idlelib, so you may need to pip install any extras if the
dependencies Fail when you execute the code.

e. 21
from tkinter import Tk

$ yoacanleamfr this code and from idlelib.TreeWidget import ScrolledCanvas,


FileTreeltem, TreeNode
import os

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(

sc = ScroiledCanv3E<root, bg=' rT highlightthickne3s=0, takefoc,us=1) highlightthickness=0/ takefocus=l)


sc.f rarcie.packfexpiand-l j, f ili-' 'i side- lef ■.">

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(>

item = FileTreeltem (os. getcwdO)


node = TreeNode(sc.canvas, None, item)
node. expand()

Python Code root.mainloop()


H*- 4iettervyrd.py
■ Balis.py
■-#* Bo ole ant est . py
—** BoxesColours.py
□ X
P CakPi.py
MJi Comments.py
h-*5 Diotlnpy ^ 3 X r* BoKe^Colours.p^i
b *? DiCtln2,py CalcPl.py
■r* Commenta, py
FJIeBrowser.py Dictln.py
- ^ FileMan.py ** Dictini id^jdsfiidhjcttogidolgi.py
f* Fi*0iWiir,py
M5 GoogleSearch.py —P FieMan.py

■ GoogleSercKpy --** Gcwgle&earch.py

/
i* GoogleSerch.py
** KeybDraw.py t'*’ KeybDram.py
—^ Numbertju&ss.py
Mj iMumberGuess,py r* PolygtKiCirde-s.py

■ ^ PoJygonCtrcIes. py
■ ^ findMLtmfien.py

l RndNumGen.py °/c f* ftnd Pass,wprd. py


* Scrcller.py
** TtintfifTal5>',.py
RndPassword.py —Tuni«Lims.py
Trf2Em,py
^ Scroller.py ^ TxtPot py
■P. bkup py
** TkinterTables.py —P calerdaryea^ py
-f. TurtkLines.py
^ Ttt2Bln.py
U f* daytiinmcinLti.py
P excepti onLpy
^ excepti on2.py
excepti on3.py
^ TxtRot.py f* hea ditatis .py
-i* bkup.py belio.py
P feapyMrs.py
f* calendaryear.py yf lOgin py
—^ logint»ne,py
** d ays inmo nth* py —»* nameist.py
print hellD.py
** exceptioni,py
** exception2,py
** exception3,py
J headstails.py
\ ■ pygamel.py
: * oxaanvetirt.cv

hello.py O
** leapyears.py
** login.py
^ logmtinne.py
namelist.py
:i pnnt hello.py
i
^ pygamel.py
J ovaafnetxt,o\ 0i
LI

Black Dog i-ftth Series - Volume 35


H ;
3'>

Basic GUI File Browser </>


I i

*
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)

from tkinter import * file.add _ command{label Open', command = OpenFile)


from tkinter import ttk file.add _ command (label * \
, command = *
*
from tkinter.filedialog import askopenfilename lambda :exit())
*
*

root = Tk( ) menu.add cascade(label = 'File7, menu = file)

OpenFile (): root. mainloop {) *


0
#
name = askopenfilename (initialdir="C:/",
*
"D
filetypes = ({"Text File", "*.txt"),("All *

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)

f ile * add_command(label ’, command = OpenFile) 5


file.add command(label — 1 Exit1 , comir.and = lambda : exit {))
#
*
*
menu.add cascade(label = _ ile1, menu = file) *

VI
root.mainloopI) 1
*
*
<
*

11
Ln: 11 Coi: 28
6
* * * * * * 4
OJt/

www.bdmpublications.com The Python Manual l


ii
e
V c MOUSETURTLE.PY
i-Li;
a 0 The First piece oF code presents the Standard Turtle window.
(?1 0 <* U Press Space and then click anywhere on the screen For the
1 q B SI Turtle to draw to the mouse pointer. The second allows you to
(51 □ 70 l_J 33 13 0 click the Turtle and drag it around the screen; but be warned,
can us< VJ
use as a : si it can crash Python.

3J re, A 1 st Code ExampLe:


(x .U i j
from turtle import Screen, Turtle
7 X
« d. a screen = Screen ()
c yertle = Turtle ()

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

a from turtle import *

@ 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

This code utilises some interesting skills. Obviously it will stretch


your Python Turtle skills to come up with any improvements,
Fl which is great, but it could make For a nice piece oF code to
insert into something a young child will use. ThereFore it can be
\
a Fantastic project For a younger person to get their teeth into;
FI
or perhaps even as part oF a game where the main character is
tasked to draw a skull and crossbones or something similar.
0 VI

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

Ever taken a quick break from working try:


at the computer, then suddenly realised if minutes > 0:
print ("Sleeping for " + str (minutes) + unit _ word)
many minutes later thatyouVe spent sleep (seconds)

all that time on Facebook? Introducing print ("Wake up")


for i in range(5):
the Python alarm clock code, where you print (chr (7)),
sleep (1)
can drop into the command promptand except Keyboardlnterrupt:

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

print ("Press Ctrl-C to terminate the alarm


clock early.")
sys.exit(l)

try:
minutes = int(sa[l])
except ValueError:
gys.exit r)

print ("Invalid numeric value (%s) for minutes" % sa[l])


print ("Should be an integer >= 0")
sys.exit(l)
Windows users, if Python 3 is the only version installed on your
if minutes < 0: system then you will need to execute the code without adding
print ("Invalid value for minutes, should be >= 0") the 3 to the end of the Python command. For example:
sys.exit(l)
python AlarmClock.py 10
seconds = minutes * 60
Again, you could easily incorporate this into a Windows batch
if minutes = 1: file and even set a schedule to activate the alarm at certain
unit _ word = " minute"
times of the day.
else:
unit word = " minutes"

www.bdmpublications.com The Python Manual 9


EPICSCROLL.PY
scrouing cexcr ics uses are rrtany
j/ ^ L * We've used the poem Cimmeria by Robert E. Howard For the
the beginning of a game or ! 0 code's scrolling text, along with a dramatic black background
and red text. We thinkyou’11 agree, it's quite epic.

UKe tpe peginnmg or every bcar


U % JF JF
import pygame as pg
from pygame.locals import *
Warssmovie: a list bf creditsat the
I 9 1 I fcj

end of somethrHg; such as a Pytho pg. init()


Ct U . »V . IAi :? I
presentation. The list goes ®n. text _ list =

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.

Vista on vista marching, hilis on hilis ,


Slope beyond slope, each dark with sullen trees,
Our gaunt land lay. So when a man climbed up
A rugged peak and gazed, his shaded eye
Saw but the endless vista - hili on hili,
Slope beyond slope, each hooded like its brothers.

It was a gloomy land that seemed to hold


All winds and clouds and dreams that shun the sun,
With bare boughs rattling in the lonesome winds,
And the dark woodlands brooding over all,
Not even lightened by the rare dim sun
Which made squat shadows out of men; they called it
Cimmeria, land of Darkness and deep Night.

It was so long ago and far away


I have forgot the very name men called me.
The axe and flint-tipped spear are like a dream,
And hunts and wars are shadows. I recall
Only the stillness of that sombre land;
The clouds that piled forever on the hilis,
The dimness of the everlasting woods.
Cimmeria, land of Darkness and the Night.

Oh, soul of mine, born out of shadowed hilis,


To clouds and winds and ghosts that shun the sun,
How many deaths shall serve to break at last
This heritage which wraps me in the grey
Apparel of ghosts? I search my heart and find
Cimmeria, land of Darkness and the Night!

'".split('\n')

Black Dog i Tfith Series - Volume 35


(verticaily Scrolling Text

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{)

File £dtt Firmat Run Qptions Windows Help


def make _ text {self,message):
font = pg.font.SysFont('Arial', self.size) splitt' n' >
text = font. render(message,True, self .color) ;s Credits:
def _init (self, screen„reet* lst):
rect = text.get _ rect(center = (self .srect. self.srect - screen_reot
centerx, self. srect. centery + self .buff _ centery) ) self.lst = lst
self.size - 16
return text,rect self.color * {255,0,0}
self.buff_centery - self-srect.height/2 + 5 fi
self.buff_lines = 50
self.timer - 0.0
def make _ surfaces (self): self.delay = 0
self,make_surfaces()
self.text = []
for i, line in enumerate (self .lst): s-f make_text(self.message}:
font • pg.font.SysFont( 'Anal* , self.size)
1 = self.make _ text (line) text * font,render(message,True,self.color)
l[l].y += i*self .buff _ lines rect » text.get_recf(center * (self.srect.centerx, self.srect.centery
return text,rect
self .text. append(l)
dnf make_surfaces(self):
self.text - []
for 1* line m enurieratefself. lst):
def update (self): 1 - self,make_text(line)
111J,y +» i*self,buff_lines U
if pg.time.get _ ticks()-self.timer > self.delay: self.text,append(1)
self.timer = pg.time.get _ ticks() kf updatefself ):
for text, rect in self.text: pg,time,get„ticks()-self,timer > self.delay:
self.timer = pg.time*get_ticks()
rect.y -= 1 for text, rect in self,text;
rect.y -* 1 b
def render(self, surf):
def render(self, surf): for text, rect in self,text:
surf,blit(text, rect)
for text, rect in self.text:
screen * pg.display,set_mode((800,600))
surf.blit(text, rect) screen_rect = screen,get_rect(}
clock * pg,time,Clock()
running-T rue
cred = Credits(screen_rect, text_Lxst)
%
screen = pg.display.set _ mode((800,600))
screen _ rect = screen.get _ rect()
ile running:
clock = pg. time. Clock () event r pg,event.get() n
i1" event,type == QUIT:
running=True running = Fa
screen,fill((0,0,0))
cred = Credits (screen rect, text list) cred.update()
cred.render(screen) t)
pg,display.update{)
clock.tick(60)

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/

www.bdmpublications.com The Python Manual


DIGCLOCK.PY
This is a surprisingly handy little script and one that we've
used in the past instead of relying on a watch or even the
clock in the system tray oF the operating system.

import time
import tkinter as 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@raspberrypi: /Ddclii tntS / K1

«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

def tick(timel= 1):


p get the current time from the PC
time2 * time.strftime( ■ q/jknJJ
if time2 S- timel:
timel = time2
clock*config(text=time2)

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)

class StopWatch(tkinter.Frame): if _ _ name _ _ == ' _ _ main _ _ ':


S topWa tch. ma i n ()

www.bdmpublications.com The Python Manual 3


_ m a > & * B < \ - v w Ji M ] vi e/
v
a/
65 E I [ □ □ / a F< \\
z 6

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")

4 h print("Superman The Movie Theme!")


print ("Loading Music...")
pygame.mixer.music.play(-1, 0.0)
3% Ji
HiPfaspb«rrjfpk:-/rit..,
‘jupif rmjn Tlse Uavie II
La-ndinr Mi.s lz . ...

□ 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

9 c rect = text.get_rect(center = [self*srect,centerx. self*srect*centery + self.buff_centery)


( tuff text,rect

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

def render(selfP surf};


for text, rect ir self*text: Scrolling Text example and as long as the MP3 is present, or you
surf.blit(textP rect)
fl pointed it to the correct location in the system, the code will scroll
screen = pg.display .set_rnode((800,600)}
screen_rect = screen.g*t_rect()
clock “ pg*time.ClockO
running* r rue
and play the music in the background.
cred = Oredits(screeo_rect* text_list)

the MP3 filename/location

.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()

using less memory too. EHe Edit

itertools 'i
Sliaeshowpy - /homs/pi/DQCurnenEs/^yChon Cods/Slidesndw.py

Firmat

• cycle
flun fiptions Windows Herp

■■i,-. ■ tkinttr ..>■ tk

• • App(tk.Tk):
"‘■Tk windaw/ label adjusts to size of image11'

SLIDESHOW.PY • lfi it (self. image .files, k. y, delay);

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)

is a great method oF building Python programming skills. 1


-• show_slides(self):
"'cycle th/ougb the* unagrs and display itirn”'

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)

se If . t it Le( ima, nane)

1 seIf.af te r t seif.deia y. seIf.sbow.slide s)


1- r run<self);
self.«namloopE1
# stt rnilliseeends ti*e betweein slides
delay - 3300
* get a serus ot git ynages you hay« in cfie wking folder
from itertools import cycle tf or use full path. or set directory to itfiere the images are
ini5ge_files = L
' /horne' p i/P i c t ure s /1. x f ’ ,

import tkinter as tk ' /horne' f p i/P ifi. lur es / 2. g.1 f ' ,


" /ham* / p i/P i etures/3. r if",

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

The time taken to display each image is handled by the delay


self.pictures = cycle ({tk.
Photolmage (file=image), image) variable, as noted in the code. To lessen or increase the time
for image in image _ files) between slides, simply reduce or increase the number relating
self .picture _ display = tk.Label(self) to the variable.
self .picture _ display.pack()
def show _ slides(self): F» e Edit ferp-^t Sun QpHons fiyitftwfS jdeJp
r itertools * r.1 ■ cycle
'"cycle through the images and display them"' - 3 X
imp ■ tkinter tk

. 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' ' '

self .title (img _ name) ung_object. img^nime = ne*t(Self.pictures)


se Lf. p ictu re _d lsp la y. conf ig( image - ifig^ob jec t)

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

self .mainloopO image_files • [

# set miliiseconds time between slides yres/4.«if

delay = 3500 x - 100


y - 50
# get a series of gif images you have in the app = App(imaye_files. x. y, delay)
app.shoh slidesf)
-rilf»()
working folder
# or use full path, or set directory to where the
Improvements to the code can include waiting for the user
images are
to press a key or a mouse button to display the next image.
image _ files = [
Perhaps you could insert the code into the text adventure you
'/home/pi/Pictures/l.gif',
'/home/pi/Pictures/2.gif', made from Page 120, displaying a scene in the game when the
'/home/pi/Pictures/3.gif character comes across something worthwhile, such as a pile of
'/home/pi/Pictures/4. gif', gold, a giant spider or some long lost city deep in the desert.

www.bdmpublications.com The Python Manual ■ 115


MUSIC.PY
The code utilises both the Time and Winsound modules,
defining the tone and pitch and inserting small pauses of .5
ofa second.
import winsound
import time

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

t ime . s 1 e ejr (0.001)


time. sleep (0.001)
1 I ox i i.. lang e (5) :

winscund.Beep •; 2C, V for i in range (5):


Ln>: 7 Coi: JS

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 ( 1C, 2*t)


winsound. Beep ( hC, t)
Sweet Music *
*
winsound .Beep ( hE, t) Obviously the Winsound module is a Windows-only set oP
winsound .Beep ( hG, t)
Punctions Por Python. Open your IDLE in Windows and copy the
time.sleep(p)
code in. Press F5 to save and execute, then press the Enter key,
*
as instructed in the code, to start the music. *

winsound .Beep ( 1G, 2*t) *

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)

winsound. Beep { 1E, 2*t)


import winsound n
beep = winsound. Beep
winsound. Beep ( E, t)
winsound .Beep ( G, t)
c = [ *
winsound. Beep ( B, t) *
{880, 700),
time.sleep(p)
(587, 1000), *
*

(698, 500), *

winsound, Beep ( 1F, 2*t)


(880, 500),
winsound .Beep ( F, t)
(587, 1000),
winsound. Beep { A, t)
winsound .Beep ( hC, t)
(698, 500), *
*
£1
(880, 250),
time, sleep (p)
(1046, 250),
* H
(988, *
winsound. Beep ( 11C, 2*t)
winsound .Beep ( C, t)
(784, 500), b
(699, 230),
winsound .Beep ( E, t) *

(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) ]

time. sleep (p)


s = c + c *
*
t)
winsound. Beep ( 1G, 2*t)
f, d in s
winsound .Beep { G, t)
beep(f, d) *
winsound .Beep ( B, t)
*

winsound .Beep ( hD, t)


H
*

time, sleep (p)


n

#
[jfc Python 3,6,2 Shell X [# 'songl.py - C:\Users\david\Documents\Python\song1.py (3.6.2] □
File Edit Shell Debug Options Window Help File Edit Format Run Options Window Help
Python 3.6.2 (v3.€.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)]
n
on win32 rt winsound
Type "Copyright", "credits" or "lrcense()N for more Information. beep = winsound.Beep
>»i
e m t
(880, 700) , 8
(S87, 1000)
(698, 500),
(880,
(587 ,
500) ,
1000) 5
(698, 500) , *
(330, 250) ,
(1046,
(588,
250)
500) , vi
(784, 500),
(699, 230), 1
(784, 250),
(880, 500) , <
(587, 500) ,
(523, 250) ,
(659, 250),
(587, 750) 6
3 — C + C
4
for f, d r n s:
fu
beep(f, d)

www.bdmpublications.com The Python Manual


an e ADVENTURE.PY
The Adventure game uses just the time module to begin
with, creating pauses between print functions. There's a help
system in place to expand upon, as well as the story itselP.

import time

print ("\n" * 200)


print ("»»»»»Awesome Adventure<<<<<<<<<<\n")
print ("\n" * 3)
time.sleep(3)
Eile £tM She|! fiebug fiptibns Jtfcr^dows, Help :e hdit f-arrn.it Hun Optiori* Wlndcrara Help print ("\nA long time ago, a warrior strode forth from
r JUge^O
cmd *'
EU^riJ^C y the frozen north/')
time.sleep(l)
iiht.sl*ta(2>

print("Does this warrior have a name?")


name=input{"> ")
giicfidt cmflisLlt
cnd ■ ii-.p j". (rivFie+
print (name, "the barbarian, sword in hand and looking
cmd cndliat
A long tue agD, n- marcio? strodr f-orth frma the FrPren north
0-9*5 this warrjrpr
* David
a I
eiturfi cmd
" ond i >- 11 - for adventure!")
OiVlU 1. '"‘K tld rdbr isfl .i nl in hdhd and loskwig for *cr^erturei
Hmewr , evil ai lurklhg ftii fh y. _. .
A. pair i:r bulbDus eysE rpgards thu tinra...
wi 11 PaMid prpvailj and Hum g-reat far-turif. r. print* .n-
time.sleep(l)
Cr die the hat*tfs ef areat evil, , -7 T ine . & leep( 1 >
prinE[ JSallI)i
t uni. e ] fl-B-pf 3-J
flsi tt J
print ("However, evil is lurking nearby.,,,")
time.sleep(l)
print ("A pair of bulbous eyes regards the hero...")
time.sleep(l)
print ("Will", name, "prevail, and win great fortune...")
time.sleep(l)
print ("Or die by the hands of great evil...?")
time.sleep(l)
print ("\n" *3)
little gold i
for adventura print("Only time will teli../')
time.sleep(l)
print (\..')
Do you □pproach the
time.sleep(l)
1. Ragged looking man print (\..')
2. Dangerous looking
David>help time.sleep(l)
as detailed in the print(\./)
leave the gane
time.sleep(l)
print(\./)
au return to your honeland without fame or fortune
time.sleep(S)
print("\n" *200)

File Edit Forrr-at Run options Windows Help


print('" You find yourself at a small inn. There's
little gold in your purse but your sword is sharp,
and you're ready for adventure.
With you are three other customers.
A ragged looking man, and a pair of dangerous
looking guards/")
cmdlist-l I " „ ‘T ]
c<iid*geccmd{c«dlist

cmd == “1
ragged()
def start():
f and ==

guardsO print ("\n-")


ragged{)
print{ ”\ | print ("Do you approach the../')
print(f+
print ("\n")
tune.sleep(2)
print("1. Ragged looking man")
print("2. Dangerous looking guards")
tiitie.sleep(2)

gE tcmdtcmdList): cmdlist=["l", "2"]


cmd - ir>p4it(naiM+w>*}
. cmd cmdlist:
cmd=getcmd (cmdlist)

Volume 35
H ;
3'>
Rl "

Text Adventure Script </>

time, sleep (2)


if cmd == "1":
ragged()
elif cmd == "2": getcmd (cmdlist):
guardsQ cmd = input(name+">")
if cmd in cmdlist:
def ragged(): return cmd
print("\n" * 200) elif cmd == "help":
print ('"You walk up to the ragged looking man and print("\nEnter your choices in
greet him. the game.")
He smiles a toothless grin and, with a strange print("or enter 'quit' to leave the game")
accent, says. return getcmd (cmdlist)
"Buy me a cup of wine, and I'll teli you of cmd = "quit": 1*
great treasure..'') print("\n-")
time. sleep (2) time, sleep (1)
print("Sadly you return to your homeland without
def guards(): fame or fortune...")
print("\n" *200) time. sleep (5)
print('"You walk up to the dangerous looking guards exit()
and greet them.
The guards look up from their drinks and
snarl at you. if _ _ name -** mam rt

"What do you want, barbarian?" One guard reaches start()


for the hilt of his sword,..'")

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

print{" n,k *20G)


oP damage as will they. You could even work out the maths
behind improving the chance oPa better hit based on youroryour print(#,k You firid yourself at i sina i i ini i r p i *- *- aoia i_n
a
but your sword is sharpP and you' readv fi I?H
opponent's combat skills, current health, strength and endurance. With you are three other customet

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/

www.bdmpublications.com The Python Manual


& VI
$ a TICKER.PY
\B
m
■ <21 We're using Tkinter here along with the Time module to
0 determine the speed the text is displayed across the window.
weftre often asked for is sOme 0
import time
import tkinter as tk

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

Ticker Time #Text blocks insert here...,

The obvious improvements to the Ticker code lie in


sl = "This is a scrolling ticker example. As you
the speed oP the text and what the text will display. can see, it's quite long but can be a lot longer if
Otherwise you can change the background colour oP necessary... "
the ticker window, the Pont and the Pont colour, along s2 = "We can even extend the length of the ticker
with the geometry oP the Tkinter window ip you want message by including more variables... "
s3 = "The variables are within the s-values in
the code. "
Yet another interesting element that could be s4 = "Don't forget to concatenate them ali before the
For loop, and rename the 'spacer' s-variable too."
introduced is one oP the many text to speech modules
available Por Python 3. You could pip install one, import it,
# pad front and end of text with spaces
then as the ticker displays the text, the text to speech
s5 = ' ' * text _ width
Punction will read out the variable at the same time, since # concatenate it all
the entire text is stored in the variable labelled 's\ s - s5 + sl + s2 + s3 + s4 + s5
x = 1
Warning!!! WarningM y = 2
T||. 11pV1'VI V,,0vClV1 ■ > r; 0j> 4 2) „ O K text = canvas.create _ text(x, y, anchor='nw', text=s,
4** 1:4n it

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

for p in range (pixels):


# move text object by increments dx, dy
# -dx —> right to left
The ticker example can be used Por system warnings, canvas. move (text, -dx, dy)
perhaps something that will display across your work or canvas. update ()
horne network detailing the shutting down oP a server # shorter delay —> faster movement
time. sleep (0.005)
over the weekend Por maintenance; or even just to
#print(k) # test, helps with pixel value
inPorm everyone as to what's happening. WeTe sure
you will come up with some good uses Por it.
root.mainloopO
U
• *1

7
a □
sck Dog i-Tec

Python Scrolling Ticker Script/Simple Python Calculator

Sometimes the simplest code can be


the most effective. Take for example,
this Simple Python Calculator script.
It's based on the Create Your Own
Modules section seen earlier but
doesn't utilise any external modules.
C ALC U LATO R. PY
We created some Function definitions to begin with, then lead
on to the user menu and inputs. It's an easy piece oF code to
Follow and as such can also be expanded well too.

£ile £dlt Shell Eebug Qptions Windows Help


Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.t) on linux
Type "Copyright", "credits" or "license()" for more Information.
>>> ================================ RESTART ===================

—-—Simple Python Calculator —--

Select operation,

1 ,Add
2,Subtract
3. MuItiply
4. Divide

Enter choice (1/2/3/4):

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.

The other area of improvement is code itself. Where there's


just a single shot at making a calculation, you could encase it in
a while loop, so once a value is presented the user is sent back
to the main menu. Perhaps, improvement to the Invalid input
section is worth looking into as well.

www.bdmpublications.com The Python Manual 121


6) n Vi 21
0 # \
n4s
□ HANGMAN.PY
v jfl' vl C
program i on It caivb»e s 0 We've made a Hangman game board (the gallows) out oF
A 0 <2 U characters that can be displayed in the IDLE Shell, along with
1 q gra a huge bank of words to randomly choose From.
A □
in 21 import random

>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

luggage responsible ambassador circumstance


f t r \f f
r congratulate frequent', split()
return bank [random. randint (0, len (bank)) ]
+—+
def main():
game = Hangman (rand _ word())
/l\ I while not game.hangman _ over():
/ \ I game .print _ game _ status ()
I user _ input = input ('\nEnter a letter: ')
rr ] game.guess(user _ input)

game .print _ game _ status ()


class Hangman: if game. hangman _ won ():
def _ _ init _ _ (self ,word): print ('\nCongratulations! You have won!!')
self.word = word else:
self .missed _ letters = [] print ('\nSorry, you have lost/)
self .guessed _ letters = [] print ('The word was ' + game.word)

def guess (self, letter): print ('\nGoodbye!\n')


if letter in self.word and letter not in self.
guessed _letters: if _ _ name main _ _ ":
self .guessed _ letters. append (letter) main()
elif letter not in self.word and letter not in
self .missed _ letters:
self .missed _ letters. append (letter)
else: quito
«
return False
Since this is the last example in our Python code repository, we I
return True
thought we'd go out with a bang and Feature the hangman :
def hangman _ over (self):
gallows being drawn with each incorrect guess oF the word. ;
return self .hangman _ won() or (len(self .missed _ Don't worry iP it looks misaligned in the text here, this is merely •
letters) == 6) due to the diPPerences between using the Python fDLE editor l
and pasting the code into a word processor (which Pormats :
def hangman _ won(self): things diFFerently). •
if ' _ ' not in self .hide _ word():
return True There's plenty you can do to improve, enhance and expand on :
return False whatweve presented here. You can include a routine that :
returns an error iP the user enters a number or character. You •
def hide _ word (self):
can include extra points Por someone who guesses the entire •
rtn = ''
for letter in self.word:
word in one go rather than one letter at a time and you could I
if letter not in self .guessed _ letters: perhaps add Chopin's Funeral March should you lose the game; :
rtn += '_' or something celebratory iPyou win. •
else:
rtn += letter
return rtn

def print _ game _ status (self):


print (board[len(self .missed _ letters)])
print ('Word: ' + self .hide _ word())
print ('Letters Missed: ',)
for letter in self .missed _ letters:
print (letter,)
print ()
print ('Letters Guessed: ',)
for letter in self.guessed _ letters:
print (letter,) Consider replacing the bank oP words too. TheyYe Pound under ;
print () the bank list, and could easily be swapped out Por something l
more diPPicult. IP you download www.github.com/dwyl/english- :
def rand _ word():
words you can Pind a text document with over 466,000 words. •
bank = 'ability about above absolute accessible
Perhaps you could swap the words in the bank to instead read •
accommodation accounting beautiful bookstore
calculator elever engaged engineer enough
the contents oP the text Pile: l
handsome refrigerator opposite socks interested
strawberry backgammon anniversary confused def rand _ word (): •

dangerous entertainment exhausted impossible with open ("/home/pi /Downloads/words. tx t", "rt") as f: l
*

overweight temperature vacation scissors bank=f .readlines() •


accommodation appointment decrease development return bank [random. randint (0, len (bank))] l
earthquake environment brand environment necessary

www.bdmpublications.com The Python Manual


124 Black Dog i-Tech Series - Volume 35
Learn Object Orientated Programming with Scratch & Python

Scratch is a Free programming


language and online community that's
targeted primarily atyoung people
but also useFul For older users too.
Its a visual language created by MIT
(Massachusetts Institute oF Technology)
and designed to help teach the building
blocks oF programming.
It's extremely versatile and as such can
be used in conjunction with Python
code to create interesting and useFul
programs. With the pairing oF Scratch
and Python you can make games,
system Utilities and control external
sensors, robots and motors.

126 Getting Started with Scratch


128 Creating Scripts in Scratch
130 Interaction in Scratch
132 Using Sprites in Scratch
134 Sensing and Broadcast
136 Objects and Local Variables
138 Global Variables and a Dice Game
140 Classes and Objects
JL\ ‘-

V s

VV ‘ ir -v - -
1-
1 - *■ a

SRv i v ' ’ -

S \v' *?s
i vvs'*. '
' '
!a-»

The Python Manual


Learn Object Orientated Programming with Scratch & Python

If you are completely new to programming Scratch is the perfect place to


start. With Scratch you can learn the and important
programming concepts in a highly visual i

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

Whafs Happonirg? Scralch Hpm

Ujvln-irsi 15. 301B


Thii Is wtiere you wl I iat upditoe fr jit, Scralchtrt you foilew W#va mada wrr* «ne cTipngi? to
F Epkwn jnd L lwLiii Itkiti?*
Cticck ouE Mino- Scmirshpn; ygu rnijjM liko to Snllnw

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.

Black Dog i-Tech Series - Volume 35


Getting Started with Scratch

* * • « • •

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 □ =

BBgMH 11 lii! r Ii-lI %


RW FdH - nlmul

^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

K fvj VV sprUL’': ^ / ii fij

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

window by dicking the Green Flag icon. Click the


ERRlTif3iiw8wb Star icon to Favourite or bookmark che project and the Heart icon
|[i[31ittaiisBwlSTi! to like it. More importantly, click the See inside to see the code

brr.i'ch_t.at_uri_ jtii je on Strjitih ■ flrefox

I £cr*tth_CiUOn_H *

tlrite Ketunlofl Fir»ct JI on iCf*lch - Hrtfgx


Cirdf Fr ,t , >4

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
#
«

Slickft- L- iLi-J Pc|. -.i t :li =

www.bdmpublications.com The Python Manual


| Learn Object Orientated Programming with Scratch & Python

Creating Scripts in Scratch


The program you make in Scratch is a script, or a bunch oF Scripts. In this tutorial we'll
take a look at howyou construet your scripts to build up a great program. This is great
starter practice For creating objects in Python.

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

Untitied-S qd Scratch - Moillla Firefox


^ Ii • A httpsy/sorai • mit-edlu/p >jects/11S9, 7S/J? editor ☆ ^O-l
j •

♦ 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

pl »y '<hph| ir t ,-.a- uirtil ibm

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

128 Black Dog i-Tech Series - Volume 35


Creating Scripts in Scratch

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//

DITING SCRIPTS fXyyXXr/ ry yyyyyyyyyy /// /yy/yy#//y//yy/yyyy >

d out of Scripts and even have several Scripts or of Scripts in


* 1 * m

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 *

♦ MI i A • mit.edu G Ol search £ ctit( m, Sesrch ♦ A & ® ■v

a + :: ;;
Shar^ ■lA&taH

clicked when space key pressed

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*

Scripts . a st ume: Sounds 4^ see prejeit page

| Motion Events ©
| Lc oks | Control
| Sound 1 Sensing

1^
| Data
| Operat ors
| Mgr€ Rlocks
y: 25

when key pressed


whj*Ti S || H<«t k i* y pl

when this sprite clicked


©
move U*9 ste
whrT» h^prliilrcHjpi ^-MtlrcheSi Ito piJfT>/|
play di um

move:
ID.
play dium

> Y- 16 -

Stage
2 b4clidr»pi

f ba(.«.droi5

ca /«i) a

Black Dog i-Tech Series - Volume 35


C Interaction in Scratch

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".

when space key pressed

i. Iii.ii i y e y by

iO change y by

FIXING YOU R SCRIPT


We know that therefs something wrong with our script and we want to see Sc. mp w space bar is
let's quickly squash this bug and see it working.

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

Flag starts our other script.


| Operators
I More Blocks
| More Blocks

when space key pi essed

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

t H mit.edu 'i ~w~r r j xa j

EditT Tips About x -v ::


Scripts costumes Sounds

1 Motio n l Evente
Contrai
| Sound | Sensi ng
| Pen | Operator5
| Drjf h J More- BiOCkfi

x: -33 y*. -igc ^

sprites New sprite: ❖ /tia

Scratch Ca!

x: o y: -15 directiora 90" (r


stage rotat turi siyl^; Q * *
1 b j ■. I .! |. .
tan drag in pldyt*r: R

** /i show: Yf

whm I itari an a dona

Black Dog i-Tech Series - Volume 35


Using Sprites in Scratch

* * • «

^ 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

9 Un t»t led S on Scratch

JfV-i Unltiljetf Scin Scratchi * + u ' a http. ■ .• mitedu l!r (G Q 4- A 9 S v lj □

^ ** rpilLt^U 153“ ~ j m 9 A n » Q Q = S' edit’ flps 4 n iivwmow fj lMryh,a[l;t>

m Filiti’ F-dll * figi*. AIkjliI fj lunfhdJii!i!,ji,T * &H-B

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

K f. i bps'*.C5 Neu spn» ❖ / ili &


ti*f l trt
Epuit« WSVv iprlta: ^ / M t

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 «

tiy tup H? arcd.

'

Ey Iu ryJ iuli it lM'’i,Ktifltli

Impprt

cpral 4J5

1 1*1-1

ti.% \

nfj(t rnstu !T|P

Sputes

pXHTC^a Let s use costume changes to animate Giga. Click


when flag clicked block to
Events and drag iviirai»ir»r«M«ilF4&r»1 Scratch Cat now moves back and forth, tapping oui
the Scripts Area. This block will activate at the same time as the a beat, and Giga animates through four different poses, You can
Scratch Cat Scripts when the Green Flag icon is clicked. move Giga lert and right using the arrow keys. It's starting to form
dnEJC.Lcd.2r titi icrjtcSi ■ MoiltCa f Irr-ftjx
into an interactive scene.
tlntJcLed-i o- Miritcb- M-oilti* l-lfefu-:

Untitle^‘ 5 o*t Scratch *


Sh*TJF
dctfATr: I i> yli-il

:c. it .1 i.tll i1- . •


M 91)0*1
Ir' '
Loi.-ks Jcarrtrol
| Sonslnt
WPlCfl llL|l l! d1' * krty pj

elutn^ w by

fhrinfjp v by d9

Dcrttch

www.bdmpublications.com The Python Manual 133


Learn Object Orientated Programming with Scratch & Python

Sensina and Broadcast


Get your sprites and Scripts to communicate with each other. The concept of Sensing
and Broadcast is similar to the way objects communicate in Python. This tutorial will
walkyou through the process.

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

L!ntltled-5 on Scratch - MoiHla rirefox


♦ «inJ • fl ' 'tf V/scfsi mit.edu -ts/nssv C Q* Searet it £ O <
?*■ 9 Uetitled-Son 5crat
Ff|0* Edit* Tip*. AttOLJt

<■ m i tittpw/i mit.edu O * ft ©


v |D*ncin9_C3t Scripts
bw lucyhattargtey lunilraradl
J Met le r
na
Ln*(fS fco.trc 3223!
II
I | More Blockt

H« Im

| Hh5 11«?'

thirik ICEErt
Hmffl..

| Hmr7,i

fwitch costumc t« co«tiin«J

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

^ M i A mit.edu oiects/l ☆^ © Untlticd-S on Scratch - MozlUo Flratox

^ 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

Kr zio y: -use * ••• •_V


Sprites New Sprite; ^ / (!a
x: 2*d i: -leo ES: ')

Spr Nuw sprite; A / ^ Q


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

Black Dog i-Tech Series - Volume 35


Sensing and Broadcast

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

4 Ii i fi n rtpK//KT9ti--h .mJt.edu 4 rt & o v q j 'UnfeItLed«i- do Seratch - MtdxIEI* Hrc-fax W 'T' |u. n ■ o

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

wlttn spute (sl‘v prtsstd

thunyi- v by

(S)
es
jc: :^a y: -sia

iiprites IMflW Spf' */iia


0 "

□ iQj
ar
' hjLcbJri
—Mtfl! -E
Scnrtch
1 IalHi i 9 J - - - L!-
N W* ftwdfafep

9 ;
Backpack
4. = <K

enables one script to interact witl It can be used to teli Scripts to


sprite does several things at once

it to the top of the broadcast

e arrow in broadcast
U-ntltted-S Q-i ItriEchi ■ MozIEIa l Ire/ox dnEltLei-S on StnUh - Moiltla Flffcfes

IMiUvd'■ 5 fl" Swjtsh *

?,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

sage anything you want but

I Operatore
1 More Blocks
UntltLetf-i «n IcfaUh ■ Meillf* Hrtfox
; Unlilksf E nsn *

when

Sc^lT^i I uriii.il (rvi.lrT


len cliIcked
when Ditftcmiff C ;■! pr*Jeet page
V k |, •!»
>eal

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

www.bdmpublications.com The Python Manual


Learn Object Orientated Proqramming with Scratch & Python

ou ve a
is
ate a dice game to help understand this

ARE YOU LOCAL OR GLOBAL?


Objects, like your Scratch Cat sprite, can have their own variables. This could be the player score or the amount oF ammunition
leFt. These are stored inside the object and are known as "local". Variables used by all objects are known as 'global'.

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 *

^ A r mit.edu rojecl 11 /ff editor G Q. Searcl tt untltLed-5 on scratch - Mozllla Firefox


PT £ Un5 on Scratch
rsFSYtcHl File» Edit» Tlps About r ■f’.
f H '1 I h Lt p s;//scratch. miLedu/p 1598Z531 /#edit C Search
Scripts sounds
: by lucyh att e rsley (unsharedj
Events
File* Edit* I ips About x^ k x ©
| Control rwt Untitled-S Scripts iunds
iJPBjj " , _____ ,
| Sentlng . v.m by iucyhattersley iunslwed)
|svents
| Dperators
Control
| Mare EI a r ks
when licked nd
I itori
□ck
when clk ked
Make a Variable

Make a List

New -variable

Variable nam e: dicel


_k: iaq yi 54 4

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

STEP2 ^ You 're going to create a simple game where Scratch


STEP4 For this sprite only means that only this
Cat rolls two dice and wins iF they're both the same W sprite can use the two dice variables. this is known
number. Click Data. Unlike other sections there are no blocks here; as a local variable. This is useFul iFyou wantto create another
instead we have to create the variables we need. We need two, one character with their own set oF dice and play against each other.
For each dice. We're doing that in the next tutorial, so choose For this sprite only
untttled-5 on scratch - MozlLla Firefox
and click OK.
J§ UntitLed-Son Scratch *
UnUhed-5 on Scratch ■ MoisUa Flrtfox
4* Bfi 'I A ratch mit.edu ipr F ! 5 982 531/Ued i to u
UntitLed-5 on Scratch x

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

Make a ust Make a Ust

New variabit

Variable name: dicel

O For >11 -.p-ltps Fnrthi? spri! o only

x: anu y: -ibo

x: .240 yr 93 New Sprite / & & OK Cancel

New sprite ^

St d 3* , Sprrfce j
3 bickdrep

b+cixtop
Staqc
1 bdf imp

Black Dog i-Tech Series - Volume 35


Objectsand Local Variables

• • •

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

Make a Varia ule

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
.

SjjBWJ f-m*J B*:i BBSIUi IR li


STEP1 STEP3
/////>
ltO_10|ama;«siiw ■« i i nn
dicel^o_[0]^^ffl^ffly2y^0^ I” 6 ■ ■=»
to pick random [1] to [6 ce
a number between 1 and 6 a mvu*]i it in the dicel Unlltlerf-S on Serate h - MoziLla Firtfo*

variable. Adda pick random [1] to [10] m block to dice 2 and 1 Untitled-Son Scrgtch

4 Ai A
*

init.cdj l59£L253V#editoi C t-k Search *m © 4 # &


also set it to r_i [untrtled-S
# FlleT Edll T Tlps Ahoiit

Scripti CrEtiJTii?:. shari'


L _J by lucyhBttersIey iunsnarea;-
| MotiOri | Fven’ j
SprittJ; dkcl
|iuoks Iconrro1'
Sprite 2: dite? | Siur.d I iemir u
S Uotit!ed-5 on Scr atch x
Ipern | Operatore

4r ii 1 i 1 mit.edu C? ^ Search £ I Mare Blocks


when
[ScftATnH Filf* t<W* ilps x + se ;; ©
i
oi to pick random
r—-1 | Untitled-5 SCinpts '.umes Sa^nt
vmi by lueyhattersley (unsliared) €A 1.0 pick i tindom £J

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* _

STEP2 We need t STEP4Finally c say [Helio! J Ol !


.

tab and dr c Change the


is uke theiOb /AA *
titsays, "if this 'S/sS
[Helio!] t in if RBlfl win!! !] and in else®[Oh no.
-=■

_click operators and |I lose!] ay the game


ck. Drag it into the space next to Y///yj^
Unti tled-5 □ n Sera tch *
AS
Untitled-S on Scratch - MoztUa Firefox 4 H 0 A I http5]//scratch miLedu/p 7o2. e Search ☆ £
i- UnCitled-5 on Scratch * i i *T -1

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

SpritrZ: drccl an |Moiion


11 □ok s
| Events

S —*
I Conerol i Win!!!
Sprlt*2: dlctz
|Saund | Senslng

IP€f1
|Data
Operators
| Mors Blocks
■i ^ 'f IjJjjHi fir! 0 i iri

twltilb 4n«turii« tu c*rtM#n#;

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.

www.bdmpublications.com The Python Manual


Learn Object Orientated Proqramming with Scratch & Python

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

kjntitled-5 ;cnpts 5 c-tumt nds


Vi e: ditEl V j T*~ - -1- J •
,:qa by lutyhattersley (unshared)
Vic: dkcZ
Canirol
Sentlncj
Vlc:<dkcl I MCftion
|'-»k |CC

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

H*nrn. . I to pick random

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

Sprite s Neu/ sprite ^

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

Is■■ i': dicti


I I Sansin^
| Qperators
Vic: dkeZ

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

Variable na me; vic_tDtal

vf :or ali sprrtes Q l-or this spnrs cnly

x: c4e- y: -13 Make a List Make a List


_ x: £4D Jf! 4

Sprites New sprite ^ £ 0 hJew sprite: ^ ^ OK Can cel

Stage Vle E-.-. Stage


L blckdrEp 1 b^cNj-np

New bacldrcp New b*ckdro^

Black Dog i-Tech Series - Volume 35


Global Variables and a Dice Game

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

jprites hiew sprite ^


S^lake a List

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?

Bob: dkcz I More I I . ■ •


wlieu
tat d i bob total 541« viC _T D CjI J i

bob total pkk random 5ȴ vi C.tdtfll

n •j-jr lcrt-*l
thinfc

Staga

set Cultor
1 iikd^Dp
Nem badedrep

set vic_total set bob total


victotal m say bob total
bob_total total bot?_total\ if l|kW rj r

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

Jice2 to pkk i anctam

when ?ob_tc :idi to dice 1 +

bob total tor secs J


bofcj total

x: 24' y: -lm
II bi ...id ■ a st tiie: iigtJ and waifc 1 5prit;es New sprite / jjfc Pi

www.bdmpublications.com The Python Manual


| Learn Object Orientated Programming with Scratch & Python

Classes and Objects


Modern coding uses a style called Object Orientated Programming, or OOP for short.
In OOP you group together variables and Functions into small blocks oF code called
objects. These objects then make up your program.

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 •

File» rdlt* Tlps Abmjt

bjiT Iucyhs.tte-rf.i15y lunshared)


Scriptu 0 fjl urn<?$ s-cnjr.ilc from random import randint
| Ev*rvts
Vici Jiif j
| cwtrol
Vic: iliccZ ■dfc* . h.1 1 J ■ J/home/llucy/Eiealriiiori
ciame.pv — k-ytrcr/f-l:» cjnc.p»
r J (.J.l v ii n L *■ 4 JMJ:
| scmnd | Sensmg J r 31 J 1 .« 3 1 1 -w * Idi i 0

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 # » =

rdi? t rips Ab«ut > TT ^ ■dlct_gjirn.ft.py - jihci¥ie/t.ucy/fcitgmfieri_kjthar/[fl-c«_g.int.p-y l+jf i -^i m m vy


r_i Diro r^ma Scnpt-i ‘diifd1 {iic^f.py -/h«^t/lucy/nR-]inprri PyH‘(ifiJrdl<re gRirn- py (j.t.tiv)»
L,,J bv*»tvhatter&€> lunana^e-di) £.*■ £J|[ Fj,i n i! £ul il H jf£F,i...iV £^. 1|.
ni vrzcrh x

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

o Ffei of lypr Pyllkin fi 1 r-, i' p.i^.T.pyw) _ j t»cri

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

Black Dog i-Tech Series - Volume 35


Classes and Objects

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

y -j nnp.i-s Uifi scracch x f v £ lil F _i i ■ .I f .i Qiini

fnn rifldH i«por randint


4 ii A mit.edi. H se ☆ O W 4 »
'dlce_g*mii.py ■ yhcmey!ucj5/UtgJnii*-Fi_eyithort/dlc*_gttraB.p f <2.7-11*1« m i -.)) 7o:
* ■* 03 O
r l j i i Dice An i nal f) :
■di-m' «ame.py -/(icunp/l-ucyfScfl^nerc.PytliefT/Filc^ flflinf-py (7,7,114]*
tdlt* itu* About i + l>
dletl * O
y Lhntkl«{-5on scfsCch x f ■■ £,dit Fgrrnjl Jur. "Imt dite? * 0

♦ » ra ndc-Ti . ■ i ; randint Mollciri I’ — dirpl - 0

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

Vfc: dhd «T®


jjione
tr/IU^I[larM> LUUfkVItli
scripti

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/

f the same as creating a variable, only instead oP passing in


r, or string, you make it equal to your class. Enter this.
vic.dice2

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

i Ufititl«d-S on Seralrch X £ ■■ £ail F_jii- il Jtur £|iitii VSni. * £■ ii


“d :e_gime.py . /home/:'jcy/tiBiglnn*ri_Rjtha-r ;'clc«_gamt.pjf
rgrtdo* ■[ fandirtt
4 fi m Tilc.Mu di« (ssme.py - ^honnc/lu(yjlHpiiinfi*rE Pyttion/dlce, qame.py [Z.7,tui

Edit * flJJF* XliOUE fj IluytiiiEU-fvF-ey *


■ &iceAni»al|]; £ V Edit Fyri .il Juri flplKH v
-I U.tti[l«d-S x
dlfp] - 0
Mij(b I EJItSS * 0 + fl A mit.ftlu ,
f o rdndow ~k>i1 raodinl
fiJUffS » 0
Mprilirvn ,j -. - Oie e An 113;
tulyh Jitloruliiy *
| Lol'SIC‘ iIh- roL Ldity K^eLJ ): dicel ■ 0
JH A tiriptt SllJIL* I (4.|, 11| r.ip.-r I p,|[p' die*2 * 0
| S«rmi*g self.dicel * ramilnt(1, 63
self.dlce^ = randlnt(l, 63 »hsrlBi dicel ■ 0
I **or* S;or!f self.total « self.dicel 4 self.dicei
(inctcr. (fnnlrr ■ rolldlceiself)\
vic - DiceAni!*aU 3 | UOund | buntir.^ solf-dicel = r a nd i nt U ■ G-)
b 3 b - D i ce An ira lM 1 f*" | {Spiriton scl^.dice2 * rarvdintfl, 6)
|.i' l |Mjr< UlOLhl s#lf,total • stU,dicel + leU.diceJ

vic = DicE-Aninal | )
i- t^tmJ k h<r* 1 -t J lti»n tot ■ niceAnin^l|3

1^1 I ili 9". 1 Hi ra f I____ _ ____

You now have two objects, a vic and a bob. You


STEP 2 STEP 4 Enter this code:
access the variables and Punctions inside the object
vic.total > bob.total:
using the objects name followed by a dot. To access Vic's dice, you
usevic.dice1 and vic.dice2. We're going to gettioth objects to roll
print “Vic wins!* oy/j
& WM

.total > vic.total


their dice and store the total in their own self.total. Enter this:
print “Bob wins”
vic. rolldiceO
bob. rolldiceQ print “It’s a draw” WyyzM
‘dicr_gjnve.py ■ /h«m*y.‘Jcy/Btglri(itri_pytkor:/Ckfl_gD'ne.py <2.7.1 +)*
'dicv ijfirud.py - .[h^mp/luty/Flii-gPython/dkp gjxnf.py (3-7,11+J^
IA) 20il7 &
Press rj game
p iJntitL^-ls ufi !j£fatcb £i,- £dit Fgfm.il R-jr. fijjliii £Li4p

frn.T rando» »pn rt randint


♦ Hi ■ A ’; .» .‘ic?dtch.vnll^du/p^i^11 C
xython 2.3.12 ihcU
LdlL * ilus About IUf,yllil!lcf*|ltFy * i D i, c cAn i rssl [ 3 -
Python 7,7.17 ItipLL
dicel - 0

jrffif S t^ripE»

MgMc-n
!<lt,lll I 0 pfDjia frJU.J ■■ dice? • fi
dlc*3 » 0
£||| E>li: It nll 2itiLi|

2,7,12 (defiult, Jwl


QF<-.rr. .viirdo* diH(a

1 1S:12‘24)
£Jlt Fyn-.ll £uri fljjtiorr'.
n rando* ■r f randint
i±^P

ICCC H.4,0 20160609] en linunJ


np' feLld!ce[fieLt]:
Ty^e 'cepyrighT", "dredtt^' er 'lUemset r far isere informatt-on. : 1 ,i - -D'lcctAn i»at |;
self.dicel * randint(1. 63 >» rt|c*l - 0
m seLf.dice? ■ randint(1, 63
ftESTART: /ftone/luty/BegInflers_Pythen/dlcc_g4Siie.py -■ dice? - 0
self.total * self.dicel * self.dice?
h| 1 ■ Ly pl&k iAiHJai!lh O Ll> O Vic railucJ «i (i Aiid ni 4 d i L-ti J ■ 0

pliL Bob roLicti a 2 and a 4


rnm tm m © tn 0 vic - DiceAninaK 3
i j t- i d L 11111. e ( s t LI ) ;
•a« fcl* t# Ac*l -
Biaf i*lt 1 Wt Wl 1 * r 1 fjE lALi
hab - D i ceAn i mpiiU 3

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?

b 71' = D ice AninuM )


_i
vlt.rolIdlCB()
*J&b
bob.relldice < 3
pU* (J ¥■« fe-n aa ijjl

jpFr J n t ‘Vic rolled aHJ vic.dicel. "anri a", vic. dice?

W.

www.bdmpublications.com The Python Manual


142 Black Dog i-Tech Series - Volume 35
Robots, Drones and Cool Python Projects

Python is not only an interesting


and easy language to learn, it's also
remarkably powerfuland can interact
with many different hardware projects.
Thanks to the likes of the Raspberry
Pi and other electronic project boards
and computers, Python can help you
build the Software and Controls around
sensors, servos, robotics, as well as an
arcade machine.
We have some cool projects for you to
consider in this last section. From here,
it's up to you how far you take your
Python skills. Do you aim for the stars
and send your code up into orbit on a
high altitude weather balloon or maybe
use it to create the next generation of
computer games and robotics?

144 Using GitHub


146 Build a CamJam EduKit Robot
148 Controlling Your Robot
150 Add Sensors to the Robot
152 Amazing Robotics Projects to Try
154 Arcade Machine Projects
156 Security Projects
158 Becomina a Coder
16U uossaryor lerms

/ \

The Python Manual 143


Robots, Drones and Cool Python Projects

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.

GETTING TO KNOW GIT


Git is an online versioning and collaboration portal that enables you to store code online, download code, make changes and
then integrate those changes. Github (github.com) is a website that developers use to host links to the code.

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.

pi@raspberrypi 0 sndo apt-ffRt update Wastebasket


Hit http://orchiue.raspberrypi .or|f wlieezyi Kelease
Mi t http://archiuE.raspberrypf.org uheczy IHtejlCiiise
■ >-.<<]
H it http: //n i rrnrd i rector. raspb i an, ory uhcezy Ro 1 easr, y py L
k
Hit http : //pasplerryp i *coi labora . con ulieezy Ro i ense , gpy File Edit Tabs Help
H i t http ■ //n i rrnrd i rector . raspb i an . ory liheezij Rrr I ense piQrsspber Typi git config global user.name- " Luc. Hattersley"
Hit http ://raspberrijp i .collabora .com uheezij Felease piQrjspberrypi $ qit config -global user.email. "lucy,[email protected]*
piiQraspbef ryjai |
Hit http://archiue.raspberrypi,org uheezy/pia in armhf Packages
Hit http: //'m i rrord i rector. raspb i an. ory wheezy/main armhf PacJcages
Hit http://radpbcrrypi.coilabora.con uheezy/rpl arrolif Packayes
Hit http://mirrordirector.raspbian.ory uhcezy/contrib armhf Packages
Hit http://mirrordfrcctor.raspbian.ory whcczy/non free armhf Parkagcs
Hit http://mirrordirector.raspbian.org whcczij/rpi armhf Packagcs
I gn http: //arch i oe T ra spberrtjp i . org uheezy/Pia i n Trans lati on-en GB
Ign http://archioe.raspberrypi.org uiheezy/main Translation-en
Ign http://raspberrypi.collabora.com uheezy/rpi Translation-en_GB
Igu http://raspberrypi.coi labora.com uheezy/rpi Translation-en
Ign http://h i rrord i rector. raspb ianory whocrzy/Dontrib Trans lat ion ciiGO
Ign http://nirrordirector.raspbian.ory wheezy/contrib Translation-en
1gn http://mirrnrdireetnr.raspbian.org wheezy/main Trans 1at ion-en GB
Ign http://mirrordirector* raspbian.ory uheezy/main Trans 1at ion-en
Ign http://mirrordirector.raspbian.ory uheezy/non-free Translatitn»-en J3B
Ign http://mirrordirector,raspbian.ory wheezy/non-free Translation-en
Ign http://nirrordirector.raspbian.org wheezy/rpi Translat1on-enJGS
Ign ht tp://nirrordIrector.raspbian.ory whcozy/rpi Translation en
Rcading package lists... Bone
piCIraspberrypi ~ 0 sudo apt-get install git
Reading package 1 ists.., Bone
Hui L.l ii m i—.0 .... ..—. ■ . ■-

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

O https.//cithub com/lucyhattersley fizzbuzz a e r o

O T hi t nepos Itory □ ren Puti requetts Imaucs Gist

lucyhatiersley / fizzbuzz O Unwatch» i ^ Ster 0 VFork 0

Dt scrfption WtLsilfc

■MDt c>n of ri We-beb* for th is repo sit ory u lon Save ur mcel t> Coda

Set up Git Create re positori es Fork re positori es Work togothei


A quick guIcte io lielpyouget Reposite rie sare where you'II work Fcrking create § a new, urtique Send puII reguests, lollowfriends, r,’ Z commiss i omne 'i 0 ele i -es iftl contributor
staried with Git. and cottabo rate on pojects. projeci fram an ejiistlng urit Star and waich projects. Pull reque a

Branch master^ fizzbuzz / +


Ly WIW
■“ ’ lucybartorslay » *•>) GltHub Univorso: The Blg Bang Fir^ commil

« T wo tuia day s on how to oulld, coi tabo rate, a nd


f* - lucyhatiersby ailhored Sep 1.2015 ate&t -onmit 2128t456af fi4
deploygreatsotiware. Jcdn us on October l fi 2
insan Francisco..
storia Haned pfanningcentei/rBact paltofTiE © README.md Initiat commil Sep 1.2015
■ 11 Gr?iphs
Vleiy J 1 nttV bfouidcELSli
0 li£zfciuzz.py First com mit sep 1, ZOIti
sloria fo rked j mcarp^marsh malbw-pagi nat ion to sloriaf rnarsh msdtaw-paginat ion
Your repositorles + New repo&itory O Seltinqi
m README.md
ebria stmrod Tai Ater/an nyong
HTTF'3.. bne U-.L

144 Black Dog i-Tech Series - Volume 35


In the bottom right oP the Github window you will Enter Is and you will see the Fizzbuzz directory in
STEP5 STEP6
_W see a text box marked HTTPS clone URL and inside it _ W your home directory. Enter cd fizzbuzz to switch
there is a URL. Click the text and press Control-A to select it ali. Now that directory and Is again to view the Pizzbuzz.py and README.
right-click and choose Copy. Now open a terminal window and enter md Piles. FizzBuzz is a classic program that counts to 100 but on
git clone and choose Edit > Paste to paste the HTTP address numbers devisable by 5 or 3 it prints "Fizz" or "Buzz" instead (or
after the command. FizzBuzz iP it's devisable by both 5 and 3). Enter python fizzbuzz.
py to run the code.
Deacripliefii Web*ile

Save or Csnce. ^ Codo

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!

[p) README.md Inilial commit Sep 1,2015


Iiii Graohs

[=] fizzbuzz py First com mu Sep 1.2015

O Setlings
m READf lE.md

HTTPS c Uy: URL

httpsi "-J-LL--L -- ^
fizzbuzz You can e |
Back
pr Forwand
ri~i c Relosd

Add Bookmark..

Send Lmk by E-mail


i

ADDING CODE TO GIT


Now that you know how to get clone code ftom Github to your Raspberry Pi# you might be wondering how to put your own
code into Git. Git is a powerful and fairly complex piece of Software but this will help you get started.

-' L JUUUI ■ VUL Jhj5' s-il L1= a ' 1 I C L.U-JI L..

YouYe going to create a Python program that First we need up&Pfit


STEP1 STEP3
_ W reverses a string and upload it to Git. Enter mkdir _ W a repository. s //github com/new

Pull requiete l»uea Giet


reverse_string and cd reverse_string.Then nano reverse_string.py Open Github (github.com) and
and enter this code: click the green New Repository Ownar Ropcaitory naina

■ lucyhnT1or*lav -
button. Enter reverse string
import sys Gi&at r^posiioiy name-siire eFiqti and me ruo rabie. Need inepiration? Howatoui I aquae

in the Repository name Field


string = sys.argv[lj D e seri pTi on m p i bm I)

and select the Initialise this


print string[::-l]
repository with a README Public
Anyonecan see mis reposmory. YGLieJiod&e wto can commit

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

Add .gitignore Nona * •Vid i • Nono -


limhJstn II» clone URL Field as you did when
File Edit Tabs Help doning a website. Return to the
nano 2.2.6 File: reverse strin
command line and enter ^
remote a BB1 and use Edit > Termi Prlvacy Securlly Cortacl Hi

Paste to paste in the URL.

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 :

www.bdmpublications.com The Python Manual 145


| Robots, Drones and Cool Python Projects

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.

146 Black Dog i-Tech Series - Volume 35


r Build a CamJam EduKit Robot

• *

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.

SETTING UP THE RASPBERRY Pl


The Raspberry Pi will need to operate on the move, so it needs power and a wireless network connection. You'll also want to
access it remotely, so you'11 want to set up VCN. Let's build the brains.
• •t • i * • t t

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.

File Edit Tabs Help


piQraspberrypi: £ sudo apt-get install tightvncserver
Reading package lists... Done
Building dependency tree
Reading state Information,,. Done
The following extra packages will be installed:
xfonts-base
Suggested packages:
tightvnc-j ava
The following NEW packages will be installed:
tightvncserver xfontSybase
0 upgraded, 2 newly installed, 0 to remove and 0 not upgradeeL
Need to get 5,736 kB of archives.
After this operatiori, 9,895 kB of additional disk spaoe will b
Do you want to continue? [Y/n]

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.

Itipkirr^ Pi 2 Ki» f 9 VI.1


< » I7( k» 1 MTl
-
{c) (Uipfeerrj Pi Z&14

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 . —

www.bdmpublications.com The Python Manual 147


Robots, Drones and Cool Python Projects

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

* import RPt.GPlQ GPLO e Import tfce GPIU Library-


1 jmpqrt tlw ■ # ■ Tnport -rhp • 71 m p • Ut?r.iry
I id IFi Cii 'r-r 4 ■■
hulltirr, Pv dpiKY feii fM trrAnr trp# Pii
N-5et the aPIO ■ PicidLii

11 «uti- [ii," LTl HJC* 3 : i


c#
T".|i _*l 'id vi VM Id ir*
L' l
»■ rii'i itM-ll i'r.li i .-«M lici l<h'i'r Ull
GPIO, t node- {GPIO. BOS)
GPIO, sttwa-rri nus(‘a1s e)
"«oat i'5n toi
C-ldiT i Bf' i:*' icm' i-|.i i in*-gi^c r FtMc* icito toro iwl wcrLr ri'a.i« I: i Sut Lhii QPIflP.li*! IhjJi; .
IUM l-aswl.JV
GPIO,SCtUp( , CPID-QUT)
ip» l«i- i*!1' PII- p I I co-mtM. IMWH i*r «VI i . k Ih i» ic v*. GPIO, sttupj1:, GPIO.our)
‘Jftrnmia GPtG.fietup^, GPrQ.QUTji
i (*im i - fcftdni
■ xu-fclNfreE i - Pfclur 'vil GPIO,«tup{10, GPIQ.&JT)
LaiH^-t «Pi cp:c *i iMj w iwr thr cpi-oi ni'o'1
l*W"t 11*1 * Iwcf !«1 ’L<I LLt^jrv
i-Turji ■ a-ll-notors-o+f-
p H: in;
e*EQ m*^iicrH-Kif}
*J(Sc l
GPIO.Output(7,'B)
G*E0 l«niPl{<fl(f »1»|
GPio.OdtpLtiji ej
■ m u-1a nr, Uk GPIO,output(H* 03
(?[(> i+TvDf?. («r- >
ia:c.ibi»;, a. Uria.Bufli
y, !.C.i+'vE ■). SMip.ifcrtJ
(?EI5.WTii?. LBi C?]0.1I.T>

ai ■ I I »irtn'i *4f P ■ T um ■ the rightiiTOtor fc-^jrdi


ii
G»EC.m1|u-.<». ti GPJO.CKltput^, 0)
r#r(i ii
omajepirttia,, <i GPIO.ajtput( ILi^ 1J-
h th» ftim mtxtr L**vira(
(*E0.*JipiJl{S. fl
L^IO.wu-vC^ir, i) ■ ■ 7um■ ttie*left motor■ farwards
■ rii*n 1 hr Ic' % rai ur GPIO.outputOS t1)
5>f[0-WtPk'M':'.. »1 GPI0.OjtpUt( d J, .)
EVEC.^iApu:^ ii
I Hlll 1, Mi*»*
IH.iLHtU) 3-h'nit for 1 ■ ^CQRd
P t*WI 1»* Ifti iiL-ij :1j“H *W Idldc t , ^;

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

k-utl ; \Mmfi0tuk. PjL-SiwO^d tart. t

llpil-i j PwvrtoM^I -.'inF,F'-liJ,ic'*c*dt^Hi'l mMAii PV


rjornmjnd cd VhriTW ‘p 'hdrjtCiUlnbnlii

riif T+d ir^r


MjI-ji ri"Wf i'ta^rwp Cd jlC mcodp(KL'2 - moievi fv - r IdeJ .'^niltcv CwMlapiT-ralxn n
rto Irii^n Mtotiu Wto'ln 11
|^K4^M«4Bid FrfiA

Ljdc*I »11 r'1-.nrs..' 1 JWi' DBK.LTP - i -ile v'<

bHIHf 1 nam
BKvn <it
SKi Mirug*r
p#?»
(H^Ul
Uiiiwd tfWKl^r SKTinflfi 'faiiai
itirr
towifi
P4SK Psn;
V.L-:

Snarsea . £FTr • SSh Fb T'»rnli' rVoioee.


r •* nvr* Bnl» f'lrr,pi r-iai M r.ic-cpc LJFI

HfCVCi! liN MrKbPTf i?,'o^»ie u tn rien 5


JDgcr t,im. 'torrrj
EtuE EJirtCliPY W. ni -.fCL* ] S U 1 UVflH 25.4] iOlb
lii fr* (WityMll J6
Scuiji^Pi ] he i rh 15 *piiv>uicl
M.Hm 1.1» ln lOiii/Jilt 11
AcciXPi-
iKi-lf-i 4 f ii* IT.-iiiUJLJ Jl
HI FU It 05 DLi 05 Cairw^itt
L.te*iigi/ib ^Kto'*^Er. li •
J-rldiMSI1..pW 6?4 ^-lii» ici P1,'»LS 11
i ni «h vk (r„ n 01.'Mi» i;..
fHimln.dt I&I1/3H1 li-
i|Lj sV i i'ji .. IflfOlEifllS 1S-,
fMW.eS-ifSl.v dU.il s<kh-p t »:SU»i6 11..
CK Ctnui

II Mn«le KffM). T^iu SritHKB J 'to. T«a >ti i7D SyWl


hnvilmHiii llampn. i f t-ic h-FHllTil SniiVl

Ntl t tiri i ji£( u i ji uinUtiii

# #

148 Black Dog i-Tech Series - Volume 35


Open the VNC program and connect to your All being well your robot should move Porwards. IP
P5
W Raspberry Pi. You should see the XFce desktop even it moves backwardsyou need to swap the position
iPyou set up the robot to book into the command Une. Entercd oP the red and black wires on both Motor A and Motor B. !P it Pails
EduKitRobotics. Make sure your robot is on the Floor and has about to move then check the wires to the motor control unit, check that
a meter oF space in Front oF it. Now enter python3 2-motors. py everything is switched on and try replacing the batteries. You need
and press Return good quality
batteries with
enough power to
move the servos.

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

me/?page_id=1035#worksheets) and download look at the 19


■ 3-dr «■ rg.pv t Ino symt<a
CPIO.setypCpinM&tDrABackwardSj GPID.OUT)^
tx itclcn) t

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)

your main block oP code. StopMotorsf). These deFinitions 21 -


29 -4
GPIO.outpuf (pinhtotorBBackwardSj, ■ B) *

30 #■ Tum -both-motors ■ forwards-

MI 41 It Hi Ull r»Ut VkVp MHlnjp WffFiup *'■ * * V © * B ift ■: L i>i: 1J ■


enable you to move the robot 32
T dafj ForwardsQ
■ ■ ■ GPIO.output (pinMotorAForwardSi ■ 1
■■ GPIO.output(pinMotorABatkwards, B)-
rjn-jjp-ldui-4 1 ■ Krtjui? (plrHo^irflSicbrapds. 1J
T Mi hltr -K¥..V
'- *
using Functions, rather than 31
GPI0.output(pinHotorBForward5} -1)-
jjEwart BPi.glO jh OPIO • import ■ the CPIQ Libmry 5$ ^ GPIO.output(pinWDtorBBackwardsj-B)-«
t* j4ira rvutb qke
) ■ 4i*lvll Ag ■ fiy m
jtt- 'Diri ■ < c*>tn V' :*ib^ ■(■"!«■ En u«* :he lllc
4
>’ DlEJ -ti¥t :he lilt j‘, l.npiorl ■ t lw S^IngorE thf fime Itbrjry

Set the ji'l0 t.jJc


typing out the code each time. 36
37 #-Turn-both-inotors ■ backwardt-
Ftunnlne the Code tt

GPID. (CIQ. ElCu) 3B T def Backwards();-i


T{P r-irt 4N- c«lt, CnJl lhs
Elrtlign) 3-drl»In(.ppy
rttb <Ei* itfrfflflJ

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

I Stt 11-4 OPIO Pio I»d*-


t?1! 01 f ht upCpinOVitOrW podarflj, e ? I(JH OUT )
to the code. 44

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

directly on your Raspberry Pi robot but we think movement 3B

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

JJ # Turn-both -inotors ^ backwards-i


program using python3 3-driving py. The robot should move . 3-driving.py program to your 3fi T
39
def Backwards():^
GPIO.output{pinHotorAFarwardsj B)i
■■
Forwards then backwards. EduKitRobotics Folder, using ^
Ai
GPI0bOutput{pinMotorABackwards#■1)-
■■■ GPIO.output(pInMotorBForwardsf ■&)-
fl2 4. .. GPIO.outputtpinMotorBBackwardSj ■ 1) ’

FTP to transFer it. Use VNC to flj


44 u ■ Turn* left-
def ■ Left():-
runpython3 3-driving.py 45


47
»
- ■ GPIO.output(pirtMQtorAFcirwards, ■ e)-
GPlO.outputtpinMotorABackwardSj. ■ 1)-

on the Raspberry Pi. The robot 4fl


iv-j -
GPIO.output{pinMotorBForwardsj■
GPIO.output^pinMotorBBackwards^ ■ B)-.
50
should move Forwards, rotate 51 #Turn-Right’.
Si T def ■ Right () I-
■ - • GPIO b out put{pinMotorAForwards^ ■ 1)-h
leFt, move Forwards again, sa
5fl ■ ■ 'GPI0.Qutput{pinWotoirABackwards* ■ 0)-
55 ■ GPIO.output<pinHotorBFcirwards, ■ 0)1

rotate right, move backwards se


» h
4. . . GPIO.output{pinMotorBBackwards>-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

n*5?ai 1 • • i ITF-gi t ^ LH4 •.- ; :'f ’ - 1,737 ■■

www.bdmpublications.com The Python Manual 149


Robots, Drones and Cool Python Projects

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.

ULTRASONIC AND LINE SENSING


Your robot has two sensors, an Ultrasonic and a Line Detector. The Ultrasonic is the one that looks like eyes and fits into the
breadboard. The Line Detector has a small blue camera on one side and fits underneath the robot.

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.

150 Black Dog i-Tech Series - Volume 35


Add Sensors to the Robot

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.

BUILDING THE CIRCUIT


You've started putting together the Circuit but now need to use the resistors and remaining cables. The resistor is used with
Echo because the sensor needs a +5v but the Raspberry Pi input only likes 3.3v. Be sure to check the resistors carefully.

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

Dist ance ■Ti 6


M

Dist anc i 95. 9


Distane^ 95. &

Distanee ; _7/4 1

Distanc^ 2
Distanee : 9
.

E _ls t anc ^ + 11C1.0n


i
Dist anc 23 5
Distanc-e : 96. _L
Distanee : Q-T
Distance ; 11. Q
Dist ane <5 : T fl r
Distanee : IX. 5
Distance 10 6
T
Distanee : 10 JL

Distance ; 12, T
Distance : 95. 4
Distance : 5E Q
Distanc® : 97 0
Distanoe ; 96.
Distance : Q o
O
Distance : 95 6

www.bdmpublications.com The Python Manual 151


| Robots, Drones and Cool Python Projects

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.

SERVOS AND CONTROLLERS


Robots use servo motors to move wheels etc. These require regular pulse signals to move to the right position, which the Raspberry
Pi isn't that great at sending. Most projects use a Pi alongside separate microcontrollers.

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.

More info: bit.ly/1 PMqqMt

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.

More info: bit.ly/1 PMqgEO

«i

152 Black Dog i-Tech Series - Volume 35


r Amazing Robotics Projects to Try
Radio frequency Identification GoPiGo is a popular robot car kit for Raspberry
RFID MUSIC ROBOT GOPIGO
W (RFID) uses electromagnetic fields _W Pi. The Starter Kit includes everything you
to transfer data and it's the technology used in contactless smart need to get started from scratch: a GoPiGo2 Base Kit, Raspberry Pi
cards. This RFID Music B+, Wi-Fi Dongle, GoPiGo Servo Package, Ultrasonic Sensor, micro
Robot plays music when SD Card, Power Supply and Ethernet Cable.
the right tag is held next Alternatively you can use the GoPiGo2 Base Kit
to it. It's a great looking and add your own components.
project and is also a nice
More info: bit.ly/1 RHjpT2
way to make something
using RFID technology.

More info: bit.ly/1 PMr4JM

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

www.bdmpublications.com The Python Manual 153


Robots, Drones and Cool Python Projects

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.

!Pyou want an upright display


RASPi TWO-PLAYER ARCADE COFFEE TABLE GALACTIC STARCADE
but don't have the space Por
IP you're looking to rebuild the classic arcade machine coPPee tables a Pull arcade machine cabinet then building a bartop is the way to
Prom yesteryear, then this project is a great one to PoLlow. It shows go. Bartops are mini arcade machines that sit on top oP a table. This
you how to place two arcade machine controllers and Pourteen project builds a bartop Prom MDF board and a 19-inch TFT monitor.
buttons inside a wooden case with a 20-inch monitor.
More info: instructables.com/id/2-Player-Bartop-Arcade-Machine-
More info: instructables.com/id/RasPi-Two-Player-Arcade-CoFPee- Powered-by-Pi/
Table/

We love this naked arcade machine known as


MULTI-CADE NaCADE
NaCade. it's much smallerand more portable
IP you want to build a classic than other arcade projects. The box is made Prom 3mm ciear acrylic
upright standing arcade and the display is a normal 7-inch LCD. The Controls are a regular
cabinet, then this project is arcade joystick and buttons. it's even solar powered. Who couldnt
the one to Pollow. It shows love a solar
you how to take apart an powered retro
old arcade machine cabinet arcade machine
and replace the insides with with all the insides
a Raspberry Pi. You can also on show?
make your own cabinet Prom
More info:
scratch and kits are available
instructables.com/
(arcadeworlduk.com).
id/NaCade-The-
More info: instructables.com/ Naked-Raspberry-
id/Mu Iti-Cade-Powered-by- Pi-Arcade-Machine/
Raspberry-Pi/

154 Black Dog i-Tech Series - Volume 35


(^Arcade Machine Projects

• • • «

PORTA-Pi MINI ARCADE ; The Porta-Pi is a mini ^ What makes this


BARTOP MINI RETRO ARCADE
W arcade machine with full _ W bartop special?
size Controls and micro switched buttons. It's more retro than most Well, it uses an old ION iCade cabinet (ionaudio.com) as its base;
micro machines, being these can be picked up
made Prom 0.25-inch on eBay for around £30.
oak plywood; others are An 8 inch display is fitted
typically made from acrylic instead of an iPad and the
or plastic. it's tiny but oozes Controls are wired up to
quality and we think it's a itvia USB. It's a lot easier
great project to than other similar projects
because you don't have to
More info: instructables.
build the cabinet.
com/id/Build-your-own-
Mini-Arcade-Cabinet-with- More info: instructables.
Raspberry-/ com/id/Bartop-Mini-Retro-
Arcade-Raspberry-Pi-and-
Customis/

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

them from Pi-Top. board (code.google.


The kit also uses a com/p/raspy-juice/). It's
Smart Battery Pack battery powered and
and Hub for power has a lot of additional
management. features. It's a great - ■ —_
package for Raspberry
More info: pi-top.com
Pion the move.
More info:
instructables.com/id/
LapPi-A-Raspberry-Pi-
Netbook/

ALL-IN-ONE WITH TOUCHSCREEN This is a smart ULTIMATE LAPTOP

More info: instructables.com/


id/The-Ultimate-Raspberry-Pi-
Laptop/

www.bdmpublications.com The Python Manual 155


Robots, Drones and Cool Python Projects

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.

MONITOR AND ALERT


The Raspberry Pi is a great device for spying and security. The Camera Module enables it to observe its surroundings and
networking allows you to get alerts when it spots something. There are some really interesting projects here.
*

Creating a networked security We love this project. You strap a Raspberry


EASY SECURITY CAM PiNOCULARS
W camera is one oP the best First W Pi 2 and Camera Module to a pair of
projects you can create. As its name suggests this is an easy project binoculars and use an Adafruit TFT LCD to view and take pictures.
that captures stili images and uploads them to a WebAPI Service. If It's a great guide too, leading you step-by-step through the project.
the network is down The end resuit is a high
then itcaches the tech pair of binoculars
images and uploads that can be used For long
them later. range image capture. The
project can be adapted
More info:
For a telescope
instructables.com/
or microscope.
id/Easy-Raspberry-Pi-
Security-Cam-With- More info: instructables.
Automatic-Web-/ com/id/PiNoculars-
Raspberry-Pi-Binoculars/

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/

156 Black Dog i-Tech Series - Volume 35


MOTION DETECTION ALARM SYSTEM . “ Want to keep an eye
SECRET INFRARED CAMERA
W on your place when
The computer can detect motion in many ways but the simplest youYe not at horne? Then the Secret Infrared Camera is a classic
is to use any USB webcam to detect motion in a room. This spy camera device that can record a room in complete darkness.
project is light on hardware but walksyou through using Reactive It will then send you messages when it detects any activity. You'll
Blocks (bitreactive. need a Raspberry Pi
com) to build Java NolR Camera Board
SE applications. (raspberrypi.org/
You don't need any products/pi-noir-
Java experience as camera/) and a PIR
everything is laid out sensor to detect
for you. movement.

More info: More info:


instructables.com/ instructables.com/
id/Motion-Detection- id/Make-a-secret-
Alarm-System/ IR-camera-security-
raspberry-pi-unit/

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.

Yaah, me hearties. The pirates stili be Recycling old technology with


PIRATEBOX 1981 P0RTABLE VCR
floating after all these years. While file modern innards is a great way
sharing online is a heartless task, this PirateBox creates a local Wi-Fi to build a quirky, cool but stili fully functional device. We think this
network completely independent from the Internet. This is then 1981 Portable VCR Project is great; it takes an old video-recorder
used with anonymous file sharing and chatting capabilities. So you and places the excellent Raspbmc Media Centre Software at its
can all share digital files locally, and it has a pretty nice case too. heart. It can then stream content like BBC iPlayer and YouTube or
play back media files.
More info:
instructables.com/ More info:
id/Raspberry-Pi- instructables.com/
PirateBox/ id/1981 -Portable-VCR-
Raspberry-PI-Media-
Centre/

Keeping children Just as old VCRs make great media


VIDEO PLAYER FOR CHILDREN ROBERTS 747
_ W occupiedisa players, classic radios make amazing
challenge but this project will keep them entertained and stealthily digital music boxes. This Roberts 747 is a classic radio from 1990
introduce them to computer hardware. This video player is based that has been transformed internally into a digital music player. It
around an ELI70-CR touchscreen and arcade buttons. The case is uses Pi MusicBox (pimusicbox.com) Software that supports Spotify,
made from laser cut parts and files for the case and Software are AirPlay and Internet Radio. You select tracks using a web browser
all included. __ from a smartphone
and it looks identical
More info:
to the original on
instructables.com/id/
the outside.
Raspberry-Pi-video-
player-for-Children/ More info:
instructables.com/

■n
id/Roberts-747-DIY-
Raspberry-Pi-internet-
radiostreame/

www.bdmpublications.com The Python Manual


Robots, Drones and Cool Python Projects

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.

Codecademy (codecademy.com) is a ^ You don't need to be a


CODECADEMY KHAN ACADEMY
good place to start. This website has mathematician to program.
interactive courses that walkyou through the process oP starting Programming is a mixture oP abstraction and word structure; in
code. It turns coding into a game, with points and rewards Por many ways it's closer to poetry than maths. Having said that, sooner
completion. Start with the HTML & CSS course, then move on to or later you might want to brush up on your maths skills. Khan
JavaScript or hone your Python skills. Academy (khanacademy.org; is the place to go.

wav khsnBcademy.org/
1 vw cottecademy com/leairPchoiceHanguaije

Icodelcademy

Recommended For You

□M JS

HTML & CSS JavaScript python


Learn how io create w&bsstes ic-v Leam rhe fundamcmals ol Leai n ro program n Python, a
ururtuimg drtil ^tyLing ywjr HavaScnpt. the pn^gramming puira-rlul tanquag? uwd by sHp-* Llke
with HTML and CSS. Language oi the Wet>, You Tube and Drodbox.

Vffiw Cijurs* Ovcrv-ew

Web Developer Skills


l earn l.rs huilrl pr me websites and appticatlOns 3S used hy rpal husir-sws.

i iv, cOTn/tra ckg/i ava srn ni <• rpsuma

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:

0 hlfp 0: The Sedup ►I ID Dfia>( ilplion / Tities S (11 v-! - 1 Ry


1: A Good First Program NEJtT
1 Multlples of 3 and r- 463257
2; CommentsAnd Hound Characters
2 Even Fibonacd numbers 360260
Numuers Mnlh
\
HELP
3 Larqest prime factor 276499
Varia bles n l
\

5; More Vanables And Prinlmg 1 Large it p ali n drome produci 249994


&: Strings And Texi
5 smaltest multiple 262506
o rv 7 More Printing
t Sum squate difterence 264324
8; Printing, Printing
9; Printing, Printing, Printing 7 10001 st prime 226578

10: What Was That? U Largesc product In a senes 197089


11 Askmg Que sudos
9 5pt*t lal Pythagoran eripiet 196412
12: Prompting Pe opi e
13: Parameters, Unpacking, Variables 10 Sumrnatlon of prlmes 100306

14: Promoti na And Passtna 11 .arge^T product In a grld 133914

158 Black Dog i-Tech Series - Volume 35


C Becoming a Coder

UDEMY.COM & LYNDA.COM “ Asyoustartto STACK OVERFLOW ^ Beyond thesitesweve


W progressyou may W mentioned so Par, there
want to move onto a more practical course. Both Udemy.com and are a huge list oP resources available online. This web page on
Lynda.com have a range of good tutorials on a range oP computing StackOverPlow (stackoverPlow.com/revisions/392926/175) collects
subjects. You have to pay For courses in Udemy, although they a huge list oP online computer books, programming tutorials and
oPten have Flash sales. Lynda.com has a wider range oP subjects but thought provoking articles. 97 Things Every Programmer Should
requires a monthly Pee. Both are great investments. Know is a good read (http://programmer.97things.oreilly.com/wiki/
r J
index.php/97_Things_Every_Programmer_Should_Know).
?* Jri . .1^ !> Ida .
t . nttp^WMVr :yndj lqffi

lyndo.com
m**1 WiUCKHiOvi-r jy,
— Hrnwt* itii' llfciiwy
Fittp jValacka wllo w ewvitv-viorti/aiiaSffih/175 m
! «q pii

New skills, Improved skills. Now


.eam technofogy. creailve and busfness skills you can use loday
l.. j stackwerftow

Ratum lo R «visioni

«faCid Mir 1 '12 k\ S: ]"■


^j ik4J|_V<.-d1iuf>« 'fliHi 04|*l11C»li^ htt£2 /. a. d 11 ‘J *ii m Ii
Wab 175 of 176 Ol and t-nfeiurl

Meifi-Llili

rt-.I.Ai «l.-MlifHj a II . .3nj

Became a OTiai Stetts >Fre?r


h [_--r 3 r f r pJk £ _£i 7.
momber
ft+fi T*eh t
* i '!■•■' ' r i ;uPli: ] (aiLJpr| ■ r il ■
Jry
Wcrw c o Dtswgn PrcnjfJWTi^ rfaaufrw- c«* uztr

Mkrosalt PWis f n» I -Pbofr

O‘Pfllt/4 DpenO&cHci PrCffiO.


hwwp Prsqram Miwwien

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.

www.bdmpublications.com The Python Manual 159


Robots, Drones and Cool Python Projects

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.

DeF High-Level Language


Used to define a function or method in Python. A programming language that's designed to be easy for people to read.

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.

160 Black Dog i-Tech Series - Volume 35


w
Glossary oF Terms

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.

Interactive Shell Random


The Python Shell, which is displayed wheneveryou launch the A Python module that implements a pseudo-random character
graphical version oP Python. generator using the Mersenne Twister PRNG.

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.

www.bdmpublications.com The Python Manual 161


To continue learning more about your tech visit us at:
www.bdmpublications.com

4^ Fof ALLGalsxySmartphMies STablets.

The SAMSUNG

Galaxy
Guidebook#
iswrt hov\ taget r hc masi fkxn your Samsufflj &j kxy

Print & digital editions «neM1


Pto«Ub 3.1

Featuring the very latest updates


Step-by-step tutorials and guides nr U/timate

Created by BDM experts 4 l.ivimustte


((kkAccfrWl
* Kd>?.i (l*d

ass
•,<**

4 CirrrMrtu' Itw- •*****¥«*>


Check out our latest tities today! ■ Disccfeff Tif*

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

^ The Complete The Complete r The Complete

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

Vd unf 25 tQtfc MDCPENDEKI IM*, INDEPDVOENT

The Complete The Complete The Complete

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

Photoshop Black & White Samsung Smartphones


Photography Galaxy & Tablets
For Seniors For Seniors For Seniors For Seniors For Seniors
Speciai 1
Large Print
v Edition

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.

Python Code Repository


This bookwill getyou upand running Once youVe mastered the finer points of Python
programming, and to help you in your quest for creating
with the latest version of Python in code, we7ve included a huge Python code repository.
Here you can snip sections out or even use the enti re
no time. Soon you'11 be learning how
code in your own programs. It's a valuable tool that will
to code and more importantly, how helpyou get the bestfrom Python and your code.
em

to apply that code to a real world


K
9
-m
M r
m
m m m
Iff
/
m
M m\
m
A

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.

You might also like