Nothing Special   »   [go: up one dir, main page]

BDM. Python Coding & Programming 12ed 2022

Download as pdf or txt
Download as pdf or txt
You are on page 1of 163
At a glance
Powered by AI
The manual provides tutorials and guides to help readers learn Python coding and programming from the basics through to more advanced concepts. It covers topics such as setting up Python, variables, functions, conditions and loops.

The manual covers topics such as setting up Python, variables, functions, conditions and loops, modules, graphics, and combining different coding concepts. It also has sections focusing on coding with Python on the Raspberry Pi and working with data types like lists, tuples and dictionaries.

The manual focuses on teaching Python, which is a widely used and versatile programming language that can be used for tasks like driving technological projects, analyzing large datasets, and creating artificial intelligence systems.

Hr BDM's Complete

« Manual Series ©

Python
Coding & Programming
The essential step-by-step manual to improving

www.bdmpublications.com 100% I NDEPEN DEI\T


Discover Windows 11
Black Dog Media
Learn New Features www.bdmpublications.corn

Master Your Desktop


NEW
PRINT
EDITION
all about
о Windows 11 Over 250 Pages of
Expert Tutorials,
Guides & Tips!

FEATURED INSIDE
■ Navigating the Start Menu
■ Connecting to the Internet
■ How to personalise Windows 11
■ Web browsing with Edge
■ Using OneDrive Cloud Storage
■ Video chatting with Skype
■ Email, Social Media & Messaging
LEARN MASTER ■ Improving Windows 11 security
discover
Get to grips with
Expert tutorials on
Improve your ■ Wi-fi and Personal wi-fi hotspots
knowledge base,
protecting your
all the essential
personal data from
gain newskillsand ■ Speeding up your computer
core features, apps build confidence
hackers and viruses
and functionality ■ Troubleshooting & User Advice
Black Dog Media and much more...
4^ 100% Independent

Click the link to BUY NOW from amazon


https://amzn.to/3EZFHKC
Available in all good bookshops
•м, BDM's Complete
" Manual Series Ф

Python
Coding & Programming

Unlock your imagination with Python...


There are few coding languages that have enjoyed the success of
Python. Thanks to Python’s unique development, everyone can learn
the code that is: helping to drive such technological projects as the
Large Hadron Collider, collating the petabytes of data that made up the
first image of a Black Hole and creating the next generation of Artificial
Intelligence. It doesn’t take long to get to grips with Python, but you
need to start small. This guide will help you form the foundation of your
Python coding future, from installing the language on to your computer,
through to forming user interaction and complex variables. There’s so
much you can do with Python and within these pages you’ll find every­
thing you need to know to become a Python programmer, ready for the
next level of advanced coding.

Whether you’re looking to learn Python for future career prospects,


or just have some fun and discover something new, our step-by-step
—гцилвг tutorials and guides will give you that much-needed foothold to help
_ aoctJrr □ s у о u о n у о u r way.
r aqrai
■ - So let’s dive in and start coding with Python.
апйЯ
Contents

Getting Started
Being a Programmer Why Python?
A Brief History of Coding Python on the Pi
What can You Do with Python? Using Virtual Machines
Python in Numbers Creating a Coding Platform

Hello World
26 Equipment You Will Need 44 Using Comments
28 Getting to Know Python 46 Working with Variables
30 How to Set Up Python in Windows 48 User Input
32 How to Set Up Python in Linux 50 Creating Functions
34 Starting Python for the First Time 52 Conditions and Loops
36 Your First Code 54 Python Modules
38 Saving and Executing Your Code 56 Python Errors
40 Executing Code from the 58 Combining What You Know So Far
Command Line
60 Python in Focus: Stitching
42 Numbers and Expressions Black Holes

Working with Data


64 Lists 76 Opening Files
66 Tuples 78 Writing to Files
68 Dictionaries 80 Exceptions
70 Splitting and Joining Strings 82 Python Graphics
72 Formatting Strings 84 Combining What You Know So Far
74 Date and Time 86 Python in Focus: Gaming

О %
a □
N • Й
j
V 5 ' 1
L
□ s f Л1
m
www.bj^np JtJtication^So
F и t W °ii i
В И d T 3 x]
и □ 6)

aо □
n fl T % aг
- V z j Й - И @ □ В d [ и- ci ~ Z “ — fl
[ ~ / ki x P т ' KI Я a В a A :
la Й 6Z
□ N U0 И
»*1 Й 7 Г \ 3 Й vi z
4 I u й И 0 u ... pj m nJ
= " #и /, e°M?cociot/t
Master Python
with the help of our
Fantastic Code Portal,
Visit-httn C°^e Featuring code For
^pubii^ttps://
games, tools and more.
L. Code-₽or°JCO,n/

Using Modules
90 Calendar Module 100 Pygame Module
92 OS Module 104 Basic Animation
94 Using the Math Module 106 Create Your Own Modules
96 Random Module 108 Python in Focus:
98 Tkinter Module Artificial Intelligence

Code Repository
112 Python File Manager 124 Vertically Scrolling Text
114 Number Guessing Game 126 Python Digital Clock
116 Random Number Generator 128 Playing Music with the Winsound
117 Random Password Generator Module
118 Text to Binary Convertor 130 Text Adventure Script
120 Basic GUI File Browser 132 Python Scrolling Ticker Script
122 Mouse Controlled Turtle 133 Simple Python Calculator
123 Python Alarm Clock 134 Hangman Game Script

Understanding Linux 136


138 What is Linux? 150 Useful System and
Disk Commands
140 Using the Filesystem
152 Using the Man Pages
142 Listing and Moving Files
154 Editing Text Files
144 Creating and Deleting Files
156 Linux Tips and Tricks
146 Create and Remove Directories
158 A-Z of Linux Commands
148 Copying, Moving and
Renaming Files 160 Glossary of Python Terms
Index

Getting
Started
opera

*.^’.irror

ill(cU, con
‘turn

!5_mirrPr object to
■lrrorj»<l.,ipr<lr ,

.operation =-
■irror no-j

www.bdmpublications.com
Getting Started

Python is a high-level, general-purpose


programming language that was
developed by Guido van Rossum in the
late eighties and is based upon a number
of other languages, while being the
successor to the popular ABC language.
It has been devised to work on a human
level, so it's readable and understandable
without needing to delve into obscure
volumes of machine code, hexadecimal
characters, or even ones and zeros. It's
clear, logical, comprehensive, powerful
and functional, yet also easy to follow
and learn.

You will find Python at the heart of some


of the most interesting and cutting-edge
technologies in the world. It's the code
that binds supercomputer algorithms
together; it's used in the space industry,
and in science and engineering. Al, and
the likes of Alexa and Siri, Cortana and
the Google Assistant all utilise Python for
their powerful voice recognition
technology. It's simply an amazing,
versatile and incredible language to learn.

So let’s get started and explore what you


need to become a Python programmer.

8 Being a Programmer
10 A Brief History of Coding
12 What can You Do with Python?
14 Python in Numbers
16 Why Python?
18 Python on the Pi
20 Using Virtual Machines
22 Creating a Coding Platform

www.bdmpublications.com
Getting Started

Being a Programmer
Programmer, developer, coder, they're all titles for the same occupation, someone who
creates code. What they're creating the code for can be anything from a video game
to a critical element on-board the International Space Station. How do you become a
programmer though?
Being a Programmer

MORE THAN CODE


For those of you old enough to remember the '80s, the golden era of home
computing, the world of computing was a very different scene to how it is
today. 8-bit computers that you could purchase as a whole, as opposed to
being in kit form and you having to solder the parts together, were the stuff
of dreams; and getting your hands on one was sheer bliss contained within
a large plastic box. However, it wasn't so much the new technology that
computers then offered, moreover it was the fact that for the first time
ever, you could control what was being viewed on the ’television’.

Instead of simply playing one of the thousands of games available at the


Times have changed since programming in the '80s, time, many users decided they wanted to create their own content, their
but the core values still remain. own games; or simply something that could help them with their homework
or home finances. The simplicity of the 8-bit home computer meant that
creating something from a few lines of BASIC code was achievable and so

It's up to you the first generation of home-bred programmer was born.

From that point on, programming expanded exponentially. It wasn't long

how far to take before the bedroom coder was a thing of the past and huge teams of
designers, coders, artists and musicians were involved in making a single
game. This of course led to the programmer becoming more than simply

your coding someone who could fashion a sprite on the screen and make it move at the
press of a key.

adventure!" Naturally, time has moved on and with it the technology that we use.
However, the fundamentals of programming remain the same; but what
exactly does it take to be a programmer?
#include< stdio.h>
#include<dos.h>
#include<stdlib.h>
The single most common trait of any programmer, regardless of what
#include<conio.h>
void getup()
they're doing, is the ability to see a logical pattern. By this we mean
{ someone who can logically follow something from start to finish and
textcolor(BLACK);
textbackground(15); envisage the intended outcome. While you may not feel you're such a
clrscr();
window(10,2,70,3); person, it is possible to train your brain into this way of thinking. Yes, it
cprintf("Press X to Exit, Press Space to 3ump");
window(62,2,80,3); takes time but once you start to think in this particular way you will be able
cprintf("SCORE : ");
window(l,25,80,25); to construct and follow code.
for(int x=0;x<79;x++)
cprintf("n");
textcolor(0);
Second to logic is an understanding of mathematics. You don't have to be
int t,speed=40; ata genius level but you do need to understand the rudiments of maths.
void ds(int jump=0)
< Maths is all about being able to solve a problem and code mostly falls under
static int a=l;
the umbrella of mathematics.
if(jump==0)
t=0;
else if(jump==2)
t—; Being able to see the big picture is certainly beneficial for the modern
else t++;
window(2,15-t,18,25); programmer. Undoubtedly, as a programmer, you will be part of a team
cprintf(" “);
cprintf(" млпллллм"); of other programmers, and more than likely part of an even bigger team
cprintf(" лллллллл");
cprintf(" лллллппп"); of designers, all of whom are creating a final product. While you may only
cprintf(" л МЛЛЛЛППП ");
cprintf(" ллм мллллллммм "); be expected to create a small element of that final product, being able to
cprintf(" пллллллллллл n “);
cprintf(" плллллллп “); understand what everyone else is doing will help you create something
if(jump==l || jump==2){
cprintf(" ллп пл ”); that's ultimately better than simply being locked in your own coding cubicle.
cprintf(“ лм лм “);
}else if(a==l)
<
cprintf(" пллп non "); Finally, there’s also a level of creativity needed to be a good programmer.
cprintf(“ лм ");
a=2; Again though, you don’t need to be a creative genius, just have the
}
else if(a==2) imagination to be able to see the end product and how the user will interact
<
cprintf(" плм пл “); with it.
cprintf(" лм ");
a=l;
}
cprintf(" “); There is of course a lot more involved in being a programmer, including
delay(speed);
learning the actual code itself. However, with time, patience and the
void obj()
determination to learn, anyone can become a programmer. Whether
Being able to Follow a logical pattern and you want to be part of a triple-A video game team or simply create an
see an end result is one of the most valued automated routine to make your computing life easier, it's up to you how
skills of a programmer. far to take your coding adventure!

www.bdmpublications.com
Getting Started

A Brief History of Coding


It's easy to think that programming a machine to automate a process, or calculate a value,
is a modern concept that's only really happened in the last fifty years or so. However, that
assumption is quite wrong, coding has actually been around for quite some time.

01000011 01101111 01100100 01101001 0110111001100111


Essentially all forms of coding are made up of ones and zeros - on or off states. This works
for both a modern computer and even the oldest known computational device.

1
It's difficult to pinpoint an exact
start of when humans began to
'program1 a device. However,
it's widely accepted that the
Antikythera Mechanism is possibly
the first 'coded' artefact. It's Joseph Marie Jacquard invents a
dated to about 87 BC and is an programmable loom, which used cards with
ancient Greek analogue computer punched holes to create the textile design.
and orrery used to predict However, it is thought that he based his
astronomical positions. design on a previous automated weaving
process from 1725, by Basile Bouchon.

Ada Lovelace translated


the memoirs of the Italian
mathematician, Francis
Maneclang, regarding
Charles Babbage's
Analytical Engine. She
made copious notes within
her writing, detailing a
The Banu Musa brothers, three Persian
method of calculating
scholars who worked in the House of
Bernoulli Numbers
Wisdom in Baghdad, published the
using the engine. This is
Book of Ingenious Devices in around
recognised as the first
850 AD. Among the inventions listed
computer program. Not
was a mechanical musical instrument:
bad, considering there
a hydro-powered organ that played
were no computers
interchangeable cylinders automatically.
available at the time.

10 www.bdmpublications.com
During the Second World From the 1970s, the development of the likes of C, SQL, C with
War, significant advances Classes (C++), MATLAB, Common Lisp and more, came to the
were made in programmable fore. The '80s was undoubtedly the golden age of the home
machines. Most notably, the computer, a time when silicon processors were cheap enough for
cryptographic machines used ordinary folk to buy. This led to a boom in home/bedroom coders
to decipher military codes with the rise of 8-bit machines.
used by the Nazis. The Enigma
was invented by the German
engineer Arthur Scherbius,
but was made famous by Alan
Turing at Bletchley Park's
codebreaking centre.

1970-1985 1990s-Present Day

Computer programming
was mainly utilised by
universities, the military and
ABAp о
Visual Basic <£ Logo '•>
big corporations during the ’60s ErlangC#D$ ^Transact-SQL
ML й ФРго|оа ф
_. . £ Prolog ф ColdFusion
Cianon u- L S' * Forth
and the '70s. A notable step JavaScript p/SE."
S| PybhOncs
Ass^blgScraW,
l 3. ><
§ g-PL/JJQL
toward a more user-friendly, 5Г * Ada
JOHaskellqpf ® igk. Lua
Io Yacc
or home user, language was
the development of BASIC dayd Dart | cj ® о? I у
SAS|H|J-«sp|CC
rascal
Swrft
(Beginners All-purpose
Symbolic Instruction Code) in
the mid-sixties.

10 INPUT "What is your name: U$


20 PRINT "Hello U$
25 REM
30 INPUT "How many stars do you want: N
The Internet age brought a wealth of new
35 5$ = ""
40 FOR I = 1 TO N
programming languages and allowed
50
55
5$ = 5$ + "
NEXT I
*
people access to the tools and knowledge
60
65
PRINT 3$
REM
needed to learn coding in a better way.
70
80
INPUT "Do you want more stars?
IF LEN(A$) = 0 THEN GOTO 70
AS
Not only could a user learn how to code,
90
100
AS = LEFTS 1)
IF (AS = "Y") OR (AS = "У") THEN GOTO 30
they could also freely share their code and
110
120
PRINT "Goodbye
FOR I = 1 TO 200
source other code to improve their own.
130 PRINT US; "
140 NEXT I
150 PRINT____________________________________________

The first true computer code was


Assembly Language (ASM) or
Regional Assembly Language. ASM Admiral Grace Hopper was part of
was specific to the architecture the team that developed the UNIVAC
of the machine on which it was I computer and she eventually
being used. In 1951, programming developed a compiler for it. In time,
languages fell under the generic the compiler she developed became
term Autocode. Soon languages COBOL (Common Business-oriented
such as IPL, FORTRAN and ALGOL Language), a computer language that's
58 were developed. still in use today.

www.bdmpublications.com 11
Getting Started

What can You


Do with Python?
Python is an open-source, object-oriented programming language that's simple
to understand and write, yet also powerful and extremely malleable. It's these
characteristics that help make it such an important language to learn.

Python's ability to create highly readable code within a small set find lots of examples of this, where Python is acting behind the
of instructions has a considerable impact on our modern digital scenes. This is why it’s such an important language to learn.
world. From the ideal, first programmers' choice to its ability to
create interactive stories and games; from scientific applications to Beautiful is better than ugly.
artificial Intelligence and web-based applications, the only limit to Explicit is better than implicit.
Simple is better than complex.
Python is the imagination of the person coding in it. Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
It's Python's malleable design that makes it an ideal language for Special cases aren't special enough to break the rules.
many different situations and roles. Even certain aspects of the Although practicality beats purity.
Errors should never pass silently.
coding world, that require more efficient code, still use Python. Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
For example, NASA utilises Python both as a stand-alone language There should be one— and preferably only one —obvious way to do it.
and as a bridge between other programming languages. This way, Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
NASA scientists and engineers are able to get to the data they Although never is often better than ‘right
* now.
If the implementation is hard to explain. It's a bad idea.
need without having to cross multiple language barriers; Python If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let's do more of those!
fills the gaps and provides the means to get the job done. You'll

BIC DATA

Big data is a buzzword you’re likely to have come across in the last couple of years.
Basically, it means extremely large data sets that are available for analysis to reveal
patterns, trends and interactions between humans, society and technology. Of course,
it's not just limited to those areas, big data is currently being used in a variety of
industries, from social media to health and welfare, engineering to space exploration
and beyond.

Python plays a substantial role in the world of big data. It's extensively used to analyse
huge chunks of the available big data and extract specific information based on
what the user/company requires from the wealth of numbers present. Thanks to an
impressive set of data processing libraries, Python makes the act of getting to the data,
in amongst the numbers, that counts and presenting it in a fashion that's readable and
useable for humans.

There are countless libraries and freely available modules that enable fast, secure and
more importantly, accurate processing of data from the likes of supercomputing clusters.
For example, CERN uses a custom Python module to help analyse the 600 million
collisions per second that the Large Hadron Collider (LHC) produces. A different language
handles the raw data, but Python is present to help sift through the data so scientists
can get to the content they want without the need to learn a far more complex
programming language.

12 www.bdmpublications.com
What can You Do with Python? I

ARTIFICIAL INTELLIGENCE

Artificial Intelligence and Machine Learning are two of the


most groundbreaking aspects of modern computing. Al is the
umbrella term used for any computing process wherein the
machine is doing something intelligent, working and reacting
in similar ways to humans. Machine Learning is a subset of Al
and provides the overall Al system with the ability to learn
from its experiences.

However, Al isn't simply the creation of autonomous robots


intent on wiping out human civilisation. Indeed, Al can be
found in a variety of day-to-day computing applications where
the 'machine', or more accurately the code, needs to learn
from the actions of some form of input and anticipate what
the input is likely to require, or do, next.

This model can be applied to Facebook, Google, Twitter,


Instagram and so on. Have you ever looked up a celebrity on
Instagram and then discovered that your searches within other
social media platforms are now specifically targeted toward
similar celebrities? This is a prime example of using Al in
targeted advertising and behind the code and algorithms that
predict what you're looking for, is Python. GAMING

Spotify, for example, uses Python based code, among Although you won't find too many triple-A rated games coded using
other things, to analyse your musical habits and Python, you may be surprised to learn that Python is used as an
offer playlists based on what you've listened to extra on many of the high-ranking modern games.
in the past. It's all clever stuff and, moving
forward, Python is at the forefront of the way The main use of Python in gaming comes in the form of scripting,
the Internet will work in the future. where a Python script can add customisations to the core game
engine. Many map editors are Python compatible and you will also
come across it if you build any mods for games, such as The Sims.

A lot of the online, MMORPG (Massively Multiplayer Online Role-


Playing Game) games available utilise Python as a companion
WEB DEVELOPMENT
language for the server-side elements. These include: code to
search for potential cheating, load balancing across the game's
Web development has moved on considerably since the early
servers, player skill matchmaking and to check whether the player's
days of HTML scripting in a limited text editor. The many
client-side game matches the server's versions. There's also a
frameworks and web management services available now
Python module that can be included in a Minecraft server, enabling
means that building a page has become increasingly complex.
the server admin to add blocks, send messagesand automate a lot
of the background complexities of the game.
With Python, the web developer has the ability to create
dynamic and highly secure web apps, enabling interaction with
other web servicesand apps such as Instagram and Pinterest.
Python also allows the collection of data from other websites
and even apps built within other websites.

As you can see, Python is quite a versatile


programming language. By learning Python,
you are creating a well-rounded skillset that's
able to take you into the next generation of
computing, either professionally or simply as
a hobbyist.

Whatever route you decide to take on your


coding journey, you will do well to have
<code> Python in your corner.

www.bdmpublications.com 13
Getting Started

’>Ossu">"n2atOrCui<lo V
There's a
lot to like about {0
Python, but don't just
take our word for it. Here are
some amazing facts and figures
surrounding one of the most popular
programming languages of recent years.

Alexa, Amazon's Virtual Data analysis and


Personal Assistant, uses Machine Learning are the
Python to help with two most used Python
speech recognition. examples.
s

PYTHON AND
2018
N umbers

LINUX SKILLS
As of the end of 2018,
ARE THE THIRD Disney Pixar uses Python
Python was the most MOST POPULAR in its Renderman software
discussed language on I.T. SKILLS IN to operate between other
the Internet. graphics packages.
THE UK.

OVER 75% OF 90% OF ALL IT'S ESTIMATED


RECOMMENDED FACEBOOK POSTS THAT OVER 75% OF
CONTENT FROM NETFLIX ARE FILTERED NASA'S WORKFLOW
IS GENERATED FROM THROUGH PYTHON- AUTOMATION
MACHINE LEARNING - CODED MACHINE SYSTEMS ON-BOARD
CODED BY PYTHON. LEARNING. THE I.S.S. USE PYTHON

www.bdmpublications.com
Python in Numbers

-PYTHON SKILL-BASED
16,000 POSITIONS ARE THE

ttttffff
titittfi
There are over 16,000 Python jobs
16th
MOST SOUGHT-AFTER
posted every six months in the UK. JOBS IN THE UK.

Python Data Science is Google is the top Data Science, Blockchain New York and San
thought to become the company for hiring Python and Machine Learning Francisco are the top
most sought-after job in developers, closely are the Fastest growing Python developer cities
the coming years. Followed by Microsoft. Python coding skills. in the world.

Python developers enjoy an average salary of

£60,000

95% OF ALL BEGINNER 75% OF ALL PYTHON 79% OF ALL 49% OF WINDOWS
CODERS START WITH DEVELOPERS USE PROGRAMMERS USE 10 DEVELOPERS
AND STILL USE, PYTHON 3, WHEREAS PYTHON ON A DAY-TO- USE PYTHON 3
PYTHON AS THEIR 25% STILL USE THE DAY BASIS, 21% USE AS THEIR MAIN
PRIMARY OR OUTDATED PYTHON 2 IT AS A SECONDARY PROGRAMMING
SECONDARY LANGUAGE. VERSION. LANGUAGE. LANGUAGE.

www.bdmpublications.com
Getting Started

Why Python?
There are many different programming languages available for the modern computer,
and some still 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 of programming carved their way into a new Regardless of whether you use an Android device, iOS device, PC,
frontier, forging small routines that enabled the letter 'A' to scroll 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-definition graphics and open world, multi­ appliances, behind them all is programming.
player online gaming. However, forty-something years ago it was
blindingly brilliant. All those aforementioned digital devices need instructions to tell
them what to do, and allow them to be interacted with. These
Naturally these bedroom coders helped form the foundations for instructions form the programming core of the device and that core
every piece of digital technology we use today. Some went on to can be built using a variety of programming languages.
become chief developers for top software companies, whereas
others pushed the available hardware to its limits and founded the The languages in use today differ depending on the situation, the
billion pound gaming empire that continually amazes us. platform, the device's use and how the device will interact with its

Bombs - GUI - ThelDE - [d:\uppsrc\CtrlLib\ArrayCtrl.cppwindows-1252] { examples }


File Edit Macro Project Build Debug Assist Setup Ln 639, Col 45
X 4» ® |sui у I pVMSCZlcdb Debuc v ®S %, l«j e # ?> П ©

Bombs ® plugin/bmp Setcursor(p.y);


® CtrlLib §Jplugin\z Ctrl::ChildGotFocus();
® CtrlCore ® plugin\png
5§RichText (ШЭ <prj-aux>
® PdfDraw ЕЭ <ide-aux> void ArrayCtrl::ChildLostFocus()
® Draw Ю <temp-aux> {
® Core if(cursor >= 0)
RefreshRow(cursor);
Ctrl::ChildLostFocus();
ft EditCtrl.h C AKeys.cpp
C EditField.cpp # RichText.h
ft TextEdit.h C RichTextView.cpp void ArrayCtrl::Paint(Draw& w) {
C Text.cpp C Prompt.cpp LTIMINGf"Paint");
C LineEdit.cpp C Help,cpp Size size = GetSizeO;
C DocEdit.cpp # DateTimeCtrl.h Rect r;
ft ScrollBar.h О DateTimeCtrl.cpp r.bottom = 0;
bool hasfocus = HasFocusDeep();
C ScrollBar.cpp o Bar
int i = GetLineAt(sb);
ft HeaderCtrl.h # Bar.h
int xs = - header.GetScrolK);
C HeaderCtrl.cpp C Bar.cpp int js;
ft ArrayCtrl. h О MenuBar.cpp for(js =0; js < column.GetCount0; js++) {
C ArrayCtrl, cpp C ToolBar.cpp int cw = header.GetTabWidth(js) ;
ft DropChoice.h C ToolTip.cpp if ( ( xs + cw - vertgrid + (js == column.GetCount() D) >= 0) 1 0
C DropBox.cpp # StatusBar.h break;
C DropList.cpp C StatusBar.cpp xs += cw; 1
C DropPusher. cpp o Tabctrl } 1 1
C DropChoice.cpp # TabCtrl.h Color fc = Blend(SColorDisabled, SColorPaper);
0 ft StaticCtrl.h C Tabctrl.cpp if(!IsNull(i))
while (i < GetCount 0) {
0
C Static.cpp (^■TreeCtrl
0
ft Splitter.h # TreeCtrl.h r.top = GetLineY(i) - sb;
C Splitter.cpp C TreeCtrl.cpp if(r.top > size.cy) break;
r.bottom = r.top + GetLineCy(i);
О FrameSplitter.cpp
ft SliderCtrl.h
(^■DlgColor
# DlgColor.h
int x = xs;
for(int j = js; j < column.GetCount0; j++) {
о 0
О SliderCtrl.cpp C DlgColor.cpp int cw = header.GetTabWidth(j);
0 1
ft ColumnList.h C ColorPopup.cpp
0 1 О ColumnList.cpp О ColorPusher.cpp
int cm = columntj].margin;
if(cm < 0)
0 0
ft Progress.h 3> FileSel cm = header .Tab(j) .GetMarginO ; 1 0
C Progress.cpp ft FileSel.h size.ex) break;
0 1 1 ft AKeys.h C FileList.cpp
if(x >
r.left = x; 0
0 о 1 1ГТ0 10,0 0 о 0 0 ) о i 0 1 0 1 о 1 о о и 0 0 0 11 1
1 о 0'1 1 0 о о о 1 1111 0 10 1 0 110 11
b<^yipt|bli(^tions.(gm 1 1
0 0 0 0 0 0 1 1110 0 0 10 1 0 0 0 11
11110 0 0 о о 1 0 « 0 о 0 о 0 о 0 1 1 1 1 1 1 o 0 0 1 1 1001001
Why Python?

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 beginner's 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 languages 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. They're Python is free to download, install and use and is available for Linux,
widely used across all 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- languages 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 of arrays, learn, exceptionally powerful, universally accepted, effective and a
variables, objects, arithmetic, subroutines, loops and 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 4.0 LET py=15
70 FOR W=1 TO 10
and easy to learn. 71 CLS
75 LET by=INT (RND+28)
80 LET bX=0
1 [//file: invoke.java 90 FOR d=l TO 20
2 import * ;java.lang.reflect. 100 PRINT AT px,py;" и "
3 110 PRINT AT bx,by;"o"
4 class Invoke { 120 IF INKEY$="p" THEN LET py=p
5 public static void main( string [] args ) { У +1
6 try { 130 IF INKEY$="O" THEN LET py=p
У -1 u
7 Class c = Class.forNamef argsfO] ); 135 FOR П=1 TO 100: NEXT П
8 Method m = c.getMethodf argsfl], new Class 14-0 IF py<2 THEN LET py=2
□ { } ); 150 IF py>27 THEN LET py=27
9 object ret = m.invoked null, null ); 180 LET bX=bX+l
10 system.out.pri ntln( 185 PRINT AT bX-l,by;" "
11 "Invoked static method: " + args[l] 190 NEXT d
12 + " of class: " + argsfO] 200 IF (by-l)=py THEN LET S=S+1
13 + " with no args\nResults: " + ret ); 210 PRINT AT 10,10;"score=";s
14 } catch ( classNotFoundException e ) { 220 FOR V=1 TO 1000: NEXT V
300 NEXT W
15 // Class.forName( ) can't find the class
16 } catch ( NoSuchMethodException e2 ) { 0 OK, 0:1
17 // that method doesn't exist
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.pri ntln( print(HANGMAN[0])
attempts = len(HANGMAN) - 1
23 "Method threw an: " + e4.
getTargetExceptiond ) );
24 while (attempts != 0 and in word guessed):
25 print(("\nYou have {} attempts remaining”).format(attempts))
joined_word = "".join(word_guessed)
26 print(joined_word)

try:
Java is a powerful
player_guess = str(input(”\nPlease select a letter between A-Z” + “\n> ”)).
language that's used in except: # check valid input
print(’’That is not valid input. Please try again.”)
web pages, set-top boxes, continue
else:
TVs and even cars. if not player_guess.isalpha(): й check the input is a letter. Also checks a
print(”That is not a letter. Please try again.”)
continue
elif len(player_guess) > 1: # check the input is only one letter
print("That is more than one letter. Please try again.”)
continue
elif player_guess in guessed_letters: # check it letter hasn't been guessed
print("You have already guessed that letter. Please try again.”)
continue
else:
pass

guessed_letters.append(player_guess)

for letter in range(len(chosen_word)):


if player_guess == chosen_word [letter]:
word_guessed[letter] = player_guess # replace all letters in the chosen

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

Python on the Pi
If you're considering on which platform to install and use Python, then give some
thought to one of the best coding bases available: the Raspberry Pi. The Pi has many
advantages for the coder: it's cheap, easy to use, and extraordinarily flexible.

THE POWER OF PI
While having a far more powerful coding platform on which to write and test your code is ideal, it's not often feasible. Most of
us are unable to jump into a several hundred-pound investment when we're starting off and this is where the Raspberry Pi can
help out.

While having a far more powerful coding platform on which to kits available will provide the Pi with a pre-loaded SD card (with the
write and test your code is ideal, it's not often feasible. Most of us latest Raspbian OS), a case, power socket and cables, this is a good
are unable to jump into a several hundred-pound investment when idea as you could, with very little effort, leave the Pi plugged into the
we're starting off and this is where the Raspberry Pi can help out. wall under a desk, while still being able to connect to it and code.

The Raspberry Pi is a fantastic piece of modern hardware that The main advantage is, oF course, the extra content that the
has created, or rather re-created, the fascination we once all had Raspberry Pi Foundation has included out of the box. The reason
about computers, how they work, how to code and foundation for this is that the Raspberry Pi’s goal is to help educate the
level electronics. Thanks to its unique mix of hardware and custom user, whether that’s coding, electronics, or some other aspect oF
software, it has proved itself to be an amazing platform on which to computing. To achieve that goal the Pi Foundation includes diFFerent
learn how to code; specifically, using Python. IDEs For the user to compile Python code on; as well as both Python
2 and Python 3, there's even a Python library that allows you to
While you're able, with ease, to use the Raspberry Pi to learn to communicate with MinecraFt.
code with other programming languages, it's Python that has been
firmly pushed to the forefront. The Raspberry Pi uses Raspbian as There are other advantages, such as being able to combine Python
its recommended, default operating system. Raspbian is a Linux code with Scratch (an Object-Oriented programming language
OS, or to be more accurate, it's a Debian-based distribution of developed by MIT, For children to understand how coding works) and
Linux. This means that there's already a built-in element of Python being able to code the GPIO connection on the Pi to Further control
programming, as opposed to a fresh installation of Windows 10, any attached robotics or electronics projects. Raspbian also includes
which has no Python-specific base. However, the Raspberry Pi a Sense HAT Emulator (a HAT is a hardware attached piece oF
Foundation has gone the extra mile to include a vast range of circuitry that oFFers diFFerent electronics, robotics and motorisation
Python modules, extensions and even examples, out of the box. projects to the Pi), which can be accessed via Python code.
So, essentially, all you need to do is buy a Raspberry Pi, follow the
instructions on how to set one up (by using one of our excellent Consequently, the Raspberry Pi is an excellent coding base, as well
Raspberry Pi guides found at www.bdmpublications.com) and you as a superb project Foundation. It is For these, and many other,
can start coding with Python as soon as the desktop has loaded. reasons we've used the Raspberry Pi as our main Python codebase
throughout this title. While the code is written and performed on a
Significantly, there's a lot more to the Raspberry Pi, which makes Pi, you're also able to use it in Windows, other versions oF Linux and
it an excellent choice for someone who is starting to learn how to macOS. IF the code requires a speciFic operating system, then, don't
code in Python. The Pi is remarkably easy to set up as a headless worry; we will let you know in the text.
node. This means that, with a Few tweaks here and there, you’re able
to remotely connect to the Raspberry Pi From any other computer,
Everything you need to learn to code with Python is
or device, on your home network. For example, once you've set up
included with the OS!
the remote connectivity options, you can simply plug the Pi into the
power socket anywhere in your house within range oF your wireless
router. As long as the Pi is connected, you will be able to remotely
access the desktop From Windows or macOS as easily as iFyou were
sitting in Front oF the Pi with a keyboard and mouse.

Using this method saves a lot oF money, as you don't need another
keyboard, mouse and monitor, plus, you won’t need to allocate
suFFicient space to accommodate those extras either. IFyouTe pushed
For space and money, then For around £60, buying one oF the many

18 www.bdmpublications.com
Python on the Pi

PI 4-EVER!

Introduced on 24th June 2019, the Raspberry Pi 4 Model В is


a significant leap in terms of Pi performance and hardware
specifications. It was also one of the quickest models, aside from the of USB 3.0 ports, Bluetooth 5.0, and a GPU that's capable of handing
original Pi, to sell out. 4K resolutions and OpenGL ES 3.0 graphics.

With a new 1,5GHz, 64-bit, quad-core ARM Cortex-A72 processor, and In short, the Pi 4 is the most powerful of the current Raspberry Pi
a choice of 1GB, 2GB, or 4GB memory versions, the Pi 4 is one-step models. However, the different memory versions have an increased
closer to becoming a true desktop computer. In addition, the Pi 4 was cost. The 1 GB version costs £34,2GB is £44, and the 4GB version will
launched with the startling decision to include dual-monitor support, set you back £54. Remember to also factor in one or two micro-HDMI
in the form of a pair of two micro-HDMI ports. You’ll also find a pair cables with your order.

RASPBIAN BUSTER

In addition to releasing the Pi 4, the Raspberry Pi team also compiled


a new version of the Raspbian operating system, codenamed Buster.

In conjunction with the new hardware the Pi 4 boasts, Buster does


offer a few updates. Although on the whole it's very similar in
appearance and operation to the previous version of Raspbian. The
updates are mainly in-line with the 4K's display and playback, giving the
Pi 4 a new set of graphical drivers and performance enhancements.

In short, what you see in this book will work with the Raspberry Pi
4 and Raspbian Buster!

Once set up, you can remotely connect to the Pi's desktop Уои can even test connected hardware with Python
from any device/PC.
Ф remotely, via Windows.

www.bdmpublications.com 19
Getting Started

Using Virtual Machines


A Virtual Machine allows you to run an entire operating system from within an app
on your desktop. This way, you're able to host multiple systems in a secure, safe and
isolated environment. In short, it's an ideal way to code.

Sounds good, but what exactly is a Virtual Machine (VM) and


how does it work?
The official definition of a virtual machine is 'an efficient, isolated
duplicate of a real computer machine'. This basically means that a
virtual machine is an emulated computer system that can operate in
exactly the same way as a physical machine, but within the confines
of a dedicated virtual machine operator, or Hypervisor.

The Hypervisor itself, is an app that will allow you to install a


separate operating system, creating a virtual computer system
within itself, complete with access to the Internet, your home
network and so on.

The Hypervisor will take resources from the host system - your
physical computer, to create the virtual computer. This means that
part of your physical computer's: memory, CPU, hard drive space
and other shared resources, will be set aside for use in the virtual You're able to install Linux, and code inside a virtual
machine and therefore won't be available to the physical computer machine on a Windows 10 host.
until the hypervisor has been closed down.

| Linux Mint 19.1 Scripting Python & C++ This resource overhead
VIRTUAL OS
can be crippling for the From within a hypervisor you're able to run a number of different

Coding for physical machine if you


don't already have enough
operating systems. The type of OS depends greatly on the
hypervisor you're running, as some are better at emulating a

Linux
memory, or hard drive particular system over others. For example, VirtualBox, a free and
space available, or your easy to use hypervisor from Oracle, is great at running Windows
Master Linux and expandyourprogramming skills computer has a particularly and Linux virtual machines, but isn't so good at Android or macOS.
slow processor. While it's QEMU is good for emulating ARM processors, therefore ideal for
entirely possible to run Android and such, but it can be difficult to master.
virtual machines on as little
as 2CB of memory, it's not There are plenty of hypervisors available to try for free, with an
advisable. Ideally, you will equal amount commercially available that are significantly more
need a minimum of 8GB powerful and offer better features. However, for most users, both
of memory (you can get beginner and professional, VirtualBox does a good enough job.
away with 4GB, but again,
your physical computer Within a hypervisor, you're able to setup and install any of the
will begin to suffer with newer distributions of Linux, or if you feel the need, you're also able
the loss of memory to the to install some of the more antiquated versions. You can install early
virtual machine), at least 25 versions of Windows, even as far back as Windows 3 complete with
Our Linux titles contain to 50GB of free space on DOS 6.22-although you may find some functionality of the VM lost
steps on how to install a your hard drive and a quad- due to the older drivers (such as access to the network).
hypervisor and OS. core processor (again, you
can have a dual-core CPU, With this in mind then, you're able to have an installation of Linux
but that can cause a bottleneck on your physical computer). Mint, or the latest version of Ubuntu, running in an app on your
Windows 10 PC. This is the beauty of using a virtual machine.
The limit to how many different virtual machines you host on your Conversely, if your physical computer has Linux as its installed
physical computer is restricted, therefore, by the amount of physical operating system, then with a hypervisor you're able to create a
system resources you can allocate to each, while still leaving enough Windows 10 virtual machine - although you will need to have a
for your physical computer to operate on. licence code available to register and activate Windows 10.

www.bdmpublications.com
Using Virtual Machines

Using virtual machines removes the need to dual-boot. Dual-booting


is having two, or more, physical operating systems installed on
ADVANTAGES FOR CODERS
the same, or multiple, hard drives on a single computer. As the For the coder, having a virtual machine setup offers many
computer powers up, you're given the option to choose which OS advantages, the most popular being cross-platform code. Meaning if
you want to boot into. While this sounds like a more ideal scenario you write code within Windows 10, then with an installation of a
it isn't always as straight forward as it sounds, as all the operating Linux distro in a hypervisor, you're able to quickly and effortlessly
systems that are booted into will have full access to the computer’s power up the virtual machine and test your code in a completely
entire system resources. different operating system. From this, you're able to iron out any
bugs, tweak the code so it works better on a different platform and
The problems with dual-booting come when one of the operating expand the reach of your code to non-Windows users.
systems is updated. Most updates cover security patching, or bug
fixing, however, some updates can alter the core - the kernel, of The advantage of being able to configure a development
the OS. When these changes are applied, the update may alter the environment, in specific ways for specific projects, is quite
way in which the OS starts up, meaning the initial boot choice you invaluable. Using a virtual machine setup greatly reduces the
made could be overwritten, leaving you without the ability to access uncertainties that are inherent to having multiple versions of
the other operating systems installed on the computer. To rectify programming languages, libraries, IDEs and modules installed, to
this, you'll need to access the Master Boot Record and alter the support the many different projects you may become involved in as
configuration to ге-allow booting into the other systems. There's a coder. Elements of code that 'talk' directly to specifics of an
also the danger of possibly overwriting the first installed OS, or operating system can easily be overcome, without the need to
overwriting data and more often than not, most operating systems clutter up your main, host system with cross-platform libraries,
don't play well when running side-by-side. Indeed, while good, dual­ which in turn may have an effect on other libraries within the IDE.
booting has more than its fair share of problems. In contrast, using a
virtual machine environment, while still problematic at times, takes Another element to consider is stability. If you're writing code
out some of the more nasty and disastrous aspects of using multiple that could potentially cause some instability to the core OS
operating systems on a single computer. during its development phase, then executing and testing that
code on a virtual machine makes more sense than testing it on your
main computer; where having to repeatedly reboot, or reset
Even old operating systems can be run inside a
something due to
virtual machine.
the code's
instabilities, can
become
inefficient and
just plain
annoying.

The virtual
machine
environment can
be viewed as a Coding in Python on the Raspberry
sandbox, where Pi Desktop OS inside a VM on
you're able to test Windows 10!
unsecure, or
unstable code without it causing harm, or doing damage, to your
main, working computer. Viruses and malware can be isolated
within the VM without infecting the main computer, you're able
to set up anonymity Internet use within the VM and you're able
to install third-party software without it slowing down your
Virtual machines can be as simple, or as complex as your
main computer.
needs require.

GOING VIRTUAL
While you're at the early stages of coding, using a virtual machine
may seem a little excessive. However, it’s worth looking into because
coding in Linux can often be easier than coding in Windows, as some
versions of Linux have IDEs pre-installed. Either way, virtualisation of
an operating system is how many of the professional and successful
coders and developers work, so getting used to it early on in your
skill set is advantageous.

To start, look at installing VirtualBox. Then consider taking a look


at our Linux titles, https://bdmpublications.com/?s=linux&post_
type=product, to learn how to install Linux in a virtual environment
and how best to utilise the operating system.

www.bdmpublications.com
Getting Started

Creating a
Coding Platform
The term 'Coding Platform' can denote a type of hardware, on which you can code,
or a particular operating system, or even a custom environment that's pre-built and
designed to allow the easy creation of games. In truth it's quite a loose term, as a
Coding Platform can be a mixture of all these ingredients, it's simply down to what
programming language you intend to code in and what your end goals are.

Coding can be one of those experiences that sounds fantastic, but


to get going with it, is often confusing. After all, there's a plethora
of languages to choose from, numerous apps that will enable you
to code in a specific, or range, of languages and an equally huge
amount of third-party software to consider. Then you access the
Internet and discover that there are countless coding tutorials
available, for the language in which you've decided you want to
program, alongside even more examples of code. It's all a little too
much at times.

The trick is to slow down and, to begin with, not look too deeply
into coding. Like all good projects, you need a solid foundation
on which to build your skill and to have all the necessary tools
available to hand to enable you to complete the basic steps. This
is where creating a coding platform comes in, as it will be your
learning foundation while you begin to take your first tentative
steps into the wider world of coding.

HARDWARE SOFTWARE

Thankfully, coding at the In terms of software,


foundation level doesn't most of the development
require specialist equipment, environments - the tools
or a top of the range, liquid that allow you to code,
hydrogen-cooled PC. If you compile the code and
own a computer, no matter execute it-are freely
how basic, you can begin to l< эгп how to code. Naturally, if available to download and install. There are some specialist
your computer in question is Commodore 64 then you may tools available that will cost, but at this level they're not
have some difficulty following a modern language tutorial, but necessary; so don't be fooled into thinking you need to purchase
some of the best programmers around today started on an any extra software in order to start learning how to code.
8-bit machine, so there's hope yet.
Over time, you may find yourself changing from the
Access to the Internet is necessary to download, install and mainstream development environment and using a collection
update the coding development environment, alongside a of your own, discovered, tools towrite your code in. It's all
computer with either: Windows 10, macOS, or Linux installed. personal preference in the end and as you become more
You can use other operating systems, but these are the 'big experienced, you will start to use different tools to get the
three' and you will find that most code resources are written job done.
with one, or all of these, in mind.

www.bdmpublications.com
Creating a Coding Platform

OPERATING SYSTEMS VIRTUAL MACHINES

Windows 10 is the most A virtual machine is a piece of software that allows you to install a
used operating system in fully working, operating system within the confines of the software
the world, so it's natural itself. The installed OS will allocate user-defined resources from the
that the vast majority of host computer, providing memory, hard drive space etc., as well as
coding tools are written for Microsoft's leading operating sharing the host computer's Internet connection.
system. However, don't discount macOS and especially Linux.
The advantage of a virtual
macOS users enjoy an equal number of coding tools to their machine is that you can work
Windows counterparts. In fact, you will probably find that a with Linux, for example, without
lot of professional coders use a Mac over a PC, simply because it affecting your currently
of the fact that the Mac operating system is built on top of installed host OS. This means
Unix (the command-line OS that powers much of the world's that you can have Windows 10
filesystems and servers). This Unix layer lets you test programs running, launch your virtual machine client, boot into Linux and use
in almost any language without using a specialised IDE. all the functionality of Linux while still being able to use Windows.

Linux, however, is by far one of the most popular and This, of course, makes it a fantastic coding platform, as you can
important, coding operating systems available. Not only have different installations of operating systems running from
does it have a Unix-like backbone, but also it's also free to the host computer while using different coding languages.
download, install and use and comes with most of the tools You can test your code without fear of breaking your host OS
necessary to start learning how to code. Linux powers most of and it's easy to return to a previous configuration without the
the servers that make up the Internet. It's used on nearly all of need to reinstall everything again.
the top supercomputers, as well as specifically in organisations
such as NASA, CERN and the military and it forms the base of Virtualisation is the key to most big companies now. You will
Android-powered devices, smart TVs and in-car systems. Linux, probably find, for example, rather than having a single server
as a coding platform, is an excellent idea and it can be installed with an installation of Windows Server, the IT team have
inside a virtual machine without ever affecting the installation instead opted for a virtualised environment whereby each
of Windows or macOS. Windows Server instance is a virtual machine running from
several powerful machines. This cuts down on the number
of physical machines, allows the team to better manage
resources and enables them to deploy an entire server
dedicated to a particular task in a fraction of the time.
THE RASPBERRY PI

If you haven't already heard


of the Raspberry Pi, then
we suggest you head over MINIX NEO N42C-4
to www.raspberrypi.org, and
check it out. In short, the Raspberry The NEO N42C-4 is an extraordinarily
Pi is a small, fully functional computer that comes with its own small computer from mini-PC developer,
customised Linux-based operating system, pre-installed with MINIX. Measuring just 139 x 139 x 30mm, this Intel N4200 CPU
everything you need to start learning how to code in Python, powered, Windows 10 Pro pre-installed computer is one of the
C++, Scratch and more. best coding platforms we've come across.

It's incredibly cheap, costing around £35 and allows you to utilise The beauty, of course, lies in the fact that with increased storage
different hardware, in the form of robotics and electronics and memory available, you're able to create a computer that can
projects, as well as offering a complete desktop experience. easily host multiple virtual machines. The virtual machines can
Although not the most powerful computing device in the world, cover Linux, Android and other operating systems, allowing you
the Raspberry Pi has a lot going for it, especially in terms of to write and test cross-platform code without fear of damaging,
being one of the best coding platforms available. or causing problems, with other production or home computers.

The MINIX NEO N42C-4 starts at around £250, with the base
32GB eMMC and 4GB of memory. You'll need to add another
YOUR OWN CODING PLATFORM hundred and fifty, or so, to increase the specifications, but
consider that a license for Windows 10 Pro alone costs £219
Whichever method you choose, remember that your coding
from the Microsoft Store and you can begin to see the benefits
platform will probably change, as you gain experience and favour
of opting for a more impressive hardware foundation over the
one language over another. Don't be afraid to experiment along
likes of the Raspberry Pi.
the way, as you will eventually create your own unique platform
that can handle all the code you enter into it.

www.bdmpublications.com
Index

www.bdmpublications.com
Q Hello, World

ng started with Python may seem a


little daunting at first, but, thankfully, the
language has been designed with
simplicity in mind. Like most things, you
need to start slow, master the basics,
learn how to get a result, and how to get
what you want from the code.

This section covers numbers and


expressions, user input, conditions and
loops and the types of errors you will
undoubtedly come across in your time
with Python: the core foundations of
good coding and Python code.

26 Equipment You Will Need


28 Getting to Know Python
30 How to Set Up Python in Windows
32 How to Set Up Python in Linux
34 Starting Python for the First Time
36 Your First Code

elect 38
40
Saving and Executing Your Code
Executing Code from the Command Line
42 Numbers and Expressions
44 Using Comments
lected" .+ strfnrodlf: 46 Working with Variables
48 User Input
50 Creating Functions
52 Conditions and Loops
54 Python Modules
56 Python Errors
58 Combining What YouKnow So Far
60 Python in Focus: Stitching Black Holes

www.bdmpublications.com
Hello, World

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.

COMPUTER
Obviously you're going to need a computer in order to learn how to program in
Python and to test your code. You can use Windows (from XP onward) on either a 32
or 64-bit processor, an Apple Mac or Linux installed PC.

J AN IDE
An IDE (Integrated Developer Environment) is used to enter and execute 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 that you're running
the latest version of Python. Windows users need to download and install Python,
which we’ll cover shortly.

TEXT EDITOR
Whilst a text editor is an ideal environment to enter code into, it's not an absolute
necessity. You can enter and execute code directly from the IDLE beta text editor,
such as Sublime Text or Notepad++, offers more advanced features and colour coding
when entering code.

INTERNET ACCESS
Python is an ever evolving environment and as such new versions often introduce
new concepts or change existing commands and code structure to make it a more
efficient language. Having access to the Internet will keep you up-to-date, help you
out when you get stuck and give access to Python’s immense number of modules.

TIME AND PATIENCE


Despite what other books may lead you to believe, you won’t become a programmer
in 24-hours. Learning to code in Python takes time, and patience. You may become
stuck at times and other times the code will flow like water. Understand you're learning
something entirely new, and you will get there.

www.bdmpublications.com
Equipment You Will Need

THE RASPBERRY PI
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. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many modules and extras.

RASPBERRY PI

The Raspberry Pi 4 Model В is the latest version,


incorporating a more powerful CPU, a choice of 1GB,
2GB or 4GB memory versions and Wi-Fi and Bluetooth
support. You can pick up a Pi from around £33, increasing
up to £54 for the 4GB memory version, or as a part of kit
for £50+, depending on the kityouTe 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 titles available via www.


bdmpublications.com. Our Pi books cover how to buy your
first Raspberry Pi,
RASPBIAN
set it up and use i Python;
Raspber.
it; there are some great step-
The Raspberry Pi's main operating system is a Debian-based Ultimate
by-step project examples
Linux distribution that comes with everything you need in
a simple to use package. It's streamlined for the Pi and is an
and guides to get the most
from the
rrypj
ideal platform for hardware and software projects, Python
Raspberry /Haspber
programming and even as a desktop computer.

Poweroftht

amazing

kspbenyf

rtwfwith

’w/edge

www.bdmpublications.com
Hello, World

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

S 0;\Users\lucyh\Dropbox\0_Action\recipe.txt - Sublime Text (UNREGISTERED)


PYTHON PROGRAMMING RECIPES File 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
conceived in the late 1980s
CODE Iclass Cake(object):
det __ init___ (selt):
by Guido van Rossum Just like a recipe, a program consists of instructions that you follow self.ingredients = []
det cook(selt,ingredients):
at Centrum Wiskunde & in order. A program that describes a cake might run like this: print "Baking cake ...”

Informatica (CWI) in the cake = Cake()


| bowl = []
Netherlands as a successor to bowl — []
| flour = 100 flour - 100
the ABC language. butter — 50
| butter = 50 milk - 100
bowl.append([f1 our,butter,mi Ik])
| milk = 100
Guido van Rossum, the cake.cook(bowl)
| 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.

www.bdmpublications.com
Q Getting to Know Python

HIGH-LEVEL LANGUAGES ZEN OF PYTHON


Computer languages that are easy to read are known as "high-level”. Python lets you access all the power of a computer in a language
This is because they fly high above the hardware (also referred 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 principles that
are known as "low-level". Low-level languages commands read a bit influences the design of the language. Principles include "Beautiful
like this: msg db , Oxa len equ $ - msg. is better than ugly" and "Simple is better than complex." Type
import this into Python and it will display all the principles.

PYTHON 3 VS PYTHON 2
In a typical computing scenario, Python is complicated somewhat by the existence of two active versions of the language:
Python 2 and Python 3.

Python 3.7 is the newest release In 2008 Python 3 arrived with several new
WORLD OF PYTHON PYTHON 3.X
of the programming language. and enhanced features. These features
However, if you dig a little deeper into the Python site, and investigate provide a more stable, effective and efficient programming
Python code online, you will undoubtedly come across Python 2. environment but sadly, most (if not all) of these new features are
Although you can run Python 3 and Python 2 alongside each other, it's not compatible with Python 2 scripts, modules and tutorials. Whilst
not recommended. Always opt for the latest stable release as posted not popular at first, Python 3 has since become the cutting edge of
by the Python website. Python programming.

L* Python 3.6.1 Shell

File Edit Shell Debug Options Window Help


Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)]
on Win32
Type "copyright", "credits" or "license))" for more information.

PYTHON 2.X So why two? Well, Python 2 was originally Python 3's growing popularity has meant that
3.X WINS
launched in 2000 and has since then it's now prudent to start learning to develop
adopted quite a large collection of modules, scripts, users, tutorials with the new features and begin to phase out the previous version.
and so on. Over the years Python 2 has fast become one of the first Many development companies, such as SpaceX and NASA use
go to programming languages for beginners and experts to code Python 3 for snippets of important code.
in, which makes it an extremely valuable resource.
Python 342 Shell
Ufc Python 2.7.13 Shell □ File Edit Shell Debug Options Windows Help
File Edit Shell Debug Options Window Help
Python 3.4.2 (default. Oct 19 2014, 13:31:11)
Python 2.7.13 (v2.7.13:a06454blafal, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit [GCC 4.9.1] on linux
Intel)] on Win32 Type "copyright”, "credits" or "licensed" for more information.
Type "copyright", "credits" or "licensee)" for more information. »> print (“Python 3.x is AWESOME!")
Python 3.x is AWESOME!

www.bdmpublications.com :9
Hello, World

How to Set Up
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 still an ideal starting point for beginners.

INSTALLING PYTHON 3.X


Microsoft Windows doesn't come with Python preinstalled as standard, so it will be necessary to install it yourself manually.
Thankfully, it's an easy process to follow.

Start by opening your web browser to www.python. Choosing the Customise option allows you to
STEP1 STEP3
org/downloads/. Look for the button detailing the
A л
specify certain parameters, and whilst you may
Download link for Python 3.x. Python is regularly updated, changing stay with the defaults, it's a good habit to adopt as, sometimes (not
the last digit for each bug fix and update. Therefore, don't worry if with Python, thankfully), installers can include unwanted additional
you see Python 3.8, or more, as long as it's Python 3, the code in this features. On the first screen available, ensure all boxes are ticked
book will work fine. and click the Next button.

S’ Python 3.8.0 (32-bit) Setup - X

python —i ч
Optional Features
About Downloads Documentation Community Success Stories News tvel 0 Documentation

Installs the Python documentation file.

0 pip

Installs pip. which can download and install other Python packages.

0 td/tk and IDLE


Looking for Python with a different OS? Python lor Windows, \ I / /
Llnux/UNIX. Mac OS X. Other , \ I /// Installs tkinter and the IDLE development environment.

Want to help test development versions of Python? Prereleases, 0 Python test suite
Docker images Installs the standard library test suite.
Looking for Python 2.7? See below for specific releases i'' \
0 py launcher 0 for all users (requires elevation)

Upgrades the global ’py' launcher from the previous version.

□uthon

Click the Download button for version 3.x and The next page of options include some interesting
STEP 2 STEP 4
save the file to your Downloads folder. When the
A 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. you're ready to continue.

5* Python 3.8.0 (32-bit) Setup

Install Python 3.8.0 (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 for installed applications


Ф Install Now
C:\Users\david\AppData\Local\Programs\Python\Python38-32 0 Add Python to environment variables

0 Precompile standard library


Includes IDLE, pip and documentation
Creates shortcuts and file associations □ Download debugging symbols

□ Download debug binaries (requires VS 2015 or later)

-> Customize installation


Choose location and features
Customize install location
I C:\Program Files (x86)\Python38-32

nuthon nuthon

www.bdmpublications.com
How to Set Up Python in Windows

You may need to confirm the installation with Clicking on the IDLE (Python 3.x 32-bit) link will launch
STEP 5 STEP 8
the Windows authentication notification. Simply
A A
the Python Shell, where you can begin your Python
click Yes and Python will begin to install. Once the installation is programming journey. Don't worry if your version is newer, as long
complete, the final Python wizard page will allow you to view the as it's Python 3.x our code works inside your Python 3 interface.
latest release notes and follow some online tutorials.
Li Python 3.8.0 Shell - □ X

Python 3.8.0 (32-bit) Setup File Edit Shell Debug Options Window Help
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (In
tel)] on Win32
Setup was successful Type "help", "copyright", "credits" or "license()" for more information.

Special thanks to Mark Hammond, without whose years of


freely shared Windows expertise. Python for Windows would
still be Python for DOS.

New to Python? Start with the online tutorial and


documentation.

See what's new in this release.

python
for
windows Close

Before you close the install wizard window STEP 9 If you now click on the Windows Start button again,
STEP 6
however, it's best to click on the link next to the
A a and this time type: CMD, you'll be presented with
shield detailed Disable Path Length Limit. This will allow Python the Command Prompt link. Click it to get to the Windows command
to bypass the Windows 260 character limitation, enabling you to line environment. To enter Python within the command line, you
execute Python programs stored in deep folders arrangements. need to type: python and press Enter.
Click Yes again, to authenticate the process, then you can Close the
installation window.

® Disable path length limit


Changes your machine configuration to allow programs, including Python, to
bypass the 260 character "MAX_PATH“ limitation.

Close

STEP 7 Windows 10 users can now find the installed Python The command line version of Python works in
a
STEP 10
3.x within the Start button Recently Added section. a
much the same way as the Shell you opened in
The first link, Python 3.x (32-bit) will launch the command line Step 8; note the three left-facing arrows (»>). Whilst it's a perfectly
version of Python when clicked (more on that in a moment). To open fine environment, it’s not too user-friendly, so leave the command
the IDLE, type IDLE into Windows start. line for now. Enter: exit () to leave and close the Command
Prompt window.

Microsoft Windows [Version 10.0.18362.418]


(r) 201Q Mirrnsnft Corporation. 411 rights reserved.
::\Users\david>python
’ython 3.8.9 (togs/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [HSC v.1916 32 bit (Intel)] on Win32
Гуре "help", "copyright", "credits" or "license" for more information.
'» exit»
f.\users\davld>

www.bdmpublications.com
Hello, World

How to Set Up
Python in Linux
While the Raspberry Pi's operating system contains the latest, stable version of Python,
other Linux distros don't come with Python 3 pre-installed. If you're not going down
the Pi route, then here's how to check and install Python for Linux.

PYTHON PENGUIN
Linux is such a versatile operating system that it's often difficult to nail down just one-way of doing something. Different
distributions go about installing software in different ways, so for this particular tutorial we will stick to Linux Mint.

First you need to ascertain which version of Python Once the update and upgrade completes, enter:
STEP 1 STEP 4
is currently installed in your Linux system. To begin л
pythons --versionagain to see if Python 3.x is
with, drop into a Terminal session from your distro's menu, or hit the updated, or even installed. As long as you have Python 3.x, you’re
Ctrl+Alt+T keys. running the most recent major version, the numbers after the 3.
indicate patches plus further updates. Often they’re unnecessary,
david@david-Mint: * but they can contain vital new elements.
File Edit View Search Terminal Help | File Edit View Search Terminal Help

david@david-Mint:-J | Need to get 1,409 кВ of archives.


After this operation, 23.6 кВ of additional disk space will be used.
Do you want to continue? [Y/n] у
Get:l http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libasound2 amd6
4 1.1.3-5ubuntu0.2 [359 кВ]
Get:2 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libasound2-data
Next, enter: python - - version into the Terminal all 1.1.3-5ubuntu0.2 [36.5 кВ]
STEP 2 Get:3 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 linux-libc-dev
screen. You should have the output relating to
A amd64 4.15.0-44.47 [1,013 кВ]
version 2.x of Python in the display. Most Linux distro come with Fetched 1,409 кВ in 0s (3,023 kB/s)
(Reading database ... 290768 files and directories currently installed.)
both Python 2 and 3 by default, as there’s plenty of code out there Preparing to unpack .../Iibasound2_1.1.3-5ubuntu0.2 amd64.deb ...
Unpacking Iibasound2:amd64 (1.1.3-5ubuntu0.2) over (1.1.3-5ubuntu0.1) ...
still available for Python 2. Now enter: python3 - -version. Preparing to unpack .../Iibasound2-data_l.1.3-5ubuntu0.2_all.deb ...
Unpacking libasound2-data (1.1.3-5ubuntu0.2) over (1.1.3-5ubuntu0.1) ...
Preparing to unpack .../linux-libc-dev 4.15.0-44.47_amd64.deb ...
Unpacking linux-libc-dev:amd64 (4.15.0-44.47) over (4.15.0-43.46) ...
david@david-Mint: - Setting up libasound2-data (1.1.3-5ubuntu0.2) ...

File Edit View Search Terminal Help

david@david-Mint:-$ python --version


However, if you want the latest, cutting edge
Python 2.7.15rcl STEP 5
version, you'll need to build Python from source.
david@david-Mint:- $ python3 --version
Start by entering these commands into the Terminal:
Python 3.6.7
david@david-Mint:$ | sudo apt-get install build-essential checkinstall
sudo apt-get install libreadline-gplv2-dev
libncursesw5-dev libssl-dev libsqlite3-dev tk-dev
In our case we have both Python 2 and 3 installed. libgdbm-dev libc6-dev libbz2-dev
STEP3
As long as Python З.х.х is installed, then the code in
A
our tutorials will work. It’s always worth checking to see if the distro da vid@david-Mint: - * О

has been updated with the latest versions, enter: sudo apt-get File Edit View Search Terminal Help

david@david-Mint: •-$ sudo apt-get install build-essential checkinstall


update && sudo apt-get upgrade to update the system. Reading package lists... Done
Building dependency tree
Reading state information... Done
david@>david-Mint: - build-essential is already the newest version (12.4ubuntul).
The following NEW packages will be installed
File Edit View Search Terminal Help checkinstall
0 to upgrade, 1 to newly install, 0 to remove and 3 not to upgrade.
david@david-Mintpython --version Need to get 97.1 кВ of archives.
Python 2.7.15ГС1 After this operation, 438 кВ of additional disk space will be used.
david@david-Mintpython3 --version Do you want to continue? [Y/n] у
Python 3.6.7
david@david-Mintsudo apt-get update && sudo apt-get upgrade
[sudo] password for david: I __________________ I
з: www.bdmpublications.com
How to Set Up Python in Linux

Open up your Linux web browser and go to the For the GUI IDLE, you'll need to enter the following
STEP 6 STEP 9
APython download page: https://www.python.org/ ______ J command into the Terminal:
downloads. Click on the Downloads, Followed by the button under
sudo apt-get install idle3
the Python Source window. This opens a download dialogue box,
choose a location, then start the download process. The IDLE can then be started with the command: idle3. Note, that
IDLE runs a different version to the one you installed from source.

python Opening Python-3.7.2.tar.xz


Donate david@>david-Mint: ~/Downloads/Python-3.7.2

File Edit View Search Terminal Help


You have chosen to open:
david@david-Mint:~/Downloads/Python-3.7.2$ sudo apt-get install idle3
About Download Python-3.7J.tarja Reading package lists... Done
which is: xz archive (16.3 MB) Building dependency tree
from: https://www.python.org Reading state information... Done
The following additional packages will be installed:
bit idle idle-python3.6 python3-tk tk8.6-blt2.5
Suggested packages:
blt-demo tix python3-tk-dbg
The following NEW packages will be installed
bit idle idle-python3.6 idle3 python3-tk tk8.6-blt2.5
0 to upgrade, 6 to newly install, 0 to remove and 3 not to upgrade.
Need to get 938 кВ of archives.
After this operation, 4,221 кВ of additional disk space will be used.
Do you want to continue? [Y/n] |

In the Terminal, go to the Downloads folder


STEP 7
Aby entering: cd Downloads/. Then unzip the
contents of the downloaded Python source code with: tar -xvf
Python-3 .Y.Y.tar .xz (replace the Y's with the version numbers
you've downloaded). Now enter the newly unzipped folder with: cd
Python-3 . Y.Y/. You'll also need PIP (Pip Installs Packages), which is
STEP 10
Python-3.7.2/0bj ects/clinic/floatobject.c.h
_______ J a tool to help you install more modules and extras.
Python-3.7.2/0bj ects/clinic/funcobj ect.c.h Enter: sudo apt-get install python3-pip
Python-3.7.2/0bjects/clinic/longobj ect.c.h
Python-3.7.2/0bjects/clinic/dictobject.c.h Once PIP is installed, check for the latest update with:
Python-3.7.2/0bj ects/clinic/structseq.c.h
Python-3.7.2/0bjects/clinic/tupleobj ect.c.h
Python-3.7.2/0bjects/clinic/moduleobject.c.h pip3 install --upgrade pip
Python-3.7.2/0bj ects/clinic/odictobj ect.c.h
Python- 3.7.2/0bj ects/bytea r rayobj ect.c
Python-3.7.2/0bj ects/typeobj ect.c When complete, close the Terminal and Python 3.x will be available
Python-3.7.2/0bjects/lnotab_notes.txt via the Programming section in your distro's menu.
Python-3.7.2/0bj ects/methodobject.c
Python-3.7.2/0bjects/tupleobject.c
Python-3.7.2/0bj ects/obmalloc.c david@>david-Mint: -/Downloads/Python-3.7.2
Python-3.7.2/0bj ects/obj ect.c
Python-3.7.2/0bjects/abst ract.c File Edit View Search Terminal Help
Python-3.7.2/0bj ects/listobject.c
david@david-Mint:-/Downloads/Python-3.7.2$ sudo apt-get install python3-pip
Python-3.7.2/0bjects/bytes methods.c
Python-3.7.2/0bj ects/dictnotes.txt Reading package lists... Done
Python-3.7.2/0bj ects/typeslots.inc Building dependency tree
david@david-Mint:-/Downloads! cd Python-3.7.2/ Reading state information... Done
david@david-Mint:-/Downloads/Python-3.7.2$ The following additional packages will be installed:
python-pip-whl python3-distutils python3-lib2to3
Recommended packages:
python3-dev python3-setuptools python3-wheel
The following NEW packages will be installed
Within the Python folder, enter:
STEP 8 python-pip-whl python3-distutils python3-lib2to3 python3-pip
______ J ./configure
0 to upgrade, 4 to newly install, 0 to remove and 3 not to upgrade.
Need to get 1,984 кВ of archives.
After this operation, 4,569 кВ of additional disk space will be used.
sudo make altinstall Do you want to continue? [Y/n] |

This could take a while, depending on the speed of your computer.


Once finished, enter: python3.7 - -version to check the latest
installed version. You now have Python 3.7 installed, alongside older
Python З.х.х and Python 2.

checking for --with-ssl-default-suites... python


configure: creating ./config.status
config.status: creating Makefile.pre PYTHON ON macOS
config.status: creating Misc/python.pc
config.status: creating Misc/python-config.sh
config.status: creating Modules/ldsoaix
config.status: creating pyconfig.h Installation of Python on macOS can be done in much the
creating Modules/Setup same way as the Windows installation. Simply go to the Python
creating Modules/Setup.local
creating Makefile webpage, hover your mouse pointer over the Downloads
link and select Mac OS X from the options. You will then be
If you want a release build with all stable optimizations active (PGO, etc),
please run ./configure --enable-optimizations
guided to the Python releases for Mac versions, along with the
necessary installers for macOS 64-bit for OS X 10.9 and later.
david@david-Mint:-/Downloads/Python-3.7.2$ sudo make altinstall

www.bdmpublications.com
Hello, World

Starting Python for


the First Time
The Raspberry Pi offers one of the best all-round solutions on which to learn and code,
in particular, Python. Raspbian, the Pi's recommended OS, come pre-installed with the
latest stable version of Python 3, which makes it a superb coding platform.

STARTING PYTHON
Everything you need to begin programming with Python is available from the Raspberry Pi desktop. However, if you want,
drop into the Terminal and update the system with: sudo apt-get update.

With the Raspbian desktop loaded, click on the For example, in the Shell enter: 2+2
STEP1 STEP3
A Menu button followed by Programming > Python A After pressing Enter, the next line displays the
3 (IDLE). This opens the Python 3 Shell. Windows and Mac users can answer: 4. Basically, Python has taken the 'code’ and produced the
find the Python 3 IDLE Shell from within the Windows Start button relevant output.
menu and via Finder.

The Shell is where you can enter code and see the The Python Shell acts very much like a calculator,
STEP 2 STEP 4
A responses and output of code you've programmed A 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.

3. www.bdmpublications.com
(^Starting Python for the First Time

While that's very interesting, it's not particularly The Python IDLE is a configurable environment. If
STEP 5 STEP 8
_______________ j exciting. Instead, try this: л
you don't (ike the way the colours are represented,
then you can always change them via Options > Configure IDLE and
print("Hello everyone!")
clicking on the Highlighting tab. However, we don't recommend
Just enter it into the IDLE as you've done in the previous steps. that, as you won't be seeing the same as our screenshots.
Python 3.4.2 (default. Oct 19 2014, 13:31:11)
[6CC 4.9.1] on linux
Type "copyright", "credits” or "licensee)" for more information.

»> 23453+64545522
64568975
»> 98778642342-12343
98778629999
>» 1287437
*43534
56047282358
»> print("Hello everyone!")
Hello everyone!

STEP 6 This is a little more like it, since you've just produced STEP 9 Just like most programs available, regardless of the
your first bit of code. The Print command is fairly л
operating system, there are numerous shortcut
self-explanatory, it prints things. Python 3 requires the brackets as keys available. We don't have room forthem all here but within the
well as quote marks in order to output content to the screen, in this Options > Configure IDLE and under the Keys tab, you can see a list
case the 'Hello everyone!’ bit. of the current bindings.

»> print!"Hello everyone!"}


Hello everyone!

You may have noticed the colour coding within The Python IDLE is a power interface and one
STEP 7 STEP 10
______ J the Python IDLE. The colours represent different that's actually been written in Python using one
A
elements of Python code. They are: of the available GUI toolkits. If you want to know the many insand
outs of 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 of
Green-Strings Dark Red - Comments
the IDLE's features.
Purple-Functions Light Red - Error Messages
Orange-Commands 25.5. IDLE

IDLE Colour Coding


Colour Use for Examples
Black Data & variables 23.6 area
25.5.1. Menus
Green Strings "Hello World"
Purple Functions len() print ()
25.5.1.1. File menu (Shell and Editor)
Orange Commands if for else
Blue User functions get_area ()
Dark red Comments #Remember VAT
Light red Error messages SyntaxError:

www.bdmpublications.com
Hello, World

Your First Code


Essentially, you've already written your first piece of code with the 'print("Hello
everyone!")' function from the previous tutorial. However, let's expand that and look at
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.

IF you've closed Python 3 IDLE, reopen it in You can see that instead of the number 4, the
STEP 1 STEP3
_______J whichever operating system version you prefer. In output is the 2+2 you asked to be printed to the
A
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)

Python 3.4.2 Shell -ax


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 "licensee)" for more information.
»> print("Hello")
Hello

STEP 2 Just as predicted, the word Hello appears in the STEP 4 You can continue as such, printing 2+2, 464+2343
A Shell as blue text, indicating output from a string. and so on to the Shell. An easier way is to use a
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

Python 3.4.2 Shell


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 "license()“ for more information.
»> print("Hello”)
Hello
»> print("2+2")
2+2
»> print(2+2)

31 www.bdmpublications.com
Your First Code

What you have done here is assign the letters a Now let's add a surname:
STEP 5 STEP 8
and b two values: 2 and 2. These are now variables, ______ J 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)

Python 3 4.2 Shell -ox


File Edit Shejl 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.
»> name»"David"
»> print(name)
David
»> surname="Hayward"
»> print(surname)
Hayward

The output of the last step displays the current If we were to apply the same routine as before,
STEP 6 STEP 9
A values of both a and b individually, as you've asked ______ J using the + symbol, the name wouldn’t appear
them to be printed separately. If you 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 result.

You can play around with different kinds of variables In Python 3 you can separate the two variables
STEP 7 STEP 10
and the Print function. For example, you could A with a space using a comma:
assign variables for someone's name:
print(name, surname)
name="David"
Alternatively, you can add the space yourself:
print(name)
print(namet" ”+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 "licensee)" for more information.
>» name“”David"
»> print(name)
David
»> surname="Hayward"
»> print(surname)
Hayward
»> print(name
surname)
*
DavidHayward
»> print(name, surname)
David Hayward
»> print(name
'
* "♦surname)
David Hayward

www.bdmpublications.com
Hello, World

Saving and Executing


Your Code
While working in the IDLE Shell is perfectly fine for small code snippets, it's not
designed for entering longer program listings. In this section you're going to be
introduced to the IDLE Editor, where you will be working from 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.

First, open the Python IDLE Shell and when it's up, You can see that the same colour coding is in place
STEP1 STEP3
A click on File > New File. This will open a new window in the IDLE Editor as it is in the Shell, enabling you
A
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 FS and you get a
Save...Check box open.

Mo Edit Shell Debug Options windows Help bdit nymat Hun upnnne Windows Help

The IDLE Editor is, for all intents and purposes, a Click on the OK button in the Save box and select a
STEP 2 STEP 4
A simple text editor with Python features, colour destination where you'll 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 or you
code as you would within the Shell, so taking an example from the can just dump it wherever you like. Remember to keep a tidy drive
previous tutorial, enter: though, to help you out in the future.

print("Hello everyone!")

3I www.bdmpublications.com
Saving and Executing Your Code

Enters name for your code, 'print hello' for Let's extend the code and enter a few examples
STEP 5 STEP 8
A example, and click on the Save button. Once the A from the previous tutorial:
Python code is saved it's executed and the output will be detailed in
a=2
the IDLE Shell. In this case, the words 'Hello everyone!’.
b=2
name="David"
surname="Hayward"
print(name, surname)
print (a+b)

If you press F5 now you’ll be asked to save the file, again, as it's been
modified from before.

This is how the vast majority of your Python code If you click the OK button, the file will be
STEP 6 STEP 9
A will be conducted. Enter it into the Editor, hit F5, overwritten with the new code entries, and
A
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 whether you've 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.

pnnt hello py -/home/pi/Documents/Python Code/pnnt hello.py (3.4.2) -ox

If you open the file location of the saved Python Now create a new file. Close the Editor, and open
STEP 7 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.

hello.py ■/home/pi/Documents/Python Code/hello.py (3.4.2) _ □ x


&le Edit Ffirmat Bun Options Windows Help

I a»”Python"
b=-is"
Il c-"cool!”
print(a. b, c)

www.bdmpublications.com
Hello, World

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.

Python, in Linux, comes with two possible ways of Now you’re at the command line we can start
STEP1 STEP3
A executing code via the command line. One of the 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 orTerminal on command line version of the Shell, with the familiar three right-
your operating system. facing arrows as the cursor (>»).

Just as before, From here you're able to enter the code you've
STEP 2 ED© Filter
STEP 4
A weTe using a
Best match
______ J looked at previously, such as:
Raspberry Pi: Windows users will
Command Prompt a=2
need to click the Start button and Desktop app
print(a)
search for CMD, then click the Search suggestions
Command Line returned search; P cmd - See web results
You can see that it works exactly the same.
and macOS users can get access
to their command line by clicking
Go > Utilities > Terminal.

/О cmd|

www.bdmpublications.com
Executing Code From the Command Line

Now enter: exit() to leave the command line Python The result oF running Python 3 code From the
STEP 5 STEP 8
A session and return you back to the command A 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; hopeFullyyou way Python 3 handles the Print command over Python 2, the result
should see the hello.py File. isn't as we expected. Using Sublime For the moment, open the
hello.py File.

From within the same Folder as the code you're Since Sublime Text isn't available For the Raspberry
STEP 6 STEP 9
going to run, enter the Following into the A 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="coolI"
print(a, b, c)

STEP 7 Naturally, since this is Python 3 code, using the Save the hello.py File and drop back to the
a syntax and layout that's unique to Python 3, it only
STEP 10
command line. Now execute the newly saved
works when you use the python3 command. IF you like, try the same code with:
with Python 2 by entering:
python3 hello.py
python hello.py
The result 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.

www.bdmpublications.com
Hello, World

Numbersand Expressions
We've seen some basic mathematical expressions with Python, simple addition and the
like. Let's expand on that now and see just how powerful Python is as a calculator. You
can work within the IDLE Shell or in the Editor, whichever you like.

IT'S ALL MATHS, MAN


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

Open up the GUI version of Python 3, as mentioned a/ You can use all the usual mathematical operations:
you can use either the Shell or the Editor. For the divide, multiply, brackets and so on. Practise with a
time being, you're going to use the Shell just to warm our maths few, for example:
muscle, which we believe is a small gland located at the back of the
1/2
brain (or not).
6/2
2+2
3
*
(1+2)+(3
4)
*
Elie Edit Shell 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 "licensed" for more information.
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 "licensed" for more information.
»> 2+2
4
»> 54356+34553245
34607601
*27344484221
»> 99867344
2730821012201179024
»> 1/2
0.5
I »> 6/2
1 3.0
»> 2+2
*3
8
»> (1+2)+(3
*
4)
15
»> I

In the Shell enter the Following: РЯВЖ You've no doubt noticed, division produces a
” decimal number. In Python these are called floats,
2+2
or floating point arithmetic. However, if you need an integeras
54356+34553245
opposed to a decimal answer, then you can use a double slash:
27344484221
*
99867344
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 (default, Oct 19 2014, 13:31:11) File Edit Shell Debug Options Windows Help
[6CC 4.9.1] on linux
Type "copyright", "credits" or “licensed" for more information. Python 3.4.2 (default. Oct 19 2014, 13:31:11)
»> 2+2 [GCC 4.9.1] on linux
4 Type "copyright", "credits" or "licensed" for more information.
»> 54356+34553245 »> 2+2
34607601
*27344484221
»> 99867344 »> 54356+34553245
2730821012201179024 34607601
*27344484221
»> 99867344
2730821012201179024
»> 1/2
0.5
| »> 6/2
I >>S 2+2
*3

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

1 »> 1//2

I »> 6//2
1 >»l

www.bdmpublications.com
Numbersand Expressions

You can also use an operation to see the remainder This will be displayed as '0Ы1 converting the
STEP 5 STEP 8
_______________ j left over from division. For example: A integer into binary and adding the prefix Ob to the
front. If you want to remove the Ob prefix, then you can use:
10/3
format(3, 'b')
Will display 3.333333333, which is of course 3.3-recurring. If you
now enter: The Format command converts a value, the number 3, to a
formatted representation as controlled by the format specification,
10%3
the 'b' part.
This will display 1, which is the remainder left over from dividing 10
»> 2*
3
into 3. 8
»> *23)
((1
4
15
»> 1//2
0
»> 6//2
3
»> 10/3
3.3333333333333335
»> 10X3
1
»> 3**
2
8
»> 10**
10000000000
»> bin(3)
•ом г
»> format(3,’b’)

Next up we have the power operator, or STEP 9 A Boolean Expression is a logical statement that will
STEP 6
exponentiation if you want to be technical. To work
A either be true or False. We can use these to compare
out the power of something you can use a double multiplication data and test to see it it's equal to, less than or greater than. Try this
symbol or double-star on the keyboard: in a New File:

3*
*
2 a = 6
**
10 b = 7
print(1, a == 6)
Essentially, it's 2x2x2 but we're sure you already know the basics
print(2, a == 7)
behind maths operators. This is how you would work it out in Python.
print(3, a == 6 and b == 7)
»> 6/2 print(4, a == 7 and b == 7)
3.0
»> 2*
3 print(5, not a == 7 and b == 7)
8
»> *23
(
4
(1 ) 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
»> 10X3
1
»> 3**
2
8
»> 10**
10000000000

Numbers and expressions don't stop there. Python Execute the code from Step 9, and you can see a
STEP 7 STEP 10
______ J has numerous built-in functions to work out sets series of True or False statements, depending on
A
of numbers, absolute values, complex numbers and a host of the result of the two defining values: 6 and 7. It’s an extension of
mathematical expressions and Pythagorean tongue-twisters. For what you've looked at, and an important part of programming.
example, to convert a number to binary, use:

bin(3)

»> 1/2
0.5
»> 6/2
3.0
»> 2*
3
8
»> *23)
((1
4
15
»> 1//2
0
»> 6//2
3
»> 10/3
3.3333333333333335
»> 10X3
1
»> 3**
2
8
»> 10**
10000000000
»> bin(3)
•0ЫГ
»>l

www.bdmpublications.com
Hello, World

Using Comments
When writing your code, the flow, what each variable does, how the overall program
will operate and so on is all 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 of the IDLE Editor Resave the code and execute it. You can see that the
STEP3
a (File > New File) and create a simple variable and output in the IDLE Shell is still the same as before,
A
print command: despite the extra lines being added. Simply put, the hash symbol (#)
denotes a line of text the programmer can insert to inform them,
a=10
and others, of what's going on without the user being aware.
print("The value of A is,", a)

Save the file and execute the code. Python 3 4 2 Shell □


Eile Edit Shell pebug Options Windows Help

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


[GCC 4.9.1] on linux
Type "copyright", "credits" or "licensee)" for more information.
RESTART

The value of A is. 10


RESTART

The

STEP 2 Running the code will return the line: The value of A STEP 4 Let's assume that the variable A that we've created
A is, 10 into the IDLE Shell window, which is what we is the number of lives in a game. Every time the
A
expected. Now, add some of the types of comments you'd normally player dies, the value is decreased by 1. The programmer could
see within code: insert a routine along the lines of:

# 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 - /home/pi/Docume. .Python Code/Comments.py (3.4.2)
* -ox
File Edit Format Run Options Windows Help

# Set the start value of A to 10


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

www.bdmpublications.com
Using Comments

Whilst we know that the variable A is lives, and Inline comments are comments that follow a section
STEPS STEP 8
that the player has just lost one, a casual viewer or
A of code. Take our examples from above, instead of
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 of just 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
a=a-l # Player lost a life!
print("You've just lost a life!")
print("You now have", a, "lives left!") # Inform
player, and display current value of A (lives)

Comments.py-/home/pi/Documents/PythonCode/Commentspy (3.4.2) _ □ x
File Edit Ffirmat Bun Options Windows Help
a=10 # Set the start value of A to 10
print("The value of A is.”, a) * Print the current value of A
a=a-1 # Player lost a life!
print("You've just lost a life!")
print(“You now have", a. "lives left!”) # Inform player, and display current value of A (lives

Essentially, the new code together with comments STEP 9 The comment, the hash symbol, can also be used to
STEP 6
______ J could look like: comment out sections of code you don't want to be
A
executed in your program. For instance, if you 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!
‘Comments. py - /home/pi/Documents/Python
a=a-l
# Inform player, and display current value of A File Edit Format Run options windows Help

(lives) # Set the start value of A to 10


print("You've just lost a life!") a=10
# ■ Print the current value of A
print("You now have", a, "lives left!") # print("The value of A is,", ai|
# Player lost a life!
File Edit Format Run Options Windows Help a=a-1
# Set the start value of A to 10
# ■ Inform player, and display current value of A (lives)
a-io 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)
# Player lost a life!
a=a-1
# Inform player, and display current value of A (lives)
print("You've just lost a life!")
print(“You now have", a. "lives left!")

STEP 7 You can use comments in different ways. For You also use three single quotes to comment
A
STEP 10
example, Block Comments are a large section of out a Block Comment or multi-line section of
text that details what's going on in the code, such as telling the code comments. Place them before and after the areas you want to
reader what variables you're planning on using: comment for them to work:

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

’Comments.py - /home/pi/Documents/Python Code/Comments py (3.4.2)


*
File Edit Format Run Options Windows Help File Edit Fprmat Run Options Windows Help
# This is the best game ever, and has been developed by a crack squad of Python experts
ft who haven't slept or washed in weeks. Despite being very smelly, the code at least t This is the best game ever. and has been developed by a crack squad of Python experts
# works really well. | || who havenOt slept or washed in weeks. Despite being very smelly, the code at least
I works really well.|
tt Set the start value of A to 10
a-10
tt Print the current value of A
print("The value of A is,", a) tt set the start value of A to 10
a-10
ft Player lost a life! ft Print the current value of A
a-a-1 tt print(“The value of A is.", a)
tt Inform player, and display current value of A (lives) tt Player lost a life!
print(”You‘ve just lost a life!") a=a-1
print(“You now have", a. "lives left!") tt 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
Hello, World

Working with Variables


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
You’ll 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 clear up any old code.

STEP1 In some programming languages you're required You've seen previously that variables can be
STEP3
л
to use a dollar sign to denote a string, which is a concatenated using the plus symbol between the
A
variable made up of multiple characters, such as a name of 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, unless you're add a colon and a space, as variables are connected without spaces,
also called David Hayward). so we need to add them manually.

Python 3 4.2 Shell Python 3.4.2 Shell _ □ x


File Edit Shell Qebug Options Windows Help File Edit Shell Qebug 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.
»> name»"David Hayward" »> name="David Hayward"
»> print (name) »> print (name)
David Hayward David Hayward
»> type (name)
<class ‘str'>
»> title“”Descended from Vikings"
»> print (name + ": " + title)
David Hayward: Descended from Vikings

STEP 2 You can check the type of variable in use by STEP 4 You can also
л
issuing the type () command, placing the name of ______ J combine variables
the variable inside the brackets. In our example, this would be: within anothervariable. For
type (name). Add a new String variable: title="Descended example, to combine both name
from Vikings". and title variables into a new
variable we use:
Python 3.4.2 Shell _ □ x
character=name + ": " +
File Edit Shell Qebug Options Windows Help

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


title
[GCC 4.9.1] on linux
Type "copyright", "credits" or "licenseO" for more information.
»> name""David Hayward"
Then output the content of the
»> print (name)
David Hayward new variable as:
»> type (name)
<class 'str'»
>» title«"Descended from Vikings" print (character)

Numbers are stored as different


variables:

age=44
Type (age)

Which, as we know, are integers.

www.bdmpublications.com
(^Working with Variables

However, you can't combine both strings and This presents a bit of a problem when you want to
STEP 5 STEP 8
integer type variables in the same command, as you
A A 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. Instead, 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 "licenseO" for more information.
»> name="David Hayward"
»> print (name) Python 3.4.2 Shell - □
David Hayward
»> type (name) File Edit Shell Debug Options Windows Help
<class *str ‘>
»> title-"Descended from Vikings" Python 3.4.2 (default. Oct 19 2014. 13:31:11)
»> print (name + : " + title) [GCC 4.9.1] on linux
David Hayward: Descended from Vikings Type "copyright", "credits" or "licenseO" for more information.
»> character=name + ”: " + title >» age- input ("How old are you? ")
»> print (character) How old are you? 44
David Hayward: Descended from Vikings »> type(age)
»> age-44 <class 'str‘>
| »> type (age)
В <class ’inf>
»> age ♦ 10
и »> print (name+age)
Traceback (most recent call last):
В Traceback (most recent call last): File ”<pyshell#2>", line 1, in <module>
В File "<pyshell#9>". line 1. in <module> age + 10
В print (name
*age) TypeError: Can't convert 'int
* object to str implicitly
В TypeError: Can't convert 'inf object to str implicitly »> int(age) + 10
54
»>l

This is a process known as Typecasting. The Python The use of Typecasting is also important when
STEP 6 STEP 9
________ Л code is: ______ J dealing with floating point arithmetic; remember:
numbers that have a decimal point in them. For example, enter:
print (character + " is " + str(age) + " years
old.") shirt=19.99

or you can use: Now enter type (shirt) and you'll 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
Python 3.4.2 Shell
between the words in quotes as the commas treat each argument
Ale Edit Shell Debug Options Windows Help
to print separately.
Python 3.4.2 (default. Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
»> print (name + age) Type "copyright", "credits" or "licenseO" for more information.
Traceback (most recent call last): »> shirt=19.99
File ■<pyshell#18>", line 1, in smodule? »> type(shirt)
print (name + age) <class * float’>
TypeError: Can't convert 'inf object to str implicitly
»> I
>» print (character + " is " + str(age) + " years old.'1)
David Hayward: Descended from vikings is 44 years old.
>» print (character, "is", age, "years old.’’)
David Hayward: Descended from vikings is 44 years old.
»>
»> I

к Another example of Typecasting is when you ask for When combining integers and floats Python
STEP 7 STEP 10
F 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 variable. called truncating; in our case instead of 19.99 it becomes 19.

Python 3.4.2 Shell


Ale Edit Shell Debug Dptions 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.
»> shirt=19.99
>» type(shirt)
float ’>
<class *
»> int(shirt)
19
>»l

www.bdmpublications.com
Hello, World

User Input
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 how you would get inFormation
From the user then store and present it.

USER FRIENDLY
The type of input you want from the user will depend greatly on the type of program you're coding. For example, a game may
ask for a character's name, whereas a database can ask for personal details.

STEP 1 If it's not already, open the Python 3 IDLE Shell, Now that we have the user's name stored in a
STEP3
a and start a New File in the Editor. Let's begin with A couple of 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? ") you're well today.")
print("Thanks.")
surname=input("And what is your surname? ")

STEP 2 Save and execute the code, and as you already no STEP 4 Run the code and you can see a slight issue, the
A doubt suspected, in the IDLE Shell the program will full stop after the surname follows a blank space.
A
ask for your first name, storing it as the variable firstname, followed To eliminate that we can add a plus sign instead of the comma in
by your surname; also stored in its own variable (surname). the code:

print("Welcome", firstname, surname+". I hope


you're well today.")

‘userinput py - /home/pi/Documents/Python Code/usennput py (3 4 2)1


File Edit Format Run Options Windows Help

print("Hello")
firstname-input(”What is your first name? ")
print("Thanks.")
surname-input("And what is your surname? ”)
print("Welcome", firstname. surname
".
* I hope you're well today.")

www.bdmpublications.com
User Input

You don't always have to include quoted text within What you've created here is a condition, which we
STEP 5 STEP 8
_______J the input command. For example, you can ask the will cover soon. In short, we're using the input from
A
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, if they enter a name other than David, the guard challenges
name=input ()
them to a fight.

userinput.py - /home/pi/Documents/Python Codete


File Edit Format Run Options Windows Help

print("Hello. What’s your name?")


name"input()

The code from the previous step is often regarded STEP 9 Just as you learned previously, any input from a
STEP 6
as being a little neater than having a lengthy
A user is automatically a string, so you need to apply a
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=input () rate = float(input("Rate: "))

*usennput.py - /home/pi/Documents/Python Code/usennput.py (3.4.2)*


file Edit Fflrmat Bun Options Windows Help
# Code to calculate rate and distance
print!"Input a rate and a distance")
rate ■ float!input!"Rate: "))|

It's a good start to a text adventure game, perhaps? To finalise the rate and distance code, we can add:
STEP 7 STEP 10
Now you can expand on it and use the raw input _______ J distance = float(input ("Distance:
from the user to flesh out the game a little:
") )
if name=="David": print("Time, (distance / rate))
print("Welcome, good sir. You may pass.")
Save and execute the code and enter some numbers. Using the
else:
float(input element, we've told Python that anything entered is a
print("I know you not. Prepare for battle!")
floating point number rather than a string.

userinputpy - /home/pi/Documents/Python Code/usehnputpy (3 4 2) - □ x


File Edit Format Bun Options Windows Help

print!“Halt! Who goes there?")


name-input()
if name== "David":
print!"Welcome, good sir. You may pass.”)
else:
print!"I know you not. Prepare for battle!")

www.bdmpublications.com
Hello, World

Creating Functions
Now that you'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 define your own functions.

FUNKY FUNCTIONS
A function is a command that you 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 result.

STEP1 It's not just data that a function works on. They can You can pass variables through functions in much
STEP3
a do alt manner of useful things in Python, such as A 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):
followed by brackets. For example, len(), list() or type().
name=input ("Enter your surname: ")
count=len(name)
print ("Your surname has", count, "letters in
it.")

Press F5 and save the code to execute it.

STEP 2 A function takes data, usually a variable, works on STEP 4 Python has tens of functions built into it, far too
A it depending on what the function is programmed A 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, but since users have created many
len ("antidisestablishmentarianism") and the number 28 more, they're not the only ones available.
would return.

Python 3.4.2 Shell

www.bdmpublications.com
Creating Functions

Additional functions can be added to Python To use a function from a module enter the name of
STEP 5 STEP 6
A through modules. Python has a vast range of A 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).

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.

Choose File > New File to enter the editor, let’s To modify it further, delete the Hello("David") line,
STEP1 STEP3
create a function called Hello, that greets a user. the last line in the script and press Ctrl+S to save
Enter: the new script. Close the Editor and create a new file (File > New
File). Enter the following:

[from Hello import Hello|

Press F5 to save and execute the code.

Let's now expand the function to accept a STEP 4 What you've just done is import the Hello function
STEP 2
variable, the user's name for example. Edityour from the saved Hello.py program and then used it
script to read: to say hello to David. This is how modules and functions work: you
import the module then use the function. Try this one, and modify
it for extra credit:
^дрг int (цHe11о", name)

This will now accept the variable name, otherwise it prints Hello
David. In the Shell, enter: name=("Bob"), then: Hello(name). Your
function can now pass variables through it.

www.bdmpublications.com
Hello, World

Conditionsand Loops
Conditions and loops are what make a program interesting; they can be simple or rather
complex. How you use them depends greatly on what the program is trying to achieve;
they could be the number of lives left in a game or just 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.

STEP 1 Let's create a new Python program that will ask Now you can use an if statement to check if the
STEP3
a the user to input a word, then check it to see if it's wordJength variable is equal to four and print a
A
a four-letter word or not. Start with File > New File, and begin with friendly conformation if it applies to the rule:
the inputvariable:
word=input("Please enter a four-letter word: ")
word=input("Please enter a four-letter word: ") word_length=len(word)
if word_length == 4:
print (word, "is a four-letter word. Well done.")

The double equal sign (==) means check if something is equal to


something else.

*
♦Untitled _ □ x
File Edit Format Run Options Windows Help

word=input("Please enter a four-letter word: ")


word_length-len(word)
lq if word_length == 4:
print (word, "is a four-letter word. Well done.")

Now we can create a new variable, then use the len The colon at the end of IF tells Python that if this
STEP 2 STEP 4
A function and pass the word variable through it to statement is true do everything after the colon
A
get the total number of letters the user has just entered: that's indented. Next, move the cursor back to the beginning of
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)
if word_length == 4 :
print (word, "is a four-letter word. Well
done.")
else:
print (word, "is not a four-letter word.")

www.bdmpublications.com
Conditionsand Loops

Press F5 and save the code to execute it. Enter Now expand the code to include another conditions.
STEPS STEP 6
a four-letter word in the Shell to begin with, you
A ______ J 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)
if word_length == 4:
print (word, "is a four-letter word. Well
done.")
elif word_length == 3:
print (word, "is a three-letter word. Try again.")
else:
print (word, "is not a four-letter word.")

LOOPS
A loop looks quite similar to a condition but they are somewhat different in their operation. A loop will run through the same
block of code a number of times, usually with the support of a condition.

Let's start with a simple While statement. Like IF, The For loop is another example. For is used to
STEP1 STEP3
this will check to see if something is TRUE, then run loop over a range of data, usually a list stored as
the indented code: variables inside square brackets. For example:

tor word, in words

looplpy-.
toe snap yeoug options wnoom weip [«e E<M Format Bun Options Windom Help
’Untitled’
£He Edit Format Bun fiptions windows Help Гуре "copyright". "credits" о

i- x<10:

The difference between if and while is when while STEP 4 The For loop can also be used in the countdown
STEP 2
gets to the end of the indented code, it goes back example by using the range function:
and checks the statement is still true. In our example x is less than
for x in range (1, 10)
10. With each loop it prints the current value of x, then adds one to
that value. When x does eventually equal 10 it stops.
The x=x+1 part isn't needed here because the range function
loopl py-/h creates a list between the first and last numbers used.
E«e Е<И Shell QeDug flprions KmOows Help File Edit Format Bun Options Windows M
Python 3.4.2 (default. Oct 19 2014. 13:31:11)
(GCC 4.9.1 J ОП UnUX
RESTART

www.bdmpublications.com
Hello, World

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

STEP 1 Although good, the built-in functions within Python The result is an error in the IDLE Shell, as the
STEP3
are limited. The use of modules, however, allows us
A A 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:
Li Python 3.62 Shell — □ X

File Edit Shell Debug Options Window Help pip install pygame
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)]
on Win32
| Type "copyright", "credits" or "license()" for more information. SB Command Prompt
I >» import math

:\Users\david>pip install pygame

Some modules, especially on the Raspberry Pi, The PIP installation requires an elevated status
STEP 2 STEP 4
are included by default, the Math module being a
A A 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 result 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.

Li Python 3.62 Shell - □ X


SB Administrator. Command Prompt
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)]
Microsoft Windows [Version 10.0.15063]
on Win32 (c) 2017 Microsoft Corporation. All rights reserved.
Type "copyright", "credits" or "license()" for more information.
»> import math
»> import pygame
C:\WINDOWS\system32>pip install pygame
Traceback (most recent call last): Collecting pygame
File "<pyshell#l>", line 1, in <module> Using cached pygame-1.9.3-cp36-cp36m-win32.whl
import pygame
ModuleNotFoundError: No module named 'pygame*1
Installing collected packages: pygame
Successfully installed pygame-1.9.3

C:\WINDOWS\system32>

www.bdmpublications.com
Python Modules

Close the command prompt or Terminal and Multiple modules can be imported within your code.
STEP 5 STEP 8
relaunch the IDLE Shell. When you now enter:
A 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. print(random.randint(1, 25))

L£ Python 3.62 Shell - □ X print(math.pi)


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)] Li Rod Number.py - C:/Users/david/Documents/Python/Rnd Number.py (3.6.2) — □ X
on Win32
File Edit Format Run Options Window Help
Type "copyright", "credits" or "license()" for more information.
»> import pygame import random
»> import math

for 1 in range(5):
print(random.randint(1, 25))

print(math.pi)

The modules contain the extra code needed to The result is a string oF random numbers Followed
STEP 6 STEP 9
achieve a certain result within your own code, as
A by the value oF Pi as pulled From the Math module
A
we've 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.
from random import randint
You can then use this module to create something like:
for i in range(5):
for i in range(10):
print(randint(1, 25))
print(random.randint(1, 25))
Rnd Number.py - C:/Users/david/Documents/Python/Rnd Number.py (3.6.2) — □ X
L« 'Untitled' — □ X
File Edit Format Run Options Window Help
File Edit Format Run Options Window Help from random import randint
import random
for i in range(5):
|for i in range(10): print(randint(1, 25))
print(random.randint(1, 25))

STEP 7 This code, when saved and executed, will display ten This helps create a more streamlined approach to
STEP 10
random numbers From 1 to 25. You can play around
A programming. You can also use import module
A *
,
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(1, 100)) print(m.pi)

Of course, adding comments helps to tell others what's going on.

L^i’Rnd Number.py - C:/Users/david/Documents/Python/Rnd Number.py (3.6.2)


* — □ X

File Edit Format Run Options Window Help


iaport math аз m

print(m.pi)
I

www.bdmpublications.com
Hello, World

Python Errors
It goes without saying that you'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 for a 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 Fluid as the written word, no matter Thankfully Python is helpful when it comes to
STEP3
л how good the programming language is. Python is A displaying error messages. When you receive an
certainly easier than most languages but even it is prone to some error, in red text from the IDLE Shell, it will define the error itself
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 find in simple dozen-line code, imagine having to debug the IDLE Editor this is a little daunting for lots of code; text editors
multi-thousand line code. help by including line numbering.

The most common of errors is the typo, as we've Syntax errors are probably the second most
STEP 2 STEP 4
A mentioned. The typos are often at the command common errors you'll come across as a programmer.
level: mistyping the print command for example. However, they also Even if the spelling is correct, the actual command itself is wrong.
occur when you have numerous variables, all of which have lengthy In Python 3 this often occurs when Python 2 syntaxes are applied.
names. The best advice is to simply go through the code and check The most annoying of these is the print function. In Python 3 we use
your spelling. printf'words"), whereas Python2 uses print "words".

www.bdmpublications.com
Python Errors

Pesky brackets are also a nuisance in programming An excellent way to check your code step-by-step
STEPS STEP 8
______ J errors, especially when you have something like: A is to use Python Tutor's Visualise web page, found
at www.pythontutor.com/visualize.html#mode=edit. Simply
print(balanced_check(input ()))
paste your code into the editor and click the Visualise Execution
Remember that tor every'(' there must bean equal number of button to run the code line-by-line. This helps to clear bugs and
any misunderstandings.
1 import sys

3’def balanced check(data):


4 stack = (]
5 characters = list data
6
7» for character in characters:
8▼ reference = {
9
10 :
•{
*
’[•: 'I1
12 }
if character in reference.keys():
stack.append(character)
15
elif character in reference.values() and len(stack) > 0:
char = stack.pop()
if reference.get(char) 1= character:
return "NO"
20 else:

There are thousands of online Python resources, Planning makes for good code. Whilst a little old
STEP 6 STEP 9
code snippets and lengthy discussions across forums
A 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 wilt
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 or outputs.
part is that you haven’t learnt anything.

You have a bare except clause; i.e.,

try:
some_code()

clean_up()

The problem with a bare except is that it will catch all exceptions, including ones you really
don't want to be ignoring (like Keyboardinterrupt and SystemExit). It would be much better if
your except block only caught the specific exception you expect, and let all others bubble up
as normal.

A few other general comments on your code:

• In line 200, you have this construction:

for letter in range(len(chosen_word)):


if player_guess == chosen_word[letter]:
word_guessed[letter] = player guess

You're looping over the index variable, but also using the list element. It would be better to
write:

for idx, letter in enumerate(chosen_word):


if player_guess == letter:

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

File Edit Format Run Options Windows Help

word=input("Please enter a four-letter word: ")


word_length=len(word)
if word_length == 4:
print (word, “is a four-letter word. Well done.")
else:
print (word, "is not a four-letter word.”)

www.bdmpublications.com
Hello, World

Combining What
You Know So Far
We've reached the end of this section so let's take a moment to combine everything
we've looked at so far, and apply it to writing a piece of code. This code can then be
used and inserted into your own programs in future; either part of it or as a whole.

PLAYING WITH PI
For this example we're going to create a program that will calculate the value of Pi to a set number of decimal places, as
described by the user. It combines much of what we've learnt, and a little more.

STEP 1 Start by opening Python and creating a New File in The previous step defines the rules that make
STEP 4
л the Editor. First we need to get hold of an equation up the algorithm and creates the string that will
that can accurately calculate Pi without rendering the computer's 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:
Chudnovsky_algorithm.
print(calc(1))

You can utilise the Chudnovsky Algorithm to create


STEP 2 You can save and execute the code at this point if
your own Python script based on the calculation. STEP 5
A 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 You can insert an input line before the Pi calculation
STEP 6
module, both oF which deal with large decimal place numbers and A 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:

Now you can insert the Pi calculation algorithm numberofdigits = int(input("please enter the
STEP3
A part oF the code. This is a version oF the number of decimal place to calculate Pi to: "))
Chudnovsky Algorithm: getcontext().prec = numberofdigits

def calc(n):
t = Decimal(0)
pi = Decimal(0)
deno = Decimal(0)
к = 0
for к in range(n):
t = (Decimal(-1)**
k) *(math.factorial
(Decimal(6)* (13591409
k) )
* k)
*
+545140134
deno = math.factorial(3
k)
* *(math,
factorial(k)
Decimal
** (3))
(640320
*
** k)
*
(3 )
pi += Decimal(t)/Decimal(deno)
pi = pi * Decimal(12)/
Decimal(640320
Decimal
** (1.5))
pi = 1/pi
return str(pi)

www.bdmpublications.com
Combining What You Know So Far

You can execute the code now and it asks the user STEP 9 Now we need to import the Colorama module
STEP 7
how many decimal places they want to calculate Pi
A (which will output text in different colours) along
A
to, outputting the result in the IDLE Shell. Try it with 1000 places with the Fore function (which dictates the foreground, ink, colour)
but don't go too high or else your computer 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
Part of programming is import colorama
STEP 8 A being able to modify code, from colorama import Fore
making it more presentable. Let's include
numberofdigits - int( input (“please enter the number of decimal places to calculate Pi to: "))
an element that times how long it takes our getcontext().prec - numberofdigits

computer to calculate the Pi decimal places


t * Decimal(O)
and present the information in a different pi - Decimal(O)
deno - Decimal(O)

colour. For this, drop into the command line for к in range(n):
*()math.
t - (Decinial( -1 k) * *(factorial(Decimal(6)
k)) 13591409»545140134
*k)
(math.factorial(3
*k
deno - ** 640320
math.factorial(k)
(3
)))
Decimal(3))
and import the Colorama module (RPi users pi Decimal(t)/Decimal(deno)
pi - pi * DecimalC12)/Decimal(640320
**
0ecimal( 1.5))
pi ■ 1/pi
already have it installed): return str(pi)

pip install colorama

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


Colorama module and start the time function at
A pi = Decimal(0)
the point where the calculation starts, and when it finishes. The end deno = Decimal(0)
result is a coloured ink displaying how long the process took (in the к = 0
Terminal or command line): for к 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
** (640320
*
(3))
** k)
*
(3 )
import colorama
pi += Decimal(t)/Decimal(deno)
from colorama import Fore
pi = pi * Decimal(12)/
colorama.init()
Decimal
**
Decimal(640320 (1.5))
numberofdigits = int(input("please enter the number pi = 1/pi
of decimal places to calculate Pi to: ")) return str(pi)
getcontext().prec = numberofdigits
print(calc(1))
start_time = time.timeO print(Fore.RED + "\nTime taken:", time.timeO -
def calc(n): start_time)

Python 3.4.2 Shell r> CalcPi py - /home/pi |^Jpi@raspbertypi:~/D_ .

CalcPi.py - /home/pi/Documents/Python Code/CalcPi.py (3.4.2)


Python 3.4 2 Shell
File Edit Shell Debug Options Windows Help EUe Edit Fermat Bun Options windows Help
.. getconte>
Python 3.4.2 (default. Oct 19 2014. 13:31:11)
[GCC 4.9.1) on linux import time
Type "copyright", “credits" or "licensee)” for more information. t colorama
»> ————————— RESTART ——————
colorama imr
please enter the number of decimal places to calculate Pi to: 1000
3.141592653589734207668453591578298340762233260915706590894145498737666209401659
,10806611734746968975779816037965556627803580134599593513286173176615982806223108 numberofdigits
04419737853125305651521157470859338317744154596022745876277128465914181337399228 getcontext( numberofdigits
59535784112988088378242126794689633529216676947336619680715159349309584269265090
80187699606147066217003750206017344284513142480930327868775560407147230694298134 time.timeO
45787466657726444985596290919860559636358984008947138101161111956856848705962570
I 13872723252284798186917184867353096708222303615292971732815423261495480206046405 Decimal(O)
| 35398750760139733285849996526642119020066783578725502635682724402886356888437352 Decimal(O)
; 88982506842338309905740013758327701784908891322958527973601013169595019458889349 Decima1(0)
| 44236412539394146530738483636665042264154387773376017707109142428744379717832620
| 33721044052592738923786964883764463574460244839242316267458666952279157823643188 in range(n):
I 34956170648852260770217962185905198741140188951968612315753706167429421120955210 (DecimalC-1)**k)*(math.factorial(Decimal(6)*k))*(13591409*545140134*k)
45317853525104446927986692358116127392886 deno = math.factorial(3*k)*(math.factorialCk)**0ecimal(3))*(640320»*(3*k))
START DecimalCt)/Decimal(deno)
please enter the number of decimal places to calculate Pi to: 1000 DecimaK l2)/Decimal(640320**Deciraal( 1.5))
3.141592653589734207668453591578298340762233260915706590894145498737666209401659
10806611734746968975779816037965556627803580134599593513286173176615982806223108
04419737853125305651521157470859338317744154596022745876277128465914181337399228
59535784112988088378242126794689633529216676947336619680715159349309584269265090
80187699606147066217003750206017344284513142480930327868775560407147230694298134 "\nTime taken:". time.timeO - start_tiree)
45787466657726444985596290919860559636358984008947138101161111956856848705962570
13872723252284798186917184867353096708222303615292971732815423261495480206046405
35398750760139733285849996526642119020066783578725502635682724402886356888437352
88982506842338309905740013758327701784908891322958527973601013169595019458889349
44236412539394146530738483636665042264154387773376017707109142428744379717832620
33721044052592738923786964883764463574460244839242316267458666952279157823643188
34956170648852260770217962185905198741140188951968612315753706167429421120955210 the number decimal calculate 1000
45317853525104446927986692358116127392886 141592653589734207668453591578298340762233260915706590894145498737666209401 1
□ [31m 1080661173474696897577981603796555662780358013459959351328617317661598280622311
Time taken: 5.99211573600769 44197378531253056515211574708593383177441545960227458762771284659141813373992;
>357841129880883782421267946896335292166769473366196807151593493095842692651
>18769960614706621700375020601734428451314248093032786877556040714723069429813.
>7874666577264449855962909198605596363589840089471381011611119568568487059625?
138727232522847981186917184867353096708222303615292971732815423261
1902006678357872550263568272440288635688843?
12506842338309905740013758327701784908891322958527973601013169595019458889■
423641253939414653073848363666504226415438777337601770710914242874437971783
13721044052592738923786964883764463574460244839242316267458666952279157823643181
1796218590519874Г 140188951968612315753706167429421 12095521
117853525104446927986692358116127392886

»I

www.bdmpublications.com
Hello, World

Python in Focus:
Stitching Black Holes
One of the biggest scientific, engineering and space-based projects came to a head in
2019, revealing humanity's first glimpse at the universe's most elusive object: a black
hole. But what's that got to do with Python?

Imaging a black hole is pretty difficult. The very nature of a in curved spacetime predicts that event horizons emit Hawking
black hole means that nothing can escape its immense gravitational radiation, with the same spectrum as a black body of a temperature
field, even light itself. To quote the Wikipedia entry for a black hole: inversely proportional to its mass. This temperature is on the order
of billionths of a kelvin for black holes of stellar mass, making it
"A black hole is a region of spacetime exhibiting gravitational essentially impossible to observe.”
acceleration so strong that nothing—no particles or even
electromagnetic radiation such as light—can escape from it. The Not that long ago a black hole was just a collection of theories
theory of general relativity predicts that a sufficiently compact mass and mathematics written down on paper, speculated only by the
can deform spacetime to form a black hole. The boundary of the brightest minds of our time. However, as with most things scientific,
region from which no escape is possible is called the event horizon. our understanding of the universe and our abilities to read it have
Although the event horizon has an enormous effect on the fate and greatly improved and, with the culmination of years of
circumstances of an object crossing it, no locally detectable features hard work by a collaboration of observatories,
appear to be observed. In many ways, a black hole acts like an ideal scientists and engineers, we got our first
black body, as it reflects no light. Moreover, quantum field theory image of a black hole.

EVENT HORIZON TELESCOPE

One of the problems regarding the imaging of such an object is


angular resolution. In Astronomy, the size of the objects in the night
sky is referred to by the amount of the sky they take up - units of
arc. An arc, or arc second, is a measurement (1/3600 of a degree)
that describes the size of an angle in degrees, designated by the
symbol °. A full circle is divided into 360° and a right-angle measures
90°. One degree can be divided into 60 arcminutes (abbreviated 60
arcmin or 60'). An arcminute can also be divided into 60 arcseconds
(abbreviated 60 arcsec or 60").

For example, looking at the moon, which is roughly 31 arcminutes,


imagine drawing a line from you to one side of the moon and
another to the opposite side of the moon, the angle between the
two lines is the angular size, or angular resolution.

The black hole at the centre of the Messier 87 galaxy, the one that
was imaged, is 55 million light years from Earth and has an angular
size of 40 microarc seconds, or one millionth of an arcsecond. So,
in order to see it, we would need a telescope with a diameter of
around 8Km, which simply isn’t possible as a single unit.

This is where the Event Horizon Telescope project comes into play.
Using a network of eight radio telescopes, scientists were able to
take images of the black hole over a period of around six months.
Critically timed, using atomic clocks, the telescopes imaged the area
of sky containing the black hole and collected the data, swapping
from one telescope array to the next as the Earth rotated.

60 www.bdmpublications.com
Python in Focus: Stitching Black Holes

This data was then collated across all the telescope arrays to the The end result is, of course, the image of the black hole at the centre
tune of over a thousand hard drives, which came to an astonishing 5 of the M87 galaxy that's surrounded by a ring of burning gasses. The
Petabytes of raw data. The problem now was collating all that data resolution isn’t great, as the team have since admitted, but, as they
into a workable form and presenting it as an image. also state, give it a couple of years and they’ll be able to increase the
image resolution significantly.
Katie Bouman, a Ph.D. in electrical
engineering and computer science All this is thanks to some clever Python code and some very brilliant
from MIT, was pivotal in creating the scientists and engineers.
Python code that was able to stitch
all that data together and form the
eventual, historic image of a black hole.

Bouman used a number of Python


libraries to achieve the result, Numpy,
Scipy, Pandas, Jupyter, Matplotlib
and Astropy, plus some unique custom Python code - which can be
found on Cithub at https://github.com/achael/eht-imaging.

www.bdmpublications.com 61
Index

Working
with Data

www.bdmpublications.com
Г Working with Data

Data is everything; it can topple


governments, change election results,
and tell us the secrets oF the universe.
Over these coming pages we look at how
you can create lists, tuples, dictionaries
and multi-dimensional lists, and then how
you can use them to Forge exciting and
useFul programs.

In addition, you will learn how you can


use the date and time Functions, write to
Files to your system and even create
graphical user interFaces that will take
your coding skills to new levels and into
new project ideas.

64 Lists
66 Tuples
68 Dictionaries
70 Splitting and Joining Strings
72 Formatting Strings
74 Date and Time
76 Opening Files
78 Writing to Files
80 Exceptions
82 Python Graphics
84 Combining What You Know So Far
86 Python in Focus: Gaming

www.bdmpublications.com
Working with Data

Lists
Lists are one of the most common types of data structures you will come 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 1 A list is a sequence of data values called items. You You can also access, or index, the last item in a list by
STEP3
a create the name of your list followed by an equals Ausing 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 isn't in the list, such as [10] will return an error:

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


mythical_creatures - ["Unicorn", "Balrog", mythical_creatures[-4]
"Vampire", "Dragon", "Minotaur"]
Python 3.4 2 Shell
File Edit Shell Qebug Options Windows Help
Python 3.4.2 Shell _ □ x
Python 3.4.2 (default. Oct 19 2014. 13:31:11)
File Edit Shell Debug Options Windows Help [GCC 4.9.1] on linux
Python 3.4.2 (default. Oct 19 2014. 13:31:11) Type “copyright”, "credits” or "licenseO" for more information.
[GCC 4.9.1] on linux »> numbers - [1. 4, 7, 21. 98, 156]
Type "copyright", “credits” or “licensee)" for more information. »> mythical_creatures = ("Unicorn”. “Balrog", “Vampire". "Dragon", "Minotaur")
>» numbers • [1. 4, 7, 21. 98. 156] »> numbers
>» mythical_creatures = ["Unicorn". "Balrog". “Vampire". "Dragon", "Minotaur") (1. 4. 7. 21. 98. 156]
»> numbers[3]
21
»> mythical_creatures
[•Unicorn’. ’Balrog’. Vampire’. ’Dragon’. ’Minotaur’)
»> mythical_creatures[3]
’Dragon’
»> numbers!-1]
156
»> numbers[-2]
98
»> mythical_creatures[-1]
’Minotaur’
>» mythical_creatures[-4]
’Balrog’
»>

STEP 2 Once you've defined your list you can call each STEP 4 Slicing is similar to indexing but you can retrieve
Aby referencing its name, followed by a number. Lists multiple items in a list by separating item numbers
A
start the first item entry as 0, followed by 1,2, 3 and so on. with a colon. For example:
For example:
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]
Type "copyright”, "credits” or “licenseO” 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_creatures = ("Unicorn". "Balrog", "Vampire". "Dragon”. "Minotaur")
»> numbers
[1, 4. 7, 21. 98. 156)
>» numbers [3]
Python 3.4.2 Shell 21
»> mythical_creatures
File Edit Shell Qebug Options Windows Help [’Unicorn’. 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 = ("Unicorn". “Balrog”. “Vampire". "Dragon". "Minotaur"] »> numbers [-2]
>» numbers 98
(1. 4. 7. 21. 98. 156) »> mythical_creatures[-1]
»> numbers[3] ’Minotaur’
21 »> mythical_creatures[-4]
»> mythical_creatures ’Balrog’
(’Unicorn’. Balrog’. ’Vampire’, ’Dragon’. ’Minotaur’] >» numbers! 1:3]
»> mythical_creatures(3] (4. 7]
>» numbers[0:4]
[1. 4, 7. 21]
>» numbers[3:5]
[21. 98]
»> numbers [1:]
[4, 7. 21. 98. 156)

www.bdmpublications.com
Lists

You can update items within an existing list, remove You can view what can be done with lists by entering
STEP 5 STEP 8
itemsand even join lists together. For example, to A 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)
Python 3.4.2 Shell _ □ x Type ‘copyright", credits" or iicense() tor more information.
»> dir(list)
File Edit Shell Qebug Options Windows Help
['__add__ ', '__ class__ ', '__ contains__ ', '__ delattr__ ’______ delitem__ ', '__ dir__ '
Python 3.4.2 (default. Oct 19 2014, 13:31:11) . '_ doc__ '. '_ eq___ '. '__ format__ '. ' ge__ '. '___ getattribute___ '. '_get item____ '
[GCC 4.9.1] on linux , '__ gt_______'_ hash__ ', '__ iadd__ ', '__ imul__ ', '__ init____ ', '__ iter_', '__ le___’
Type "copyright", "credits" or "licensee)" for more information. . '_ len__ ', '_ It___ '. '__ mul__ '. '__ ne__ '. '___ new__ '. '_ reduce____ '. '__ reduce_e
»> numbers - [1. 4. 7. 21. 98. 156] x__ ', '____ repr_ ', '__ reversed__ '. '__ rmul___', '__ setattr___ ', '_ setitem___ ', '____ s
»> mythical_creatures = ["Unicorn". "Balrog", “Vampire", "Dragon". "Minotaur"] izeof__ '. '__ str__ '. '__ subclasshook__ '. 'append', 'clear', 'copy', 'count', 'ex
>» everything = nunbers * mythical_creatures tend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>» everything »> numbers = [1. 4, 7. 21. 98. 156]
[1. 4. 7. 21. 98. 156. 'Unicorn'. 'Balrog', 'Vampire'. 'Dragon'. 'Minotaur'] »> numbers
(1. 4. 7. 21. 98. 156]
»> numbers. insert(4, 62)
»> numbers
[1. 4. 7, 21, 62, 98, 156]
ff
>» numbers.pop(4)
62
>» numbers
(1. 4, 7, 21. 98. 156]

Items can be added to a list by entering: You also use the list Function to break a string down
STEP 6 STEP 9
______ J numbers=numbers+[201]
________J into its components. For example:
list("David")
Or for strings:
Breaks the name David into 'D', 'а', V, T, 'd'. This can then be passed
mythical_creatres=mythical_creatures+["Griffin"]
to a new list:
Or by using the append function:
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
['Unicorn', 'Balrog', 'Vampire', 'Dragon', 'Minotaur']
»> numbers=nunbers+[201]
»> numbers
[1. 4, 7, 21. 98. 156. 201]
[
»> mythical_creatures-mythical_creatures
* "Griffin"]
»> mythical_creatures
['Unicorn', 'Balrog', 'Vampire', 'Dragon'. 'Minotaur', 'Griffin']
»> mythical_creatures.append("Nessie")
»> mythical_creatures
['Unicorn', 'Balrog'. 'Vampire'. 'Dragon'. 'Minotaur', 'Griffin', 'Nessie']
»> numbers.append(278)
»> numbers
[1, 4, 7, 21, 98, 156, 201, 278]
»> |

STEP 7 Removal of items can be done in two ways. The first STEP 10 Based on that, you can create a program to store
________J is by the item number: someone's name and age as a list:

del 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", "Vampire", "Dragon", "Minotaur ] user = Iname + lage
»> numbers
[1, 4, 7. 21, 98, 156]
»> mythical_creatures
[’Unicorn’, ’Balrog’, 'Vampire', '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]
»> mythical_creatures-mythical_creatures
*
[ "Griffin"]
»> mythical_creatures
['Unicorn', 'Balrog', 'Vampire', 'Dragon', 'Minotaur', 'Griffin']
»> mythical_creatures.append( "Nessie")
»> mythical_creatures
['Unicorn', 'Balrog', 'Vampire'. 'Dragon'. 'Minotaur', 'Griffin', ‘Nessie']
>» numbers.append(278)
»> numbers
[1, 4, 7, 21, 98. 156, 201, 278]
»> del numbers!7]
»> numbers
[1. 4. 7, 21. 98. 156. 201]
»> mythical_creatures.remove( "Nessie")
»> mythical_creatures
['Unicorn', 'Balrog', 'Vampire', 'Dragon', 'Minotaur'. 'Griffin']

www.bdmpublications.com
Working with Data

Tuples
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 they're
perfect 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 they're 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
STEP 3
a instance you use curved brackets instead of square a
multiple sets of data. For instance, here is a tuple
brackets. For example: called NPC (Non-Playable Characters) containing the character name
and their combat rating for an adventure game:
months^("January" , "February", "March", "April",
"May", "June") NPC= [ ("Conan", 100), ("Belit", 80), ("Valeria",
months 95) ]

Python 3.4.2 Shell _ □ x


File Edit Shell Eebug 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.
>>> months=("January”, "February", "March", "April", "May", "June")
»> months
(‘January’, ’February'. ’March’. ’April', ’May'. ’June')

STEP 2 Just as with lists, the items within a named tuple can STEP 4 Each of these data items can be accessed as a
a be indexed according to their position in the data whole by entering NPC into the Shell; or they can be
A
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 result Will display 100.
in an error in the Shell.
Python 3.4.2 Shell _ □ x
Eile Edit Shell £>ebug 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" tor more information.
»> MPC=[("Conan”. 100), ("Belit", 80). ("Valeria”, 95)]
»> NPC
[('Conan'. 100), (’Belit’, 80). (’Valeria’. 95)]
»> NPC[0]
(’Conan’. 100)
»> NPC[0] [1]
100

www.bdmpublications.com
Tuples

It's worth noting that when referencing multiple Now unpack the tuple into two
STEP 5 STEP 8
A tuples within a list, the indexing is slightly different ________J 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]

Python 3.4 2 Shell


£ile Edit Shejl fiebug Options windows Help

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


[6CC 4.9.1] on linux
Type "copyright", "credits" or "licenseO" for more information.
»> NPC=("Conan", 100)
»> (name, combat_rating)-NPC
»> name
’Conan'
>» combat.rating
100

This means of course that the indexing follows thus: STEP 9 Remember, as with lists, you can also index tuples
STEP 6
______ J using negative numbers which count backwards
A
from the end of the data list. For our example, using the tuple with
multiple data items, you would reference the Valeria character with:

NPC [2] [-0]

Python 3 4.2 Shell _ □ x


Which as you can imagine, gets a little confusing when you’ve 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 "copyright", "credits" or "licenseO" for more information. Type "copyright", “credits" or "licenseO" for more information.
»> NPC-(("Conan". 100). ("Belit", 80). ("Valeria". 95)] »> NPC-J("Conan", 100), ("Belit", 80). ( "Valeria", 95)]
»> NPC(O) »> NPC[2][-0]
('Conan'. 100) 'Valeria'
»> NPC[0][0] »>l
'Conan'
»> HPC[0][1]
100
»> HPC[1]
('Belit'. 80)
»> NPC[1][0]
'Belit'
»> NPC[1][1]
80
»> NPC[2]
('Valeria'. 95)
»> llPC[2] [0]
'Valeria'
»> HPC[2][1]
95

STEP 7 Tuples though utilise a feature called unpacking, You can use the max and min functions to find the
A
STEP 10
where the data items stored within a tuple are highest and lowest values of a tuple composed of
A
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=("Conan" , 100)
The numbers can be integers and floats. To output the highest and
lowest, use:

print(max(numbers))
print(min(numbers))

www.bdmpublications.com
Working with Data

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

Let's say you want to create a phonebook in Python. As with lists and tuples, you can check the contents
STEP1 STEP3
________ J You would create the dictionary name and enter ________ J 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 fashion to a list, which you're no doubt familiar
with by now.
phonebook={"Emma": 1234, "Daniel": 3456, "Hannah":
6789}

STEP 2 Just as with most lists, tuples and so on, strings STEP 4 The benefit of using a dictionary is that you
__________ A need be enclosed in quotes (single or double), can enter the key to index the value. Using the
A
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"}

www.bdmpublications.com
Dictionaries

Adding to a dictionary is easy too. You can include Next, you need to define the user inputs and
STEPS STEP 8
A a new data item entry by adding the new key and A
variables: one for 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: "))

You can also remove items from a dictionary by STEP 9 Note we've kept the number as an integer instead
STEP 6
______ л issuing the del command followed by the item's of a string, even though the value can be both
A
key; the value will be removed as well, since both work as a pair of an integer or a string. Now you 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:
de 1 phonebook["David" ]
phonebook[name] = number

STEP 7 Taking this a step further, how about creating a Now when you save and execute the code, Python
STEP 10
a piece of code that will ask the user for the dictionary will ask for a name and a number. It will then insert
A
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:

Phonebooks {} phonebook
phonebook["David" ]

If the number needs to contain spaces you need to make it a string,


so remove the int part of the input.

tile Edit Shell Debug Options Windows Help

Enter name: David


»> phonebook
('David': 98761
phonebook(0j:
RESTART

>» ................................ RESTART


Enter name: Bob
Enter phone nmber: 0987 654 3321 3344
»> phonobook
('Bob': ('0987 654 3321 3344')}

www.bdmpublications.com
Working with Data

Splitting and
Joining Strings
When dealing with data in Python, especially from a user's 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 functions, using .insert, .remove, and .pop but there are also functions that can be applied
to strings.

The main tool in the string function arsenal is .split(). Note that the text.split part has the brackets,
STEP1 STEP3
With it you're able to split apart a string of data,
A A 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="Daniel Hannah Emma"
text="January,February,March,April,May,June"
months=text.split(",")
months

Now let’s turn the string into a list and split the You've previously seen how you can split a string
STEP 2 STEP 4
________J content accordingly: ________J 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', 'а', V, T, 'd'. Whilst it may seem a little
Python 3.4 2 Shell _ о x useless under ordinary circumstances, it could be handy for creating
file Edit Shell Debug Options Windows Help a spelling game for example.
Python 3.4.2 (default. Oct 19 2014. 13:31:11)
[GCC 4.9.1] on linux
Type "copyright", "credits” or "licensee)” for more information.
»> text-’Daniel Hannah Enina"
»> names=text.split(" ”)
»> names
[’Daniel". "Hannah", ’Emma"]

www.bdmpublications.com
Splitting and Joining Strings

The opposite of the .split function is .join, where As with the .split function, the separator doesn't
STEP 5 STEP 8
Ayou will have separate items in a string and can join ______ J have to be a space, it can also be a comma, a full
them all together to form a word or just a combination of items, stop, a hyphen or whatever you like:
depending on the program you're writing. For instance:
colours=["Red", "Green", "Blue"]
alphabet="".join( ["a","b","c","d","e"]) col=",".join(colours)
alphabet col

This will display 'abcde' in the Shell.

You can therefore apply .join to the separated name There's some interesting functions you apply to a
STEP 6 STEP 9
A you made in Step 4, combining the letters again to ______ J string, such as .capitalize and .title. For example:
form the name:
title="conan the Cimmerian"
name="" .join (name) title.capitalize()
name title.title ()

We've joined the string back together, and retained the list called
Python 3.4.2 She)
name, passing it through the .join function.
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 "licensee)" for more information.
>» title-’conan the Cimmerian”
>» title.capitalize()
’Conan the Cimmerian’
»> title. title()
’Conan The Cimmerian’
>»> I

STEP 7 A good example of using the .join function is when You can also use logic operators on strings,
STEP 10
A you have a list of words you want to combine into a with the 'in' and 'not in' functions. These enable
A
sentence: you to check if a string contains (or does not contain) a sequence
of characters:
list=["Conan", "raised", "his", "mighty", "sword",
"and", "struck", "the", "demon"] message="Have a nice day"
text=" ".join(list) "nice" in message
text
"bad" not in message
Note the space between the quotes before the .join function (where "day" not in message
there were no quotes in Step 6's .join). "night" in message

www.bdmpublications.com
Working with Data

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

The basic formatting in Python is to call each You can of course also include integers into the mix:
STEP 1 STEP 3
_______J variable into the string using the curly brackets: A
number=10000
name="Conan" print("{} of {} was a skilled mercenary,
print("The barbarian hero of the Hyborian Age is: and thief too. He once stole {} gold from a
{}".format(name)) merchant.".format(name, place, number))

Remember to close the print function with two sets There are many different ways to apply string
STEP 2 STEP 4
л
of brackets, as you've encased the variable in one, л formatting, some are quite simple, as we've 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="Conan"
found at www.docs.python.org/3.1/library/string.html. Here, you
place="Cimmeria"
will find tons of help.
print("{} hailed from the North, in a cold land
known as {}".format(name, place))

Python 3.4.2 Shell - □ x


EHe Edit Shell Debug fiptions Windows Help
Python 3.4.2 (default. Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "copyright”. "credits" or "licensed" for more information.
»> name="Conan"
»> place»"Cimmeria"
»> print(“O hailed from the North, in a cold land known as {}".format(name. place))
Conan hailed from the North, in a cold land known as Cimmeria
»>l

www.bdmpublications.com
Formatting Strings

Interestingly you can reference a list using the string You can also print out the content of a user's input
STEP 5 STEP 8
formatting function. You need to place an asterisk in ________J 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! )

With indexing in lists, the same applies to calling a You can extend this simple code example to display
STEP 6 STEP 9
______ J list using string formatting. You can index each item ________J the first letter in a person's entered name:
according to its position (from 0 to however many are present):
name=input("What's your name? ")
numbers=l, 4, 7, 9 print("Hello {}.".format(name))
print("More numbers: {3}, {o}, {2}, lname=list(name)
{1}.".format(‘numbers)) print("The first letter of your name is a {o}".
format(‘Iname))

And as you probably suspect, you can mix strings You can also call upon a pair of lists and reference
STEP 7 STEP 10
________J 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 ("{o} 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[l] }
is {1[1] } years old.". format(names, ages))
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.
»> characters-["Conan". "Belit”, "Valeria", 19. 27. 20]
»> 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.
»>

www.bdmpublications.com
Working with Data

Date and Time


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.

First you need to import the Time module. It's one You can see the structure of how time is presented
STEP1 STEP3
л that’s built-in to Python 3 so you shouldn't need to ________ J by entering:
drop into a command prompt and pip install it. Once it's imported,
time.local.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, tm_
time.asctime()
min=6, tm_sec=13, tm_wday=3, tm_yday=250, tm_
isdst=o)'; obviously dependent on your current time as opposed
to the time this book was written.

The time function is split into nine tuples, these are There are numerous functions built into the Time
STEP 2 STEP 4
A divided up into indexed items, as with any other ________ J module. One of the most common of these is
tuple, and shown in the screen shot below. .strftimeQ. With it, you're able to present a wide range of arguments
as it converts the time tuple into a string. For example, to display the
current day of the week you can use:

Index Field Values time.strftime(’%A')

0 4-digit year 2016

1 Month 1 to 12

2 Day 1 to 31

3 Hour 0 to 23

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

www.bdmpublications.com
Date and Time

This naturally means you can incorporate various You saw at the end of the previous section, in the
STEP 5 STEP 8
_______________ j functions into your own code, such as: л
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.time ()-start_time

Note the last two entries, with %H and %H%M, as The output will look similar to the screenshot below.
STEP 6 STEP 9
Ayou can see these are the hours and minutes and as ______ J 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 log in. The length of time is
then displayed on the last line of the code as the endtime variable.
time.strftime("%H:%M")

This means you're going to be able to display There’s a lot that can be done with the Time
STEP 7 STEP 10
__________ .j either the current time or the time when module; some of it is quite complex too, such as
A
something occurred, such as a user entering their name. Try displaying the number of seconds since January 1st 1970. If you
this code 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")
Python 3.4 2 Shell _ □ x
print("User, name, "logged in at", time, Eile Edit Shell Debug Options Windows Help
strftime("%H:%M")) 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.
Try to extend it further to include day, month, year and so on. »> import tune
»> 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 tune. One is the number
of seconds since the Epoch, 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 1st, 1970.
The actual value can be retrieved by calling gntune(O).

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


The tuple items are:
year (including century, e.g. 1998)
month (1-12)

www.bdmpublications.com
Working with Data

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

STEP1 Start by entering some text into your system's text If you now enter poem into the Shell, you will get
STEP3
л editor. The text editor is best, not a word processor, л some information regarding the text file you've just
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 of the file:
Robert E Howard. You need to save the file as poem.txt.
poem.read()

Note than a /n entry in the text represents a new line, as you


used previously.

STEP 2 You use the open() function to pass the file into a STEP 4 If you enter poem.readQ a second time you will
A variable as an object. You can name the file object ______ J notice that the text has been removed from the file.
anything you like, but you will need to tell Python the name and You will need to enter: poem=open ( "/home/pi/Documents/
location of the text file you’re opening: Poem.txt") again to recreate the file. This time, however, enter:

poem=open("/home/pi/Documents/Poem.txt" ) print(poem.read())

This time, the /n entries are removed in favour of new lines and
readable text.

www.bdmpublications.com
Opening Files

Just as with lists, tuples, dictionaries and so on, STEP 8 Extending this further, you can use readlinesQ to
STEP 5
______ J you're able to index individual characters of the ________J grab all 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 [1]
lines [2]
Will display the next five. Entering (1) will display one character at
a time.

Similarly, you can display one line of text at a time by You can also use the for statement to read the lines
STEP 6 STEP 9
_______________ j using the readlineQ function. For example: of text back to us:

poem=open("/home/pi/Documents/Poem.txt") for lines in lines:


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

STEP 7 You may have guessed that you can pass the Let's imagine that you want to print the text one
STEP 10
readlinefl function into a variable, thus allowing you A 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 you've looked
at here. Try this:
poem=open("/home/pi/Documents/Poem.txt" )
line=poem.readline() import time
line poem=open("/home/pi/Documents/Poem.txt")
lines=poem.read()
Python 3.4.2 Shell _ □ x
for lines in lines:
File Edit Shell Debug Options 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 "licensee)" for more information.
»> poem=open("/home/pi/Docunents/Poem.txt") The output is fun to view, and easily incorporated into your own code.
»> line-poem. readline()
»> line
‘I remember\n’
>»l

www.bdmpublications.com
Working with Data

Writing to Files
The ability to read external files within Python is certainly handy but writing to a file is
better still. Using the write() function, youTe able to output the results of a program to
a file, that you 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.

STEP1 Start by opening IDLE and enter the following: However, the actual text file is still blank (you can
STEP3
a A check by opening it up). This is because you've
t=open("/home/pi/Documents/text.
written the line of text to the file object but not committed it to the
txt","w")
file itself. Part of the write() function is that you need to commit the
Change the destination from /home/pi/Documents to your own changes to the file; you can do this by entering:
system. This code will create a text file called text.txt in write mode
t.close ()
using the variable't'. If there's no file of that name in the location, it
will create one. If one already exits, it will overwrite it, so be careful.

You can now write to the text file using the write() If you now open the text file with a text editor,
STEP 2 STEP 4
function. This works opposite to read(), writing lines
A A you can see that the line you created has been
instead of reading them. Try this: written to the file. This gives us the foundation for some interesting
possibilities: perhaps the creation of your own log file or even the
t.write("You awake in a small, square room. A
beginning of an adventure game.
single table stands to one side, there is a locked
door in front of you.")

Note the 109. It's the number of characters you've entered.

Python 3.4.2 Shell


File Edit Shell flebug flptions 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.
»> t=open("/home/pi/Documents/text.txt". ”w")
»> t.write("You awake in a small, square room. A single table stands to one sid
e. there is a locked door in front of you.")
109

www.bdmpublications.com
Writing to Files

To expand this code, you can reopen the file using You can pass variables to a file that you've created
STEPS STEP 8
A 'a’, for access or append mode. This will add any text A in Python. Perhaps you want the value of Pi to be
at the end of the original line instead of wiping the file and creating written to a file. You can call Pi from the Math module, create a new
a new one. For example: file and pass the output of Pi into the new file:

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

You can keep extending the text line by line, Now let's create a variable called pi and assign it the
STEP 6 STEP 9
A ending each with a new line (\n). When you're ________J value of Pi:
done, finish the code with t.closeQ and open the file in a text
pi=math.pi
editor to see the results:
You also need to create a new file 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!.\n")
Remember to change your file location to your own particular
t.close ()
system setup.

STEP 7 There are various types of file access to consider To finish, you can use string formatting to call the
STEP 10
A using the open() function. Each depends on how the variable and write it to the file, then commit the
A
file is accessed and even the position of the cursor. For example, r+ changes and close the file:
opens a file in read and write and places the cursor at the start of
t.write("Value of Pi is: {}".format(pi))
the file.
t.close ()

You can see from the results that you're able to pass any variable to
a file.

www.bdmpublications.com
Working with Data

Exceptions
When coding, you'll naturally come across some issues that are out of your 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 of your code, Python includes exception objects which handle unexpected errors in the code. You
can combat errors by creating conditions where exceptions may occur.

STEP 1 You can create an exception error by simply trying You can use the functions raise exception to create
STEP3
a to divide a number by zero. This will report back A 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, of however results in a warp core breach. To stop the game from
which there are many. exiting due to the warp core going supernova, you can create a
custom exception:

raise Exception("warp core breach")

Most exceptions To trap any errors in the code you can encase the
STEP 2 STEP 4
A are raised A potential error within a try: block. This block consists
automatically when Python of try, except, else, where the code is held within try:, then if there's
comes across something that's an exception do something, else do something else.
inherently wrong with the code.
However, you can create your
own exceptions that are designed
to contain the potential error and
react to it, as opposed to letting
the code fail.

www.bdmpublications.com
Exceptions

For example, use the divide by zero error. You can Naturally, you can quickly fix the issue by changing
STEP 5 STEP 8
create an exception where the code can handle the A 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 result 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(input("Enter the second number: "))
print(a/b)
except ZeroDivisionError:
print("You have tried to divide by zero!")
else:
print("You didn't divide by zero. Well done!")

You can use exceptions to handle a variety of useful You can also use a finally: block, which works in a
STEP 6 STEP 9
A tasks. Using an example from our previous tutorials, ______ J 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", txt = open("/home/pi/Documents/textfile.txt",
"r") "r")
txt.write("This is a test. Normal service will try:
shortly resume!") txt.write("This is a test. Normal service will
except lOError: shortly resume!")
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. txt.close()
except lOError:
print ("Error: unable to write the file. Check
permissions")

STEP 7 Obviously this won't work due to the file textfile. As before an error will occur as you've used the
STEP 10
txt being opened as read only (the "r" part). So in A "r" read-only permission. If you change it to a "w",
this case rather than Python telling you that you’re doing something then the code will execute without the error being displayed in the
wrong, you've created an exception using the lOError 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.

www.bdmpublications.com
Working with Data

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

GOING GRAPHICAL
You can draw simple graphics, lines, squares and so on, or you can use one of the many Python modules available, to bring out
some spectacular effects.

One of the best graphical modules to begin learning The command turtle.circle(50) is what draws the
STEP1 STEP3
л
Python graphics is Turtle. The Turtle module is, as л 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. circle (50,
of paper on the floor. The Turtle module can be imported with: 180), where the size is 50, but you're telling Python to only draw
import turtle. 180° of the circle.

STEP 2 Let’s begin by drawing a simple circle. Start a New STEP 4 The last part of the circle code tells Python to keep
_______________ j File, then enter the following code: л 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.getscreen()._root.mainloop() 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)
turtle.getscreen()._root.mainloop()

You can see that we've inserted a loop to draw the sides of the square.

www.bdmpublications.com
Python Graphics

You can add a new line to the square code to add Now let's get the code by importing the Pygame module:
STEP 5 STEP 8
some colour: ________J
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) ■st py - /home/pi/Docui


File Edit Format Run Options Windows Help
w = 900
You can also use the command turtle.begin_fill 0 , and I1 । ■ pygame
h = 450 pygame.init()
turtle. end_f ill () to fill in the square with the chosen colours; img “ pygame. image.load("RPi.png")
screen = pygame.display.
red outline, yellow fill in this case. white - (255, 255, 255)
set_mode((w, h))

I
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(img.(0.0))
pygame.display.flip()
screen.blit(img, (0,0))
while True:
pygame.display.flip() for event in pygame.event.get():
if event.type -- pygame.QUIT:
pygame.quit()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()

You can see that the Turtle module can draw STEP 9 In the previous step you imported pygame, initiated
STEP 6
Aout some pretty good shapes and become a little A the pygame engine and asked it to import our saved
more complex as you begin to master the way it works. Enter Raspberry Pi logo image, saved as RPi.png. Next you defined the
this 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('red', ’yellow')
begin_fill ()
w - 900
while True:
h = 450
forward(200) screen = pygame.display.set_mode{(w, h))
left (170) screen.fill((white))
if abs(pos()) < 1:
break screen.fill((white))
end_f 1110 Screen.bLit(img,(0„□))
done() pygame.display.f1 ip <)
It's a different method,
Ah lie True:
but very effective.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()

STEP 7 Another way in which you can display graphics is Press F5 to save and execute the code and your
STEP 10
A by using the Pygame module. There are numerous A 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 browser and finding an image, then save it to the folder
where you save your Python code.

www.bdmpublications.com
Working with Data

Combining What
You Know So Far
Based on what you've looked at over this section, let's combine it all and come up with
a piece of code that can easily be applied into a real-world situation; or at the very
least, something which you can incorporate into your programs.

LOGGING IN
For this example, let's look to a piece of 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'.

Begin by importing the Time module, creating The global status statement separates a local
STEP1 STEP3
A a new dictionary to handle the usernames and variable from one that can be called throughout
A
passwords and creating a variable to evaluate the current status of the code, this way you can use the q=quit element without it being
the program: changed inside the function. We've also referenced some newly
defined functions: oldUser and newUser which we’ll get to next.
import time
users = {} def mainMenu():
global status
status = "" status - input("Do you have a login account? y/n? Or press q to quit.”)
if status == “y“:
oldUser()
elif status == "n”:
newllser()
elif status == "q”:
quite)

The newUser function is next:


STEP 4
A
def newUser():
STEP 2 Next you need to define some functions. You can createLogin = input("Create a login name: ")
a begin by creating the main menu, where all users
if createLogin in users:
will return to after selecting the available options:
print ("\nLogin name already exists!\n")
def mainMenu() : else:
global status createPassw = input("Create password: ")
status = input("Do you have a login account? users[createLogin] = createPassw
y/n? Or press q to quit.") print("\nUser created!\n")
if status == "y": logins=open("/home/pi/Documents/logins.txt",
oldUser() "a")
elif status == "n": logins.write("\n" + createLogin + " " +
newUser() createPassw)
elif status == "q": logins.close()
quit()
This creates a new user and password, and writes the entries into a
file called logins.txt.

quit()

def newUser():
createLogin = input("Create a login name: “)

if createLogin in users:
print (“\nLogin name already exists!\n“)
else:
createPassw - input(“Create password: ")
usersfcreateLogin] = createPassw
print(“\nUser created!\n“)
logins=open( "/home/pi/Oociments/logins.txt", "a")
logins.write( "\n" ♦ createLogin * " " ♦ createPassw)
logins.close( )|

www.bdmpublications.com
Combining What You Know So Far

You will need to specify your own location for the Finally, you need to continually check that the 'q' key
STEP 5 STEP 8
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 = displayMenu()
de" newUser():
createLogin = input("Create a login name: ") ‘login py-/home/pi/Documents/Python Code/login.py (3.4.2)
* _ □ x
File Edit Format Run Options Windows Help
if createLogin in users: I import time
print ("\nLogin name already exists!\n") users - {}
else: status =
createPassw ■ input(”Create password: ")
users[createLogin] = createPassw def mainMenu():
global status
print(”\nUser created!\n")
status = input("Do you have a login account? y/n? Or press q to quit.")
logins=open("/home/pi/Documents/logins.txt", "a") if status — “y“:
logins.write("\n" ♦ createLogin ♦ " " ♦ createPassw) oldUser()
logins.close() elif status ■■ “n“:
new<Jser()
elif status ■■ “q“:
quit()

def newUser():
Now to create the oldllser Function:
STEP 6 createLogin ■ input("Create a login name: ")

if createLogin in users:
print ("\nLogin name already exists!\n")
else:
createPassw = input("Create password: ")
def oldUser(): users[createLogin] ■ createPassw
print("XnUser created!\n")
login = input("Enter login name: ") logins-open("/home/pi/Documents/logins.txt", "a”)
logins.write(“\n" + createLogin +■■■•+ createPassw)
passw = input("Enter password: ") logins.close()

def oldUser():
# check if user exists and login matches login = input("Enter login name: ")
passw ■ input("Enter password: ")
password
# check if user exists and login matches password
if login in users and users[login] == passw: it login in users and users[login] == passw:
print (“XnLogin successful!\n")
print ("\nLogin successful 1\n") print ("User:", login, "accessed the system on:". tune.asctime())
else:
print ("User:", login, "accessed the system print ("XnUser doesn't exist or wrong password!\n")

on:", time.asctime()) while status ! = "q":


status - displayMenu()
else:
print ("\nUser doesn't exist or wrong
password!\n")
Although a seemingly minor two lines, the while
STEP 9
status " input("Do you have a login account? y/n? Or press q to quit.
*
') loop is what keeps the program running. At the end
if status == "y":
oldUser() of every function it's checked against the current value of status. If
elif status =» “n":
newUser() that global value isn't 'q' then the program continues. If it's equal to
elif status == "q“:
quit() ‘q’ then the program can quit.
def newUser():
createLogin = input(“Create a login name: “)

it createLogin in users:
print ("XnLogin name already exists!\n”)
else:
status ’ = q :
createPassw - input("Create password: ")
users[createLogin] = createPassw
status - displayMenuf)
print("\nUser created!\n“)
logins=open("/home/pi/Oocunents/logins.txt". "a")
logins.write(“\n" ♦ createLogin ♦ '' ” ♦ createPassw)
logins.close()

def oldUser():
login - input("Enter login name: “) You can now create users, then log in with their
passw = input(“Enter password: ") STEP 10
# check if user exists and login matches password
names and passwords, with the logins.txt file
A
if login in users and users[login] == passw:
print ("XnLogin successful!\n")
being created to store the login data and successful logins being
print (“User:", login, "accessed the system on:", time.asctune())
else:
time-stamped. Now it's up to you to further improve the code.
print ("\nUser doesn't exist or wrong password!\n")
Perhaps you can import the list of created users from a previous
session and display a graphic upon a successful login?

There’s a fair bit happening here. There are login


STEP 7
and passw variables, which are then matched to the
users dictionary. If there’s a match, then you have a successful login
and the time and date of the login is outputted. If they don’t match,
then you print an error and the process starts again.

def olduser():
login - input(“Enter login name: “)
passw ■ input(“Enter password: “)

# check if user exists and login matches password


if login in users and users[login] == passw:
print ("\nLogin successful!\n“)
print ("User:", login, "accessed the system on:". time.asctimeO)
else:
print ("\nUser doesn’t exist or wrong password!\n”)

www.bdmpublications.com
Working with Data

Python in Focus:
Gaming
Although not always considered as the ideal programming language for developing
games, Python has come a long way in recent years and is now one of the contributing
elements to a huge number of titles.
The video game industry generates something in the region of $140 billion each year, and that number is growing fast. It's a long way from
the 8-bit days of the Commodore 64 and ZX Spectrum; the arcade titles that used to devour our pocket money and the wood panelled
home consoles that Atari lovingly developed. These days, it's all about teams of coders, graphic artists, musicians, PR, projects and
development platforms.

GAME CODE

Coding a game from scratch, using raw code, has become


something of the past. Most games these days are created using
a range of development tools. These tools can be off-the-shelf
engines, such as the Unreal Engine, while others are custom built
around an original product, such as the world generating engine
that Bethesda use for the Skyrim and Fallout series of games.
Others examples can be coded from the ground up, but these
are generally few and far between. So where does Python fit
into all this?

The limiting factor with Python is performance. While most


games require a huge degree of performance from the platform BUILDING TOOLS
for which they are written, Python's code, which is good, isn’t
really designed to cope with the fast-paced formula on which In the game industry, Python is mostly limited to the
games such as Battlefield or the Call of Duty series are based. development of in-game tools used by the developers of the
These games are often coded with C++, or some other form of game, or to help bridge the gaps between different areas of
low-level programming language. But that doesn't mean Python code. For example, in-game tools coded in Python can be used by
is left out in the cold when it comes to game development, in designers to create levels for the game, or specific elements that
fact it's quite the opposite. would make up a character's inventory, or even creating dialog
between the player and non-playing characters in the game.

You will also find that Python can be used to control the game's
MONITOR FOR 6802 1.4 9-14-80 TSC ASSEMBLER PAGE 2
Al (Artificial Intelligence), which will give the characters in a game
CO00 ORG ROM+$0000 BEGIN MONITOR a certain element of life. As an example, the popular Sims games
C000 8E 00 70 START LDS #STACK
consist of characters other than the one the gamer controls.
These Sims will go about their business with their actions
* FUNCTION: INITA Initialize ACIA
* INPUT: none determined by the player's choices, this involves an advanced
* OUTPUT: none
* CALLS: none
form of Artificial Intelligence that is coded using Python.
* DESTROYS: acc A

0013 RESETA EQU %00010011 Other examples include many of the available open world
0011 CTLREG EQU %00010001
games, where the introduction of the player will change the
C003 86 13 INITA LDA A #RESETA RESET ACIA
course of a village’s, Town's, or even city's inhabitant’s behaviour.
C005 B7 80 04 STA A ACIA
C008 86 11 LDA A #CTLREG SET 8 BITS AND 2 STOP Blow up a few cars in the middle of the street and it'll affect
C00A B7 80 04 STA A ACIA
the way the other drivers behave; jump up and down on top of
C00D 7E CO Fl JMP SIGNON GO TO START OF MONITOR
a market stall in the middle of a medieval village and the folk
around you will react. This, again, is all down to Python code
* FUNCTION: INCH - Input character
* INPUT: none written within the main code of the game, alongside the game
* OUTPUT: char in acc A
♦ DESTROYS: acc A
development engine.
* CALLS: none
♦ DESCRIPTION: Gets 1 character from terminal

8i www.bdmpublications.com
PYTHON-POWERED GAMES

Some good examples of the types of games in which Python is


used are the following:

Battlefield 2 - Python is used for the game's add-ons and


functionality of the player elements.

The Sims - Al, and many of the game's interactions.


Civilisation - Python is used throughout the Civ games,
controlling movement and the non-player Al.

Eve Online - Utilises Python for floating point number


calculations and other tasks.

World of Tanks-Python is used to control Al objectsand detail


the large amount of graphical data.

In particular, it's worth noting that Python's use in games is due


to its ability to automate repetitive tasks quickly. While another
programming language may be faster at drawing the graphics
on the screen, Python can quickly repeat resizing hundreds of
textures in batches. There's also Python's excellent and sizeable
libraries that can be tweaked for certain tasks, specifically
in-game tasks freeing up other components to deliver the
performance that modern games need.

KEEP ON
GAMING
In short, while Python may
not be the ideal language
with which to create a
modern game entirely, its
use is often behind the
scenes, in areas where other
programming languages
will struggle. Python can
be used as the glue that
sticks elements of game
technologies together,
creating complex Al or simply
designing a dialog box.
Index

www.bdmpublications.com
Using Modules

A Python module is a Python-created


source File that contains the necessary
code for classes, functions and global
variables. You can bind and reference
modules to extend functionality,
and create even more spectacular
Python programs.
Are you curious about how to improve
your use of 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 with
graphics, animations and operating
system specific commands.

90 Calendar Module
92 OS Module
94 Using the Math Module
96 Random Module
98 Tkinter Module
100 Pygame Module
104 Basic Animation
106 Create Your Own Modules
108 Python in Focus: Artificial Intelligence

www.bdmpublications.com
Using Modules

Calendar Module
Beyond the Time module, the Calendar module can produce some interesting results
when executed within your code. It does Far more than simply display the date in the
Time module-like Format, you can actually call up a wall calendar type display.

WORKING WITH DATES


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

Launch Python 3 and enter: import calendar to There are numerous Functions within the Calendar
STEP 1 STEP3
________ J call up the module and its inherent Functions. Once module that may be of interest to you when
A
it's loaded into memory, start by entering: forming your own code. For example, you can display the number of
leap years between two specific years:
sep=calendar.TextCalendar(calendar.SUNDAY)
sep.prmonth(2019, 9) leaps=calendar.leapdays(1900, 2019)
print(leaps)
♦Python 3.5.3 Shell
*
The result is 29, starting From 1904 onward.
£ile Edit Shell Debug Dptions Window tfelp
Python 3.5.3 (default, Sep 27 2Q18, 17:25:39)
[GCC 6.3.0 20170516] on linux Python 3.5.3 Shell
license() ” for more information.
Type "copyright", "credits" or **
>» impor calendar File Edit Shell Debug Options Window Help
»> sep=calendar.Textcalendar(calendar.SUNDAY)
»> sep.prmonth(2019, 9) Python 3.5.3 (default, Sep 27 2018, 17:25:39)
September 2019 [GCC 6.3.0 2G170516] on linux
Su Mo TuWe Th Fr Sa Type "copyright”, "credits" or ,rlicense()” for more information
1 2 3 4 5 6 7 »> import calendar
8 9 1011 12 13 14 »> leaps=calendar.leapdays(19G0r 2019)
15 16 17 18 19 20 21 »> print(leaps)
22 23 2425 26 27 28 29
29 30 »>
»>
»>

You can see that the days of September 2019 are You could even Fashion that particular example into
STEP 2 STEP 4
displayed in a wall calendar fashion. Naturally you
A A a piece oF working, user interactive Python code:
can change the 2019,9 part of the second line to any year and
import calendar
month you want, a birthday for example (1973, 6). The first line
print (">>>>>>>>>>Leap Year Calculator
:
* <<<<<<<<<\n" )
configures Textcalendar to start its weeks on a Sunday; you can opt
yl=int(input("Enter the first year: "))
For Monday if you prefer.
y2=int(input("Enter the second year: "))
leaps=calendar.leapdays(yl, y2)
print("Number of leap years between", yl, "and",
y2, "is:", leaps)

www.bdmpublications.com
Calendar Module

You can also create a program that will display all You're also able to print the individual months, or
STEP 5 STEP 8
________ J the days, weeks and months within a given year: ________J days, of 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 you'll agree that’s quite a handy bit of code to have import calendar
to hand. for name in calendar.day_name:
print(name)

Python 3.5.3 Shell _ □ x


File Edit Shell Debug Options Window Help

Python 3.5.3 (default, Sep 27 2018, 17:25:39)


[GCC 6.3.G 20170516] on linux
Type "copyright", "credits" or "license()" for more information.
»> import calendar
»> for name in calendar.monthname:
print(name)

January
February
March
April
May

Interestingly we can also list the number of days in a The Calendar module also allows us to write the
STEP 6 STEP 9
month by using a simple: for loop: ________J functions in HTML, so that you can display it on a
website. Let's start by creating a new file:
import calendar
cal=calendar.Textcalendar(calendar.SUNDAY) import calendar
for i in cal.itermonthdays(2019, 6): cal=open("/home/pi/Documents/cal.html", "w")
print(i) c=calendar.HTMLCalendar(calendar.SUNDAY)
cal.write(c.formatmonth(2019, 1))
daysinmonth.py - /home/pi/Documents/daysinmor cal.close()
file Edit Format Run Options Window Help This code will create an HTML file called cal, open it with a browser
import calendar and it displays the calendar for January 2019.
cai=caler>dar .TextCalendarfcalerdar.SUNDAY)
for i in cal.iterjnonthdays(2019, 6): years.py-zn
print(i) В cal.html \ —____________________________ I file Edit Ffirmat Bun Options window Help
C © file:///home/pi/Documents/cal html >ort calendar
cal=open("/home/pi/Documents/cal.html", "w")
January 2019 c=calendar.HTMLCalendar(calendar.SUNDAY)
SunMonTueWedThuFriSat cal.write(c.formatmonth(2019, 1))
1 2 3 4 5 cal.close()
6 7 8 9 10 11 12
13 14 15 16 17 1819
20 21 22 23 24 25 26
27 28 29 30 31

STEP 7 You can see that, at the outset, the code produced Of course, you can modify that to display a given
STEP 10
some zeros. This is due to the starting day of the _________ J year as a web page calendar:
week, Sunday in this case, plus overlapping days from the previous
import calendar
month. Meaning the counting of the days will starton Saturday 1st
June 2019 and will total 30, as the output correctly displays. year=int(input("Enter the year to display as a
webpage: "))
Python 3.5.3 Shell cal=open("/home/pi/Documents/cal.html", "w")
cal.write(calendar.HTMLCalendar(calendar.MONDAY) .
formatyear(year))
cal.close()

This code asks the user for a year and then creates the necessary
webpage. Remember to change your file destination.

www.bdmpublications.com
Using Modules

OS Module
The OS module allows you to interact directly with the built-in commands Found in your
operating system. Commands vary depending on the OS youTe 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.

STEP 1 You can start the OS module with some simple The Windows output is diFFerent as that's the
STEP3
a Functions to see how it interacts with the operating A current working directory oF Python, as determined
system environment that Python is running on. iFyou’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.getcwd()
print(home)

The returned result From printing the variable home Yet another interesting element to the OS module,
STEP 2 STEP 4
is the current user’s home Folder on the system.
A A 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, iFyou wanted to launch the
the user name you log in as and the operating system you use. Chromium browser From within a Python program you can use
For example, Windows 10 will output: C:\Program Files (x86)\ the command:
Python36-32.
import os
[_# Python 3.62 Shell — □ X 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)]
on Win32
Type "copyright", "credits" or "license()" for more information.
»> import os
»> home=os. getcwd ()
»> print (home)
C:\Program Files (x86)\Python36-32
»>

www.bdmpublications.com
OS Module

The os.system() function is what allows interaction The ability to manipulate directories, or folders if
STEP 5 STEP 8
with external programs; you can even call up 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 file 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"')

You can also rename any directories you've created


STEP 9
______ J by entering:

import os
os.rename("NEW", "OLD")

To delete them:
For Step 5’s example we used Windows, to show
STEP 6
л 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
os.system('chromium-browser "http://
bdmpublications .com/" ' )

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 = r'/home/pi/Documents'
root_dst_dir = '/home/pi/backup/' + time.asctime()

for src_dir, dirs, files in os.walk(root_src_dir) :


dst_dir = src_dir.replace(root_src_dir, root_
Note in the previous step’s example the use of dst_dir, 1)
STEP 7
л 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 call 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=('chromium-browser "http://bdmpublications.
os.remove(dst_file)
com/"')
shutil.copy(src_file, dst_dir)
b=('chromium-browser "http://www.google.co.uk"’)
os.system(a + b) print(">>>>>>>>>>Backup complete<<<<<<<<<<")

www.bdmpublications.com
Using Modules

Using the Math Module


One of the most used modules you will come across is the Math module. As we've
mentioned previously in this book, mathematics is the backbone of programming and
there's an incredible number of uses the Math module can have in your code.

E- MG2
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 As you will no doubt be aware by now, if you know
STEP3
no need to PIP install it. As with the other modules л the name of the individual functions within the
present, you can import the module's function by simply entering module you can specifically import them. For instance, the Floor and
import math into the Shell, or as part of your code in the Editor. Ceil functions round down and up a float:

from math import floor, ceil


floor (1.2) # returns 1
ceil(1.2) # returns 2

Importing the Math module will give you access to The Math module can also be renamed as you
STEP 2 STEP 4
A the module's code. From there, you can call up any л import it, as with the other modules on offer within
of the available functions within Math by using math, followed by Python. This often saves time, but don't forget to make a comment
the name of the function in question. For example, enter: to show someone else looking at your code what you've done:

math.sin(2) import math as m


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

www.bdmpublications.com
Using the Math Module

Although it's not common practise, it is possible to For further accuracy, when it comes to numbers the
STEP 5 STEP 8
a import Functions From a module and rename them. A exp and expml functions can be used to compute
In this example, we're importing Floor From Math and renaming it precise values:
to F. Although where lengthy code is in use, this process can quickly
from math import exp, expml
become contusing:
exp(le-5) - 1 # value accurate to 11 places
from math import floor as f expml(le-5) # result accurate to full precision
f(1.2)

Importing all the Functions oF the Math Module can STEP 9 This level oF accuracy is really quite impressive, but
STEP 6
A be done by entering: quite niche For the most part. Probably the two
A
most used Functions are e and Pi, where e is the numerical constant
from math import *
equal to 2.71828 (where the circumFerence oFa 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. However, iF it works For you then go ahead.
print(math.e)
print(math.pi)

Python 3.4.2 Shell


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 "licensed" for more information.
»> import math
»> pnnt(math.e)
2.718281828459045
»> pnnt(math.pi)
3.141592653589793
»> I

Interestingly, some Functions within the Math The wealth oF mathematical Functions available
STEP 7 STEP 10
л
module are more accurate, or to be more precise are through the Math module is vast and covers
A
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 https://d0cs.pyth0n.0rg/3/
sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
library/math.html# Fora list oFavailable Math module Functions.
will return the value oF 0.999999999. Whereas:

fsum([.l, .1, .1, .1, .1, .1, .1, .1, .1, .1])

returns the value oF 1.0.

Python 3.4.2 Shell


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 "licensed" for more information.
»> from math import *
»> sum((.1, .1, .1, .1, .1, .1, .1, .1, .1. .1])
0.9999999999999999
>» fsum((.1, .1, .1, .1, .1, .1, .1, .1, .1, .1))
1 .0

www.bdmpublications.com
Using Modules

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

STEP1 Just as with other modules you need to import However, the Random module isn't used exclusively
STEP 4
л random before you can use any of the functions _______J for numbers. You can use it to select an entry from a
we're going to look at in this tutorial. Let's begin by simply printing a list from random, and the list can contain anything:
random number from 1 to 5:
import random
import random random.choice(["Conan" , "Valeria", "Belit"] )
print(randomint(0,5) )
This will display one of the names of our adventurers at random,
which is a great addition to a text adventure game.

In our example
STEP 2
A the number four
was returned. However, enter
the print function a few more
times and it will display different
integer values from the set of
numbers given, zero to five. The
overall effect, although pseudo­
STEP 5 You can extend the previous example somewhat by
random, is adequate for the
л having random.choiceQ select from a list of mixed
average programmer to utilise in
variables. For instance:
their code.
import random
1st=["David", 44, "BDM Publications", 3245.23,
"Pi", True, 3.14, "Python"]
rnd=random.choice(1st)
For a bigger set of numbers, including floating
STEP3 print(rnd)
______ J point values, you can extend the range by using the
multiplication sign:

import random
print(random.random() 100)
*

Will display a floating point number between 0 and 100, to the tune
of around fifteen decimal points.

www.bdmpublications.com
Random Module

Interestingly, you can also use a function within the Let's use an example piece of code which flips a
STEP 6 STEP 9
________J Random module to shuffle the items in the list, thus ________J 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(1st) import random


print(1st) output={"Heads":0, "Tails":0}
coin=list(output.keys 0)
This way, you can keep shuffling the list before displaying a random
item from it. for i in range (10000):
output[random.choice(coin) ] +=1

Python 3 4 2 Shell print("Heads:", output["Heads"])


File Edit Shell Qebug Options Windows help
print("Tails:", output [ "Tails"])
Python 3.4.2 (default. Oct 19 2014, 13:31:11)
(6CC 4.9.1) on linux
Type "copyright", "credits" or "licensee)" for more information.
»> import random
»> lst-["David", 44. "BDM Publications". 3245.23. "Pi". True. 3.14, “Python")
>» rnd=random.choice(1st)
»> print(rnd)
3245.23
»> random.shuffle(lst)
»> print(lst)
[3245.23, 44. ■David*1, "Python1. ’Pi1, True, 3.14. "BDM Publications’]
»> random.shuffle(lst)
>» print(lst)
I (44, 'BDM Publications'. True, 3245.23, ’Pi*. 'Python1, 3.14, ’David1]

Using shuffle, you can create an entirely random list


STEP 7
________ J of numbers. For example, within a given range:
import random
lst=[[i] for I in range (20)]
random.shuffle(1st) Here’s an interesting piece of code. Using a text
STEP 10
print(1st) A 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<<<<<<<<<<")


print("\nUsing a 466K English word text file I can
pick any words at random.\n")

wds=int(input("\nHow many words shall I choose?


") )

with open("/home/pi/Downloads/words.txt", "rt") as


f:
words = f.readlines()
...................................................... words [w.rstripO for w in words]

You can also select a random number from a given print("


STEP 8
______ J range in steps, using the start, stop, step loop:
for w in random.sample(words , wds):
import random print(w)

www.bdmpublications.com
Using Modules

Tkinter Module
While 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 interact with the user, and it's surprisingly powerful too.

GETTING GUI
Tkinter is easy to use but there's a lot more you can do with it. Let’s start by seeing how it works and getting some code into it.
Before long you will discover just how powerful this module really is.

STEP1 Tkinter is usually built into Python 3. However, if it's The ideal approach is to add mainloopQ into the
STEP3
л available when you enter: import tkinter, then A code to control the Tkinter event loop, but we'll
you need to pip install tkinter from the command prompt. get to that soon. You've 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=Button ()
import tkinter as tk btn.pack()
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.

STEP 2 It's not recommended to import everything from a STEP 4 You can combine the above into a New File:
A module using the asterisk but it won't do any harm л
import tkinter as tk
normally. Let's begin by creating a basic GUI window, enter:
from tkinter import *
wind=Tk() btn=Button()
btn.pack()
This creates a small, basic window. There's not much else to do at
btn["text"]="Hello everyone!"
this point but click the X in the corner to close the window.
Then add some button interactions:

def click():
print("You just clicked me!")
btn["command"] =click

www.bdmpublications.com
Tkinter Module

Save and execute the code from Step 5 and a You can create radio buttons too. Try:
STEP 5 STEP 8
A window appears with 'Hello everyone!’ inside. If you
from tkinter import *
click the Hello everyone! button, the Shell will output the text 'You
just clicked me!’. It's simple but shows you what can be achieved root = Tk()
with a few lines of code.
v = IntVar()
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux Label(root, root.title("Options"), text="""Choose
Type "copyright”, "credits" or "licenser)" for more information.
»> ================================ RESTART =================== a preferred language:""",
»> You just clicked me! justify = LEFT, padx = 20) .pack()
You just clicked me!
You just clicked me! Radiobutton(root,
text="Python" ,
padx = 20,
variable=v,
value=l).pack(anchor=W)
Radiobutton(root,
text="C++",
padx = 20,
variable=v,
You can also display both text and images within value=2).pack(anchor=W)
STEP 6
Aa Tkinter window. However, only GIF, PGM or PPM
mainloop()
formats are supported. So find an image and convert it before using
the code. Here's an example using the BDM Publishing logo:
STEP 9 You can also create check boxes, with buttons and
from tkinter import *
______ j output to the Shell:
root = Tk()
from tkinter import *
logo = PhotoImage (file=''/home/pi/Downloads/BDM_logo.
root = Tk()
gif")
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.get ()))
the BDM brand quickly grew from a single publication
Label(root, 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
varl = IntVar()
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 = IntVar()
the foundation that it has been built upon remains
Checkbutton(root, text="Mage", variable=var2).
the same, which is why we believe BDM isn't just
grid(row=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") mainloop()
root.mainloop()

The code from Step 9 introduced some new


STEP 10
A geometry elements into Tkinter. Note the
STEP 7
sticky=N, E and W arguments. These describe the locations of the
The previous code is check boxes and buttons (North, East, South and West). The row
quite weighty, mostly argument places them on separate rows. Have a play around and
due to the content see what you get.
variable holding a part
of BDM's About page
from the company
website. You can
obviously change the
content, the root.title
and the image to suit
your needs.

www.bdmpublications.com
Using Modules

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

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

Naturally you need to load up the Pygame modules Sadly you can't close the newly created Pygame
STEP1 STEP3
л into memory before you're able to utilise them. л window without closing the Python IDLE Shell,
Once that's done Pygame requires the user to initialise it prior to which isn't very practical. For this reason, you need to work in the
any of the functions being used: editor (New > File) and create a True/False while loop:

import pygame import pygame


pygame.init() from pygame.locals import *
pygame.init()

gamewindow=pygame .display.set_mode((800,600))
pygame.display.set_caption("Adventure Game")

running=True

while running:
for event in pygame.event.get():
if event.type==QUIT:
running=False
pygame.quit()

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


________ J it a title:
gamewindow=pygame.display.set_mode((800,600))
pygame.display.set_caption ("Adventure Game")

You can see that after the first line is entered, you need to click back
into the IDLE Shell to continue entering code; also, you can change
the title of the window to anything you like.

100 www.bdmpublications.com
Pygame Module

If the Pygame window still won't


STEP 4 Adventure Game
A close don't worry, it's just a
discrepancy between the IDLE (which is written
with Tkinter) and the Pygame module. If you
run your code via the command line, it closes
perfectly well.

You're going to shift the code around a bit now, img=pygame.image.load("/home/pi/Downloads/


STEP 5
A running the main Pygame code within a while loop; spritel.png")
it makes it neater and easier to follow. We’ve downloaded a graphic
def sprite(x,y):
to use and we need to set some parameters for pygame:
gamewindow.blit(img, (x,y))
import pygame
x= (800
0.45)
*
pygame.init ()
0.8)
*
y=(600
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

Let’s quickly go through the code changes. We've downloaded image called sprite) .png and allocated it to the
STEP 6
A defined two colours, black and 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 pygame *0.45)


x=(800
from pygame.locals import * *0
y=(600
.8)
pygame.init()
gamewindow-fill(white)
running=T rue sprite(x ry)
pygame.display.update()
while running:

gamewindow=pygameidisplay.set_mode((800,600))
pygame.display.set_caption("Adventure Game")
black=(0.0,0) foi event in pygame.event.get():
wtlite=(255,255,255) if event,type==QUIT:
img=pygame.image.load( '*/home/pi/Downloads/sprite1.png") running-False
pygame.quit()
def spriteCx^y):
gam ewindow, blit (img, (x,y))

www.bdmpublications.com
Using Modules

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


STEP 7
time containing a movement option within the
A
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.init()
i f 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:
black=(0,0,0)
if event.key==pygame.K_LEFT or event
white=(255,255,255)
key==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.f i11(white)
sprite(x, y)
0.45)
*
x= (800
pygame.display.update()
y=(600
0
* .8)
pygame.quit()
xchange=0

STEP 8 Copy the code down and using the left and right arrow keys on the keyboard you can move your sprite across the bottom of
the screen. Now, it looks like you have the makings of a classic arcade 2D scroller in the works.

le running:
import pygame
for event in pygame.event.get():
from pygame.locals import *
if event.type==QUIT:
pygame.init()
running=False
running»!rue
if event.type == pygame.KEYDOWN:
gamewindow=pygame.display .set_mode((800,600)) if event.key==pygame.K_LEFT:
pygame.display.set_caption( "Adventure Game") xchange=-5
black=(0,0,0) elif event.key==pygame.K_RIGH!:
white«(255,255,255) xchange=5
img=pygame.image.load("/home/pi/0ownloads/sprite1.png") if event.type==pygame.KEYUP:
if event.key==pygame.K_LEFT or event.key==pygame.K_RIGHT:
de- sprite(x.y): xchange=0
gamewindow.blit(img, (x.y))
x ♦- xchange
0.45)
*
x-(800
*
0.8)
y-(600 gamewindow.fill(white)
sprite(x.y)
xchange=0 pygame.display.update()
ungspeed=O
pygame.quit()

www.bdmpublications.com
Pygame Modules

You can now implement a few additions and utilise pygame.di splay.f1ip()
STEP 9
A some previous tutorial code. The new elements are clock.tick(60)
the Subprocess module, of which one function allows us to launch a continue
second Python script from within another; and we're going to create a break
New File called pygametxt.py:
pygame.quit()
import pygame
import time
import subprocess
pygame.init()
screen = pygame.display.set_mode((800, 250))
clock = pygame.time.Clock()

font = pygame.font.Font(None, 25)

pygame.time.set_timer(pygame.USEREVENT, 200)

def text_generator(text):
tmp = ''
for letter in text:
tmp += letter
if letter != ' ':
yield tmp

class DynamicText(object):
def _init__ (self, font, text, pos,
autoreset=False):
self.done = False
self.font = font
self.text = text
self._gen = text_generator(self.text)
self.pos = pos
self.autoreset = autoreset
self.update()

def reset (self):


self._gen = text_generator(self.text)
self.done = False
self.update()

def update(self):
if not self.done:
try: self.rendered = self.font, When you run this code it will display a long,
STEP 10
render(next(self._gen), True, (0, 128, 0)) A narrow Pygame window with the intro text
except Stopiteration: scrolling to the right. After a pause of 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 effect is quite good but there’s always room
subprocess.Popen("python3 /home/pi/Documents/ for improvement.
Python\ Code/pygame1.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 hand...")

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.
update()
else:
screen.fill(pygame.color.Color('black'))
message.draw(screen)

www.bdmpublications.com
Using Modules

Basic Animation
Python's modules make it relatively easy to create shapes, or display graphics and
animate them accordingly. Animation though, can be a tricky element to get right in
code. There are many different ways of achieving the same end result and we'll show
you one such example here.

LIGHTS, CAMERA, ACTION


The Tkinter module is an ideal starting point For learning animation within Python. Naturally, there are better custom modules
out there, but Tkinter does the job well enough to get a grasp on what's needed.

STEP1 Let's make a bouncing ball animation. First, we Insert the new code between the balll
STEP3
A will need to create a canvas (window) and the ball A = canvas.create_oval(5,5,60,60,
to animate: fill = 'red') line and the gui .mainloop () line. Save it and
Run. You will now see the ball move from the top left corner of the
from tkinter import *
animation window, down to the bottom right corner. You can alter
import time
the speed in which the ball traverses the window by altering the
gui = Tk() time . sleep (. 01) line. Try (.05).
gui.geometry("8 00x600" )
Pi Animation
gui.title("Pi Animation")
canvas = Canvas(gui,
width=800,height=600,bg='white')
canvas.pack()

balll = canvas.create_oval(5,5,60,60, fill='red')

gui.mainloop()

Save and Run the code. You will see a blank window
STEP 2
Aappear, with a red ball sitting in the upper leFt
corner oF the window. While this is great, it's not very animated.
Let's add the Following code:

a = 5
b = 5

for x in range(0,100):
canvas.move(balll, a,b)
gui.update()
time.sleep(.01)

step2.py-/home/pi/Documents/step2.py (3.5.3) - n
STEP 4 The canvas .move (balll, a, b) line is the part
File Edit Format Run Options Window Help
A that moves the ball From one corner to the other;
Il from tkinter import *
I import time obviously with both a and b equalling 5. We can change things around
gui = Tk() a bit already, such as the size and colour oF the ball, with the line:
gui.geometry("800x600") balll = canvas.create_oval(5,5,60,60, fill='red')
gui.title("Pi Animation")
canvas = Canvas(gui, width=800, height=600, bg='white‘) and we can change the values oF a and b to something else.
canvas.pack()

balll = canvas.create_oval(5,5,60,60, fill='red') balll = canvas.create_oval(7,7,60, 60, f111='red')


a = 5
b = 5
a = 8
b = 3
for x in range(0,100):
canvas.move(balll,a,b) for x in range(0,100):
gui.update()
time.sleep(.01)
canvas.move(balll, a, b)
gui.update()
I gui.mainloop() time.sleep(.05)

www.bdmpublications.com
Basic Animation

Let's see if we can animate the ball so that it bounces STEP 9 Now add the Following:
STEP 5
________J around the window until you close the program. л
def main():
xa = 5
pygame.init()
ya = 10
screen = pygame.display.set_mode((640,480))
while True: pygame.display.set_caption("Starfield
canvas.move(balll,xa,ya) Simulation")
pos=canvas.coords(balll) clock = pygame.time.Clock()
if pos[3] >=600 or pos [1] <=0:
init_stars(screen)
ya = -ya
if pos[2] >=800 or pos[0] <=0: while True:
xa = -xa # Lock the framerate at 50 FPS
gui.update() clock.tick(50)
time.sleep(.025)
# Handle events
for event in pygame.event.get():
Remove the code you entered in Step 2 and insert if event.type == pygame.QUIT:
STEP 6
A the code From Step 5 in its place; again, between the return
balll = canvas.create_oval(5,5,60,60, fill='red')
screen.fill((0,0,0))
and the gui. mainloop () lines. Save the code and Run it as normal.
move_and—draw_stars(screen)
IF you've entered the code correctly, then you will see the red ball
pygame.display.flip()
bounce oFF the edges oF the window until you close the program.
if _ name__ == "__ main__ " :
main()
The bouncing animation
STEP 7
A takes place within the
canvas.nove(balll, xa, va) def main():
while True loop. First, we have the values pos=canvas.coords(balll)
if pos[3j >=6«a or pos[i] <=b: pygame.init()
screen = pygame.display.set_mode((640,480))
of xa and xy before the loop, both of 5 and if pos[2] >-800 or pos[0] <-0;
pygame.display.set_caption("Starfield Simulation")
gui.update()
10. Thepos=canvas . coords (balll) line time.sleep(.025) clock = pygame.time.Clock()

takes the value of the ball's location in the | init_stars(screen)


window. When it reaches the limits of the
while True:
window, 800 or 600, it will make the values # Lock the framerate at 50 FPS
negative; moving the ball around the screen. clock.tick(50)

# Handle events
for event in pygame.event.get():
Pygame, however, is a much better module at if event.type == pygame.QUIT:
STEP 8 return
A producing higher-end animations. Begin by creating
a New File and entering: screen.fill((0,0,0))
move_and_draw_stars(screen)
pygame.display.flip()
import pygame
from random import randrange if __ name__ == "__ main__
main()
MAX_STARS = 250
STARJSPEED = 2

def init_stars(screen): Save and Run the code. You will agree that the
STEP 10
""" Create the starfield """ лsimulated starfield code looks quite impressive.
global stars Imagine this as the beginning of some game code, or even the start
stars = [] to a presentation? Using a combination of Pygame and Tkinter, your
for i in range(MAX_STARS): Python animations will look fantastic.
# A star is represented as a list with this
format: [X,Y]
star = [randrange(0,screen.get—width() - 1),
randrange(0,screen.get—height() - 1)]
stars.append(star)

def move_and—draw_stars(screen) :
""" Move and draw the stars """
global stars
for star in stars:
star[l] += STAR_SPEED
if star[l] >= screen.get—height():
star[l] = 0
star[0] = randrange(0,639)

screen.set—at(star,(255,255,255))

www.bdmpublications.com
Using Modules

Create Your Own Modules


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

BUILDING MODULES
Modules are Python files, containing code, that you save using a .py extension. These are then imported into Python using the
now familiar import command.

STEP1 Let's start by creating a set of basic mathematics Now you're going to take the function definitions
STEP3
л functions. Multiply a number by two, three and л out of the program and into a separate file.
square or raise a number to an exponent (power). Create a New File Highlight the function definitions 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 files, one with the function definitions, the other with
def timestwo(x):
the function calls.
return x * 2

def timesthree(x):
return x * 3

def square(x):
return x * x

def power(x,y):
return x ** у

STEP 2 Under the above code, enter functions to call the STEP 4 If you now try and execute the basic_math.py code
______ J 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 function definitions.
print (timesthree(3))
print (square(4)) Traceback (most recent call last):
File "/home/pi/Documents/Python Code/basic_math.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. >»l_____________________________________________________

Return to
STEP 5
the newly
created window containing
the function definitions, and
click File > Save As. Name this
minimath.py and save it in the
same location as the original
basic_math.py program. Now
close the minimath.py window,
so the basicjmath.py window is
left open.

www.bdmpublications.com
Create Your Own Modules

Back to the basic_math.py window: at the top of the STEP 9 Finally, you can now create a range of if statements
STEP 6
_______________ j code enter: a to determine what to do with the number and
utilise the newly created function definitions:
from minimath import *
if choice == '1' :
This will import the function definitions 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")

You can now use the code further to make the


STEP 7
Aprogram a little more advanced, utilising the newly
created module to its full. Include some user interaction. Start by
creating a basic menu the user can choose from:

print("Select operation.\n")
print("1.Times by two")
print("2.Times by Three")
print("3.Square")
print("4.Power of")

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

Now we can add the user input to get the number


STEP 8
________ J the code will work on:
numl = int(input("\nEnter number: "))

This will save the user-entered number as the variable numl.


STEP 10 Note that for the last available options, the Power
A of choice, we've added a second variable, num2.
This passes a second number through the function definition called
power. Save and execute the program to see it in action.

www.bdmpublications.com
Using Modules

Python in Focus:
Artificial Intelligence
Artificial Intelligence (Al) and Machine Learning (ML) are the new hot topics of the IT
industry. Al is fast becoming the working science fiction that it has been portrayed as in
the past, and behind it is Python.

Despite how close Al and ML are, there are distinct differences


between the two technologies. Al refers to the study of how to train a
computer to accomplice the things that humans can do significantly
better and faster. Whereas, ML is the ability for a computer to learn
from its experiences, so that the outcome and performance will
eventually become more accurate and accomplished.

While different, they are both essentially discussing the same


element: training a system to learn and do things independently.
Where Al is said to lead to wisdom, ML reportedly leads to knowledge
and, thanks to Python, that gap is getting closer every day.

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D

batch_size =126
num_classes = 10
epochs = 12

# input image dimensions


img_rows, img_cols = 28, 28

(x_train, y_train), (x_test, y_test) = mnist.load_data()

APPLICATIONS DIGITAL ASSISTANTS

Both Al and ML are hugely present in today's technology. Where, The rise of digital assistants has been one of the kick-starters of
just a few years ago, most of us associated Al with the rise of a Al and ML programming. Siri, Cortana, Alexa and Google Assistant
super-intelligent legion of killer robots, nowadays you'd be amazed are all coded using Python, and are designed to listen, learn and
at the numerous examples of Al in your house, and even being respond to what we ask of them. With Python, this level of Al is
carried around with you. surprisingly simple, thanks to the many libraries and customisation
of the language. These frameworks make creating Al and ML easy
Let's begin with the obvious use of Al and ML, the smartphone. for intelligent coders, cutting down on the development time in
These devices have infiltrated most of our modern world, with other languages and, thanks to Python's easy to read code and
globalcoverage reaching 5.5 billion for 2019 and set to rise to over complex algorithms, these developers can devote significant time to
6 billion by the end of 2020, it's little surprise to discover that Al and improving the performance and accuracy of Al.
ML are advancing in leaps and bounds.
Every time we ask one of these digital assistants for something, the
With nearly all of the population of humanity within reach of a Python-driven Al code is reading our voice, determining what it is
smartphone, the coding behind these devices has been developed we're asking by plucking out key words and acting on them. If we
to take individuals into account. These devices are designed to ask for a thirty second countdown, it'll start the device's stopwatch
learn what the user requires, or uses, the device for. Common function; if we ask for dinner suggestions, it'll open a specific set of
numbers called are pushed to the top of the list, in-app and in-game web pages, and if we ask it to play some music, it'll interrogate the
advertising is moulded around our browser and search preferences, available music apps to select what it is we wanted. All the time,
as well as other apps we've installed in the past. And even our the Al code is being trained to listen more intently, while the ML
voices, fingerprints and faces are stored and analysed by Al and ML is learning from the Al results so that its accuracy is improved for
in order to recognise who we are. future questions and requests.

108 www.bdmpublications.com
Python in Focus: Artificial Intelligence

BEYOND THE SMARTPHONE

Consider Google, social media and the content you look up. How many times
have you entered a search string into Google, such as car parts Fora Mk1
Ford Escort and, when you've opened Facebook, you suddenly Find a group
suggestion oFFord Escort owners? That’s Al and ML injecting themselves into
your everyday computing tasks.

Another example oF Al and ML working together is Gmail's recent addition oF


suggested completions For sentences you are typing. iFyou Frequently sign
oFF with 'See you soon', or 'All the best', then typing 'See' or 'All' will prompt
the ML side oF the equation to autoFill the remainder oF the words For you. All
the time, the ML is learning while the Al is telling it what to improve on.

Facial recognition is another element oF Al and ML that’s been the target oF


the popular press For some time. Throughout 2019, Facial recognition systems
on both smartphones and CCTV Footage have improved dramatically.
Agencies controlling this level oF Al now have the ability to single out an
individual From a crowded street and, while that's great For law and order,
it does pose a potential threat to our privacy. AFter all, who watches the
watcher?

Tesla's work on selF-driving cars means they are getting closer to being the
norm, and it’s Python along with its controlling Al and ML work that’s, excuse
the pun, driving it Forward. In these circumstances, Python is doing a lot
oF the heavy liFting, providing the connective tissue and libraries that are
designed to implement Al and ML. In the background, you’ll usually Find
C++, or some other language, that's supporting the performance and
overall program in which the Al and ML are working.
I’№
While it's easy to portray a bleak Al Future, let's not Forget
the many great instances oF Al we currently enjoy: optical
character recognition, handwriting recognition, image
processing, helping people with visual and hearing
disabilities, advancements in space exploration,
engineering improvements, conservation,
pharmaceutical and drug improvements and
greater Freedom For those limited in their
ability to travel. It's not all about two Al bots
arguing about eliminating the human race.

THE FUTURE
OF Al
Whether well end up creating true
Al, killer robots and selF-aware
androids is up For debate. There are
plenty oF arguments For and against
the evolution oF Al, with many
believing that Al will be the worst
possible Future humans can create
-worse even than nuclear war. For
the moment, however, we’re at the
early stages oF Al development,
but with Python's continual
advancements and improved
libraries, it may not be too long
before we’ve got an Al system
that's getting better by the hour.

www.bdmpublications.com
A и
л Index
*1 d.

V 1 & € i □ S 11
i vl p a TaP w 1
Я □
и n
u X
&
o'

# си z Л A 9 □ a E II F a fU $
A Q 11 И И a J л к b И c сс'
11 P b 3 Й1 ; - й I Я u О Й w X A
□“ -11 / 14 Л о и
co in h й л и и д □ A Z aj d # Я 4 ?Г 1/1 1 "ие о и -
0 1
1 1
ии
1 1 000

Code
1 1
1
0 01
1 000

000
4
10

Repository
0
1
0
11 100
01 0 0 i11
и 1
0
1 0 00 1 я
0 0 0
1 0 Й 1 0»
1 0 г
0 1
1 1 й
0 0 10101
1
0 0
1 0 0 1
0 1
°?
0
0

j 1Й 0

0
q
11“

SHARE YOUR CODE!


The code listed within this section can be downloaded
as a Python file, so you don't have to type it out. Simply
visitwww.bdmpublications.com/code-portal, sign up
for access to the portal and the code is available as a
compressed file for you to download and execute.
Maybe you've written something amazing and want to
show it off; if so, why not send it in and we can add it
to the Code Portal as well as mention it via our social
media accounts.

Tell 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: enquiries:bdmpublications.com. We look


forward to seeing what you've done.

V '' A
ow w VI
u/o и
A V 5 m
N • s f ?
j ai
110 w ww. bd£h p ublica ti о n Cfeo i F t W “II LJ A
В d 1 a 0
n Л % 5
я L □□BaaBaA:_ a

oi i i j о vv и , i__ i ■

\ й » F В d fy c- / y@
vi 7 . _ • 1 в W,Й 5 1 "n ; = й й се И ii ... nJ rii cu
9
W B □ n Is fl W 0 ' ' ■ - r

We've included a vast Python code


repository For you to Freely use in
your own programs. There's plenty in
here to help you create a superb piece oF
programming, or extend your project ideas.

We've got 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. We've
broken down some oF the newer, and
extended, concepts oF the code to help
you better understand what’s going on.
This way you can easily adapt it to your
own uses.

This is an excellent resource that you


won't Find in any other Python book. So
use it, take it apart, adapt it to your own
programsand see what you can create.

112 Python File Manager


114 Number Guessing Came
116 Random Number Generator
117 Random Password Generator
118 Text to Binary Convertor
120 Basic GUI File Browser
122 Mouse Controlled Turtle
123 Python Alarm Clock
124 Vertically Scrolling Text
126 Python Digital Clock
128 Playing Music with the Winsound Module
130 Text Adventure Script
132 Python Scrolling Ticker Script
133 Simple Python Calculator
134 Hangman Game Script

ц ? И ci q , , ” Я u $ n \
t ’ Ч V X V ) \ П www-bdrn^blj^tiojK.corn f 111
5 A G x % ■ Я в □ } g n d
** I I v F7I
Python File Manager
G> •u ® QJ

V
This Hie manager program displays FILEMAN.PY
a list of optionsShat allow you to
Copy the code below into a New > File and save it as FileMan.py.
(Я О read a file, write to a file, append to Once executed it will display the program title, along with the
1 q current time and date and the available options.
о a file, delete a file, list the contents la
a of a directory and much more. It's
J remarkably easy to edit and insert A import shutil

и О4 intfiybift own code, or add to. import os


import time
import subprocess
7 х
def Read():
о
W +
path=input("Enter the file path to read:")
file=open (path, "r")
0 print (file. read ())
4 h input('Press Enter../)
file, close ()

def Write ():


path=input("Enter the path of file to write or create:")
if os .path. isfile (path):
print ('Rebuilding the existing file')
VI pi@raspbenypi: -/Documents/Python Code
else:
S И File Edit Tabs He
print ('Creating the new file')
»»»»»Python 3 File Manager<««««< text=input("Enter text:")
The current time and date is: Fri Sep 15 08:22:42 2017 file=open(path,"w")
4 Choose the option number:

1.Read a file
file .write (text)

О M 2.Write to a file
3.Append text to a file
def Add():
Ca '5.Check file existence path=input("Enter the file path:")
7.Move a file
text=input("Enter the text to add:")
10.Delete a directory file=open (path, "a")
11.Open a program
12.Exit file .write ('\n'+text)

def Delete ():


This part of the code imports the necessary modules. path=input("Enter the path of file for deletion:")
if os.path.exists(path):
The OS and Subprocess modules deal with the
print ('File Found')
operating system elements of the program.
os. remove (path)
ГП
№ print ('File has been deleted')
Each def XXX() functions store the code for each else:
В
of the menu's options. Once the code within the print ('File Does not exist')
a function is complete, the code returns to the main
menu for another option. def Dirlist():

я This is part of the code that checks to see what OS


path=input("Enter the Directory path to display:")
sortlist=sor ted (os. listdir (path))
i=0
CQJ the user is running. In Windows the CLS command
while (i<len (sortlist)):
vl clears the screen, whereas in Linux and macOS, the
Clear command wipes the screen. If the code tries
print (sortlist [i]+' \n')
и to run CLS when being used in Linux or macOS, an
i+=l

error occurs, which then prompts it to run the Clear def Check():
command instead. fp=int(input('Check existence of \nl.File \n2.
Directory\n'))
These are the options, from 1 to 12. Each executes if fp==l:
the appropriate function when the relevant number path=input("Enter the file path:")
is entered. os .path. isfile (path)

a
г g It ?
112 www.bdmpoplicationLcom t ’ *1
□ Cl ° d 5 A
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) 11 . Open a program
if os .path.isdir (path) ==False: 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('1.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()
4
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 ,path2) 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 ("1.Return to menu\n2.Exit \n"))
print ('Directory Created') if run==2:
exit()
def Removedir ():
path=input('Enter the path of Directory:')
treedir=int(input('1.Deleted Directory \n2.Delete
Directory Tree \n3.Exit \n'))
if treedir==l:
os. rmdir (path)
if treedir==2:
shutil. rmtree (path)
print ('Directory Deleted')
if treedir==3:
exit()

def Openfile ():


path=input('Enter the path of program:')
try:
os. startfile (path)
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( 'clear')
managementand manipulation; and theTime 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 clear the screen, while Linux uses clear.
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 113
Number Guessing Game
G> a И В u о
QJ - Л П.
0
This is a simple little piece of code NUMBERGUESS.PY
V C
0/ but it makes good use of the о Copy the code and see if you can beat the computer within
₽i о Random module, print and input, и five guesses. It's an interesting bit of code that can be quite
1 q and a while loop. The number of handy when your implementing a combination of the Random
ci c la module alongside a while loop.
a guesses can be increased from 5
and the random number range tan import random 1
>3
u 0 easily be alterecEtoo. C " a A guessesUsed = 0
4 0 9 n Name=input('Hello! What is your name? ')
Й A U J1 9 9 fl
7 x q И number = random.randint(l, 30)
print ('Greetings, ' + Name + I\'m thinking of a
о NumberGuess.py - /home/pi/Docum...hon Code/NumberGuess.py (3.4.2) a number between 1 and 30.')
W
Eile Edit
import random
Farm at Bun Options Windows Help
c while guessesUsed < 5:

0 6) guess=int(input('Guess the number within 5 guesses...'))

4 h
guessesUsed - 0
Натегinput('Hello! what is your name? ') guessesUsed = guessesUsed + 1
number - random.randint(1, 30)
print('Greetings. ' + Name + '. I\'m thinking of a number between 1 and 30.') if guess < number:
g P
while guessesUsed < 5:
guess=int(input('Guess the number within 5 guesses...'))
A print ('Too low, try again.')
guessesUsed - guessesUsed + 1
j if guess < number: if guess > number:
5
print('Too low. try again.)
if guess > number:
print('Too high, try again.')
к print ('Too high, try again.')

й € f guess == number:
break
if guess == number:
guessesUsed • str(guessesUsed)
w if guess == number:
break
VI if guess == number:
и к
print('Well done. ' + Name + ! You guessed correctly in ' * guessesUsed <

Б if guess != number: guessesUsed = str (guessesUsed)


nunber - str(number)
print('Sorry. out of guesses. The nunber I was thinking of is ' + number) print ('Well done, ' + Name + '! You guessed
correctly in ' + guessesUsed + ' guesses.')

4 h. if guess != number:
Python 3 4 2 Shell

0 M File Edit Shell Debug Options Windows Help number = str (number)
Python 3.4.2 (default. Oct 19 2014. 13:31:11) print ('Sorry, out of guesses. The number I was
Ся [GCC 4.9.1] on linux
Type "copyright", "credits" or "licensee)” for more information. thinking of is ' + number)
В »> ................................ RESTART — °/c
*1 Hello! What is your name? David
Greetings, David, I'm thinking of a number between 1 and 30.
Guess the number within 5 guesses...26 Although this is a reasonably easy to follow program, there are
Too high, try again. 11 1
Guess the number within 5 guesses...20
Too high, try again.
some elements to the code that are worth pointing out. To begin
Guess the number within 5 guesses...15 & with, you need to import the Random module, as you’re using
Well done, David! You guessed correctly in 3 guesses.

@ random numbers within the code.


9 c 1Z_Y 1 2
У и Elie Edit
NumberGuess py - /home/pi/Docum...hon Code/NumberGuess py (3.4 2)
Farm at Bun Options Windows Help
0 This section of the code creates the variables for the number
of guesses used, along with the name of the player, and also
m random

guessesUsed - 0
setsup the random number between 1 and 30. Ifyou wanta
Hame=input('Hello! What is your name? ') ”i wider range of random number selection, then increase the
number - random.randint( 1, 30)

a print('Greetings. ' + Name + '. I\'m thinking of a number between 1 and 30.')
while guessesUsed < 5:
guess=int(input('Guess the number within 5 guesses...'))
61 number=random.randint(1,30) end value of 30; don’t make
it too high though or the player will never be able to guess it.
guessesUsed ■ guessesUsed ♦ 1 q
if guess < number:
c If the player guesses too low or too high, they are given the
a guess > number:
print('Too high, try again.') appropriate output and asked to try again, while the number
■и guess == number:
of guesses is less than five. You can also increase the number of
guess == number:
CQj guessesUsed - str(guessesUsed) guesses from 5 by altering the while guessesUsed < 5: value.
□ vl printf’Well done. ' + Name + '! You guessed correctly in ’ + guessesUsed
a
cn
guess != number:
number - str(number)
print('Sorry. out of guesses. The number I was thinking of is ' + number)
1 If the player guessed the correct number then they are given a
'well done' output, along with how many guesses they used up.
w 9 6i
If the player runs out of guesses, then the game over output is
displayed instead, along with revealing the number the computer
A vl C was thinking of. Remember, ifyou do alter the values of the
a random number chosen by the computer, or the number of

il 9 guesses the player can take, then along with the variable values,
you also need to amend the instructions given in the print
1 statements at the start of the code.
a a
ll ?
www.bdm ;.com t ’
a
Number Guessing Game

pi@raspberrypi ~/Documents/Python Code


File Edit Tabs Help
piPraspberrypi:-/Doc men ts/Python Code $ python3 HumberGuess.py
Hello! What is your name? David
Greetings, David. I'm thinking of a number between 1 and 30.
Guess the number within 5 guesses...25
Too low. try again.
Guess the number within 5 guesses...27
well done. David! You guessed correctly in 2 guesses.
pi€raspberrypi:~/Docuaents/Python Code S |

Code Improvements
Since this is such as simple script to apply to a situation, there’s For example, as per the screenshot provided, you could use
plenty of room to mess around with it and make it more something along the lines of:
interesting. Perhaps you can include an option to take score, the
best out of three rounds. Maybe an elaborate way to congratulate Endurance=O
the player for getting a 'hole in one' correct guess on their first try. CR=0
Luck=0
Endurance = random. randint(l, 15)
Moreover, the number guessing game code does offer some room
CR = random.randint(l, 20)
for implementing into your code in a different manner. What
Luck = random. randint(l, 10)
we mean by this is, the code can be used to retrieve a random Print ("Your character's stats are as follows :\n")
number between a range, which in turn can give you the start of a Print ("Endurance:", Endurance)
character creation defined function within an adventure game. Print ("Combat Rating:", CR)
Print ("Luck:", Luck)
Imagine the start of a text adventure written in Python, where
the player names their character. The next step is to roll the
The player can then decide to either stick with their roll or try again
virtual random dice to decide what that character's combat
for the hope of better values being picked. There's ample ways in
rating, strength, endurance and luck values are. These can then be
which to implement this code into a basic adventure game.
carried forward into the game underaset of variables that can be
reduced or increased depending on the circumstances the player's
character ends up in.

www.bdmpublications.com 115
Random Number Generator
6> U qj “ t
# User input and the ability to
0 RNDNUMGEN.PY
v C
manipulate that input are important It might be simple but this little piece of code will ask the user
(Я О elements with any programming & U For two sets oF numbers, a start and a Finish. The code will then
pluck out a random number between the two sets and display it.
1 q language. It's what separates
□ la from random import *
a a good program from a great
program, one that allows the user print ("\n»»»»»Random Number Generator<<<<<<<<<<\n")

11 0 to interact^nd see the results of A nmbl=int(input("Enter the start number:


nmb2=int(input("Enter the last number:
"))
"))
4
7 x th# interaction. “ q 0 x = randint(nmbl, nmb2)

0 3 □ О . < n Ga I o a print("\nThe random number between",nmbl,"and",nmb2,"is:\n")

W 7 nJ । -|- % cv c print (x)

0
4h More Input
P
g«2
j While an easy code to Follow, it could be more interesting if you For example, the code could be edited to this:

□5 prompt the user for more input. Perhaps you can provide them
with addition, subtraction, multiplication elements with their from random import *
numbers. If you're feeling clever, see if you 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, left (90)
turtle. forward (nmb2)

You can also introduce the Turtle module into the code and turtle, left (90)
turtle. forward (nmb3)
perhaps set some defined rules for drawing a shape, object or
turtle, left (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. left (90)
really interesting.

m j Whilst it's a little rough around the edges, you can easily make it
more suitable.
В
a Python 3.4.2 Shell
Python Turtle Graphics

File Edit Shell Debug Qptlons ffimdows Help jmb.py -/home/pi/Docu. on Code^rtleRndNumb py (3 4 2) - □ x

Python 3.4.2 (default. Oct 19 2014, 13:31:11) Eile Edit Format Bun Qptions Windows Help
(GCC 4.9.1) on linux t'cii random import *
Type "copyright”, "credits" or "licensed" for more information.
RESTART —
print("\n>>»>>>>»Random Turtle Image<<««<«<\n")
nmb1-int(input("Enter the start nunber: ”))
nmb2=int(input("Enter the second nunber: "))
ClJ Enter the start nunber: 23
nmb3-int(input("Enter the
nmb4=int(input("Enter the
third number: "))
fourth number: “))
Enter the second nunber: 21
vl Enter
Enter
the
the
third nunber: 45
fourth number: 33 turtle.forward(nmb1 )
RESTART turtle.left(90)
cn turtle.forward(nmb2)
turtle.left(90)
»»»»»Random Turtle Image<<«««« turtle.forward(nmb3)
turtle.left(90)
enter the start nunber: 86 turtle.forward(nmb4)
Enter the second number: 45 turtle.left(90)
Enter the third nunber: 86
Enter the fourth nunber: 70 ffx = randint(nmbi. mb 2)
»print("\nThe random number between".nmb!."and",nmb2."is:\n")
»print(x)

www.bdmi ;.com t «1 v
<1 ■j A
Random Number Generator/Password Generator

Random Password
Generator
We're always being told that our RNDPASSWORD.PY
passwords aren't secure enough; well Copy the code and run it; each time you'll get a random string
here's a solution For you to implement of characters that can easily be used as a secure password
which will be very difficult for a password cracker to hack.
into your own Future programs. The
import string
random password generator code import random
below will create a 12-letter string oF
def randompassword():
words (both cases) and numbers each chars=string.ascii _ uppercase + string.ascii _
lowercase + string, digits
time it's executed. size= 8
return ''.join(random.choice (chars) for x in
range (size,20))

print (randompassword ())

Secure Passwords
There's plenty you can do to modify this code and improve it Adding a loop to print a password fifty times is extremely easy, for
further. For one, you can increase the number of characters the example:
generated password displaysand perhaps you can include special
characters too, such as signs and symbols. Then, you can output import string
the chosen password to a file, then securely compress it using the import random
previous random number generator as a file password and send it
to a user for their new password.
def randompassword():
chars=string.ascii _ uppercase + string.ascii _
An interesting aspect to this code is the ability to introduce a loop
lowercase + string, digits
and print any number of random passwords. Let's assume you have size= 4
a list of SO users for a company and you're in charge of generating return ''.join (random.choice (chars) for x in
a random password for them each month. range (size,20))

n=0
while n<50:
print (randompassword())
n=n+l

This will output fifty random passwords based on the previous


random selection of characters.

RndPasswordLoop.py - /home/pi/D . Code/RndPasswordLoop.py (3.4.2) - n x


File Edit Format Bun Options JVindows Help

import string
import random

def randompassword():
chars=string.ascii_uppercase + string.ascii_lowercase + string.digits
size- 4
return 1'.join(random.choice(chars) for x in range(size.2O))

n=0
while n<50:
print(randompassword())
n-n+1

www.bdmpublications.com
Text to Binary Convertor
G) П W В } U И QJ If 0 *1
# Whilst bay HofL^... TXT2BIN.PY
V
this textjto bii^a^Aonvertorjs <
a Naturally we're using the format function to convert the
Pl о actuallyciuLteigood Fun. Ibalsb & user’s entered text string into its binary equivalent. If you
1 q only uses tyv$Urfe$ oF cod^ <&> i^'s want to check its accuracy, you can plug the binary into an
PI online convertor.
a extrepn^ycea^y to insert irrto)your
text=input("Enter text to convert to Binary:
>3 own script. i & D л й
и 0
h 1 Pi ~ 4! СГ ® A print(' \join(format(ord(x), 'b') for x in text))
4 & и т N g| Q я Й 9 n
7 x . f) _ > ст. CT.F2I
Python 3.4.2 Shell Txt2Bin.py - /home/pi/Documents/Python Code/Txt2Binpy (3.4.

о g: File Edit Shell Debug Options Windows Help File Edit Format Run Options Windows Help

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


[GCC 4.9.1] on linux
j

Type “copyright", "credits" or "licensee)“ for more information. I text-input("Enter text to convert to Binary: ")
0 »> ................................ RESTART —————————

4 h
*
print( ‘.join(format(ord(x). 'b') tor x in text))

g P Enter text to convert to Binary: David


1000100 1100001 1110110 1101001 1100100
j
5

0 M
Ca
и
*1
N
@
9 C
У
m j

“1
nJ
vl
о

а п u
г p LJ m ii ?
8
□ Q
www.bdmpnplicationt.com
° ■ a
t ’ *1
-3 A
Text to Binary Convertor

1000010 1101001 1101110 1100001 1110010


1111001
The text to binary convertor does otter some room tor
pygame. display, set _ caption ("Binary Conversion")
improvement and enhancement. There are many uses: it could be
utilised in a password or secret word script, as part ot an adventure done = False
game or just a novel way to display someone's name. clock = pygame. time.Clock ()

With regards to improvements, you could display the binary text _ rotate _ degrees = 0
conversion in a Pygame window, using the animated text options
trom page 100. You could also ask the user it they wanted to have Binary=(' '.join (format (ord(x), 'b') for x
in conversion))
another go, or even ask it they wanted the binary output to be
saved to a tile.
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
import pygame
pygame. init() screen .fill (WHITE)
font = pygame.font.SysFont('Calibri', 25, True, False)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255) text = font, render (Binary, True, BLACK)
BLUE = (0, 0, 255) text = pygame.transform. rotate (text, text _
GREEN = (0, 255, 0) rotate _ degrees)
RED = (255, 0, 0) text _ rotate _ degrees += 1
screen, blit (text, [100, 50])
print ("»»»»»Text to Binary Convertor«««««\n") pygame. di splay, flip ()

conversion=input ("Enter text to convert to Binary: ") clock.tick(60)

size = (600, 400) pygame. quit ()


screen = pygame. display, set _ mode (size)
print (' '. join (format (ord (x), 'b') for x in conversion))

www.bdmpublications.com 119
Basic GUI File Browser
6) n
и #Here's a helpful and interesting FILEBROWSER.PY
V C
piece of code. It's an extremely basic Tkinter is the main module in use here but we’re also using
Fl file browser that's presented in a U idlelib, so you may need to pip install any extras if the
1 И. dependencies fail when you execute the code.
graphical user interface using the
Fl
a Tkinter module. There's a lot you can
from tkinter import Tk
0 $ learn from this code and implement й
U 0 intgyW^^rams. C 9 « A from idlelib.TreeWidget import ScrolledCanvas,
4 FileTreeltem, TreeNode

7 x fi n ii J* q Y 21 q Й import os

о g: root = Tk()

W + root.title ("File Browser")

0 □ sc = ScrolledCanvas (root, bg="white",


4 h highlightthickness=O, takefocus=l)

g sc.frame.pack(expand=l, fill="both", side="left")

□ item = FileTreeItem(os.getcwd())
node = TreeNode(sc.canvas, None, item)
node, expand ()
File Browser
ll Python Code
4letterwrd.py
* Balls.py
И root .mainloop ()
Booleantest.py
Boxes Colours, py
-Л CalcPi.py
Comments.py
Dictln.py
Dictln2.py
FileBrowser.py
FileMan.py
GoogleSearch.py
< GoogleSerch.py
KeybDraw.py
NumberGuess.py
PolygonCirdes.py
RndNumGen.py
RndPassword.py
Scroller.py
TkinterTables.py
TurtleLines.py
Txt2Bln.py
TxtRot.py
bkup.py
calendaryear.py
daysinmonth.py
exceptionl.py
exception2.py
exception3.py
-Л headstails.py
hello.py
leapyears.py
-И! login, py
logintime.py
namelist, py FileBrowser py -/home/pi/Documen. Python Code/FileBrowserpy (3.4.2) -ox
print hello.py
pygamel.py File Edit Format Run Options Windows Help
»* ovaametxt.ov
from tkinter import Tk

from idlelib.Treewidget .mport ScrolledCanvas. FileTreeltem. TreeNode


import os

root - Tk()
root.title("File Browser”)

sc = ScrolledCanvas(root. bg="white“, highlightthickness=O. takefocus=1)


sc.frame.pack(expand-1, fill-”both", side-’left")

item - FileTreeItem(os.getcwd())
node = TreeNode(sc.canvas. None, item)
node.expand()

root.mainloop()
Basic GUI File Browser

Advanced Filing try:

When executed, the code will display the current directory’s with open (name,'r') as UseFile:
print (UseFile. read ())
contents. If you want to see the contents of another directory, you
except:
can run the code from a command line within the chosen directory;
print ("No files opened")
just remember to call the code from where it's located on your
system, as per the second screenshot. You can also double-click any
of the file names shown in the directory tree and rename them. Title = root.title( "File Opener")
label = ttk. Label (root, text ="File
This is an interesting piece of code and one thatyou can insert into Open", foreground="red", font= ("Helvetica", 16))
your own programs. You can extend the code to include a user label .pack ()
specified directory to browse, perhaps your own unique file icons
too. If you're using Linux, create an alias to execute the code and
menu = Menu (root)
then you can run it from wherever you are in the system.
root. config (menu=menu)

Windows users may have some trouble with the above code, an
file = Menu (menu)
alternative can be achieved by using the following:
file.add _ command(label = 'Open', command = OpenFile)
from tkinter import * file, add _ command (label = 'Exit', command =
from tkinter import ttk lambda: exit ())
from tkinter.filedialog import askopenfilename
menu.add _ cascade (label = 'File', menu = file)
root = Tk( )
root. mainloop ()
def OpenFile ():
name = askopenfilename (initialdir="C:/",
filetypes =(("Text File", "
.txt"),("All
*
.")),
*
Files","
It's not quite the same but this code allows you to open files
title = "Choose a file."
in your system via the familiar Windows Explorer. It’s worth
)
print (name)
experimenting with to see whatyou can do with it.

[4k filetestl.py - C:\Usen\david\Documents.Python\filetest1.py (3.6.2)

File Edit Format Run Options Window Help


from tkinter import. *
from tkinter import ttk
from tkinter.filedialog import askopenfilename

root = Tk( )

def OpenFile():
name = askopenfilename(initialdir-"C:/”,
filetypes -(("Text File", " *
* .txt"),("All Files","
.")),
title = "Choose a file."
)
print (name)

with open(name,’r’) as UseFile:


print(UseFile.read())
except:
print("No files opened")

Title = root.title( "File Opener")


label = ttk.Label(root, text «"File Open",foreground-"red",font=("Helvetica", 16))
label.pack()

menu = Menu(root)
root.config(menu-menu)

file = Menu(menu)

file.add_command(label — ’Open’, command = OpenFile)


file.add_command(label = *
,'Exit command = lambda:exit())

menu.add_cascade(label — 'File', menu = file)

root.mainloop()

www.bdmpublications.com 121
Mouse Controlled Turtle
A A M b } U 0 qj И u _ О
# We've already seen the Turtle MOUSETURTLE.PY
V
module being controlled by the The first piece of code presents the standard Turtle window.
A о user via the keyboard but now we df U Press Space and then click anywhere on the screen for the
1 q thought we'd see how the user can Turtle to draw to the mouse pointer. The second allows you to
A □ 70 rJ ,i ijl 0 . la click the Turtle and drag it around the screen; but be warned,
a use their mouse as a drawing tool it can crash Python.

>3 within Python. We have two possible 1st Code Example:


ii 0 rnrlo here, ni
examples hara
code av^mnloc rlz i*/which
pick hirK> 1
4
works best q И
7 x from turtle import Screen, Turtle

О a □о" n gs i О a
W 7 nJ । т % c screen = Screen ()
yertle = Turtle ()
0 ° o; h f Л 7 5)
4 h MouseTurtle.py -/home/pi/Docume_ython Code/MouseTurtlepy (3.4.2) - □ x
Eile Edit Ffirmat Bun Options Windows Help
def kl01():
screen.onscreenclick(click _ handler)
g p turtle inipoi Screen. Turtle
A
j screen ■ Screen()
def click _ handler (x, y):
□ 5
yertle = Turtle()

let k101():
к screen.onscreenclick(None) # disable event inside
€ screen.onscreenclick(click_handler)

def click_handler(x, y):


w event handler
screen.onscreenclick(Hone) # disable event inside event handler yertle. setheading (yertie. towards (x, y))
VI yertle.setheading(yertle.towardsfx, у))

5
yertle.goto(x. y)
screen.onscreenclick(click_handler) « reenable event on event handler exit

screen.onkey(k101. " ") ft space turns on mouse drawing


к yertle.goto(x, y)
screen.onscreenclick(click _ handler) # reenable
event on event handler exit
screen.listen()

screen.mainloop()

4 screen.onkey(kl01, " ") # space turns on mouse drawing

0 M screen. listen ()

G"
И °/c screen. mainloop ()

4
и
W & 2nd Code Example:
@
jLn: 1 Col: ol

9 C
У и 11 2 H О from turtle import *
shape("circle")
m J *
♦Untitled
pencolor ("blue")
В Eile Edit Ffirmat Bun Options Jtfindows Help
turtle
-1
A
width (2)
ondrag(goto)
a И shape("circle")

q
pencolorC'blue”)
width(2) listen ()
ondrag(goto)

«Warning - This code can crash Python, so use it sparingly.!

”1
cu Ga
A Ninja TurtleMouse
vl
1
о This code utilises some interesting skills. Obviously it will stretch
A your Python Turtle skills to come up with any improvements,
W 9
which is great, but it could make fora nice piece of code to
Й
A vl □ insert into something a young child will use. Therefore it can be
a fantastic project for a younger person to get their teeth into;
a or perhaps even as part of a game where the main character is
iJ 9 tasked to draw a skull and crossbones or something similar.
1
a a ТГ e
m Il ?
www.bdmi ;.com t ’ «1 V
a ■j A
Mouse Controlled Turtle/ Python Alarm Clock |

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 that you've spent all sleep (seconds)
print ("Wake up")
that time on Facebook? Introducing the for i in range (5):
Python alarm clock code, where you can print (chr(7)),
sleep (1)
drop into the command prompt and tell except Keyboardinterrupt:
print ("Interrupted by user")
the code how many minutes until the sys. exit (1)
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 for your tea break.

import sys
Linux users, try making the alarm clock code into an alias, so
import string you can run a simple command to execute it. Then, why not
from time import sleep integrate a user input at the beginning to ask the user for the
length of time they want until the alarm goes off, rather than
sa = sys.argv having to include it in the command line.
Isa = len (sys.argv)
if Isa != 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.")
print ("Press Ctrl-C to terminate the alarm
clock early.")
sys. exit (1)

try:
minutes = int(sa[l])
except ValueError:
print ("Invalid numeric value (%s) for minutes" % sa[l])
print ("Should be an integer >= 0")
sys. exit (1)

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

www.bdmpublications.com
Vertically Scrolling Text
6)0 W к } U. W fl. и if _ ъби
га # гт’ Чгч “ [71 П га га
What's not to like about vertically EPICSCROLL.PY
scrolling text? Its uses are many: the We’ve used the poem Cimmeria by Robert E. Howard for the
beginning of a game or introduction code's scrolling text, along with a dramatic black background
and red text. We think you'll agree, it's quite epic.
to something epic, like the beginning
of every Star Wars movie; a list of
credits at the end Of something such
import pygame as pg
as a Pythorj presentation. The list from pygame. locals import *
7 x 9°^s^ntL J1 9 ? q й ... E
pg.initO

text list =

I remember
The dark woods, masking slopes of sombre hills;
The grey clouds' leaden everlasting arch;
The dusky streams that flowed without a sound,
And the lone winds that whispered down the passes.

Vista on vista marching, hills on hills,


Slope beyond slope, each dark with sullen trees,
Our gaunt land lay. So when a man climbed up
A rugged peak and gazed, his shaded eye
Saw but the endless vista - hill on hill,
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 hills,
The dimness of the everlasting woods.
Cimmeria, land of Darkness and the Night.

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


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')
Vertically Scrolling Text |

class Credits:
def _ _ init _ _ (self, screen _ rect, 1st): A Long Time Ago...
self.srect = screen _ rect The obvious main point of enhancement is the actual text
self.1st = 1st
itself. Replace it with a list of credits, or an equally epic opening
self.size = 16
storyline to your Python game, and it will certainly hit the
self.color = (255,0,0)
self .buff _ centery = self .srect.height/2 + 5
mark with whoever plays it. Don't forget to change the screen
self .buff _ lines = 50 resolution if needed; we're currently running it at 800 x 600.
self.timer = 0.0
self, delay = 0
self .make _ surfaces ()

def make _ text(self,message):


font = pg. font. SysFont('Arial', self.size)
text = font, render (message,True, self, color)
rect = text.get _ rect(center = (self.srect.
centerx, self .srect. centery + self .buff _ centery) )
return text,rect

def make _ surfaces (self):


self.text = []
for i, line in enumerate (self .1st):
1 = self .make _ text (line)
l[l].y += i*
self .buff _ lines
self. text. append (1)

def update (self):


if pg.time.get _ ticks()-self.timer > self.delay:
self.timer = pg.time.get _ ticks()
for text, rect in self .text:
rect.у -= 1

def render (self, surf):


for text, rect in self.text:
surf .blit (text, rect)

screen = pg.display.set _ mode((800,600))


screen _ rect = screen.get _ rect()
clock = pg.time.Clock()
running=True
cred = Credits (screen _ rect, text _ list)

while running:
for event in pg.event.get():
if event.type == QUIT:
running = False
screen.fill ((0,0,0))
cr ed. update ()
cred. render (screen)
pg. display, update ()
clock.tick(60)

www.bdmpublications.com
Python Digital Clock
6> a “И U . И QJ t t 0
0 #
There is already a clock displayed DIGCLOCK.PY
V
on the desktop of most operating This is a surprisingly handy little script and one that we've
A о systems but it's always handy to have и used in the past instead of relying on a watch or even the
1 q one
Ul onI UUU
It Ul top ofa*l Ul
VI the currently
It. ttll open
I VI I ci у VUtl I
clock in the system tray of the operating system.
a □ 7U I I I [“] Л feflo ~ \J 1D I
import time
a window. To that end, why not create import tkinter as tk

0 a Python digital clock that can be a


и 0
def tick(timel="):
colpWoftdesktopwidg^tf^^ou "B # get the current time from the PC
4 time2 = time, strftime ('%H:%M:%S')
7 x A fl U J1 9 j 111 q 0 if time2 ’= timel:

© g: ‘■Python 3.4.2 Shell1 □


a timel = time2
clock. config (text=time2)
W File Edit Shell Qebug Options Windows Help

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


[GCC 4.9.1] on linux
a clock.after(200, tick)

4 h
Type "copyright" ” for more information.
RESTART

root = tk.Tk()
g p
RESTART A
clock = tk. Label (root, font=('arial', 20, 'bold'),
j RESTART

5
RESTART
к bg='green')
clock .pack (fill='both', expand=l)

й € w tick()
root. mainloop()
VI 09:19:27
5 к
pi@raspberrypi: -/Documents/Python Code - n
File Edit Tabs Help
|pit»raspberrypi:-/Doctaaents/Python Code $ pythonS DigClock.py

4
a M
DigClock py - /home/pi/Documents/Python Code/DigClock py (3.4.2)
Сл
0 File Edit
time
Fflrmat Bun Options Windows

tkintei tk
Help
°/c
*1 def tick(time1=’’):
# get the current time from the PC
time2 = time.strftime(•
if time2 !- timel:
:**
.«: 4S ’) и
timel = time2
N clock.config(text”time2)

@ clock.after(200. tick)
В
root - tk.Tk()
9 C clock = tk.Label(root. font-('arial
*
clock.pack(fill-'both , expand-1)
, 20. bold'). bg='green)

У Hl
tick»
root.mainloop()
О
m J DigClockpy - /home/pi/Documents/Python Code/DigClodcpy (3.4.2) - a
В
a И A File Edit
II impoi t tune
Format Run Options Endows Help

q import tkinter as tk

a 8 ii
0 I
def tick(time1-’*):
ff get the current tune from the PC
tune2 = tune.strftime(’%H:IO4:%S’)
”1 °1I if time2 != timel:

eu u w la Gs
timel = time2
clock.config(text-time2)
О У 0 It A
□ vl clock.after(200, tick)

co 1 b - 1 root - tk.Tk()
clock» tk.Label(root. font=(’arial’, 20, bold’). bg= green’)

w 9 и I r
X a V 6) clock.pack(fill-’both’, expand-1)
tick()

m u a
root.mainloop()

₽i vl a t la a
1 о □
a VI О u z %
11 9 s “ii
4 9
C
a o' 0 R n
7 0
a У a a € e
f m n ?
126 www.bdmpflplicationkcom t *] V
a, a 5 A
Python Digital Clock

TickTock
This is a piece of code we've used many times in the past to keep
track of time while working on multiple monitorsand 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 affecting the time, padding = dict(padx=5, pady=5)
widget = StopWatch (root, **
padding)
maximised or closed by the user at will. We haven't given the
widget. grid (sticky=tkinter. NSEW, **
padding)
Tkinter clock window a title, so you can add to that easily enough
root. mainloop ()
by snipping the code from other examples in this book.
kw):
def _ _ init _ _ (self, master=None, cnf={}, **
Another area of improvement is to include this code when padding = diet (padx=kw.pop ('padx', 5), pady=kw.
Windows or Linux starts, so it automatically pops upon the pop('pady', 5))
desktop. See also, if you're able to improve its functionality by kw)
super()._ _ init _ _ (master, enf, **
including different 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,
text='Total Time:')
self. _ _ time = tkinter.StringVar(self,
'0.000000')
self. _ _ display = tkinter. Label (self,
textvariable=self. _ _ time)
self. _ _ button = tkinter. Button (self,
text='Start', command=self. _ _ click)
self. _ _ label.grid(row=0, column=0,
sticky=tkinter.E, **
padding)
self. _ _ display.grid(row=0, column=l,
sticky=tkinter.EW, **
padding)
self. _ _ button.grid(row=l, column=0,
columnspan=2,sticky=tkinter.NSEW, **
padding)

def _ _ click(self):
if self. _ _ button ['text'] == 'Start':
self. _ _ button ['text'] = 'Stop'
self. _ _ start = time, clock ()
self. _ _ counter = self .after _ idle(self. _ _ update)
else:
self. _ _ button ['text'] = 'Start'
self .after _ cancel(self. _ _ counter)

def _ _ update (self):


now = time, clock ()
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 _ _


StopWatch. main ()
@classmethod
def main (cis):
tkinter.NoDefaultRoot()
root = tkinter.Tk()

www.bdmpublications.com
Playing Music with the
Winsound Module
PI О \ U „ П n ■■■ ! и &

1 ' ял и 0— я
Of course, instead of playing an
-я I\1 я в
MUSIC.PY
6) □ la
a existing MP3, you can always make The code utilises both the Time and Winsound modules,
d $ your own music. The code below deFining the tone and pitch and inserting small pauses oF .5
3J 0
oF a second.
will play out Pachelbel's Canon in D,
4 ciui га о Я К 5 1 Иr<
no less, я ' import winsound
7 x import time

о d t = 250
1
W p = .50
0
4 h 11C = 65

g P
J 1C = 131

5 IDb = 139
ID = 147
lEb = 156
IE = 165
IF = 175
1Gb = 185
1G = 196
lAb = 208
1A = 220
IBb = 233
IB = 247

C = 262
Db = 277
D = 294
Eb = 311
i л Миясру G/UKrs/davidAJocumcnts/Pythoo/Music.py (3,6.21
E = 330
F = 349 2
Gb = 370
G = 392
Ab = 415
A = 440
Bb = 466
В = 494

hC = 523
hDb = 554
hD = 587
hEb = 622
hE = 659
hF = 698
hGb = 740
hG = 784
hAb = 831
hA = 880
hBb = 932
hB = 988

time. sleep (0.001)


Playing Music with the Winsound Module

for i in range (5):


Sweet Music
Obviously the Winsound module is a Windows-only set of
winsound.Beep( 1C, 2
*
t)
functions for Python. Open your IDLE in Windows and copy the
winsound.Beep( hC, t)
code in. Press F5 to save and execute, then press the Enter key,
winsound.Beep( hE, t)
as instructed in the code, to start the music.
winsound.Beep( hG, t)
time, sleep (p)
Naturally you can swap out the winsound.Beep frequency and
winsound.Beep( 1G, 2
*
t) durations to suit your own particular music; or you can leave it as
winsound.Beep( G, t) is and enjoy. Perhaps play around with the various methods to
winsound.Beep( B, t) make other music.
winsound.Beep( hD, t)
time, sleep (p) For example, players of the Nintendo classic game, The Legend
of Zelda: Ocarina of Time, can enjoy the game's titular musical
winsound.Beep( 1A, 2
*
t)
intro by entering:
winsound.Beep( A, t)
winsound.Beep( hC, t)
import winsound
winsound.Beep( hE, t)
beep = winsound.Beep
time, sleep (p)

c = [
winsound.Beep( IE, 2
*
t)
(880, 700),
winsound.Beep( E, t)
(587, 1000),
winsound.Beep( G, t)
(698, 500),
winsound.Beep( B, t)
(880, 500),
time, sleep (p)
(587, 1000),
(698, 500),
winsound.Beep( IF, 2
*
t)
(880, 250),
winsound.Beep( F, t)
(1046, 250),
winsound.Beep( A, t)
(988, 500),
winsound.Beep( hC, t)
(784, 500),
time, sleep (p)
(699, 230),
(784, 250),
winsound.Beep( 11C, 2
*
t)
(880, 500),
winsound.Beep( C, t)
(587, 500),
winsound.Beep( E, t)
(523, 250),
winsound.Beep( G, t)
(659, 250),
time, sleep (p)
(587, 750)

winsound.Beep( IF, 2
*
t) ]
winsound.Beep( F, t)
s = c + c
winsound.Beep( A, t)
winsound.Beep( hC, t)
for f, d in s:
time, sleep (p)
beep(f, d)

winsound.Beep( 1G, 2
*
t)
winsound.Beep( G, t)
winsound.Beep( B, t)
song1.py - C:\Users\david\Documents\Python\song1.py (3.62)’
U *
winsound.Beep( hD, t)
File Edit Format Run Options Window Help
time, sleep (p)
import winsound
beep = winsound.Beep

(880, 700),
(587, 1000)
The start of the code imports the Winsound and Tie modules; (698, 500),
1 remember, this is a Windows-only Python script. The variable t
(880, 500),
(587, 1000)
(698, 500),
is setting the duration, while p equals .5, which you can use for (880, 250),
the time.sleep function. (1046, 250)
(988, 500),
(784, 500),
(699, 230),
These variables set the frequencies, with the corresponding (784, 250),
2 numbers, which can be used in the next section of the code.
(880, 500),
(587, 500),
(523, 250),
(659, 250),
(587, 750)
Winsound.beep requires a frequency and duration within the
3 brackets. The frequencies come from the large set of variables
called in the second section of the code and the duration is
for f, d in s:
through the t variable set at the start of the code. There's a beep(f, d)

half-second, using the variable p, pause between blocks of


winsound.beep statements.

www.bdmpublications.com
Text Adventure Script
M о у U И qj И If _ t ОЙ

Text adventures are an excellent ADVENTURE.PY


way to build your Python coding The Adventure game uses just the Time module to begin
о skills and have some fun at the same with, creating pauses between print Functions. There's a help
q time, this example that we created system in place to expand upon, as well as the story itselF.

a will start you on the path to making
a classidText adventure; where it will import time

print("\n" * 200)
4 print ("»»»»»Awe s ome Adventure«««««\n")
x print("\n" * 3)

о c£ time, sleep (3)

W + print("\nA long time ago, a warrior strode forth from


the frozen north.")
0 □ time, sleep (1)
4 h print("Does this warrior have a name?")
name=input("> ")
g P print (name, "the barbarian, sword in hand and looking
«/ j for adventure’")
□ 5 time, sleep (1)
Й € print ("However, evil is lurking nearby....")

Vi □ time, sleep (1)


print("A pair of bulbous eyes regards the hero...")
s И time, sleep (1)
□ print("Will", name, "prevail, and win great fortune...")

□ □ time, sleep (1)

й 4 print ("Or die by the hands of great evil...?")


You find yourself at a small inn. There's little gold in your purse time, sleep (1)
0 M but your
With you
sword is sharp, and you're ready for adventure.
are three other customers. print("\n" *
3)
Gt □ A ragged looking man. and a pair of' dangerous
' looking guards.
print("Only time will tell...")
you approach the... °/c time, sleep (1)

И 4 1. Ragged looking man


print!'...')

! 2. Dangerous looking guards


Oavid>help 11 time, sleep (1)
print!'...')
w nter your choices as detailed in the game.
r enter 'quit' to leave the game & time, sleep (1)
a avid>quit
В print!'...')
@
9 c homeland time, sleep (1)
print!'...')
У и p
Adventure py -/home/pi/Documen /Python Code/Adventure py (3 4 2)
* - □ x~I 0 time, sleep (5)
m j File Edit Format Run Options Windows Help 200)
print("\n" *

В □ You find yourself at a small inn. There's little gold in your pur
“1
print('" You find yourself at a small inn. There's
a в
but your sword is sharp, and you're ready for adventure.

A ragged looking man. and a pair of dangerous looking guards.


a
little gold in your purse but your sword is sharp,
□ i print("Do you approach the..
q and you're ready for adventure.
With you are three other customers.
f)
-1
print!"!. Ragged looking man")
print("2. Dangerous looking guards")
о A ragged looking man, and a pair of dangerous
cmdlist»["1". "2") looking guards.'")
1£)
cu cmd=getcmd(cmdlist)

cmd == "г
G3

vl ragged!)
• cmd -- '
It A def start():

.< n
guards!)

ragged!):
1 print ("\n----------------- ")

w 9 print!"in" * 200)
print!'"You walk up to the ragged looking man and greet him. V A print ("Do you approach the...")

’ И
He smiles a toothless grin and. with a strange accent, says.
"Buy me a cup of wine, and I'll tell you of great treasure..
fl print("\n")


time.sleep!2)
print("1. Ragged looking man")
(4 Vl guards!):
print!"in" *200)
0 print("2. Dangerous looking guards")

Я Й
print!''' You walk up to the dangerous looking guards and greet them
The guards look up from their drinks and snarl at you.
"What do you want, barbarian?" One guard reaches for the hilt of his s

11 9 time.sleep!2)
9 cmdlist=["l", "2"]
cmd=getcmd (cmdlist)
i □ getcmd(cmdlist):
cmd = input!name
*
i‘ cmd in cmdlist:
"


и e
a @ 7 у a
m ll ?
130 www.bdmift-T t ■ «1 V
a □a ■j A
Text Adventure Script

if cmd == "1": def getcmd(cmdlist):


ragged () cmd = input (name+">")
elif cmd == "2": if cmd in cmdlist:
guards () return cmd
elif cmd == "help":
def ragged(): print("\nEnter your choices as detailed in
print("\n" * 200) the game.")
print('"You walk up to the ragged looking man and print("or enter 'quit' to leave the game")
greet him. return getcmd (cmdlist)
He smiles a toothless grin and, with a strange elif cmd == "quit":
accent, says. print ("\n------------------- ")
"Buy me a cup of wine, and I'll tell you of time, sleep (1)
great treasure...'") print("Sadly you return to your homeland without
time, sleep (2) fame or fortune...")
time, sleep (5)
def guards (): exit()
print(”\n" *
200)
print('"You walk up to the dangerous looking guards
and greet them. if _ _ name _ _ ==" _ _ main
The guards look up from their drinks and start()
snarl at you.
"What do you want, barbarian?" One guard reaches
for the hilt of his sword...'")
time, sleep (2)

Adventure Time
This, as you can see, is just the beginning of the adventure and ‘Adventure py - /home/pi/Documents/Python Code/Adventure py (3 4.2)
*
takes up a fair few lines of code. When you expand it, and weave E<le Edit Ffirmat Bun Options Windows Help

the story along, you'll find thatyou can repeat certain instances 200)
print("\n" *

such as a chance meeting with an enemy or the like. CR-0


Strength-0
Health-0
Luck-0
We've created each of the two encounters as a defined set
print("The mountains of the north make for a hard life.")
of functions, along with a list of possible choices under the print("Press Enter to roll the dice and see how strong", name, "is:”)
input()
cmdlist list, and cmd variable, of which is also a defined function. Strength-random.randint(1.20)
print(name, "has a Strength value of:". Strength)
Expanding on this is quite easy, just map out each encounter and print("\nlt's a hard life indeed, and all northeners are born warriors.")
print("Press Enter to roll the dice and see the Combat Rating for", name
*
".")
choice and create a defined function around it. Providing the user input()
CR-random.randint(1, 30)
doesn't enter quit into the adventure, they can keep playing. print(name, "has a Combat Rating of:", CR)
print("\nYour Health is the total of your Strength and Combat Rating.")
print("Press Enter to see", name
* "'s“, "Health value.")
inputf)
There's also room in the adventure for a set of variables designed Health-Strength+CR
print(name, "has a Health value of:". Health)
for combat, luck, health, endurance and even an inventory or print("\nEveryone needs a certain amount of luck to survive.")
print("Press Enter to roll the dice and see how lucky", name, "is.")
input()
amount of gold earned. Each successful combat situation can Luck-random.randint(1. 15)
if Luck > 13:
reduce the main character's health but increase their combat skills print(name, "is luck indeed, and has a Luck value of:". Luck)
else:
or endurance. Plus, they could loot the body and gain gold, or earn print(name, "has a Luck value of:". Luck)
time.sleep(5)
gold through quests. print("\n" * 200)
print("Here
s
* your character stats:\n")
print(name)
print("\nCombat Rating -", CR)
Finally, how about introducing the Random module. This will print("Strength =", Strength)
'print("Health Health)
enable you to include an element of chance in the game. For print("Luck =“, Luck)
print("\n" * 5)
example, in combat, when you strike an enemy you will do a print("Press Enter to start your adventure...”)
inputf)
random amount of damage as will they. You could even work out print("\n“ * 200)

the maths behind improving the chance of a better hit based on


print(”’ You find yourself at a small inn. There’s little gold in your purse
your or your opponent's combat skills, current health, strength and but your sword is sharp, and you're ready for adventure.
With you are three other customers.
endurance. You could create a game of dice in the inn, to see if you A ragged looking man. and a pair of dangerous looking guards.'
*
')

win or lose gold (again, improve the chances of winning by working def start():
print("\n -............")
outyour luck factor into the equation). print("0o you approach the...")
print("\n")
print("l. Ragged looking man")
print("2. Dangerous looking guards")
Needless to say, your text adventure can grow exponentially
and prove to be a work of wonder. Good luck, and have fun with
your adventure.

www.bdmpublications.com
Python Scrolling
Ticker Script
\’ 11 ™ П 1b ••• ЭД ! И (XU
о
3

«л II л Я N А |b M
i-x
Qq

You may be surprised to hear that TICKER.PY


3

one of the snippets of code we're We're using Tkinter here along with the Time module to
<
"

.!ло-№ И

determine the speed the text is displayed across the window.


I 6)asked for is some form of
often A*
if о

fyj * J | f"''

scrolling ticker. Whilst we've covered


various forms of scrolling text
x

import time
previously, the ticker is something
Cl

import tkinter as tk
*Р- 1.е3 > Е |П П е ) ^ 1 а П е е Ю ^ О ^ О Х 1 '
2 _--3 ieiE I2 -N Z I 13 □ <т> (л ^-тз = г П +

that seems to keep cropping up. So, root = tk.Tk()


herpjis. a * b a B . canvas = tk. Canvas (root, root, title ("Ticker Code"),
height=80, width=600, bg="yellow")
ТЕ# ЛЛ.Н.л %... . ...... " A canvas.pack ()

................... in font = ('courier', 48, 'bold')


Ticker Time 1к text _ width = 15

The obvious improvements to the Ticker code lie in w #Text blocks insert here....
the speed of the text and what the text will display.
Otherwise you can change the background colour of К
si = "This is a scrolling ticker example. As you
the ticker window, the font and the font colour, along can see, it's quite long but can be a lot longer if
I

with the geometry of the Tkinter window if you want to. necessary... "
s2 = "We can even extend the length of the ticker
message by including more variables... "
Yet another interesting element that could be
s3 = "The variables are within the s-values in
introduced is one of the many text to Speech modules
the code. "
available for Python 3. You could pip install one, import it, I s4 = "Don't forget to concatenate them all before the
then as the ticker displays the text, the text to speech °/c For loop, and rename the 'spacer' s-variable too."
function will read out the variable at the same time, since
the entire text is stored in the variable labelled 's'. # pad front and end of text with spaces
11
s5 = ' ' * text _ width
&
E>

# concatenate it all
в s = s5 + si + s2 + s3 + s4 + s5
±3 — IS lE H -t2 n ©

x = 1
у = 2

и text = canvas.create _ text(x, y, anchor='nw', text=s,


font=font)
1 dx = 1
A dy = 0 # use horizontal movement only

q # the pixel value depends on dx, font and length of text


E pixels = 9000
I
Ga for p in range(pixels):

A
±a

# move text object by increments dx, dy


# -dx —> right to left


1
S Л

canvas.move (text, -dx, dy)


О13^-13^ОЗ

The ticker example can be used for system warnings,


perhaps something that will display across your work or
A canvas .update ()

# shorter delay —> faster movement


home network detailing the shutting down of a server time. sleep (0.005)
over the weekend for maintenance; or even just to e
t±. 2) Э

# print(k) # test, helps with pixel value


inform everyone as to what's happening. We're sure в
you will come up with some good uses for it. } root. mainloop()
©□ у
j <

И уa n S И- €e
|£Э

f ? u m u> ? □□
132 www.bdmpnplicationf.com t л V
□ g
,, D
П- a Г n
ч I
AI
Q Python Scrolling Ticker Script/Simple Python Calculator

Simple Python Calculator


Calculatorpy - /home/pi/Documents/Python Code/Calculator.py (3.4.2) - □ x
Sometimes the simplest code can be File Edit Format Run Qptions Windows Help И
the most effective. Take for example, print("------------------- Simple Python Calculator-------------------- \n")

this Simple Python Calculator script. It's


def add(x, y):
return x ♦ у я
def subtract(x, y):
based on the Create Your Own Modules return x - у

def multiply(x, y):


section seen earlier but doesn't utilise return x * у

def divide(x, y):


any external modules. return x / у

print("Select operation.\n")
print("1.Add")
print("2.Subtract")
CALCULATOR.PY print("3.Multiply")
print(”4.Divide”)

choice ■ input("\nEnter choice (1/2/3/4):")


We created some function definitions to begin with, then lead
numl - int(input("\nEnter first number: "))
on to the user menu and inputs. It's an easy piece of code to num2 - int(input(“Enter second number: "))

follow and as such can also be expanded well too. if choice == ’1’:
print(num1.mm2,add(num 1 .mm2))

elif choice -- '2':


print(num1,“,num2,"=“. subtract(num1.mm2))

elif choice == ‘3‘:


print(num1,num2,multiply(nim1 .mm2))

print ("----------------- Simple Python Calculator------------------ \n") elif choice -- ’ 4’:


print(numl.mm2. divide(num1.mm2))
else:
def add(x, y): print("Invalid input")

return x + у

♦Python 3 4 2 She I* _ □ x
def subtract (x, y):
Elie Edit Shell Qebug Qptions windows Help
return x - у
Python 3.4.2 (default. Oct 19 2014. 13:31:11)
[GCC 4.9.1] on linux
Type "copyright", "credits" or "licensee)” for more information.
def multiply(x, y): »> ================================ RESTART ================================

return x * у ------------------- Simple Python Calculator--------------------

Select operation.
def divide (x, y):
return x / у
1 .Add
2.Subtract D
print ("Select operation .\n")
3.Multiply
4.Divide u
Enter choice (1/2/3/4):
print ("1. Add")
print ("2. Subtract") □
print ("3. Multiply") H
print ("4. Divide") Ll
choice = input("\nEnter choice (1/2/3/4):")
#
numl = int(input("\nEnter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
print (numl, num2,, add (numl, num2))
Improved Calculations
elif choice == '2': The obvious contender for improvement here is using the
print (numl,num2,, subtract (numl, num2))
Create Your Own Modules route and extracting the function

elif choice == '3':


definitions as a module. You can then call the module and focus
on the body of the code.
1
print (numl, , num2,, multiply (numl, num2))

elif choice == '4': The other area of improvement is code itself. Where there's
print (numl, num2,, divide (numl, num2)) just a single shot at making a calculation, you could encase it in 6
else: a while loop, so once a value is presented the user is sent back
print ("Invalid input") to the main menu. Perhaps, improvement to the Invalid Input
section is worth looking into as well.

www.bdmpublications.com
Hangman Game Script
on M b } U И W if _ tо и

Hangman is a great game to program HANGMAN.PY


into Python. It can be extremely We've made a Hangman game board (the gallows) out of
complex, displaying graphics, the characters that can be displayed in the IDLE Shell, along with
a huge bank of words to randomly choose from.
number of guesses left in the secret
word, a huge bank of available words
picked at random and countless import random

either рГргпрпК; It ran akn hp rffiitp board = ['"

»»»»»Hangman«<««<«

о
/I

О
/|\

о
/|\
Hangman Game Script

i luggage responsible ambassador circumstance


congratulate frequent'.split()
return bank [random. randint (0, len (bank)) ]

i i def main():
0 I game = Hangman (rand _ word())
/|\ I while not game.hangman _ over():
I \ I game.print _ game _ status()
I user _ input = input('\nEnter a letter: ')
========="'] 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:
return False
Quito
return True Since this is the last example in our Python code repository, we
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 if it looks misaligned in the text here, this is merely
letters) == 6)
due to the differences between using the Python IDLE editor
def hangman _ won (self):
and pasting the code into a word processor (which formats
if ' _ ' not in self.hide _ word(): things differently).
return True
return False There's plenty you can do to improve, enhance and expand on
what we’ve presented here. You can include a routine that
def hide _ word (self): returns an error if the user enters a number or character. You
rtn = w can include extra points for someone who guesses the entire
for letter in self.word:
word in one go rather than one letter at a time and you could
if letter not in self .guessed _ letters:
perhaps add Chopin's Funeral March should you lose the game;
rtn += '_'
or something celebratory if you 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 of words too. They're found under
print () the bank list, and could easily be swapped out for something
more difficult. If you download www.github.com/dwyl/english-
def rand _ word(): wordsyou can find 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 the contents of the text file:
calculator clever engaged engineer enough
handsome refrigerator opposite socks interested
def rand _ word():
strawberry backgammon anniversary confused
with open("/home/pi/Downloads/words.txt", "rt") as f:
dangerous entertainment exhausted impossible
bank=f. readlines ()
overweight temperature vacation scissors
return bank [random. randint (0, len (bank)) ]
accommodation appointment decrease development
earthquake environment brand environment necessary

www.bdmpublications.com 135
Index

136 www.bdmpublications.com
( Understanding Linux

Linux is a remarkably versatile and


powerful operating system. It's used
throughout the programming and
engineering world, in science, space
■<$=°
exploration, education, gaming and
everything else in between. It's the OS
of choice For high-perFormance servers,
it's the backbone oF the Internet and it
powers the Fastest supercomputers in
the world.
Knowing how to use Linux, and how it's Г„
structured, is key to being able to create
better Python content. The Raspberry Pi, X
X
for example, uses a Linux-based OS and,
as such, makes For an excellent coding
platform. Regardless oF whether you're
using a Pi, like us, or a Linux Mint or
Ubuntu, these pages will prove invaluable
For your Python learning. Master Linux,
master Python, and start engineering
your coding Future.

138 What is Linux?


140 Using the Filesystem
142 Listing and Moving Files
X
144 Creating and Deleting Files
146 Create and Remove Directories
148 Copying, Moving and Renaming Files
0
150 Useful System and Disk Commands
152 Using the Man Pages
154 Editing Text Files
156 Linux Tips and Tricks
158 A-Z of Linux Commands
160 Glossary of Python Terms

www.bdmpublications.com
Understanding Linux

What is Linux?
The Raspberry Pi operating system is Raspbian, which is a Linux operating system; but
what exactly is Linux? Where did it come from and what does it do? In a world where
Windows and macOS have supremacy of the desktop, it's easy to overlook it, but
there's more to Linux than you might imagine.

Linux is a surprisingly powerful, fast, secure and capable operating system. It's used as the OS of choice for the Raspberry Pi, in
the form of Raspbian OS, as well as in some of the most unlikely places.

Despite only enjoying a 1.96% share (according to netmarketshare. Torvalds needed a system that could mirror Unix's performance and
com) of the total desktop operating system market, Linux has a features, without the licensing cost. Thus was born Linux, the
dedicated following of enthusiasts, usersand contributors. It was Unix-like operating system which used freely available code from
created in 1991 by University of Helsinki student, Linus Torvalds, the GNU project. This enabled users around the world to utilise the
who had become frustrated with the limitations and licensing of the power of the Unix-like system, completely free of charge, an ethos
popular educational system Minix, a miniature version of the Unix that still holds today: Linux is free to download, install and use.
operating system, in use at the time.
Linux is much like any other operating system, such as Windows or
Unix itself was released in the early 70s, as a multi-tasking, modular- macOS in that it manages the computer hardware, provides an
designed operating system originally developed for programmers interface for the user to access that hardware and comes with
who needed a stable platform to code on. However, its performance, programs for productivity, communications, gaming, science,
power and portability meant that it soon became the system of education and more. Linux can be broken up into a number of
choice for companies and universities where high-end computing significant elements:
tasks were needed.

BOOTLOADER GRAPHICAL SERVER

The bootloader is the software that initialises and boots up This is a module within Linux that provides a graphical output
your computer. It loads up the various modules the OS uses to to your monitor. It’s referred to as the X server or simply just
begin to access the hardware in the system. You can modify a X. X is an application that manages one or more graphical
bootloader to load more than one OS installed on the system. displays and one or more input devices (keyboard, mouse, etc.)
connected to the computer.

DAEMONS
KERNEL
Daemons are background services that start as the operating
system is booting. These can enable printing, sound, The kernel is the core of the system and the single element
networking and so on. They run unobtrusively rather than that is actually called Linux. The Linux kernel manages the
under the direct control of the user, often waiting to be computer processor, memory, storage and any peripherals you
activated by an event or condition. have attached to your computer. It provides the basic services
for all other parts of the OS.

DESKTOP ENVIRONMENTAL
PROGRAMS/APPLICATIONS
The Desktop Environment, or DE, is the main Graphical User
Interface (GUI) that users interact with. It’s the desktop, that With Linux being an open source, free operating system, it
includes Internet browsers, productivity, games and whatever also makes use of the tens of thousands of freely available
program or app you're using. There are countless DEs applications. The likes of LibreOf fice, GIMP and Python are just
available. Raspbian uses PIXEL. the tip of the iceberg.

131 www.bdmpublications.com
What is Linux?

SHELL

The Linux shell is a command-line interface environment that a


Linux user can use to enter commands to the OS that directly
affect it. Within the shell you can add new users, reboot the
system, create and delete files and folders, and much more.
BASH (Bourne Again Shell)
is the most popular shell
used in Linux, although
more are available. The
shell is also known as the
Terminal, and it's where
you're going to work
Linus Torvalds, the creator of the
from through this section
Linux kernel.
of the book.

Linux is used throughout the world, in a number of basic and


quite unique uses. While it may look radically different from one
Tux, the environment to the next, the actual Linux kernel, can be found
Linux in modern smart TVs, in-car entertainment systems and GPS,
mascot supercomputers, loT devices and the Raspberry Pi. It's used by
(Linus likes NASA, both in the command centre and on-board the ISS. Linux
penguins). servers power the backbone of the Internet, along with most of the
websites you visit daily. Android utilises components of the Linux
kernel, as do set top boxes, games consoles and even your fridge,
freezer, oven and washing machine.

Linux isn't just a free to use operating system. It's stable,


powerful and fast, easily customised and requires very little
maintenance. However, it's more than just performance stats;
Linux means freedom from the walled garden approach of other
operating systems. It's a lively community of like-minded individuals
Raspbian on the Raspberry Pi, is the who want more from their computers without the shackles of price
Linux distribution of choice. or conformity. Linux means choice.

www.bdmpublications.com 139
Understanding Linux

Using the Filesystem


To master Linux, it's important to understand how the filesystem works. What's more,
it's also important to become familiar with the Terminal, or shell. This command line
environment may appear daunting at first, but with practise, it soon becomes easy to use.

GETTING AROUND
To drop into the Terminal, click on the fourth icon from the left along the top of the Raspberry Pi desktop, the one with a right­
facing arrow and an underscore. This is the shell, or Terminal.

STEP 1 First, you're going to look at directories and the Enter: is to view the contents of the current
STEP3
A directory path. A directory is the same thing as a A directory. You should see Desktop, Documents,
folder, however in Linux it's always called a directory. These are and Downloads and Scratch in Blue. You may also see other items
placed inside each other using a character. So when you see / depending on how much you have used your Raspberry Pi. The
home/pi it means the pi directory is inside the home directory. colour code is worth knowing: directories are blue while most files
Enter: clear and press return to clean the screen. Now enter: pwd. are white. As you go on you’ll see other colours: executable files
This stands for Print Working Directory and displays/home/pi. (programs) are bright green, archived files are red and so on. Blue
and white are the two you need to know to get started.

piBraspberrypi “ $ pud
zhomezpi
piOraspberrypi $ Is
Desktop Documents Dounloads exit indiecity python_games Scratch
piOraspberrypi ~ $

When you log in to your Raspberry Pi, you don't Now you’re going to move from the pi directory into
STEP 2 STEP 4
A start at the base of the hard drive, known as the A the Documents directory. Enter: cd Documents.
Toot' (also known as the topmost directory). Instead you begin Note the capital "D". Linux is case sensitive, which means you have
inside your user directory, which is named 'pi' by default and is to enter the exact name including correct capitalisation. The cd
itself in a directory called 'home'. Directories are indicated by the'/' command stands for change directory. Now enter: pwd again to
symbol. So, '"/home/pi"' tells you that in the root is a directory called view the directory path. It will display /home/pi/ Documents. Enter:
home, and the next"'/'" says that inside "home" is a directory called Is to view the files inside the Documents directory.
"pi". That’s where you start.

piBraspberrypi ~ $ pwd
zhomezpi
piBraspberrypi ' $ Is
Desktop Documents Downloads exit indiecity python games Scratch
pieraspberrypi “ $ pwd piBraspberrypi $ cd Documents
zhomezp i piBraspberrypi “zDocuments $ pwd
zhomezp izDocuments
piOraspberrypi ~ $
piBraspberrypi “zDocuments $ Is
Amber archiue.tar Cryptol01.pdf dog_jump euro fizzbang_backup.py fizzbang.py mes
piBraspberrypi “zDocuments S _

140 www.bdmpublications.com
Using the Filesystem

JSWS: How do you get back up to the pi directory? By using The "Is" and "cd" commands can also be used with
a command "cd In Linux two dots means the more complex paths. Enter: is Documents/
directory above, also known as the parent directory. Incidentally, a pictures to view the contents oF a Pictures directory inside
single dotis used For the same directory. You never use "cd ." to your Documents directory. You can switch to this directory using
switch to the same directory but it's worth knowing because some cd Documents/Pictures; use cd . . /. . to move back up two
commands need you to speciFy the current directory. parent directories.

pieraspberrypi “/Documents $ pwd piOraspberrypi “ $ Is Documents/Pictures


/home/р i/Documents LEGO LucyHattersley.jpg rdspberry_pi_Z_photoi
piOraspberrypi "/Documents $ cd piOraspberrypi $ cd Documents/Pictures
piOraspberrypi " $ pwd piOraspberrypi "/Documents/Pictures 0 pwd
/home/р i /home/рi/Documents/P ictures
piOraspberrypi " $ piOraspberrypi "/Documents/Pictures $ cd ../..
piOraspberrypi ' $ pwd
/home/pi
piOraspberrypi " $

ABSOLUTE VS RELATIVE PATHS


It is important to know the difference between the working directory, root directory and home. There are also two types of
path: Absolute and Relative. These are easier to understand than they sound. Let's take a look...

By default, commands tike "Is" use the working The second command ("Is /Documents/Pictures")
STEP1 STEP3
directory. This is the current directory that you're attempts to list the content of Pictures in a
looking at and is set to your home directory by default (/users/ directory called Documents inside the root directory (because the
pi). Using "pwd'' (Print Working Directory) lets you know what the path started with '/', which is root). There is typically no Documents
working directory is, and using "cd" changes the working directory. directory in root, so you will get a "No such file or directory"
error. Starting a path with'/’ is known as an "absolute path”, while
starting without the '/' is known as a "relative path" because it is
relative to your working directory.
piBraspberrypi “ $ pwd
/home/pi
piOraspberrypi " $
piOraspberrypi $ Is /
bin boot deu etc home lib lost found
* media mnt opt proc
piOraspberrypi $ Is /Documents/Pictures
Is: cannot access /Documents/Pictures: No such file or directory
piOraspberrypi $ _

The root directory is always'/'. Entering: iHfj There is also an absolute path shortcut to your
STEP 2 STEP 4
lists the contents of root, and entering: user directory, and that is the tilde character.
switches to the root directory. This is important because there is a Entering: Q3E always lists the contents of your home directory,
difference between "Is Documents/Pictures" and "Is /Documents/ while "cd moves straight to your home directory, no matter
Pictures". The First command lists the contents of the Pictures what your working directory is. You can also use this shortcut
directory in Documents inside the working directory (which, if you wherever you are: enter: |ls -/Documents/Pictures] to display
are in the home directory, will work). the contents of the Pictures.

pi@raspber
File Edit Tabs Help File Edit Tabs Help
piOraspberrypi:- $ pwd piOraspberrypi:- $ cd -
/home/pi piOraspberrypi:- $ pwd
piOraspberrypi:' $ Is Documents/Pictures /home/pi
BDM-Web-logo-dark1.jpg David Hayward.jpg RPi.png piOraspberrypi:- S Is -/Documents/Pictures
piOraspberrypi:- $ | BDU-Web-logo-dark1.jpg David Hayward.jpg RPi.png
piOraspberrypi:- $ |

www.bdmpublications.com
Understanding Linux

Listing and Moving Files


Admittedly, using the desktop GUI to list and move files is much easier than using the
Terminal and keyboard. However, it's an important skill that you will appreciate as you
advance with the Raspberry Pi and Linux.

LOOKING AT FILES
Operating systems are built on files and folders, or directories if you prefer. While you're used to viewing your own files, most
operating systems keep other files out of sight. In Raspbian, you have access to every file in the system.

STEP 1 We've already looked at "Is”, which lists the files in After the permission letters come a single number.
STEP3
a the working directory, but you are more likely to A This is the number of files in the item. If it's a file
use a command like "Is-I". The bit after the command (the '-lah') then it'll be 1, but if it's a directory it'll be at least 2. This is because
is known as the argument. This is an option that modifies the each directory contains two hidden files; one with a single dot (.)
behaviour of the command. and one with two dots (..). Directories containing files or other
directories will have a higher number.

piBraspberrypi " $ Is -1
piBraspberrypi $ Is -1
total Z4
-rw-r—r— 1 pi pi 0 May 11 20:56 articles.txt
drwxr-xr-x 2 pi pi 4096 Apr 21 17:55 Desktop
drwxr-xr-x 5 pi pi 4096 Apr 21 14:50 Documents
drwx--------- 2 pi pi 4096 Apr 21 15:23 Downloads
drwxr-xr-x 3 pi pi 4096 Apr 17 18:48 indiecity
-rw-r—r— 1 pi pi 0 May 11 20:56 names.txt
drwxrwxr-x 2 pipi 4096 Jan 1 1970 python_games
drwxr-xr-x 2 pi pi 4096 Apr 17 12:53 Scratch
piBraspberrypi ” S

STEP 2 The "-1" argument lists files and directories in long STEP 4 Next you’ll see the word "pi" listed twice on each
A format. Each file and directory is now on a single A line. This refers to the user rather than the name of
line, and before each file is a lot of text. First you'll see lots of letters your computer (your default username is "pi"). The first is the owner
and dashes, like 'drwxr-xr-x'. Don't worry about these for now; they of the file, and the second is the group. Typically these will both be
are known as 'permissions' and we'll come to those later. the same and you'll see either'pi'or Toot'. You can enter: is -1 /
to view the files and directories in the root directory that belong to
the root account.
piBraspberrypi $ Is -1
tota1 24
-rw-r—r— 1 pi pi 0 May 11 20:56 articles.txt piBraspberrypi $ Is -1
drwxr-xr-x 2 pl pi 4096 Apr 21 17:55 Desktop total 28
drwxr-xr-x 5 pi pi 4096 Apr 21 14:50 Documents -rw-r—r— 1 pi pi 0 May 11 20:56 articles.txt
drwx--------- 2 pi pi 4096 Apr 21 15:23 Downloads drwxr-xr-x 2 pi pi 4096 Apr 21 17:55 Desktop
drwxr-xr-x 3 pi pi 4096 Apr 17 18:48 indiecity drwxr-xr-x 5 pi pi 4096 Apr 21 14:50 Documents
-rw-r—r— 1 pi pi 0 May 11 20:56 names.txt drwx--------- 2 pi pi 4096 Apr 21 15:23 Downloads
drwxrwxr-x 2 pi pi 4096 Jan 1 1970 pythun_tjames drwxr-xr-x 3 pi pi 4096 Apr 17 18:48 indiecity
drwxr-xr-x 2 pi pi 4096 Apr 17 12:53 Scratch -rw-r—r— 1 pi pi 0 May 11 20:56 names.txt
piBraspberrypi ~ $ drwxrwxr-x 2 pi pi 4096 Jan 1 1970 python_games
drwxr-xr-x 2 pi pi 4096 Apr 17 12:53 Scratch
drwxr-xr-x 3 pi pi 4096 May 11 21:15 test
piBraspberrypi ” $ Is -1 z
total 74
drwxr-xr-x 2 root root 4096 Jan 1 1970 bin
drwxr-xr-x 3 root root 2048 Jan 1 1970 boot
drwxr-xr-x 12 root root 3280 May 11 09:03 deu
drwxr-xr-x 109 root root 4096 May 11 09:03 etc
drwxr-xr-x 3 root root 4096 Jan 1 1970 home
drwxr-xr-x 12 root root 4096 Jan 1 1970 lib
drwx--------- 2 root root 16384 Feb 15 11:21 lnst
*
found
drwxr-xr-x 3 root root 4096 May 11 07:42 media
drwxr-xr-x 2 root root 4096 Jan 11 00:02 mnt
drwxr-xr-x 6 root root 4096 Jan 1 1970 opt

www.bdmpublications.com
Listing and Moving Files

The next number relates to the size of the file, in Finally, you should be aware that there are many
bytes. In Linux each text file is made up of letters hidden files in Linux. These are listed using the "-a"
and each letter takes up a byte, so our names.txt file has 37 bytes argument. Hidden files and directories begin with a dot (.), so you
and 37 characters in the document. Files and directories can be should never start a file or directory with a dot, unless you want to
extremely large and hard to determine, so use "Is - Ih". The "h" hide it. Typically, you can combine all three arguments together into
argument humanises the number, making it easier to read. the command '"s-lah".

pieraspberrypi $ Is -1 piOraspberrypi “ $ Is -lah


total 32 total 520K
-rw-r—r— 1 pl pi 0 Hay 11 20:56 artlcles.txt drwxr-xr-x 33 Pi Pi 4.OK May 11 21:14
drwxr-xr-x 2 pi pi 4096 Apr 21 17:55 Desktop drwxr-xr-x 3 root root 4.OK Jan 1 1970
drwxr-xr-x 5 pi pi 4096 Apr 21 14:50 Documents drwx--------- 2 Pi Pi 4.OK Apr 20 14:31
drwx--------- 2 pi pi 4096 Apr 21 15:23 Downloads -rw-r—r— 1 Pi Pi 0 Hay 11 20:56 articles.txt
drwxr-xr-x 3 pi pi 4096 Apr 17 18:48 indiecity -rw---------- 1 Pi Pi 8.7K May 11 09:03 .bash_history
-rw-r—r— 1 pi pi 37 May 11 21:27 names.txt -rw-r—r— 1 Pi Pi 220 Feb 15 14:05 .bash_logout
drwxrwxr-x 2 pi pi 4096 Jan 1 1970 python_games -rw-r—r— 1 Pi Pi 3.2K Feb 15 14:05 . bashrc
drwxr-xr-x 2 pi pi 4096 Apr 17 12:53 Scratch drwxr-xr-x 10 Pl Pi 4.OK Apr 21 17:08
drwxr-xr-x 3 pi pi 4096 May 11 21:15 test drwxr-xr-x 20 Pi Pi 4.OK Apr 21 13:33
piOraspberrypi $ Is -Ih drwx--------- 3 Pi Pi 4.OK Feb 16 14:16 .dbus
total 32K drwxr-xr-x 2 Pi Pi 4.OK Apr 21 17:55 Desktop
-rw-r—г— 1 pi pi 0 May 11 20:56 articles.txt -rw-r—r— 1 Pi Pi 35 Apr 17 12:17 .dmrc
drwxr-xr-x 2 pi pi 4.OK Apr 21 17:55 Desktop drwxr-xr-x 5 Pi Pi 4.OK Apr 21 14:50 Documents
drwxr-xr-x 5 pi pi 4.OK Apr 21 14:50 Documents drwx--------- 2 Pi Pi 4.OK Apr 21 15:23 Downloads
drwx--------- 2 pi pi 4.OK Apr 21 15:23 Downloads drwxr-xr-x 2 Pi Pi 4.OK Apr 20 13:45
drwxr-xr-x 3 pi pi 4.OK Apr 17 18:48 in.! i । ifi| drwxr-xr-x Pi Pi 4.OK (iiir- 18:15 .fontconf ig

SOME COMMON DIRECTORIES


Now that you know how to view the contents of your hard drive you'll start to notice a lot of directories with names like bin, sbin,
var and dev. These are the files and directories that you are kept away from on a Mac, and won't encounter on a Windows PC.

Enter: to view all of the files and Entering: displays the contents of your
STEP1 STEP3
directories, including the hidden items, in the root home directory, which contains pi; the directory
directory of your hard drive. Here you will see all the items that that you start in. So, entering: is the same as just "Is”
make up your Raspbian OS (which is a version of Linux). It's worth from the default home directory. This is where you are expected
taking the time to know some of them. to place most of the documents you create. Don’t confuse home
with "usr"; the /usr directory is where find you find program tools
and libraries.
piOraspberrypi $ Is -lah z
total 82K
drwxr-xr-x 22 root root 4.OK May 11 21:23
drwxr-xr-x 22 root root 4.OK May 11 21:23
drwxr-xr-x 2 root root 4.OK Jan 1 1970 bin
drwxr-xr-x 3 root root 2.OK Jan 1 1970
drwxr-xr-x 12 root root 3.3K May 11 09:03 deu piOraspberrypi “ $ Is
drwxr-xr-x 189 root root 4.OK May 11 09:03 etc articles.txt Desktop Documents Downloads indiecity names.txt python_g
drwxr-xr-x 3 root root 4.OK Jan 1 1970 home piOraspberrypl $ Is zhomezpi
drwxr-xr-x 12 root root 4.OK Jan 1 1970 lib articles.txt Desktop Documents Downloads indiecity names.txt pythonj
drwx--------- 2 root root 16K Feb 15 11:21 lost«found piOraspberrypi " $
drwxr-xr-x 3 root root 4.OK May 11 07:42 med ia
drwxr-xr-x 2 root root 4.OK Jan 11 00:02
drwxr-xr-x 6 root root 4.OK Jan 1 1970 opt
dr-xr-xr-x 85 root root 0 Jan 1 1970
drwx--------- 9 root root 4.OK May 11 07:36 root
drwxr-xr-x 10 root root 460 May 11 09:03 run
drwxr-xr-x 2 root root 4.OK Jan 1 1970 sbin
drwxr-xr-x 2 root root 4.OK Jun 20 2012 * 1 | nll-V
or

Bin is a directory that stores binaries. This is the Lib is a directory that contains libraries of code
STEP 2 STEP 4
Linux way of saying programs or applications. that are referred to by other programs (different
Sbin is for system binaries, which are the programs that make programs share files in Lib). "Var" is short for various, which is
up your system. Dev contains references to your devices: hard mostly files used by the system, but you may need to work with
drive, keyboard, mouse and so on. Etc contains your system items here. Finally there is a directory called "imp", which is for
configuration files. temporary files; files placed here are on your system for the short
term and can be deleted from the system.

piOraspberrypi $ Is /bin
bash bzfgrep chgrp dash domainname fgconsole 8™ piOraspberrypi ’ $ Is zuar
bunzip2 bzgrep chmod date dumpkeys fgrep gzi backups cache lib local lock log mail opt run spool swap ПЕЯ
bzcat bzip2 chown dd echo findmnt h(M piOraspberrypi ~ $
bzcmp bzipZrecouer chut df ed fuser ip
bzdiff bzless con2fbmap dir egrep fusermounf kb-'
bzegrep bzmore cp dmesg false grep kil
bzexe cat cpio dnsdoma i nname fbset gunzip kmt ।
piOraspberrypi ' $

www.bdmpublications.com
Understanding Linux

Creating and Deleting Files


Being able to create and delete a file is an everyday computing skill. However, when
using the Linux Terminal, there's an element of care required, chiefly because any
deleted files aren't placed in the system recycle bin.

CREATING FILES
Once you learn to recognise the files and directories that make up Raspbian OS, it's time to discover how to make your own.
Knowing how to make, edit and delete files and directories is essential if you want to make your own projects.

STEP 1 We're going to create a File using a command called If you try to touch a file that doesn't exist, you
STEP3
a Touch. Touch is an interesting command that reaches A create a blank file with that name. Try it now. Type
out to a file, or directory, and updates it (this changes the system time touch testfile and Is -1 to view the files. You'll now have a
as if you'd just opened the file). You can see Touch in access using "Is new file in your home directory called "testfile". Notice that the size
-I" and checking the time next to a directory (such as Scratch). of the file is 0, because it has nothing in it.

piBraspberrypi $ Is -1 piBraspberrypi $ touch testfile


total 24 piBraspberrypi “ $ Is -1
drwxr-xr-x 2 pi pi 4096 Apr 21 17:55 Desktop total 24
drwxr-xr-x 5 pi pi 4096 May 13 10:57 Documents drwxr-xr-x 2 pi pi 4096 Apr 21 17:55 Desktop
drwx------------- 2 pi pi 4096 May 13 11:01 Downloads drwxr-xr-x 5 pi pi 4096 May 13 10:57 Document ,
drwxr-xr-x 3 pi pi 4096 Apr 17 18:48 indiecity drwx------------ 2 pi pi 4096 May 13 11:01 Downloads
drwxrwxr-x 2 pi pi 4096 Jan 1 1970 python games drwxr-xr-x 3 pi pi 4096 Apr 17 18:48 indiecity
drwxr-xr-x 2 pi pi 4096 Apr 17 12:53 Scratch drwxrwxr-x 2 pi pi 4096 Jan 1 1970 python_games
piBraspberrypi $ _ drwxr-xr-x 2 pi pi 4096 May 13 11:05 Scratch
-rw-r—r— 1 pi pi 0 May 13 11:10 test file
piBraspberrypi $ _

STEP 2 Now enter: touch Scratch and is -1 again and STEP 4 A quick word about file names: remember that
A notice that the time has changed. It now matches л Linux is case sensitive, so if you now enter: touch
the current time. You might be wondering what this has to do with Testfile (with a capital T), it doesn't update 'testfile'; instead, it
creating files or directories. Touch has a second, more popular, use, creates a second file called 'Testfile'. Enter: is -1 to see both files.
which is to create files. This is confusing, so most people stick with using lowercase letters
at all times.

piBraspberrypi $ Is -1 piBraspberrypi touch testfile


total 24
piBraspberrypi ’ $ Is -1I
total Z4
drwxr-xr-x 2 pi pi 4096 Apr 21 17:55 Desktop Desktop
drwxr-xr-x Z Pi Pi 40% Apr Z1 17:55
drwxr-xr-x 5 pi pi 4096 May 13 10:57 Documents drwxr-xr-x 5 Р> 4096 May 13 10:57 Documents
Pi
drwx------------- 2 pi pi 4096 May 13 11:01 Downloads drwx---------- Z Pi Pi 4096 May 13 11:01 Downloads
drwxr-xr-x 3 pi pi 4096 Apr 17 18:48 indierity drwxr-xr-x 3 Pi Pi 4096 Apr 17 18:48 indiecity
drwxrwxr-x 2 pi pi 4096 Jan 1 1970 python games drwxrwxr-x Z Pi Pi 4096 Jan 1 1970 python_qames
drwxr-xr-x 2 pi pi 4096 Apr 17 12:53 Scratch drwxr-xr-x Z Pi Pi 4096 May 13 11:05 Scratch
-rw-r—r— 1 Pi Pi 0 May 13 11:08 testfile
piBraspberrypi $ touch Scratch
p i Braspberryp i 5 touch Testfile
piBraspberrypi $ Is -1 p i Braspberryp i Is -1
S
total 24 total Z4
drwxr-xr-x 2 pi pi 4096 Apr 21 17:55 Desktop drwxr-xr-x Z Pi pi 4096 Apr Z1 17:55 Desktop
drwxr-xr-x 5 pi pi 4096 May 13 10:57 Documents drwxr-xr-x 5 Pi Pi 4096 May 13 10:57 Documents
drwx------------ 2 pi pi 4096 May 13 11:01 Downloads drwx---------- Z Pi Pi 4096 May 13 11:01 Downloads
drwxr-xr-x 3 Pi Pi 4096 Apr 17 18:48 indiecity
drwxr-xr-x 3 pi pi 4096 Apr 17 18:48 indiecity
drwxrwxr-x Z Pi Pi 4096 Jan 1 1970 python_games
drwxrwxr-x 2 pi pi 4096 Jan 1 1970 python_games drwxr-xr-x Z Pi 4096 May 13 11:05 Scratch
Pi
drwxr-xr-x 2 pi pi 4096 May 13 11:05 Scratch -rw-r—r— 1 Pi Pi 0 May 13 11:08 testfile
piBraspberrypi $ _ -rw-r—г— 1 pi P' 0 May 13 11:10 Testfile
piBraspberrypi ■ 3

144 www.bdmpublications.com
Г Creating and Deleting Files

Another important thing to know is never to use a Here are some other files names to avoid:
space in your File names. If you try to enter: touch *
?#%&{}\<>
/$!'":@+'|=. The full stop (.) is used to
test file, you create a document called "test” and another called create an extension to a file; usually used to indicate a file type,
"file". Technically there are ways to create files containing a space such as textfile.txt or compressedfile.zip, and starting a file with
but you should always use an underscore character instead of a a full stop makes it invisible. Don't use full stop in place of a space
space, such as "touch test_file". though; stick to underscores.

piBraspberrypi “ $ touch test file


piBraspberrypi $ Is -1
tota1 Z4 piBraspberrypi ” $ touch don't.use<odd}symbols&in<filenames>or=you’ 1lAconfu
drwxr-xr-x 2 pi pi 4096 Opr 21 17:55 Desktop
drwxr-xr-x 5 pi pi 4096 May 13 10:57 Document •
drwx--------- 2 pi pi 4096 May 13 11:01 Downloads
-rw-r—r— 1 pi pi 0 May 13 11:15 file
drwxr-xr-x 3 pi pi 4096 Apr 17 18:48 indiecity
drwxrwxr-x 2 pi pi 4096 Jan 1 1970 python_gar
drwxr-xr-x 2 pi pi 4096 May 13 11:05 Scratch
-rw-r—r— 1 pi pi 0 May 13 11:15 test
-rw-r—r— 1 pi pi 0 May 13 11:10 testfile
-rw-r—r— 1 pi pi 0 May 13 11:12 Testfile
piBraspberrypi $ _

REMOVING FILES
We've created some files that we don't want, so how do we go about removing them? It turns out that deleting files in your
Raspberry Pi is really easy, which may be a problem, so be careful.

Enter: to view the files in your home directory. We're going to use a wildcard (*) to delete our next
STEP1 J
STEP3
If you've followed the steps before then you should two files, but again this is something you really
have three files: "test”, "testfile", and "Testfile". WeTe going to get rid need to do with care. First use "Is” to list the files and make sure
of these items because they were created as an example. it's the one you want to delete. Enter: |ПЕКЯ5ЯД to view files that
match the word "test" and any other characters. The character
is called a "wildcard" and it means any characters here.
piBraspberrypi ' $ Is -]I
total 24
drwxr-xr-x 2 Pi Pi 4096 Apr 21 17:55 Desktop piBraspberrypi $ Is -1
drwxr-xr-x 5 Pi
total 24
Pi 4096 May 13 10:57 Documents
drwxr-xr-x Z Pi Pi 4096 Jul 9 08:36 Desktop
drwx------------ 2 Pi Pi 4096 May 13 11:01 Downloads drwxr-xr-x 2 Р> 4096 Jul 9 00:36 Documents
Pi
-rw-r—r— 1 Pi P> 0 May 13 11:15 file drwxr-xr-x 2 Pi Pi 4096 Jul 9 08:36 Downloads
drwxr-xr-x 3 Pi Pi 4096 Apr 17 18:48 indiecity -rw-r—r— 1 Pi Pi 0 Jul 9 08:37 file
drwxrwxr-x 2 Pi Pi 4096 Jan 1 1970 python_games drwxr-xr-x 2 Pi Pi 4096 Jul 9 08:36 indiecity
drwxrwxr-x 2 Pi Pi 4096 Jan 1 1970 python_game?
drwxr-xr-x 2 l’i P
* 4096 May 13 11:05 Sera tch
drwxr-xr-x 2 Pi Pi 4096 Jul 9 08:36 Scratch
-rw-r—r— 1 Pi Pi 0 May 13 11:15 test -rw-r—г— 1 Pi pi 0 Jul 9 08:37 test
-rw-r—г— 1 Pi Pi 0 May 13 11:10 testf ile -rw-r—r— 1 Pi Pi 0 Jul 9 08:37 testf ile
-rw-r—r— 1 P> Pi 0 May 13 11:46 Testf ile piBraspberrypi *
Is test
piBraspberrypi S test testfile
piBraspberrypi

To get rid of files you use the "rm” command. We see that "Is test
"
* matches two files: "test” and
STEP 2 STEP 4
Enter: t° delete the file called "testfile”, but not the file called "file". That’s because
"Testfile" (with the uppercase "t"). Enter: and you'll find it's it didn't match the "test" part of "test
".
* Check carefully over groups
gone. Where is it? It's not in the Trash or Recycle Bin, like on a Mac of files you want to remove (remember you can't recover them) and
or Windows PC. It's deleted completely and cannot be recovered. replace the "Is" with "rm". Enter: ЯЯВЖЕПВ to remove both files.
Bear this in mind and always think before deleting files. Finally enter: to get rid of the confusing file.

piBraspberrypi $ rm Testfile
p i Braspberryp i $ Is -1 piBraspberrypi $ rm test
*
total Z4 piBraspberrypi $ Is -1
drwxr-xr-x 2 pi pi 4096 Apr 21 17:55 Desktop total Z4
drwxr-xr-x 5 pi pi 4096 May 13 10:57 Documents drwxr-xr-x 2 pi pi 4096 Jul 9 08:36 I) >p
drwxr-xr-x 2 pi pi 4096 Jul 9 08:36 BOCUN
drwx----------- Z pi pi 4096 May 13 11:01 Downloads
drwxr-xr-x 2 pi pi 4096 Jul 9 08:36 Downloads
-rw-r—r— 1 pi pi 0 May 13 11:15 file
-rw-r—r— 1 pi pi 0 Jul 9 08:37 file
drwxr-xr-x 3 pi pi 4096 Apr 17 18:48 indiecity
drwxr-xr-x 2 pi pi 4096 Jul 9 08:36 indiecity
drwxrwxr-x 2 pi pi 4096 Jan 1 1970 pythun_games
drwxrwxr-x Z pi pi 4096 Jan 1 1970 pylhun_yames
drwxr-xr-x 2 pi pi 4096 May 13 11:05 Scratch
drwxr-xr-x Z pi pi 4096 Jul 9 08:36 Scratch
-rw-r—г— 1 pi pi 0 May 13 11:15 test
piBraspberrypi $ rm f i le
-rw-r—r— 1 pi pi 0 May 13 11:10 testfile piBraspberrypi " $
piBraspberrypi

www.bdmpublications.com
Understanding Linux

Create and Remove


Directories
Creating, moving and deleting directories aren't as easy in the Terminal as they are within a
desktop interface. You need to tell Linux to move the directories inside other directories, a
process known as recursion. Sounds complex but you should quickly get the hang of it.

MANAGING FILESAND DIRECTORIES


Now that you know how to create files, you'll want to learn how to make directories, which are the same thing as folders, as
well as move items around. If you are more used to working with a desktop interface, this can take a bit of getting used to.

Enter: Is to quickly view all the directories currently Like touch, you can create multiple directories
STEP1 STEP3
A in in the home location. Directories are created л at once with the mkdir command. Enter: mkdir
using the "mkdir" command (make directory). Enter: mkdir testdir2 testdir3 and enter: is. You’ll now find several
testdir to create a new directory in your home directory. Enter: directories called testdir. Also, like files, you should know this means
is again to see it. you can't (and really shouldn't) create directories with spaces. As
with files, use an underscore ("_") character instead of a space.

piBraspberrypi $ Is
piBraspberrypi $ mkdir testdirZ testdir3
Desktop Documents Downloads indiecity python yames Sc piBraspberrypi $ Is
piBraspberrypi $ mkdir testdir
Desktop Documents Downloads indiecity python_games Sera'
piBraspberrypi $ Is
piBraspberrypi $ _
Desktop Documents Downloads indiecity python_games Sc
piBraspberrypi ~ _

The "mkdir" command is different to touch, in that You can create directories inside of each other using
STEP 2 STEP 4
A it doesn't update the timestamp if you use it with a the directory path. Enter: mkdir Documents/
directory that already exists. Enter: mkdir testdir again and you'll photos to create a new directory called "photos” inside your
get the error "mkdir: cannot create directory 'testdir: Fite exists". documents directory. The directory has to already exist, though,
try to enter: mkdir articles/reports and you'll get an error
because there is no articles directory.

piBraspberrypi ' $ mkdir testdir


mkdir: cannot create directory 'testdir’: File exists
piBraspberrypi $ Is
piBraspberrypi $ _
Desktop Documents Downloads indiecity python_c|ames Sera1
piBraspberrypi $ mkdir Documents/photos
piBraspberrypi ~ $ mkdir articles/reports
mkdir: cannot create directory 'articles/reports': No such f
piBraspberrypi ~ $

www.bdmpublications.com
Г Create and Remove Directories

•ЯЧЯЧ To create a directory path you need to pass in the Now you’re starting to get a bit more advanced,
"p" option to mkdir (which stands For "parents”). ttKIiF weTe going to just reiterate something. In Linux
Options, if you remember, come after the command and start with the command structure is always: command, option and argument,
aSo enter: mkdir -p articles/reports. Enter: Is to view in that order. The command is the function, next are the options
the articles directory, or "Is articles" to view the reports directory (typically single letters starting with "-") and finally the argument
sitting inside. (often a file, or directory structure). It's always command, option
then argument.

piOraspberrypi ~ $ mkdir -p articles/reports

piOraspberrypi $ Is -1 articles
total 4
drwxr-xr-x Z pi pi 4096 May 13 1Z:36 reports
piOraspberrypi $ _

GETTING RID OF DIRECTORIES


Deleting directories is pretty easy in Linux, along with files, and this can be a problem. It's too easy to delete entire directories
containing files and these are instantly removed, not sent to a trash directory. Tread carefully.

WeTe going to remove one of the directories we To delete a directory containing files or other
STEP1 STEP3
J created earlier using the "rmdir” command. Enter: directories, you return to the "rm" command used
ЕБ to view the files and directories in the current directory. We’ll to remove files, only now we need to use the "-R" option (which
start by getting rid of one of the test directories. Enter: ИДПЯ stands for "recursive”.) Using "rm -R" removes all the files and
and ES again to confirm the directory has been removed. directories to whatever you point it at. Enter: to
remove the articles directory.

piBraspberrypi “ $ Is
piOraspberrypi ~ $ Is
articles Desktop Documents Dounloads indiecity py
articles Desktop Documents Dounloads indiecity python_g<
piOraspberrypi $ rm -R articles
piOraspberrypi $ rmdir testdir3_
piOraspberrypi ” $ Is
Desktop Documents Downloads indiecity python_games
piOraspberrypi ~ $

Now we'll try to get rid of the articles directory STEP 4 As with multiple files, you can delete multiple
STEP 2
(containing the reports directory). Enter: ДДЯЯ directories inside the same directory using the "rm”
press return. You'll get an error saying "rmdir: failed command with the wildcard character (*). This should be done with
to remove ‘articles’: Directory not empty". This is a puzzler; the care though so use the Mootion (which stands for "interactive").
rmdir command only removes directories that having nothing in This will prompt you before each deletion. Enter: r—~
them (no files or other directories). and press Sand to each prompt. It's a good idea to use the
ДЯ option whenever using the rm command.

piBraspberrypi ~ $ rmdir articles


rmdir: failed to remoue 'articles': Directory not empty piOraspberrypi $ rm -Ri test
*
piOraspberrypi $ _ rm: remoue directory 'testdir'? у
rm: remoue directory 'testdirZ'? у
rm: remoue directory 'testdir3'? y_

www.bdmpublications.com 147
Understanding Linux

Copying, Moving and


Renaming Files
Taking command of the Terminal is essential when learning how your Raspberry
Pi's operating system works. The copying, moving and renaming of files is equally
important, as you'll be doing a lot of this throughout your Pi projects.

USING THE MOVE COMMAND


In Linux, renaming a file is simply moving it from one name to another and copying a file is moving it without deleting the
original. Don't panic, it’s quite easy to master.

Before we can move anything around, we need to Enter: mv testfile testdir and press return
STEP1 STEP3
A have a few test items in our home directory. Enter: ______ J to move the testfile document into the testdir
touch testf lie and mkdir testdir to create a test file and directory. Enter: is to see that it's no longer in the home directory,
test directory in your home directory. Enter: Is to check that they and Is testdir to see the testfile now sitting in the testdir
are both present. directory. Now enter: mkdir newparent to create a new directory.

piGraspberrypi $ Is
piGraspberrypi $ touch testfile
Desktop Documents Doon loads indiecity python_games Sera
piGraspberrypi $ mkdir testdir
piGraspberrypi $ mu testfile testdir
piGraspberrypi $ Is
piGraspberrypi ~ $ Is
Desktop Documents Downloads indiecity python_games
Desktop Documents Downloads indiecity python_games Sera
piGraspberrypi ~$
piGraspberrypi ~ $ Is testdir
testfile
piGraspberrypi " $

Files and directories are moved using the mv Directories with files are moved in the same way.
STEP 2 STEP 4
command. This is different to the commands we've Enter: mv testdir newparent to move the
looked at so far because it has two arguments (remember Linux testdir directory inside the newparent directory. Let's move into the
command line is command, option, argument). The first argument directory to find the file. Enter: cd /newparent/testdir and
is the source (the file or directory to be moved) and the second is enter: Is to view the testfile sitting inside the directory.
the destination.

piGraspberrypi $ Is
Desktop Documents Downloads indiecity python_games Scr
piGraspberrypi $ mkdir newparent
piGraspberrypi $ Is
piGraspberrypi $ mu testdir newparent
Desktop Documents Downloads indiecity python_yames Scrd
piGraspberrypi $ cd newparent/testdir
piGraspberrypi ~ $ mu testfile testdir
piGraspberrypi "/newparent/testdir $ Is
testfile
piGraspberrypi “/newparent/testdir $

www.bdmpublications.com
Copying, Moving and Renaming Files

Files and directories can be moved up using the You can also move files using longer paths. Enter:
double dot as an argument. Enter: is -la cd ~ to return to the home directory and
to view your testfile and the single and double dot files. The mv newparent/testfile newparent/testdir/testfile
single dot is the current directory and the double dot is the parent to move the testfile from its current location back inside the testdir
directory. Enter: mv testfile .. to move the testfile up into directory. Enter: Is newparent/testdir to view the file back in
the newparent directory. Enter: cd . . to move up to the parent its current directory.

pieraspberrypi "/newparent $ cd
pieraspberrypi $ cd newparent/testdir pieraspberrypi $ Is
pieraspberrypi "/newparent/testdir $ Is Desktop Documents Downloads indiecity newparent pythoi
testf ile pieraspberrypi " $ mu newparent/testfile newparent/testdir-
pieraspberrypi "/newparent/testdir $ mu testfile piOraspberrypi ~ $ Is newparent/testdir
piOraspberrypi "/newparent/testdir $ cd testfile
pieraspberrypi $ _

RENAMING FILESAND DIRECTORIES


The mv command isn't used just to move files; it also serves the purpose of renaming files (effectively it moves it from its old
name to a new name). Let's see how to use mv to rename items.

Let's start by making a new test file called "names". You can rename directories inside other directories
STEP1 STEP3
Enter: and then IS to make using paths. Let's rename the testdir directory,
sure the testfile is present. We're going to turn this into a file that which is now inside the people directory. Enter:
contains the names of some people. So let's call it something more [testdir names/friendsMflM names people/]
appropriate, like "names". to move the names file inside the friends directory.

pieraspberrypi $ Is
Desktop Documents Downloads indiecity newparent pythoi piOraspberrypi $ Is
piOraspberrypi $ mu testfile names
Desktop Documents Downloads indiecity names people pyth
pieraspberrypi " $ Is
piOraspberrypi $ mu people/testdir people/friends
Desktop Documents Downloads indiecity names newparent
piOraspberrypi " $

Enter: /1')Ж!ЕИ1ЛД1ЖВ1ЯЕЕ and EE- Now we can It is easy to overwrite files using the mv
STEP 2 STEP 4
see the new "names" file in our directory. The mv command, so if you have files with the same
command can also be used to rename directories. We should still name use the "-n" option, which stands for "no overwrite".
have our newparent directory in our home directory. Enter: ffiB Enter: ДВЯ5ПЖЯЯ!1ДДПНЗ to create a new file and ^3B3I
to rename the newparent directory. Enter: testfile people/friendsl There's no error report though,
into view it. enter: EE and you'll find testfile still there.

piOraspberrypi $ touch testfile


piOraspberrypi ~ $ touch testfile piOraspberrypi $ mu -n testfile people/friends
piOraspberrypi $ Is piOraspberrypi ~ $ Is
Desktop Documents Downloads indiecity newparent python Desktop Documents Downloads indiecity people python_gai
piOraspberrypi $ mu newparent people piOraspberrypi $ Is
piOraspberrypi $ Is Desktop Documents Downloads indiecity people python gai
Desktop Documents Downloads indiecity peoplepythongai piOraspberrypi " $ Is people/friends
pieraspberrypi " $ names testfile
piOraspberrypi " $

www.bdmpublications.com 149
Understanding Linux

Useful System and


Disk Commands
Understanding these core Linux commands will enable you to not only master the
inner workings of your Raspberry Pi but also to transfer those skills to other Linux
distros, such as Ubuntu or Linux Mint.

LOTS OF LINUX
Linux is a huge and versatile command line language and there are hundreds of commands you can learn and use. Here are a
few that can help you get more from your Raspberry Pi.

STEP 1 The Raspberry Pi is a great little computer, so STEP 3 Enter: uname to view the name of the operating
A let's start by getting some information. Enter: л system’s kernel, this is the element that sits
cat /proc/cpuinf о to view some details on your Raspberry Pi between the interface and hardware. Just as you would suspect, the
processors. If you have a Raspberry Pi 3 you will see four processors, response from the command is Linux, as Raspbian is a Linux distro,
along with the model name and other info. which in itself is based on another Linux distro called Debian. While
it may sound complicated, it actually demonstrates how versatile
piBraspberrypi 0 cat zproc/cpuinfo
processor 0 Linux is.
model name ARMu? Processor reu 5 Cu71)
BogoMIPS 38.40
Features half thumb fastmult ufp edsp IK ufpu3 tls ufpu4 idiua idiut ufpd32 Ipac cu
CPU implementer 0x41
CPU architecture ?
CPU uariant 0x0 piGraspberrypi ~ $ uname
CPU part OxcO?
CPU reuision 5 Linux
piGraspberrypi ~ $
processor
mode 1 name ARMu? Processor reu 5 (u71)
BogoMIPS 38.40
Features half thumb fastmult ufp edsp neon ufpu3 tls ufpu4 idiua idiut ufpd32 1pae eu
CPU implementer 0x41
CPU architecture
CPU uariant 0x0
CPU part OxcO?
CPU reuision 5

processor 2
model name ARMu? Processor reu 5 Cu71)
BogoMIPS 38.40
Features half thumb fastmult ufp edsp in ini ufpu3 tls ufpu4 idiua idiut ufpd32 Ipae eu
CPU implementer 0x41
CPU architecture 7
CPU uariant 0x0
CPU part OxcO?

STEP 4 Enter: uname -a to view some more detailed


STEP 2 piOraspberrypi
MemTota1:
S cat zproczmeminfo
884304 кВ
MemFree: 784576 кВ information. Here you'll see the kernel name,
McmAua i table: 834088 кВ
Remember that cat is Buffers:
Cached:
11660 кВ
56340 кВ
hostname and kernel version (3.18.7-v7 on ours). If you have
SuapCached: 0 кВ
used to list the contents Actiue: 49148 кВ a Raspberry Pi 2 you'll see SMP (symmetric multiprocessing),
Inactiue: 30072 кВ
of a text file, which is ActiueCanon): 11256 кВ followed by the system date, CPU architecture and operating
Inactiue(anon): 228 кВ
what cpuinfo is. There ActiueCfIle): 37892 кВ system (GNU/Linux).
InactiueCfile): 29844 кВ
are other text files with Uneuictable:
M locked:
0 кВ
0 кВ
SuapTota1: 102396 кВ
system info available. SwapFree: 102396 кВ
Dirty: 36 кВ
Try "cat/proc/meminfo" Uriteback: 0 кВ
piGraspberrypi ~ $ uname
AnonPages : 11132 кВ
to get information Mapped: 7464 кВ Linux
Shmem: 260 кВ
piGraspberrypi ~ $ uname -a
about your memory, Slab:
SReclaimable:
10384 кВ
4512 кВ Linux raspbcrrypi 3.10.7-и?» Й755 SMP PREEMPT Thu Feb 1Z 17
SUnrecla im: 5872 кВ
"cat /ргос/partitions" for KernelStack: 672 кВ piGraspberrypi ~ _
PageTables: 564 кВ
information aboutyour NFSJJnstable: 0 кВ
Bounce: 0 кВ
SD card, and "cat/proc/ UritebackTmp:
CommitLimit:
0 кВ
544548 кВ
version" shows which Committed_AS:
UmallocTotal:
43712 кВ
1171456 кВ
UmallocUsed: 3880 кВ
version of Raspberry Pi Uma1locChunk: 922360 кВ
piGraspberrypi S cat zproczpartitions
you are using. major minor lib locks name

173 0 7761920 mmcblkO


179 1 835890 mmcblkOpl
179 2 1 mmcblk0p2

www.bdmpublications.com
Useful System and Disk Commands

Enter: vcgencmd measure_temp to view the One command you might be wondering about is
current operating system temperature of your how to switch off or restart your Raspberry Pi from
Raspberry Pi. Enter: vcgencmd get_mem arm to view the RAM the command line. Don't just hit the power switch. Enter: sudo
available, and vcgencmd get_mem gpu to view the memory showdown -h now to shut down the Raspberry Pi (the "-h” option
available to the graphics chip. Finally try Is usb to view a list of stands for "halt"), or enter: sudo shutdown -r now to restart
attached USB devices. your Raspberry Pi.

piBraspberrypi ” $ ucgencmd measure_temp


temp=36.9’C piBraspberrypi ” $ sudo shutdown -r now
piBraspberrypi " $ ucgencmd get_mem arm
arm=880M Broadcast message from rootBraspberrypi (ttyl) (Thu May 14 12:20:29 2015):
piBraspberrypi " $ ucgencmd get_mem gpu The system is going down for reboot MOW?
gpu=128M
piBraspberrypi ' $ Isusb
Bus 001 Deuice 002: ID 0424:9514 Standard Microsystems Corp.
Bus 001 Deuice 001: ID ldbb:0002 Linux Foundation 2.0 root hub
Bus 001 Deuice 003: ID 0424:ec00 Standard Microsystems Corp.
Bus 001 Deuice 004: ID 04d9:1503 Holtek Semiconductor, Inc. Shortboard Lefty
Bus 001 Deuice 005: ID la40:0101 Terminus Technology Inc. 4-Port HUB
Bus 001 Deuice 00f>: ID 276d:1105
piBraspberrypi ' $

DISK COMMANDS
Learn the two commands that enable you to view your disk space and the files on it: df (disk free space) and du (disk usage).
With these two commands you can view the file usage on your SD card.

Start by entering: in the command line. It Now enter: ss- You should see lots of text fly
STEP1 STEP3
returns a list of the volumes contained on your up the screen. This is the disk usage for the files
SD card. You might be wondering what a volume is. It's best to contained in your home directory and their sub-directories. As
think of your SD card as the drive. This contains partitions, which is with df, it is better to use du with the "-h" option to humanise the
where you split one drive to act like two or more drives. And each output. If you want to slow down the output, you'll also need to
partition can contain volumes, which are storage spaces. pipe it through less. Enter: to view the files and
their respective usage one page ata time.

piBraspberrypi “ $ df
Filesystem IK-blocks Used Auailable Usez Mounted on
rootfs 6581636 3484164 Z740096 56z
p iBraspberryp i ■ S df -h
/deu/root 6581636 3484164 2740096 56z /
Filesystem Size Used Auai 1 Usez Mounted on
deutmpfs 437856 0 437856 Oz /deu
tmpfs 88432 Z60 88172 1Z /run rootfs 6.3G 3.4G Z.7G 56z /
tmpfs 51Z0 0 51Z0 Oz /run/lock /deu/root 6.3G 3.4G Z.7G 56z /
tmpfs 176860 0 176860 OZ /run/shm deutmpfs 4Z8M 0 4Z8M Oz /deu
/deu/mmcblk0p5 60479 14536 45943 Z5z /boot tmpfs 87M Z60K 87M 1Z /run
piBraspberrypi s tmpfs 5.OM 0 5.0M Oz /run/lock
tmpfs 173M 0 173M OZ /run/shm
/deu/mmcblk0p5 60M 15M 45M 25Z /boot
piBraspberrypi

Enter: to get the list in human readable form. You don't typically enter: du on its own; most of
STEP 2 STEP 4
The first two lines should read "rootfs” and "/dev/ the time you want to view the disk usage of a
root” and have matching Size, Used, Avail and Use% listings. This specific directory. Enter: |du -h python game s| to view how
is the main drive, and is an indication of how much space you have much space the pythonjgames directory (installed alongside
used, and have free, on your Raspbian OS. The other volumes are for Raspbian) takes up. It should be 1.8M. If you want a more
booting and initialising devices (you can ignore these for now). comprehensive breakdown of the files contained, use the "-a”
option (all). Enter: |du -ha python_games| to view all the files
piBraspberrypi § du -h I less
contained and their disk usage.
ZZM ./.m inecraft/games/com.mojang/m inecraftWorIds/worId
ZZM ./.mi necra ft/games/com.mojang/mi necra ftUorIds
ZZM ./.minecraft/games/com.moJang piBraspberrypi $ Is
ZZM ./.minecraft/games Desktop Documents Dounloads indiecity people python_games Scratch testfile
4.OK ./.pu1se piBraspberrypi $ du -h python_games
16K ./.config/gedit 1.8M puthon games
8.OK ./.config/1ibfm piBraspberrypi § du -ha python_games
12k python_games/RedSe1ector.png
1.4M ./.config/epiphany/adblock 12K python_games/4row_board.png
1.5H ./.config/epiphany 12K python_games/Star.png
0.0K ./.config/lxsession/LXDE-pi 28K python_games/4rou_humanu inner.png
1ZK ./.config/1xsession 1ZK python_games/Ua11_B1ock_Ta11.png
8.OK puthon games/pr i ncess.png
8.OK ./.config/dconf 12K puthon games/Selector.png
8.OK ./.config/rncbc.org 8.OK python_games/4row_b1ack.png
8.OK ./.config/lxterminal 4.OK python_games/catanimation.py
8.OK ./.config/uk.ac.cam.cl 20K python_games/f1i ppy.py
8.OK ./.config/lndieCity 36K python_games/match3.uau
4 AJ4 _—_—. , ----- -- -------- ____ ---- --------- -- ----- „---------------------------- ----- Z4K^ _ i

www.bdmpublications.com
Understanding Linux

Using the Man Pages


Linux comes with man (manual) pages that explain each command and show you all the
options you can use. Once you get the hang of reading the man pages, you'll be able to
find and do just about anything in Linux.

HEY, MAN!
The man pages are one of the best features of Linux, and as a built-in tool it's invaluable for both beginner and senior level
Linux administrators. Let's see how it works.

Linux has a built-in manual, known as man for Most commands are pretty easy to figure out how
STEP1 STEP3
л
short. Using the man command you can obtain to use, so what you spend most of the time in the
A
information on all the Linux commands we've talked about. Simply man pages is looking under the Description. Here you will see all the
enter: man and the name of the command you want to learn more options and the letters used to activate them. Most man pages are
about. Start by entering: man Is in the command line. longer than a single page, so press any key, such as the space bar, to
move to the next page of content.

piPraspberrypi $ man Is

STEP 2 The man pages are a bit more detailed than you
might be used to. First you have a name, which tells
A
you what the command is called; in this case "list directory contents"
and then the synopsis shows you how it works. In this case: "Is
[OPTION].. [FILE..]". So you enter: Is followed by options (such as
- la) and the file or directory to list.

LS(1)

NAME

SYNOPSIS
Is [OPTION!... [FILE!...

DESCRIPTION
List information about the FILES (the current directory by default). Sort entries alphabetic
Press the H key while looking at a man page to view
Mandatory arguments to long options are mandatory for short options too. STEP 4
the commands you can use to control the view.
A
do not ignore entries starting with .
This is called the Summary of Less Commands (the less command
is something we'll come to when we look at editing text). For now
—author
with -1, print the author of each file realise that you can move back and forward with Z and W. Press Q to
print C-style escapes for nongraphic characters
quit this help screen and return to the man page.
—block-size-SIZE
scale sizes by SIZE before printing them. E.g., '—block-size=M’ prints sizes in uni'
SUMMARY OF LESS COMMANDS
-B, —ignore-backups
do not list implied entries ending with Commands marked with « may be preceded by a number,

sort by. and show.


h H Display this help.
list entries by columns q :q Q :Q ZZ Exit.

—color[=UHEN!
colorize the output. WHEN defaults to 'always' or can be 'neuer' or 'auto'. Ноге ini MOUING

—directory e "E J “N CR »
у ~Y к “К "P *
f "F 'XlSPACE »
b "B ESC-u »
generate output designed for Emacs' dired mode z «

do not sort, enable -all, disable ESC-SPACE


d “D
—classify u 'U *
append indicator (one of wz=>el) to entries ESC-) RightArrow * Left one half screen width (or N positions).
ESC-( LeftArrow » Right one half screen width (or N positions).
-file-type Forward foreuer; like "tail -f".
likewise, except do not append г "R "I. Repaint
R Repaint discarding buffered
—format-WORD
Default "window" is the screen height.
Default "half-window" is half of the screen height.
—full-time
like -1 —tlme-style-fnI 1-iso
SEARCHING

« Search forward for (N-th) matching line.

www.bdmpublications.com
Using the Man Pages

Scroll to the bottom of the man page to discover The man command can be used forjust about every
STEP 5 STEP 6
more information. Typically you will find the command you use in Linux. You can even enter:
author's name and information on reporting bugs, including web man man to get information on using the man tool. From now on,
links that can be useful for more information. Press Q to exit the whenever you come across a new command in this book, such as
man page and return to the command line. "nano" or "chmod", take time to enter: man nano or man chmod

USING MAN OPTIONS


Because man doesn't change anything, like mv or mkdir, it is tempting not to see it as a command. But it is, and like all other
commands it has options. These can be very handy to learn.

Entering: Я1Д enables you to view some of One of the most powerful man options is the -k
STEP1 STEP3
the options, but sometimes you'll just want a quick option, which is for "apropos”. This enables you
overview. Fortunately man has a built-in help option that quickly to search a wider range of man pages than the exact command.
lists the options. Press Q if you're in a man page and enter: щЯДЕ Enter: to view all of the man pages relating
at the command line. to directories "(man -k directory | less” to view one page at a time).
Here you'll find commands like "Is", "mkdir” and "cd” along with
their description.

If you’re fast you may have noticed the start of the STEP 4 Entering the man page for all the commands
STEP 2
text flew up off the page. This is because the "man you come across can be a little long-winded,
-h" option doesn't use the less command by default (less is what although ultimately productive. If you simply want to know what a
enables you to move down text one screen ata time). We’ll look command does you can read just the description using the "whatis”
into pipes ("|”) later on, but for nowjust use "man -h | less” to read command. Enter: to read the description of the
long text one page at a time. "pwd" command ("print name of current/working directory").

piGraspberrypi " $ whatis pwd


piGraspberrypi ~ $ man -h I less pwd (1) - print name of current/working directory
piGraspberrypi " S

www.bdmpublications.com
Understanding Linux

Editing Text Files


A text Hie in Linux can be anything from a simple set of instructions on how to use an
app, to some complex Python, C++ or other programming language code. Text files can
be used for scripting, automated executable files, as well as configuration files too.

THE JOY OF TEXT


To be able to edit or create a text file, you need a good text editor. Linux has many but here are some in action on the
Raspberry Pi.

STEP1 The first text editor for the Raspberry Pi is the Vi is the original Unix command but in this case it
STEP3
л default desktop environment app: Leafpad. To A launches VIM, the new Linux version of Vi. Although
use, you can either double-click an existing text file or click the simple looking, Vi is considered, even by today's standards, to be
Raspberry Pi menu icon (in the top left of the desktop) and from the one of the most widely used text editors, There's a lot you can do
Accessories menu, choose Text Editor. with it, so check out the man pages for more Vi information.

vim - Vi iMproved

version 7.4.576
by 8ram Moolenaar et al.
Modified by pkg-vim-maintainers@lists.alioth.debian.org
Vim is open source and freely distributable

Become a registered Vim user!


type :help registered ter > for information

type :q-Entei to exit


type :help<Ente or for on-line help
type :help version7 _ i-r • for version info

Running in Vicompatible mode


type :set nocp Ente for Vim defaults
type :help cp-default^Entei for info on this

STEP 2 From the Terminal there are even more options, Nano is another favourite, and simple, text editor
STEP 4
л although using the correct command, you can л available for Linux. Enter: nano into the Terminal
launch any of the desktop apps via the Terminal. One of the to launch it. You can use Nano for editing code, creating scripts or
simplest, and a classic text editor that's carried over from the Unix writing your own help files. To exit Nano, press Ctrl + X, followed by
days, is vi. In the Terminal, enter: vi. Y to save the file or N to exit without saving.

File Edit Tabs Help


oi^raspberrypi:- $ vij

154 www.bdmpublications.com
Editing Text Files

Emacs, or GNU Emacs, is an extensible and Emacs can offer an uncomplicated view of your text
STEPS STEP 8
customisable, self-documenting, real-time display
A file or one with a plethora of information regarding
A
editor. It's a fantastic text editor and one that's worth getting used the structure of the file in question; it's up to you to work out your
to as soon as you can. Sadly, it's not installed on the Pi by default, own preference. There’s also a hidden text adventure in Emacs,
so you'll need to install it. In the Terminal, enter: sudo apt-get which we cover later in this book, why not see if you can find it
install emacs without our help.

pi@raspberrypi: ~ pi@raspberrypr -
File Edit Tabs Help
File Edit Tabs Help
Preparing to unpack .../ghostscript_9.06~dfsg-2
deb8u6_armhf.deb
* ...
piBraspberrypi:- $ sudo apt-get install emacs Unpacking ghostscript (9.06'dfsg-2+deb8u6) ...
Reading package lists... Done Selecting previously unselected package libpaper-utils.
Building dependency tree Preparing to unpack .../libpaper-utils_1.1.24+nmu4_armhf.deb ...
Reading state information... Done *nmu4)
Unpacking libpaper-utils (1.1.24 ...
The following extra packages will be installed: Processing triggers for man-db (2.7.5-i~bpo8+1) ...
emacs24 emacs24-bin-common emacs24-common ghostscript imagemagick-common libgs9 Processing triggers for hicolor-icon-theme (0.13-1) ...
libm17n-0 libmagickcore-6.q16-2 libmagickwand-6.q16-2 libotfO libpaper-utils lit Processing triggers for gnome-menus (3.13.3-6) ...
Processing triggers for desktop-file-utils (0.22-1) ...
Suggested packages: Processing triggers for mime-support (3.58) ...
emacs24-common-non-dfsg emacs24-el ghostscript-x m17n-docs litxnagickcore-6. q16-) Processing triggers for install-info (5.2.0.dfsg.1-6) ...
The following NEW packages will be installed: Settingup imagemagick-common (8:6.8.9.9-5»deb8ul2) ...
emacs emacs24 emacs24-bin-common emacs24-common ghostscript imagemagick-common I Settingup libijs-0.35:armhf (0.35-10) ...
libm17n-0 libmagickcore-6.q16-2 libmagickwand-6.q16-2 libotfO libpaper-utils lit Settingup liblqr-l-O:armhf (0.4.2-2) ...
0 upgraded. 18 newly installed. 0 to remove and 0 not upgraded. Settingup libmagickcore-6.q16-2:armhf (8:6.8.9.9-5
deb8u12)
* ...
Need to get 23.6 MB of archives. Settingup libmagickwand-6.q16-2:armhf (8:6.8.9.9-5
deb8u12)
* ...
After this operation. 105 MB of additional disk space will be used. Setting up libpaperlzarmhf (1.1.24+nmu4) ...
Do you want to continue? [Y/n] |
Creating config file /etc/papersize with new version
Setting up emacs24-common (24.4
*
1 -5+deb8u1) ...
Setting up emacs24-bin-common (24.4+1-5+deb8u1) ...
update-alternatives: using Zusr/bin/ctags.emacs24 to provide Zusr/bin/ctags (ctags) in auto

The previous command contacts the Debian Gedit is another excellent text editor for Linux.
STEP 6 STEP 9
(Raspbian is based on a Debian Linux distribution)
A AAgain, it's not installed by default on the Raspberry
repositories and pulls down the information needed to install Pi; however, by entering: sudo apt-get install gedit and
Emacs. When the Pi asks to continue with the installation, press Y. accepting the installation, the program can be on the Pi in a matter
This installs the latest version and when it's done, you'll be back to of seconds. Once it's installed, use gedit in the Terminal to launch
the command prompt. it. Gedit is a great text editor for coding.

Circle.py
Open - Pl
—/Documents
Import turtle

for t in range(4):

printf Making a square...')

turtle.forwardfl 00)

turtle. left(90)

turtle.getscreenO-root.mainloopO

STEP 7 Once the installation is complete, enter: emacs Finally, Jed is an Emacs-like, cross-platform text
STEP 10
A
into the Terminal. The Emacs splash screen opens editor that's lightweight and comes with a wealth
A
in a new window, offering a tutorial (which we recommend you run of features. To install it, enter: sudo apt-get install jed.
through) and a guided tour amongst other information. Accept the installation and when it’s complete, use: jed to launch.

emacs@raspberrypi _ □ x
| File Edit Options Buffers Tools Text Help pi@raspbern
I В В Q X llsave undo „ l £> File Edit Tabs Help
I remember F10 key — > File Edit Search Buffers Windows System Help
The dark woods, masking slopes of sombre hills; I
The grey clouds' leaden everlasting arch;
The dusky streams that flowed without a sound, This is a scratch buffer. It is NOT saved when you exit.
And the lone winds that whispered down the passes.
To access the menus, press F10 or ESC-m and the use the arrow
Vista on vista marching, hills on hills, keys to navigate.
Slope beyond slope, each dark with sullen trees.
Our gaunt land lay. So when a man climbed up Latest version information is available on the web from
A rugged peak and gazed, his shaded eye <http://www.jedsoft.org/jed/>. Other sources of JED
Saw but the endless vista - hill on hill, information include the Usenet newsgroups comp.editors and
Slope beyond slope, each hooded like its brothers. alt.lang.s-lang. To subscribe to the jed-users mailing list, see
<http://www. jedsoft.org/jed/mailinglists.htnl>.
It was a gloomy land that seemed to hold
All winds and clouds and dreams that shun the sun. Copyright (C) 1994. 2000-2009 John E. Davis
With bare boughs rattling in the lonesome winds, Email comments or suggestions to <jedejedsoft.org>.
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.

www.bdmpublications.com
Understanding Linux

Linux Tips and Tricks


The Linux Terminal, you'll no doubt agree, is an exceptional environment and with a
few extra apps installed along with a smidgen of command knowledge, incredible and
often quite strange things can be accomplished.

TAKING COMMAND
There are countless Linux tips, secrets, hacks and tricks out there. Some are very old, originating from Linux's Unix heritage,
while others are recent additions to Linux lore. Here are our ten favourite tips and tricks.

EASTER EGGS Emacs text editor, is a great piece of Ever fancied being able to
TERMINAL BROWSING
л software but did you know it also contains A browse the Internet from
a hidden Easter Egg? With Emacs installed (sudo apt-get install the Terminal? While not particularly useful, it is a fascinating thing to
emacs24), drop to a Terminal session and enter: behold. To do so, enter:

emacs -batch -1 dunnet sudo apt-get install elinks

Dunnet is a text adventure written by Ron Schnell in 1982, and Then:


hidden in Emacs since 1994.
elinks

Enter the website you want to visit.

pi@raspberrypi ~

web Hisi
Google

_________________________________________________________________ Advanced ’
[ Google Search ] [ I’m Feeling Lucky ]

Celebrate Pride Month. ffThisIsFamily


Advertising ProgramnesBusiness Solutions+GoogleAbout GoogleGoogle.com

© 2018 - Privacy Terns

Based on the classic 1982 arcade game, Snowing in the Terminal console isn't
MOON BUGGY LET IT SNOW
J Moon Patrol, Moon Buggy appeared something you come across every day. IF
on home computers in 1985 amid much praise. It’s a cracking Atari you’re interested, however, enter:
game available in the Linux Terminal by entering:
wget
sudo apt-get install moon-buggy
https://gist.githubusercontent.com/sontek/1505483/
Then: raw/7d024716ea57e69fb52632fee09f42753361c4a2/
snowj ob.sh
moon-buggy
chmod +x snowj ob.sh
Enjoy.
./snowjob.sh

156 www.bdmpublications.com
( Linux Tips and Tricks

Memory Hogs - If you need to see Back in the days of dial-up connections, the online world
MEMORY HOGS
which apps are consuming the most
A was made up of Bulletin Board Systems. These remote
memory on your Raspberry Pi, simple enter: servers provided hangouts for users to chat, swap code, play games
and more. Using Telnet in Linux, you can still connect to some active
ps aux | sort -rnk 4
BBSes:
This sorts the output by system memory use.
telnet battlestarbbs.dyndns.org

There are countless operational BBSes available; check out


www.telnetbbsguide.com/bbs/list/detail/ for more.

SHREDDER When you delete a File, there's still a chance of


A someone with the right software being able to
retrieve it. However, files can be securely and permanently deleted
using Shred:
Ifyou want to create an entire
DIRECTORY TREES
shred -zvu NAMEOFFILE.txt л directory (or folder) tree with a
single command, you can use:
Replace NAMEOFFILE with the name of the file to delete.
mkdir -p New-Dir/
{subfolderl,subfolder2,subfolder3,subfolder4}

This creates a New-Dir with four sub folders within.

pi@raspbenypr ~/New-Dir
File Edit Tabs Help
lieraspberrypi:- $ mkdir -p New-Dir/{subfolderl,subfolder2,subfolder3.subfolder4}
>it»raspberrypi: - S cd llew-Dir/
ligraspberrypi: -/iiew-Oir $ Is
.ubfolderl subfolder? subfоIder3 subfоIder4
lieraspberrypi: -/Hew-Dir $ |

ASCII ART ASCII art can be quite striking when applied to


A some images. However, it's often difficult to FORGOTTEN COMMANDS It's not easy trying
getjust right. You can create some great ASCII art from the images to remember all the
you already have on the Raspberry Pi by using img2txt: available Linux commands. Thankfully, you can use apropos to help.
Simply use it with a description of the command:
img2txt NAMEOFIMAGEFILE.png
apropos "copy files"
Replace NAMEOFIMAGEFILE with the actual name of the image file
apropos "rename files"
on your system.

www.bdmpublications.com
Understanding Linux

A-Z of Linux Commands


There are literally thousands of Linux commands, so while this is not a complete A-Z, it
does contain many of the commands you will most likely need. You will probably find
that you end up using a smaller set of commands over and over again but having an
overall knowledge is still very useful.

adduser Add a new user


dd Data Dump, convert and gawk Find and Replace text
arch Print machine architecture copy a file within file(s)

awk Find and replace text diff Display the differences grep Search file(s) for lines that
within File(s) between two files match a given pattern

dirname Convert a full path name groups Print group names a user

В
be An arbitrary precision
du
to just a path

Estimate file space usage gzip


is in

Compress or decompress
named file(s)
calculator language

c E
echo Display message on screen
H
head Output the first part
cat Concatenate filesand print
ed A line oriented text editor of file(s)
on the standard output
(edlin)
hostname Print or set system name
chdir Change working directory
egrep Search file(s) for lines
chgrp Change the group that match an

chroot
ownership of files

Change root directory env


extended expression

Display, set or remove


1 id Print user and group ids
environment variables
cksum Print CRC checksum and
info Help info
byte counts expand Convert tabs to spaces
install Copy filesand
emp Compare two files expr Evaluate expressions
set attributes
comm Compare two sorted files

cp
line by line

Copy one or more files to


F
factor Print prime factors
another location join Join lines on a
fdisk Partition table common field
crontab Schedule a command to
manipulator for Linux
run ata later time

csplit Split a file into context-


determined pieces
fgrep Search file(s) for lines that
match a fixed string К
kill Stop a process
find Search for files that meet
cut Divide a file into from running
a desired criteria
several parts
fmt Reformat paragraph text

D
date Display or change the
fold Wrap text to fit a
specified width less Display output one screen
ata time
format Format disks or tapes
date & time
In Make links between files
f sck Filesystem consistency
de Desk calculator
check and repair locate Find files

www.bdmpublications.com
A-Z of Linux Commands

logname

Ipc
Print current login name

Line printer
control program
rm
rmdir
rpm
Remove files
Remove folder(s)
Remote Package Manager
uumount Unmount a device

lpr Off line print unexpand Convert spaces to tabs


rsync Remote file copy
Iprm Remove jobs from the (synchronise file trees) uniq Uniquify Files
print queue units Convert units from one

M s
screen Terminal window manager
unshar
scale to another

Unpack shell archive scripts


useradd Create new user account
man See Help manual sdif f Merge two files interactively
usermod Modify user account
mkdir Create new folder(s) select Accept keyboard input
users List users currently
mkfifo Make FIFOs (named pipes) seq Print numeric sequences logged in
mknod Make block or character shutdown Shutdown or restart Linux
special files

more Display output one screen


ata time
sleep

sort
Delay for a specified time

Sort text files


Vvdir Verbosely list directory
mount Mount a file system split Split a file into contents ('Is -l-b')
fixed-size pieces

N
nice Set the priority of a
SSH Connects to a remote host
computer as a specified
user, using secure
wwatch Execute or display a
encrypted protocols. program periodically
command orjob
su Substitute user identity wc Print byte, word, and
nl Number lines and
write files sudo Execute a command as line counts
another user, primarily as whereis Report all known
nohup Run a command immune
the Root level, instances of a command
to hangups administrator user.
which Locate a program file in
sum Print a checksum for a file the user's path

p
passwd Modify a user password
symlink Make a new name for
a file
who Print all usernames
currently logged in
sync Synchronise data on disk Print the current user id
paste Merge lines of files whoami
with memory
and name
pathchk Check file name portability

pr Convert text files

printcap
for printing

Printer capability database tac Concatenate and write


Xxargs Execute utility, passing
files in reverse
printenv Print environment variables constructed argument list(s)
tail Output the last part
printf Format and print data of files
tar Tape Archiver
tee Redirect output to yes Print a string
multiple files until interrupted

quota Display disk usage test Evaluate a


and limits conditional expression

quotacheck Scan a file system for time Measure Program


disk usage Resource Use
touch Change file timestamps
quotactl Set disk quotas
top List processes running on
the system

Rram Ram disk device


traceroute
tr
Trace Route to Host
Translate, squeeze and or
rep Copy files between delete characters
two machines tsort Topological sort

www.bdmpublications.com 19
Glossary of Python Terms

Glossary of Python Terms


Just like most technology, Python contains many confusing words and acronyms. Here
then, for your 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 detailed 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 interact with the
interact 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
Used to define a function or method in Python.
High-Level Language
A programming language that's designed to be easy for people to read
Dictionaries
A dictionary in Python is a data structure that consists of key and
IDLE
value pairs. Stands for Integrated Development Environment or Integrated
Development and Learning Environment.
Distro
Also Distribution, an operating system that uses the Linux Kernel as its Immutable
core but offers something different in its presentation to the end user. Something that cannot be changed after it is created.

Editor Import
An individual program, or a part of the graphical version of Python, Used in Python to include modules together with all the
that enables the user to enter code ready for execution. accompanying code, functions and variables they contain.

Exceptions Indentation
Used as a means of breaking from the normal flow of a code block in Python uses indentation to delimit blocks of code. The indents are
order to handle any potential errors or exceptional conditions within four spaces apart, and are often created automatically after a colon
the program. is used in the code.

160 www.bdmpublications.com
Glossary of Python 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 still being powerful enough to enjoy.

Interactive Shell Random


The Python Shell, which is displayed whenever you launch the A Python module that implements a pseudo-random character
graphical version of Python. generator using the Mersenne Twister PRNG.

Kernel Range
The core of an operating system, which handles data processing, A function that used to return a list of integers, defined by the
memory allocation, input and output, and processes information arguments passed through it.
between the hardware and programs.
Root
Linux The bottom level user account used by the system itself. 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 of values, which can be Sets are a collection of unordered but unique data types.
of any type and can readily be modified.
Strings
Local Variable Strings can store characters that can be modified. The contents of
A variable that's defined inside a function and is only useable inside a string are alphanumerical and can be enclosed by either single or
that function. double quote marks.

Loop Terminal
A piece of code that repeats itself until a certain condition is met. Also Console or Shell. The command line interface to the operating
Loops can encase the entire code or just sections of it. system, namely Linux, but also available in macOS. From there you
can execute code and navigate the filesystem.
Module
A Python file that contains various functions that can be used within Tkinter
another program to further extend the effectiveness of the code. A Python module designed to interact with the graphical
environment, specifically the tk-GUI (Tool Kit Graphical User
Operating System Interface).
Also OS. The program that's loaded into the computer after the
initial boot sequence has completed. The OS manages all the other Try
programs, graphical user interface (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 from the program to a screen, printer or other An immutable Python data type that contains an ordered set of
external peripheral. either letters or numbers.

PIP UNIX
Pip Installs Packages. A package management system used to install A multitasking, multiuser operating system designed in the 70s at
and manage modules and other software written in Python. the Bell Labs Research Centre. Written in C and assembly language

Print Variables
A function used to display the output of something to the screen. A data item that has been assigned a storage location in the
computer's memory.
Prompt
The element of Python, or the Command Line, where the user X
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 for 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 of Python
October 2000. is displayed.

www.bdmpublications.com
Are you interested in Coding?
Then don't miss our latest essential
Coding user guide on Readly now!

December 2021 Update

Coding
C,oA'*9.

Advanced
ъ. Black Dog Media

FROM BEGINNER
Master Your Tech TO EXPERT
To continue learning more about Your Tech visit us at:
www.bdmpublications.com

FREE Tech Guides

Samsung & Android

Apple iPhone, iPad, Coding Python,


Mac, MacBook & Watch Raspberry Pi & Linux
The Complete
Raspberry P
GuideBook
EXCLUSIVE OFFERS
on Tech Guidebooks
Windows!!
Print & Digital Editions The Essentials
ultimate rnoLOsnop
Featuring the Latest Updates bdmpublications.com/ultimate-photoshop
Step-by-step Tutorials & Guides Buy our Photoshop guides and download tutorial
images for free! Simply sign up and get creative.
Created by BDM Experts

PLUS SPECIAL DEALS and Bonus Content monthly newsletter!

Black Dog i-Tech Series required hardware. It remains the purchaser's sole responsibility to determine
the suitability of this book and its content for whatever purpose. Any images
endorsed or associated in any way with The Linux Foundation, The Raspberry
Pi Foundation, ARM Holding, Canonical Ltd, Python, Debian Project, Linux
12th Edition | ISSN: 2044-4060
reproduced on the front and back cover are solely for design purposes and are Mint, Microsoft, Lenovo, Dell, Hewlett-Packard, Apple and Samsung or any
Published by: Black Dog Media Limited not representative of content. We advise all potential buyers to check listing associate or affiliate company. All copyrights, trademarks and registered
Visit us at: www.bdmpublications.com prior to purchase for confirmation of actual content. All editorial opinion herein trademarks for the respective companies are acknowledged. Relevant graphic
Managing Editor: James Gale is that of the writer as an individual and is not representative of the publisher imagery reproduced with courtesy of Lenovo, Hewlett- Packard, Dell,
Production Director: Mark Ayshford or any of its affiliates. Therefore the publisher holds no responsibility in regard Microsoft, Samsung, Linux Mint, NASA, and Apple.
Editor: David Hayward to editorial opinion and content. Black Dog Media Limited reserves the right not All copyrights, trademarks and registered trademarks for the respective
Production Manager: Karl Linstead to be held responsible for any mistakes or inaccuracies found within the text manufacturers, software and hardware companies are acknowledged.
Design: Robin Drew, Lena Whitaker of this publication. The publisher, editor and their respective employees or All editorial content and design are copyright © Papercut Limited and
Editorial: David Hayward affiliates will not accept responsibility for loss, damage, injury occasioned to reproduced under license to Black Dog Media Limited.
Digital distribution by: Readly, Pocketmags & Zinio any persons acting or refraining from action as a result of the content with Additional images contained within this publication are reproduced under
this publication whether or not any such action is due to any error, negligent license from shutterstock.com.
2022 © Copyright Black Dog Media Limited. All rights reserved. Notice: Before omission or act on the part of the publisher, editor and their respective All information was correct at time of print. Some content may have been
purchasing this publication please read and ensure that you fully understand employees or affiliates. Our articles are intended as a guide only. We are not previously published in other volumes or titles. We advise potential buyers to
the following guidelines, if you are in any doubt please don't buy. No part of advising you to change your device, and would actually advise against it if you check the suitability of contents prior to purchase.
this publication may be reproduced in any form, stored in a retrieval system or have even the slightest doubts. There are potential risks to the hardware/
integrated into any other publication, database or commercial programs software involved, and you must be aware of these before you decide to alter
л Black Dog Media Limited
without the express written permission of the publisher. Under no
circumstances should this publication and its contents be resold, lent, loaned
anything on your device. Read all of the information here carefully and then
make up your own mind whether you want to follow our guides. We take no
чИ Registered in England & Wales No: 05311511
out or used in any form by way of trade without the publisher's written responsibility for damage to your camera or any other device used in the
permission. While we pride ourselves on the quality of the information we process. If you are unsure, please do not buy this publication. ADVERTISING: Please contact: james@bdmpublications.com
provide, Black Dog Media Limited reserves the right not to be held responsible INTERNATIONAL LICENSING: Black Dog Media Limited has many great
for any mistakes or inaccuracies found within the text of this publication. Due This Black Dog Media Limited publication is fully independent and as such does publications and all are available for licensing worldwide.
to the nature of the software industry, the publisher cannot guarantee that all not necessarily reflect the views or opinions of the manufacturers or hardware For more information go to: www.bdmpublications.com
software and/or tutorials, tips, guides will work on every version of the and software, applications or products contained within. This publication is not or email James Gale: james@bdmpublications.com

You might also like