329 107 120MB
English Pages [195]
.
\
|
: \
Expert Tutorials to Improve Your Skills
Ta
The Complete
The Complete
Black & White
Android Manual
Photography
Manual
The Complete
The Complete
Build Your Own PC
Canon Manual
, Manual
&
Expert Tutorials to Improve You
feb
100% INDEPENDENT
The Complete
The Complete
Cloud Computing
The Complete
The Complete
FRITZ'Box
Google Manual
Manual
i
'
a we Expert Tutorials to Improve Yaur Skills
pS
Expert Tutorials to Improve Your Skills
Expert Tutorials to Improve Your Skills
The Complete
The Complete
The Complete
GoPro
Instagram
WhatsApp
Improve Your Skills.
.
Manual
\
a
Manual
The Complete
|
Internet
Manual
—
Security @
Manual
" i
x
Expert Tutorials to Improve Your Skills
The Complete
The Complete
The Complete
iPhone
Landscape
Linux
Expert Tutorials to Improve Your Skills
The Complete
iPad OS ;
iE
Expert Tutorials to Improve Your Skills
Expert Tutorials to Improve Your Skills
pu
Manual Oeg Es
|
Photography
Manual
|
a
100% INDEPENDENT
The Complete
Coding Manual eee yer
SE)
FLAY
na eae
5
a eee or obje
Ti Talesc anueace if Rg
Les
eT
LeRoy Peele ai
ere
y
a
ersive game, cr, aa
ts pars Tai it all
parla
how learn works. imagination and g juires you understand what to enter,.
you can’
ee
=e
ree
v7] @bdmpubs
-
BDM Publications
os www.bdmpublications.com
A Brief History of Coding Being
a
Programmer
Choosing
Creating
a a
Programming Language Coding Platform
Starting Python For the First Time Your First Code Saving and Executing Your Code
Executing Code From the Command Line Numbers and Expressions Using Comments
Working with Variables User Input
Creating Functions
Conditions and Loops Python Modules Python Errors
Combining What You Know So Far
Python
in
Numbers
Why Python? Equipment You Will Need Dictionaries
How to Set Up Python in Windows
Splitting and Joining Strings Poa
Formatting Strings a
How to Set Up Python in Linux
Date and Time
Opening Files
Writing to Files Exceptions Python Graphics
Combining What You Know So Far
Ls
Getting to Know Python
o=
Using Modules
a
Calendar Module
86
OSModule
88
Random Module
144
While Loop
Tkinter Module
146
ForLoop
Pygame Module
148
Do... While Loop
90
_—_
92
if
Create Your Own Modules
IF
Statement
IF... Else
Statement
C++ Facts & Figures
104
Equipment You Will Need
106
Howto Set Up C++ in Windows
108
Howto
110
SetUp C++ ona Mac Howto Set in Linux Up C++
112
Other C++ IDEs to Install
156
Whatis a Batch File?
158
Getting Started with Batch Files Getting an Output
162
Playing with Variables
164
Batch File Programming
166
Loops and Repetition
168
Creating a Batch File Game
Your First C++ Program 118
Structure of
120
Compile and Execute
122
Using Comments
a
C++ Program
Variables 126 128
Types Data Strings C++ Maths
User Interaction
Character Literals 138
Defining Constants File Input/Output
Passing Variables to Python
174
Retro Coding
176
Text Animations
178
Creating
180
Tracking the ISS with Python
a
i
Loading Screen I |
184
Using Text Files for Animation
186
Common Coding Mistakes
188
Python Beginner's Mistakes
190
C++ Beginner's Mistakes
192
Where Next?
-Oundation® www.bdmpublications.com
Coding Foundations
Where to start learning how to code? Remarkably, this is the most difficult Ae) 1m) MTeoR) ee Tin aye)
eee
m
languages out there, and a seemingly unlimited number of tools to help ‘ you achieve what you want; but
where do you begin? In
this section, we look at what you'will
need to take those first tentative steps
into the world of coding. You won't become a programmer in twenty-four hours, learning how to code correctly
takes time and patience, but witha
little help, you can master the basics and start your'coding journey. eee
www.bdmpublications.com
....--- EEE ESL MMe oem
OM
..--
EE...
Leeseety ORR
sees
em
Biel) RPMI eRe
CETMC
IT
fe eee
(Rae
.....Helos
DSM
bA z
H
ir i eee) eee Ree
RSNA
rel
E-wLey|
ES
SBCA
|
LOLOOLLO OOLOOLLO LLLLOLLO LLOOOOLO |-MUl-c-Le Wi]
|-10s]-B-)-10 poe]| poem aU (en/
Won]em
MUlo]mcalUe]ns-1-ma[-16p)
p1
peo
START
ORG
—-ROMYS§0000
Los
PAG
‘FUNCTION
en
FRO
BEGIN MONITOR
IMITA - Initialize
ACIA
yoooi0012 yoooso002 PRREETA.
RRSET ACIA.
ACTUREG
«SET 6
BITS
GO TO
START OF HONTTER
ACA
AND 2 sTOr
ACTA SIGHON
‘
FUNCTION
INCE - Input character
Gets
1
character from terminal
MIR mca AGING.
Ger _starus SHINY RORY FLAG TWTO -AnT* RECIEVE WOT READY GET CHAR MASK PARITY ECHO & RTS
cure
0
‘*
FUNCTION
INBEX - INFOT EEX DIGIT
none
OUTPUT: *
CALLS
5
aca A
INCH
DESTROTS +
Digit in
INPUT = BE
acc A
Returns to monitor if not
MEX
anpot
FOR
40
5
3
BSRSESESES
0
4
MEXRTS
BTR
INPUT "What 13 your name: “"; Us PRINT "Hello “; Ug PEN
AF
ro
RETURN TO CONTROL
” "How T=
many
stars
do you
want:
":s
N
1 TOWN
INPUT “Do you want more stars? "; Ag IF LEN(A) = 0 THEN GOTO 70 LEFTS(a$, 1) IF (Ag = "¥") OR (A$ = "y") THEN GOTO 30 PRINT "Goodbye "; FOF I = 1 TO 200
Ag =
cna
BD
Programmer wowapemieeialledeat
PREM
ic
eae
Being a Programmer
MORE THAN CODE
wW
—
aie
hs
;
Times have changed since programming in the ‘80s, but the core values still remain.
“It's up to you how far to take your coding
adventure!” #include #include
#include #include void getup()
t
textcolor (BLACK);
textbackground(15);
cirscr();
window(10,2,70,3)3
eprintf(“Press X to Exit, Press Space to Jump");
window(62,2,80,3)5 cprintf("SCORE : “); window(1,25,80,25); for(int x=0;x
= 2
D &
a E
So
oO
www.bdmpublications.com
Introducing Python
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 new frontier, Forging small routines that enabled the letter ‘A’ to scroll across the screen. It may not sound terribly exciting to a generation
Regardless of whether you use an Android device, iOS device, PC, Mac, Linux, Smart TV, games console, MP3 player, GPS device built-in to a car, set-top box or a thousand other connected and ‘smart’
that’s used to ultra high-definition graphics and open world, multiplayer online gaming. However, Forty-something years ago it was blindingly brilliant.
appliances, behind them all is programming.
a
All those aforementioned digital devices need instructions to tell them what to do, and allow them to be interacted with. These instructions Form the programming core of the device and that core can be built using a variety of programming languages.
Naturally these bedroom coders helped form the foundations for every piece of digital technology we use today. Some went on to become chief developers For top software companies, whereas others pushed the available hardware to its limits and founded the billion pound gaming empire that continually amazes us.
The languages in use today differ depending on the situation, the platform, the device’s use and how the device will interact with its
Bombs - GUI - ThelDE - [d:\uppsrc\CtriLib\rrayCtrl.cpp windows-1 252] { examples }
File
Edit
Macro
Project
&
&B ctricore @WrichtText
®patoraw
en #
}
#
Editctrl.h
Headerctrl.h
S ScroliBar.cpp HeaderCtrl.cpp
Arrayctrl.h
GS ArrayCtrt.cpp
#
€ Droptist.cpp
& DropPusher.cpp Dropchoice. cpp
#
#
S Akeys.cpp
Splitter.h
@
#
€ FrameSplitter.cpp
}
Sliderctrl.h Sliderctrl.cpp
#
Columnist.
}
Columntist.cpp
#
Progress.h
HE
Help.cpp DateTimectrl.h
€ DateTimectrl.cpp
> Bar
# Bah Bar.cpp
€ MenuBar.cpp
S ToolBar.cep 4
ToolTip.cpp StatusBar.h
€ StatusBar.cpp & Tabctrl #
TabCtrl.h
Tabctrl.cpp
& Treectrt #
Treectri.h Treectrl.cpp
Splitter.cpp
#
RichText.h
& Prompt.cpp
Staticctrl.h Static.cpp
.
yoid
&
Dropchoice.h
DropBox.crp
Ce >|/0@
Ctrl: :ChildGotFocus();
@ @
@ RichTextview.cpp
#
S BBS
SetCursor (p.y);
plusiniz
4
#
obey @
§Bopluginipng
Textécit.h
Docédit.cop ScroliBar.b
#
BE
|
Ln 639, Col 45
Setup
&B pluginfomp
EditField.cpp
€ Text.cpp } Lineedt.cpp
Assist
vi mci
§B Bombs
Beek
Debug
Build
lau
§& DigColor $# DigColor.h
€ Digcolor.cpp € ColorPopup.cpp ColorPusher.cpp
& Filesel
Progress.cpp
4
Akeys.h
€} Filetist.cpp
FileSel.h
www.bdmpublications.com
.
ArrayCtrl::ChildLostFocus()
if(cursor
>= 0) Ref reshRow(cursor) ;
Ctrl: :ChildLostFocus () ;
Al ~
void
,
ArrayCtrl::Paint(Draw& LTIMING("Paint"); Size size = GetSize();
w)
{
=.
Rect rr; r.bottom = 0; bool hasfocus = HasFocusDeep();
int i = GetLineAt(sb); int xs = -header.GetScroll(); int js;
for(js = 0; js < column.GetCount(); js++) { int cw = header.GetTabwidth(js); if ( ( xs + cw - vertgrid + (js == column.GetCount() break;
xS += cw;
Color fc = Blend(ScolorDisabled, SColorPaper);
if IsNull (i)) < (1
while(i
r.top
GetCount()) { =
if(r.top
GetLiney(i)
> r.bottom =
-
sb;
size.cy) break; r.top
+
GetLineCy(i);
int x = xs; for(int j = js; } < column.GetCount(); j++) { int cw = header.GetTabwidth(j); int cm = column[j].margin; if(cm
< 0)
cm =
header.Tab(j).GetMargin();
if(x > size.cx) r.left = x;
break;
-
1))
>=
0)
Why Python?
environment or users. Operating systems, such as Windows, macOS and such are usually a combination of C++, C#, assembly and some form of visual-based language. Games generally use C++ whilst web pages can use a plethora of available languages such as HTML, Java, Python and so on. More general-purpose programming is used to create programs, apps, software or whatever else you want to call them. They're widely used across all hardware platforms and suit virtually every
conceivable application. Some operate Faster than others and some are easier to learn and use than others. Python is one such generalpurpose language.
Python is what's known as a High-Level Language, in that it ‘talks’ to the hardware and operating system using a variety ofarrays, variables, objects, arithmetic, subroutines, loops and countless more interactions, Whilst it’s not as streamlined as a Low-Level Language, which can deal directly with memory addresses, call stacks and registers, its benefit is that it’s universally accessible and easy to learn.
//File: import ma
6
Invoke. java
java.lang.reflect.*;
class Invoke { public
try static
.
void main( string [] args )
Class c = Class.forName( args[0] = c.getMethod( args[1], Wethod
‘.
);
new
f{
Class
Object ret = m.invoke( null, null ); system. out. printin “Invoked static method: + args(1] " + of class: " + args[0] " + with no args\nResults: + ret ); } catch ( ClassNotFoundException e)f{ // Class.forname( ) can't find the class } catch ( NoSuchMethodexception e2){ // that method doesn't exist catch € T] ion ed) { have permission to invoke that // we don’tlegalAccessExcept 3}
method
} catch ( InvocationTargetException e4 ) {
// an exception ocurred method
computer. It’s perfect for the hobbyist, enthusiast, student, teacher and those who simply need to create their own unique interaction
between either themselves or a piece of external hardware and the computer itself. Python is free to download, install and use and is available For Linux, Windows, macOS, MS-DOS, OS/2, BeOS, IBM i-series machines, and even RISC OS. It has been voted one of the top five programming
languages in the world and is continually evolving ahead of the hardware and Internet development curve. So to answer the question: why Python? Simply put, it’s Free, easy to learn, exceptionally powerful, universally accepted, effective anda superb learning and educational tool.
py=15
4@ LET
72 FOR w=1 TO 198 71 CLS 7S LET by =INT (RNDO#25) 6@ LET bx= 90 FOR d=1 TO 20 1@@ PRINT AT Px,Py;" U " 110 PRINT AT bx,by;"o" IF INKEY $="Pp" THEN LET pPY=P y+120 IF INKEY THEN LET PY=P 130 S="0" 135 FOR TO 100: NEXT 140 IF py2? THEN LET py=27 180 LET bx=bx+1 " 16S PRINT AT bx-1,by;" 19@ NEXT d 200 IF (by-1) =py THEN LET s=s41 2190 PRINT AT_10,10; 220 FOR v=i1i TO 1000: "score=";,5 NEXT v 300 NEXT w @ OK, @:1 nn
&=
BASIC was once the starter language that early 8-bit home computer users learned.
print(HANGMAN[®])
system.out.printIn
‘Method threw an:
"
getTargetException(
Java is PJ =
while invoking that
Python was created over twenty six years ago and has evolved to become an ideal beginner’s language For learning how to program a
attempts = len(HANGMAN) -
+ e4.
)
);
1
while (attempts != @ and "-" in word_guessed): print(("\nYou have {} attempts remaining”).fornat(attempts)) joined_word = "”. join(word_guessed) print (joined_word) try:
a powerful
player_guess = str(input("\nPlease select a letter between A-Z" + "\n> except: # check valid input print(*That is not valid input. Please try again.”) continue
language that's used in web pages, set-top boxes, TVs and even cars.
")).
else:
if
player_guess.isalpha(): # check the input is a letter. Also checks print("That is not a letter. Please try again.”)
not
a
continue
i
11
elif len(player_guess) > 1: # check the input is only one letter print("That is more than one letter. Please try again.")
1.
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 aN
guessed_letters. append(player_guess)
for letter in range(len(chosen_word)):
if
if
player_guess == chosen_word[letter]: word_guessed[letter] = player_guess
#
replace all letters in the chosen
player_guess not in chosen_word:
Python is more modern take on BASIC, it’s easy to learn and makes for an ideal beginner's programming language. a
www.bdmpublications.com
-guipmen You
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 aeNllele) (en
ace
WHAT WE'RE USING Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linux, Raspberry Pi and more. you have one of those systems, then you can easily start using Python.
IF
| _] 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.
[|_|
ANIDE
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.
~
Cee |_| Download
the Latest version for
Windows
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 but a 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 more efficient language. Having access to the Internet will keep you up-to-date, help you a
out when you get stuck and give access to Python’s immense number of modules. tapeses
|
[| 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 B is the latest version, incorporating a more powerful CPU, a choice of 1GB, 2GB or 4GB memory versions and Wi-Fi and Bluetooth
mene
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 kit you're interested in.
FUZE PROJECT
meee
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 at www.fuze.co.uk.
HHO OHS TOO EHOD
RASPBIAN The Raspberry Pi’s main operating system is Debian-based Linux distribution that comes with everything you need in a
programming and even as a desktop computer.
Raspberry Pi too.
|
CodeProject,
arangyroren Fp
LETE Guipg Wer
OF
the
Respbemy pyi
HORE
COMETH
ppansene
EOE
a rreiszsw:
by-step project examples and guides to get the most from the
OHH
BRO
it; there are some great step-
eH
BD
HER EOO
simple to use package. It’s streamlined for the Pi and is an ideal platform For hardware and software projects, Python a
We have several great Raspberry Pi titles available via www. bdmpublications.com. Our Pi books cover how to buy your first Raspberry Pi, set it up and use
www.bdmpublications.com
Getting to Know Python Python is one of the most used and popular programming languages. It’s a great language on which to learn how to code, but it’s also powerful enough to be used by companies when trawling through petabytes of raw data.
PYTHON POWER Python is a high-level, general-purpose programming language that was designed by Guido van Rossum in the late ‘80s, as a successor to the ABC Programming Language, and became available to use in 1990.
h
Guido van Rossum, the
designer of Python.
The Python Software Foundation, a non-profit organisation devoted to both furthering and improving Python, currently develops the language. The Foundation’s purpose is to “promote, protect, and advance the Python programming language, and to support and Facilitate the growth of a diverse and international community of
e
Python programmers.”
As aside note, it’s not just the likes of the Stock Exchange that use Python to study large quantities of data; in April 2019 the First image of a black hole was released, the supermassive black hole in the galaxy called M87, located roughly 55 million light years away. Thanks to the collaboration of over 200 scientists, using an array of telescopes spanning the world (called the Event Horizon Telescope Project), the combined power of the telescopes formed an impressive five petabytes of data, spread across tens of hard drives weighing in at nearly one ton. Five petabytes, by the way, equates to around 5,000 years’ worth of MP3 files. Once all those hard drives were gathered together and shipped to a central supercomputer cluster, the team then used Python to painstakingly stitch together all the Fragments of data from the Five petabytes to Finally form the most talked about astronomic event of the decade.
The structure of Python code has been designed to Flow easily, allowing those who are just beginning to code to follow it without too much difficulty. Yet, despite its ease of use, Python is regularly used throughout a number of industries in real-world scenarios. Big Data and Al are the two fastest growing Python-backed technologies at the moment. Big Data is simply a modern term used to describe huge amounts of data, such as sequences of numbers collated
during a day's worth of trading on the Stock
Exchange. Python code is used to dig into the voluminous
collection of numbers, and then feed back
Made up From over 5 Petabytes of data, spread across a ton of hard drives, Python helped science to unveil the First image of a black hole.
iF you’re not familiar with the term, stands for Artificial Intelligence. Although we're still a long way off From the visionary stories of Arthur C. Clarke, Al is Fast becoming one of the most influential technologies of our modern age. Rather than controlling robots, the Al that Python drives is designed to create autonomous
Al,
Getting to Know Python
>>
ILE Clave no custom themes
Batt Custom Thine:
conzext
>>>
Custom Theme
Background
nere tyou can arn cnonae irene
This is a little more like it, since you've just produced your First bit of code. The Print command is Fairly self-explanatory, it prints things. Python 3 requires the parentheses as well as quotes in order to output content to the screen, in this case the ‘Hello everyone!’ bit.
dBuik in Theme a
st
tot
Fle
Shel
Edit
Gpbons
Debug
Window
Help
Python 3.7.0 (v3.7. sibf5ec8093, Jun 27 2018, 04:06:47) IMBC v. 1914 32 Type "copyright", “credite" or "license()" for more information,
bit (Intel)]
on wind?
292
>>>
|
>>> 23453645549822 O455€0975 >>> 99778642342 12343
Settings
CB
General
Fonts/Tabs Highlights Keys
Extensions
Key set @
print ("Helle everyone !")
>>>
Hello
everyone!
ike Use
>>>
chinksA] a
Custom Key Set
OE
Clank Widows,
-nocustom keys-
[_Dileteccanteen
New
Cantor
Key
Set
Custom Key Bindings ‘Achon - keys) beginning-oflcenter-mnsert
a
tome>
ichange-indlenttwidth «Meta-Keyatieck-rodule > print ("Helio") Hello
File
Feit
Shell
Aebug
Python 3.7.6
Aptiens
Windew
Help
(w3.7.0:1br9cc093, Jun
27 2010, 04:06547)
[MSC
v.1919 32 bit
(Intel}]
on
win32
Type "copyright", “credits” p>>
or
“License{)" for
more
information.
print ("Hello")
Hello poo print ("242") 242.
>>> nrinn (242) >>>
As predicted, the word Hello appears in the Shell as blue text indicating output From a string. It’s fairly straightforward, and doesn’t require too much explanation. Now try:
You can continue as such, printing 2+2, 464+2343 and so onto the Shell. An easier way is to use a variable, which is something we will cover in more depth later. For now, enter:
print(*2+2”)
a=2
STEP 4
b=2 File
Frit
Shell
Net
Options
Windaw
Help
Python 9.7.0 (v3. 7 Ibf9cc5099, Jun 27 2016, 04:06:47) [MSC v.1914 92 bit win32 Type "copyright", “eredito" ox “liccnac{)" for morc information. >>> print
("242")
242.
>>»
(Intel)]
on
L& Fone File
Eda
Shel
Shell
Debug
242 Da>
www.bdmpublications.com
Options
Window
Pythun 3.7.0 (v3.7 +02 1b$uu5033, wii32 Type "copyright", “credits” or vey prant ("Nello") Hello poo print ("212%")
print (242)
Help
Juu 27 2018, 04:06:47)
“license()" for
more
(MSC
v.1914 32 Bil
information.
(Zutel)}
un
Care QE What you have done here is assign the letters a and b two values: 2 and 2. These are now variables,
aaaa)
Now let's add
Edit
Edit
File
Shell
Debug
Options
Window
Help
Jun 27 2020,
"liccnsc()"
for
(MSC v.1914 92 bit
G47)
0:
more
(Intel)}
on
information.
Shell
a
x
o
shell
[L& Phen
27
Python 9.7.0 (v3.7.0:1b9cc5093, windz Type "copyright", "ercdits™ or >>> print ("Hcl10") Hello >>> prant ("242' >>>
printCsurname) We now have two variables containing both a First name and surname, and we can print them independently.
print(a) print(b) file
surname:
surname="Hayward”
which can be called upon by Python to output, add, subtract, divide and so on, for as long as their numbers stay the same. Try this:
La Psthen
a
Debug
Options
Window
Help
Python 3.7.0 (v3,7,0r1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)] on win32 Type "copyright™, "credits" or "license()™ for more information.
*
(Inte
>>> name="David"™ >>> print (name)
David
>>> surname="Hayward” >>> print (surname)
prin (242)
Hayward >>>
>>>
print (b}
The output of the last step displays the current values of a and b individually, as essentially you've asked them to be printed separately. IF you want to add them up, you can use the Following:
This code takes the value of both a and b, adds them together, and outputs the result.
File
Edit
Sheil
Debug
IF
printCname+surname)
printCa+b)
Gptions
Python 3.7.0 (v3.7.0:1b$cc5093, win32 Type "copyright", "credits" ox pao print ("Hello")
we were to apply the same routine as before, using the + symbol, the name wouldn’t appear correctly in the output in the Shell. Try it:
STEP 9
[MSC
“license{)" for
moze
v.1914 32 bic
(Intel}]
on
information.
We need a space between the two, defining them as two separate values and not something you mathematically play around with.
_
Lo Peter ae
ell
File
Debug
Edit
Shell
Options
Window
Python 3.7.0 (v3.7.0:lb9cc5093, 1)] on win32 Type "copyright", "credits" or >>> name="David" >>>
print
x
Oo
Help
Jun 27 2018, 04:06:47)
"license()” for
more
[MSC
v.1914
32
bit (Inte “
information.
(name)
David
print ("242")
>>> surname="Hayward® >>> print
print (242)
Hayward >>>
(surname)
print (name+surname)
Davidtayward >>>
print (a) print (b} Print (atb)
You can play around with different kinds of variables together with the Print Function. For example, we could assign variables for someone’s name:
a
print(name, surname)
name=”David”
Alternatively, you can add the space yourself:
printCname)
printCname+” File
Edit
Shell
vytnon 3.7.0 wainsz
Debug
Options
Window
Help
(v3.7. UrIpryccouys, Jun
Type “Gupytight™, pov priue ("Belly") Hello pee print ("242")
In Python 3 we can separate the two variables with a space by using comma:
STEP 10
ZY 2018, U42U0T97)
TLiceuse(}" Lor
more
IMSC
V.a¥14 3Z Dit
infuimalion.
(intel}s
on
»
6
“+surname)
As you can see, the use of the comma is much neater. Congratulations, you've just taken your first steps into the wide world of Python. x
print (212) File
So aed pan baz S>> print (a)
>>>
prinr th)
>>>
print (atb)
>>> name="David™ >>> print (name)
Edit
Shell
Debug
Options
Window
Help
Python 3.7.0 (v3.7.0:IbfSec5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)} on win32 Type “copyright”, “credits” or “license()" for more information. >>> name“"David" >>>
(Inte
print (name)
David
>>> surname="Hayward" >>> print (surname) Hayward
David
>>>
>>>
DavidHayward
print (name+surname)
www.bdmpublications.com
~
BD
aving and Executing Your Code While working in the IDLE Shell is perfectly Fine For snippets of code, it’s not designed For entering longer program listings. In this section, we'll introduce you to the IDLE Editor, where most of our code will be entered 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.
STEP
1
First, open the Python IDLE Shell. When it’s up, click on File > New File, this will open a new window with
Untitled as its name. This is the Python IDLE Editor, and within it, you can enter the code you need to create your Future programs.
0 ype
WvE7.9uMbepeeS093, Tun 27
“cepysight™, “creates
201, 04:06:47)
(MET v.LH14 32
As you can see the same colour coding isin place in the IDLE Editor as it is in the Shell, enabling you to better understand what’s going on with your code. To execute the code, however, you need to first save it. Press F5 and you'll have a Save...Check box open.
STEP 3
bis (Inte re
ox
Pyenan 4.7.0
itay (937d
1EEsee8093,
Wy on winte Type “ecpyeigbt", “ereaite’
nee Sun 27 2078,
ehom
g4r0E97)
TREC
Fad
92 Bae
conde
Ne
(Ince
of “Aucense()* ror moxe spfoxmaticn.
Souter
Svea.
Mut 86 Son?
‘Okie
The IDLE Editor is, For all intents and purposes, a simple text editor with Python Features, colour coding and so on. You enter code as you would within the Shell, so taking an example From the previous tutorial, enter:
printC“Hello everyone!”)
Click on the OK button in the Save box, and select a destination where you'll save all your Python code. The destination can be a dedicated Folder called Python, or you can just dump it wherever you like. Remember to keep a tidy File system,
though, it’ll help you out
Tha PC
dn
+
Roce Dak
= Mew
in
(Ca
tales Name
ects esp
$
Prwnloade
La 1
Feeder Filter
Anmes
F
manking
File feller
Prrthoge
Hie
laid
le
Loder
4 Progiem Files 1
tne
activity
‘SGerCumert
= Thabo
Caeumente
the future.
Progen Files 186)
intotder
Flet
see
Flot Het File fonder
Far totter Fale torden
go Hew solume tah Network
Fleder ie letdee Fae tuber
Fle ners
www.bdmpublications.com
Saving and Executing Your Code
( STEP5
Enter a name for your code, ‘print hello’ For example, and click on the Save button. As soon as the Python code is saved, it’s executed and the output will be detailed in the IDLE Shell; In this case, the words ‘Hello everyone!’
aaaa)
Let’s extend the code and enter a Few examples from the previous tutorial:
a=2 b=2
name=”David” He
efpecsS0#3, Jun 27 2018,
"copyright", "credits"
ype
or
format
Nie
7)
@:
"license()" for
more
RESTART! C1/Python Code/print
(MSC
7.1914
32
Han
Optom
bic (Ince
information.
surname="Hayward” print(name, surname)
print Catb)
nello.py
meite everyone! >>>
IF you press F5 now, you'll be asked to save the file again, as it’s been modified from before.
be
This is how the vast majority of your Python code will be conducted, Enter it into the Editor, hit F5,
STEP 6
save the code, and look at the output in the Shell. Sometimes things will differ, depending on whether you've requested a separate window, but essentially that’s the process and, unless otherwise stated, this is the method we will use.
tree
IF you click the OK button the file will be overwritten with the new code entries, and executed; with the output in the Shell. It’s not a problem with just these Few lines, but if you were to edit a larger File overwriting can become an issue. Instead, use File > Save As from within the Editor to create a backup.
STEP 9
L& *print hello.py - C:/Python Code/print hello.py (3.7.0)" [&
Pvthen
File
27.2 Shell
Edit
=
Shei
Debug
Options
Window
Format
Edit
File
oO
Python 3.7.0 (v3.7.0:1bf9$ccS093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)) on win32 Type “copyright”, “credits” or “license(}" for more information.
(inte
>>>
Run
Options
Open...
Ctrl+0
Open Module...
Alt+M
Hello everyone!
hello.py
Help
>
Recent Files
RESTART: C:/Python Code/print
Window
Ctr+N
New File
Help
Module Browser Alt+C Path Browser
>>>
Exit
IF you open the Fite location of the saved Python code, you'll notice that it ends in a .py extension. This is the default Python Filename, any code you create will be
a new file. Close the Editor, and open : . new instance (File > New File from the Shell). Enter the Following, and save it as hello.py:
whatever.py, and any code downloaded from the many Internet Python resource sites will be .py. Just ensure that the code is written for Python 3.
a=”Python” b=" 1 5”
Python
Now create
STEP 10
;
a
c="cool!” print(a, b, c)
Cae
We will use this code in the next tutorial. ‘Name
1 prebetoy OneDrive
>
Me
Mins
+
>
Desktop
>
Documents
>}
>
Te Python Fite
-
L& hello.py C:/Python Code/hello.py (3.7.0) File
Edit
Format
Run
Options
Window
Help
a="Python”
90 Cen
+
Date modified
be"is"
c=*cool!™
print(a, b,
c)|
Downloads Mun db
>
Pitures
>
(Videos
>
Hy
LocalC9
>
an New >
gh
Oem
Volume (0)
Network
www.bdmpublications.com
BD
Executing Code from the Command Line While we're going to be working from the GUI IDLE, it’s worth taking moment to look at Python’s command line handling. Sometimes, depending on the code you write, executing via the command line is better solution over the IDLE. a
a
COMMAND THE CODE Using the code we created in the previous tutorial, the one we named hello.py, let’s see how we can run code that was made in the GUI at the command line level.
When you first installed Python, the installation routine automatically included all the necessary components to allow the execution of code outside of the GUI IDLE; in other words, the command line. To begin with, click on the Windows Start Button, and type: cmd.
STEP
1
Now you're at the command line, we can start Python using the command python and pressing the Enter key. This will put you into the command line version of the Shell, with the Familiar, three right-Facing arrows as the cursor (>>>).
STEP 3
ex hea haa Piatt eg
pong
As you did when launching the Python IDLE, click on the returned result from the search, the Command Prompt App. This will launch a new window, with a black background and white text. This is the command line, also called a Terminal in macOS, Linux, and Raspberry Pi operating systems.
era glk Sede
ia
Meech ares
fo Ble
Tir
rie
Mp
are
Peed
aed
From here you're able to enter the code you've
STEP 2
looked at previously, such as:
a=2
print(Ca) As you can see, it works exactly the same.
www.bdmpublications.com
Rede
ee
(Executing
Now enter exi tC) to leave the command line
Python session, and return back to the command prompt. Enter the folder where you saved the code From the previous tutorial, and list the available Files within; you should see
STEP 6 python
Code from the Command Line
From within the same folder as the code you're going
to run, enter the Following into the command line:
hello.py
This will execute the code we created, which to remind you
the hello.py file.
is:
a=”Python” b="18s8” SO
Redan tisce
c=”cool!” print(a, b, c)
|
I>python
tenth atest oe bh Ge “help”, “copyright”, “credits” or “license” for more inforastion.
ype.
OE
EUS HE Command Prompt
eta
Volume in drive
2 +
ei C
has no. lebel.
ag
bi Beieea Die(s) 76,554,990,728 bytes free
Pe
\Python: Code>
errr erererererer
errr err eer ererer
errr rerereyy)
DIFFERENT VERSIONS OF PYTHON IF you've previously used Python 3 on a Mac or Linux, and subsequently the Raspberry Pi, you may be a little confused as to why the Windows version of Python uses the command line: python, instead of python3.
This isn’t an issue with Windows, as it doesn’t use any Python libraries other than the ones installed by the user themselves
The reason behind this
is that UNIX-like systems, such as macOS and Linux, already have Python libraries pre-installed. These older libraries are present because some of the macOS and Linux system
entering: path into the command line. This points to the python. exe File required to execute Python code from the command line.
utilities rely on Python 2, and therefore installing newer version of Python, and thus altering the executable name, could have dire consequences to the system.
We don’t recommend you install both Python 2 and Python 3 within Windows 10; naturally, you can if you want, but realistically, although Python 2 still has a foothold in the coding world, Python 3 is the newest version. However, if you do, then you will need to rename one of the Python versions names; as they will be installed
a
Asaresult, developers decided that the best approach for macOS and Linux systems would be to leave the command line ‘python’ as exclusive Python 2 use, and newer versions of user-installed Python would be ‘python3’. Gea
Command Prompt
when actually installing Python. When a Windows user installs Python, the installation wizard will auto-include the command line instance to the core Windows PATH variable, which you can view by
in different Folders and both use python.exe as the command line executable. It’s a little long-winded, so unless there’s a dire need to have both versions of Python installed, it’s best to stick to Python 3.
_
O
x
eee
Microsoft Windows [Version [email protected]] (c) 2018 Micreseft Cerperation. All r ts reserved. \Users\david>path :\ProgramData\Oracle\Java\javapath;C:\Pragram Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\icLs Client\; :\Windows\system32;C: C:\Windows \System32\WindowsPowerShell\v1.0\;C:\Program Files (x86
IC:
Ithon37 -32\Scripts\;C: \Users\david\AppData\Local \Programs\Python\Python37-32\;"C: \Users\david\AppData\Local \Microsoft\Win idowsApps; C:\Users\david\AppData\Local \Programs\Python\Python36-32";;C:\Users\david\AppData\Local\Microsoft\WindowsApps
www.bdmpublications.com
BD
Numbers and Expressions We've seen some basic mathematical expressions with Python, simple addition and the like. Now let’s expand on that, 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 from the mathematical powers of Python, as maths is the driving force behind the code with most, if not all, programming languages.
STEP
Open up the GUI version of Python 3, as mentioned you can use either the Shell or the Editor. For the
1
You can use all
apsecmm
[a
Python 3.7.0 Shelt Edit
Fite
time being, we're going to use the Shell. IF you've opted to use a third-party text editor, note that you need to get to the IDLE Shell
the customary Mathematical operations: divide, multiply, brackets and so on.
Type
for this part of the tutorial.
Practise with afew, Forexample:
37”
G File
-
Python 3.7.0 Shell Edit
Shell
Debug
Options
Window
a
Help
x (Inte “
Python 3.7.0 (v3.7.0:1lbfS9ccS093, Jun 27 2018, 04:06:47) [MSC v.2914 32 bit 1))] on win32 Type “copyright”, “credits” or "license()" for more information. >>>
Debug
Options
Window
f/)"on gingp “copyright”, "credits" ?*?
or
“1
>>> 543564+34553245 34607601 >>> 99867344*27344484221 2730821012201179024 >>> 1/2
1/2 6/2 242*3 /
Shell
2
(14+2)+3
90.8
4)
>>> 6/2
3.0 |>>> 2+2*3 8
>>> (142)4(3*4)
as >>>
STEP 2
In
the Shell enter the Following:
As you've no doubt noticed, division produces a decimal
242 54356434553245 99867344*27344484221
number. In Python, these are called floats, or Floating point arithmetic. IF however, you
.
.
As you can see, Python can handle some quite large numbers. [ib Python
3.7.0 Shell
File
Shell
Edit
Debug
Options
Window
Python 3.7.0 (v3.7.0:1b9cc5093, 1)} on win32 Type "copyright", "credits" or >>> 242 a
>>> 54356434553245 34607601 >>> 99967344*27344484221 2730821012201179024 >>>
a
x
Help
Jun 27 2018, 04:06:47)
"license(}" for
more
i
ivisi
[MSC
v.1914 32 bit
information.
(Inte
*
.
need an integer as opposed toa decimal answer, then you can use . a double slash:
1//2 6//2 and so on.
Python 3.7.0 Shell File
Edit
Debug
Options
Type "copyright", “credits” >>> 242 4
54356434553245 34607601 >?_: 99867344*27344484221 2730821012201179024 >>> 1/2
G.5 >>> 6/2
3.0 >>> 24+2*3 8
>>> (142) 4(3*4) 15
>>> 1//2 a
>>> 6//2 3
>>>
www.bdmpublications.com
Shell
Windc
cc (v.7.0:1bf9cc509;
“python 3.7.0 v; mm on 3-750
or
and Expressions
(Numbers
You can also use an operation to see the remainder left over from
division. For example:
[&
-
Python 3.7.0 Shell Edit
File
Shell
Debug
Options
Window
4
will display 3.333333333, which is, of course, 3.3-recurring. IF you now enter:
>>> 543564+34553245 34607601 >>> 99867344*%27344484221 2730821012201179024 >>> 1/2
This will display 1, which is the remainder left over from dividing
8
beer eaeaaniaell O.5 6/2
€
format(3,
a
‘b’) >
The Format command converts a value, the number 3, toa formatted representation as controlled by the format specification, the ‘b’ part.
1S un 9
is
6//2
1//2
oO
3
>>> 10/3
3.3333333333333335
a> >>>
6//2
"Obll'
>>> format crue >>>
1
>>>|
operator, or exponentiation if you want to be technical. To work out the power of
something you can use a double multiplication symbol, or double-star on the keyboard:
Edit
File
Shell
Debug
Options
Window
H
Python 3.7.0 (v3.7.0:1bf9cc5093, Ju 1)] on win32 Type "copyright", “credits” or "lic >>> 242
34607601 >>> 99867344*27344484221 2730821012201179024 pep 1/2
outin Python.
a
New File: {2 Ecoteanteit.py
6
File
b=7
>>> (14+2)4+(3*4) 1s >>> 14/2 9
>>> 6//2 3
>>> 10/3
3.3333333333333335 >>> 10%3
Edit’
C:Python Code/Booleantez
Format
Run
Wineew
Options
223
print(1, print(2, print(3, print(4, print(S, print(6, print(7, print(8, print(9,
0.5 >>> 6/2
8
This is how you would work it
A Boolean Expression is a Logical statement that will either be true or False. We can use these to compare data, and test to see if it’s equal to, less than, or greater than. Try
a=
>>> 242*3
Essentially, it’s 2x2x2, but we're sure you already know the basics behind maths operators.
{3,'b')
STEP 9
this in
4
>>> 543564+34553245
3.0
2*83 10**10
283
>>> 1o**10 1ceaoo00eca0 >>> bin (3)
>>> 10/3 3.33333333333333358 >>> 10%3
Next up we have the power
1083
8
3
STEP 6
24+2*3 3
>>> (142)4(3%4)
>>> (142) 4(3*4)
>>>
Help
>>> 54356434553245 34607601 >>> 99867344*27344484221
.
>>>
Window
Options
3.0
>>> 24+2*3
10 by 3.
Debug
4
.
>>> 6/2
3.0
Shell
>>> 242
can use:
Q.5
10%3
Edit
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 i 2)1 on win32 Type "copyright", "credits" or “license (!
aes)
displayed as ‘0b11’, converting the integer into binary, and adding the prefix Ob to the Front. IF you want to remove the 0b prefix, then you
Python 3.7.0 (v3.7.0: lbf9cc5093, 1)j on win32 Type “copyright”, “credits” or "1 >>> 2+2
10/3
‘File
oo.
This will be
oy =]
a=
6) 7)
a
==
6 and b
a
==
7 and b
a
==
not a
@
a
==
7
==
7
=
7) 7)
==
7 and b
==
a
tunciz, = 7) rea t=IeRS
or or
b
==
b
==
==
4
parce BERLIa, coy
fe
7 al
7)
7) 6)
not Ca == 7 and b == 6)) not a == 7 and b == 6)
1
>>> Zee
:
>>> 10**10
|
10000000000 >>>
|
|
anlar
Numbers and
expressions don’t there. stop Python has numerous built-in functions to work out sets of numbers, absolute values,
complex numbers, and a host of Mathematical expressions and Pythogarian tongue-twisters. For example, to convert binary, use:
a
number to
Python 3.7.0 (v3.7.0: ibf$cc5093, Jun i)]} on win32 Type “copyright”, “credits” or "licer >>> 242 4
>>> $43564+34553245 34607601 >>> 99867344%27344484221 2730821012201179024 >>> 1/2
O.s >>> 6/2
3.0 >>> 242*3 8
>>> (142)4+(3*4) 15
>>> 2//2 oO
bin3)
>>> 6//2 3
>>> 10/3
3.3333333333333335 >>> 10%3 1
>>> 2883 8
Execute the code From Step 9, and you'll see a series of True or False statements depending on the result of the two defining values: 6 and 7. It’s an extension of
STEP 10
what we've looked at, and an important part of programming. L& Python File
Edit
-
3.7.0 Shell
Shell
Debug
Options
Window
Python 3.7.0 {(v3.7.0:lbf9cc5093, 1)) on win32 Type "copyright", "credits" or
a
Help
Jun 27 2018, 04:06:47)
"license{)" for
more
[MSC
v.1914
32
bit (Int
information.
>>>
RESTART: C:/Python
True
Code/Booleantest .py
False True
False True True
False True
False >>
>>> 10**10 10000000000 >>> bin(3)
‘obil’
>>>|
www.bdmpublications.com
Python Foundations
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 when the code starts to hit thousands of lines, things get a little difficult to read.
#COMMENTS! Amethod used by most programmers for keeping their code readable, is by commenting on certain sections. For example, if a variable is used, the programmer comments on what it’s supposed to do. It’s just good practise.
a toe
We'll start by creating a new instance of the IDLE Editr (File New Fle), and then create a simple variable and print command: >
a=10
printC(“The value of A
is,”,
a)
Re-save the code and execute it. You'll see that the output in the IDLE Shell is still the same as before, despite the extra lines being added. Simply put, the hash symbol (#) denotes a line of text the programmer can insert, to inform them and others of what’s going on, without the user being aware.
STEP 3
(&
Save the file, and execute the code.
Edit
Edit
Format
Run
Options
Window
STEP 2
is,",
Running the code will return the line: The value of
to
10
Print the current value of
printC“The value of
A
is,”,
#
Edit
Format
Set the start
Run
Options
Window
value of A to
a)
x (Inte
The value of A >>>
is,
10
RESTART: C:/Python Code/Comments py RESTART: C:/Python Code/Comments. py
(3 *Comments.py - C:/Python Code/Comments.py (3.7.0)" File #
Help
Edit
Format
Set the start
Run
Qptions
Window
Help
value of A to 10
a=10
10
#
Print the current value of A
print ("The value of A is,", a)
#
www.bdmpublications.com
10
printC“You’ve just lost a life!”) printC“You now have”, a, “Lives Left!”)
A
a=10
Print the current value of A print ("The value of A is,“, a)
is,
a=a-1
(& *Comments.py - C:/Python Code/Comments.py (3.7.0) File
Q
Help
Let’s assume that the variable A we've created is the number of lives in a game. Every time the player dies, the value decreases by 1. The programmer could insert a routine along the lines of:
a=10 #
Window
STEP 4
Ais, 10 into the IDLE Shell window — which is what
A
The value of A >>>
=
a)
Set the start value of
Options
>>>
Help
we expected. Now let's add some of the types of comments you'd normally see within code: #
Debug
1)}
a=10
print ("The value of A
Shell
Python 3.7.0 (v3.7.0:lbf9ccS093, Jun 27 2018, 04:06:47) {MSC v.1914 32 bit on win32 Type “copyright”, “credits” or “license()" for more information,
[s Comments.py - C:/Python Code/Comments.py (3.7.0) File
-
Python 3.7.6 Shell
File
|
a=a-1l
print ("You've just lost a life!*) print ("You now have", a, “lives left!*")
I
+
Using Comments
STEP5
While we know that the variable A denotes number
of lives and the player has just lost one, a casual viewer, or someone checking the code, may not know. Imagine for a moment that the code is twenty thousand lines long, instead of just our seven. You can see how handy comments are. ~
L& Python 3.7.0 Shell File
Edit
Shell
Debug
Options
Window
x
a
Help
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)) on win32 Type "copyright", “credits” or “license()" for more information.
(Inte
>>>
RESTART: C:/Python Code/Comments.py
Ais,
The value of >>>
10
The value of A >>>
is,
10
The value of A
is,
10
RESTART: C:/Python Code/Comments py
start value of A to 10 value of A is,”, a) # Print the current print(“The value of A a=a-1 # Player lost a life! printC“You’ve just lost a life!”) printC“You now have”, a, “Lives Left!”) # Inform player, and display current value of A (lives) a=10 # Set the
-
*Comments.py Edit
Format
$
Set the
a=lO
Run
Options
Window
value of A
start
print ("The value of A is,", 2) nenwl
#
-
C:/Python Code/Comments.py (3.7.0)"
Player fost
a
x
Help
to
16
Print the
#
current
value of A
a
print ("You've just lost a life!*) print ("You now have", a, “lives left!")
#
Inform player, and display current of A
(lives)
|
The comment, the hash symbol, can also be used to comment out sections of code you don’t want to be executed in your program. For instance, iF you wanted to remove the First print statement, you would use:
Essentially, the new code together with comments : could look like:
STEP 6
Set the start value of
#
section of code. Take our examples from above, instead of inserting the code ona separate line, we could use:
File
You've just lost a life! You now have § lives left! >o>
Inline Comments are comments that follow a
STEP 8
L&
RESTART: C:/Python Code/Comments.py
to
A
10
a=10
Print the current value of A printC“The value of A is,”, a) # Player lost a life! a=a-1 # Inform player, and display current value of
#
Clives)
printC“You’ve just lost
prinC“Yo
now
Format
4
Bev che
#
[rant
Run
value uf A
che
current
Windew
is,”,
a)
Options
Window
Help
value of A to 10
a=10
Print the current value of A A is,™, ail
#
have”, a, “Lives Left!”)
Options
Rum
Set the start
#
print ("The value of Player lost a life!
# #
a=a-1 # Inform player, and display current print ("You've just lost a life!*) print ("You now have", a, “lives
-
Edit
Format
Edit
Fite
A
L& *Comments.py CPython Code/Comments.py (3.7.0)* File
A
te *Comments.py - C/Python Code/Comments.py (3.7.0}"
lfe!”)
a
print(“The value of
#
Help
Lu 10
valuc of A
of A {lives}
a)
$
Trfovr
player, and display emrrent nf ‘ve just lost a life!™) now have", a, “Lives left!*)
a
(lives)
("Y:u
STEP7
You can use comments in different ways. For example, Block Comments are a large section of text that details what's going on in the code, such as telling the code
You also use three single quotes to comment out a Block Comment, or multi-line section of comments. For them to work, place them before and after the areas
reader which variables you're planning on using:
you want to comment:
This is the best game ever, and has been developed by a crack squad of Python experts # who haven’t slept or washed in weeks. Despite being very smelly, the code at least
en?
#
works
#
File
Edit
Format
Run
Options
Window
-
(3.7.0)"
a
Help
#
is the best game ever, and has been developed by a crack squad of Python experts haven't slept or washed in weeks. Despite being very smelly, the code at least works really well.
#
Set the start value of A to 10
+ #
This
This who
x
works [od
ana-1 # Inform player, and display current of A
print ("You've just lost a life!*) print ("You now have", a, "lives left!
really well.
This
#
299
3.7.0)" “Comments py C/Python Code/Cammentspy -
ble
-
nn
Run Opbons Window Help is the best game ever, and has been developed by a crack squad of Python experts haven't slept or waghed in weeks. Despite being very mmcliy, the code at cast
“re
# Print the current value of A print ("The value of A is,", a) # Player lost a life!
is
the best game ever, and has been developed crack squad of Python experts who haven’t slept or washed in weeks. Despite being very smelly, the code at Least
who
a=10
8)
by a
really well.
L& *Comments.py- C:/Python Code/Comments.py
auto
Feaily well.
Set che start
ato
valuc of
A to 10
wrant the current value of & Print ("The value af A te, ", A} Player lost a life! #
(lives)
aval
t Inform player, and display current of A (lives) Print ("You've just lest # lite!") Yuu mes have®, ay
www.bdmpublications.com
BD
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 We'll be working with the Python 3 IDLE Shell in this tutorial. IDLE Shell to clear up any old code.
a
to
IF you
As we've seen previously, variables can be concatenated using the plus symbol between the variable names. In our example, we can use: print Cname + “: * + The middle part, between the quotations, allows us to add a colon and a space. As variables are connected without spaces, we need to add them manually.
some programming languages, you're required to use a dollar sign to denote a string, which is a variable made up of multiple characters, such as aname of aperson. In
STEP 3
In
title).
Python this isn’t necessary, so, For example, in the Shell enter:
name=”David Hayward” (use your own name, unless you're also called David Hayward). [&
-
Python 3.7.0 Shell Edit
File
Shell
Debug
Options
Window
File
(Inte
«
Edit
a
3.7.9 Shell
Shell
Debug
Options
Window
x
|
Help
Python 3.7.0 (v3.7.0:1lbf9cc5093, Jun 27 2018, 04:06:47} [MSC v.1914 32 bit ] on win32 Type *copyright", “credits” or “license()" for more information. >>> name="David Hayward”
(Intel)
«
>>>
print (name)
print (name) David Hayward >>> type (name)
David Hayward >>>
L& Python
Help
Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47} [MSC v.1914 32 bit 1)] on win32 Type "copyright", "credits”™ or "license()" for more information. >>> name="David Hayward* >>>
x
a
haven’t already, open Python 3 or close down the previous
|
>>> >>>
title="Descended from Celts” print (name + ": * + title}
David Hayward: Descended from Celts >>>
You can check the type of variable in use by issuing the type C) command, placing the name of the variable inside the brackets. In our example, this would be:
type Cname). Add a new string variable: from
Celts”.
Edit
Shell
Debug
Options
Window
Combine variables
within another variable. For
example, to combine both name and title variables into new variable, we use:
x
character=name +
(Intel)
title
“: “
+
print (mame)
Then output the content of the new variable as:
title="Descended from Ceits™
print Ccharacter)
David Hayward >>> type (name)
>>> >>>
a
Help
Python 3.7.0 (v3.7.0:lbf9ec5093, Jun 27 2018, 04:06:47) (HSC v.1914 32 bit ] on win32 Type “copyright”, "credits" or "license()" for more information. >>> name="David Hayward” >>>
Witenelce
a
[LB Python 3.7.9 Shell File
tit Le=”Descended
STEP 4
Numbers are stored as different variables:
age=44 Type Cage) Which, as we know, are integers.
www.bdmpublications.com
a
que
3.70 Shell Python
tas
OOnOnS
ndOn elD,
a Jun ; Python 3.7.0 (v3.7.0:1bf9cc5093, J on win32 Type “copyright", “credits” or “licen: >>> name="David Hayward”
>>>
print (name)
David Hayward >>> type (mame)
>>> title="Descended from Celts® >>> print{name + %: " + title) David Hayward: Descended from Celts >>> character=name + "; " + title >>> print (character) David Hayward: Descended from Celts >>> age=46 >>> type (age)
>>
process known as TypeCasting. The Python
+
Window
56
to str
code is:
print (character
Options
age + 10
TypeError:
>>>
STEP6
=
Debug
>>> age + 10
(name+age)
str
Shelt
(name+age)
only concatenate
Edit
Traceback (most recent call last)! File "", line 1, in
Traceback (most recent call last): File *", line 1, in can
+ 10
Python 3.7.0 (v3.7.0:lbf9ccS093, Jun 27 2018, 04:06:47) [MSC v.1914 32 1)] on win32 Type "copyright", “credits” or “license()" for more information. >>> age=input old are you? ") ("How How old are you? 46 >>> type (age)
>>
his presents a bit of
with Variables
old.”)
-
Go Python 3.7.9 Shell
Notice again that in the last example, you don’t need the spaces between the words in quotes, as the commas treat each argument to print separately.
File
Edit
Shell
Debug
Options
Window
x
oO
Help
Python 3.7.0 (v3.7.0: 1bf8cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 2)] on win32 Type "copyright", "credits* or "License(}" for more information.
(Inte
>>> shirt=19.99 >>> type (shirt)
David Hayward: Descended from Celts
>>
32
bit (Inte
—__To
printC“Welcome”, firstname, surname+“. I hope
you’re well today.”) [@ *Userinput.py- C:/Python File
Helio. is your first
What
RESTART: C:/Python Code/UserInput .py name? David
Thanks. And what >>>
is your surname? Hayward
www.bdmpublications.com
eliminate that, we can add a plus sign instead of the commain
the code:
Edit
Format
Run
-
Code/Usertnput (3,7.0)" py
Options
Window
Help
print ("Hello.")
firstname=input ("What is your first
print ("Thanks."}
name?
")
Surname=input ("And what is your surname? ") print ("Welcome”, firstname, surname+P. I hope you're well
today.")
a
xX
c-/> STEP
You don’t always have to include quoted text within the input command. For example, you can ask the
5
user their name, and have the input in the line below:
printC“Hello. What’s your name?”
What you've created here is a condition, based on the user’s input. In short, we're using the input from the user and measuring it against a condition. Therefore, if the user enters David as their name, the guard will allow them to pass unhindered. IF, however, they enter name other than David, the
STEP 8
a
name=input()
guard challenges them to a Fight.
[& *Userinput.py - C:/Python Code/Userlnput.py (3.7.0)" UB
File
Edit
format
print ("Hello.
Run
Window
Options
What is
Help
your name?*)}
input()|
370
Ppmon
Pychon
-
Snel
Seat Debug Opa onde 3.7.0 tei. 7-01ibeSeckOss,
o
x
Hele “Gun
BF
01s,
OATOATET
TEC
w. 181d 32 Shy Cinee
-
*, Mexedite” or “License()* for more information. Ar.
Maret Mo goes chere?
ARSTART: Ci/Pythen Cone/Userioput.py
Frine(*E
Pavia
Marcas, good siz.
You may
kmow you
act.
You mey
peas.)
Prepare for bacele!")
pass.
ALSTART: Ci/Pytben Code/UserIngue.py Maat! woe goer there? 1
tmow you
a>
The code from the previous step is often regarded as being a little neater han having a lengthy of text in the input command, but it’s not a rule that’s set in
STEP 6 amout
F
tn
ooe
stone, so do as you like
in
these situations. Expanding on the code,
try this: Who
to calculate rate and distance printC“Input a rate and a distance”) rate = floatCinputC“Rate: “))
there?”)
goes
name=inputC) (@ *Userinput C:/Python Code/Userinput.py (3.7.0) py
Edit
Format
print ("Halt!
Run
Who
name=input ()
Options
if
th
Window
[& File
Help
goes there?*)
a
know you
Edit
-
Format
Code to
#
name=="David”: printC“Welcome, good
else: printC“I
*Userinput.py
Run
Options
Window
File
*Userinput.py
Edit
-
Format
sir.
You may
not. Prepare for
print("Halt!
C:/Python Code/Userinput.py (3.7.0)* Run
Options
x
o
Help
calculate rate and distance
pass.”)
battle!”)
STEP 10
}
And to Finalise the rate and distance code, we can add:
distance = floatCinputC“Distance: “)) printC“Time:”, Cdistance / rate)) Save and execute the code, and enter some numbers, Using the Float(input element, we've told Python that anything entered is floating point number rather than a string.
-
Ub Python 3.7.0 Shot
L&
-
C:/Python Code/Userinput.py (3.7.0)"
iprint ("Input a rate and a distance”) rate = float (input (*"Rare: *})|
good start to a text adventure game, perhaps? Now we can expand on it, and use the raw input user to Flesh out the gamea little: It’s
from
As you learned previously, any input from a user is automatically a string, so you'll need to apply a TypeCast in order to turn it into something else. This creates some interesting additions to the input command. For example:
STEP 9
# Code
printC“Halt!
File
oot. Prepare for battle!
Window
Help
Who goes there?”) name=input {} if name="David": print ("Welcome, good sir. You may pass.") else: print ("I know you not. Prepare for battle!*)
a
«x
kde Stel Debuy Ophea Wanton Help Python $.7.0 (¥3.?.0rimfoeeso98, dun 27 2018, 04706747) [MSC v.1914 92 20} on wing2 ‘Type “oopyrionts, “eredica™ er “hicense()" for more information,
RESTART Cr/PycnOR Inpur a rave and a dtacance
Aeenemnuneemnmnmane
Code/Usexinput py
Far
bit (inte
opt
PD
fle
~
@
Fee
cin
Format
come to
Cote
Bahra fun Ophant
a
Peingss py
175)
Window
Help
calculate rare ana auatance
# rate and a dvatences) fleatqimpur(*Race: ")) duavance = Pleat (Distance? ")) (input / vave}) Frine(*Time:, (gasvanse
Print(tinput rate
2
www.bdmpublications.com
BD
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 Function.
FUNKY FUNCTIONS A function is command that you enter into Python in order to do something. It’s a little piece of self-contained code that a
takes data, works on it, and then returns the result.
a to
It’s not only data that a Function works on. Functions
can do all manner of useful things in Python, such as sort data, change items From one Format to another, and check the length or type of items. Basically, Function is a short word Followed
number of letters in a person's surname, you could use the Following code (enter the text editor For this example):
a
by brackets. For example, len(), list(), or type(). L&
-
*Python 3.7.0 Shll”
File
Edit
Shell
Debug
Options
Window
a
iType “copyright”, "credits™ or >>> leng|
name=input C“Enter your surname: count=LenCname)
x
Help
‘Python 3.7.0 (w3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.i914 32 bit {Inte j2)] on win32
"license(}" for
more
You can pass variables through functions in much the same manner. Let's assume you want the
aie
=f
«
information.
print C“Your
it.”)
surname
“)
has“, count, “letters in
Press F5 and save the code to execute it. Ube Meee
seer Shek
Debug
Opens
Window
Hele
Pysbce 2.7.0 (v4.7.0:abEtce4089, dua 2? 2010, O810G:47) [MSC ¥eibIN aT Bat (inte
*
34)
oa wanda Type “copyeagnes,
“aredicer
ox
*iscenses)" fox
moze
antoruatacn.
pane
has", count, “Letters an
st")
phen AESTART: Ci/zytbc0.
Enter your auroame: Maywara Your name bag
7
ertera
4m
at,
>>>
A function takes data, usually a variable, works on it depending on what the function is programmed to do, and returns the end value. The data being worked on goes inside the brackets, so if you wanted to know how many letters are in the word antidisestablishmentarianism, then you'd enter:
Python has tens of functions built into it, far too many to get into in the limited space available here.
STEP 4
STEP 2
However, to view the list of built-in Functions available to Python 3, navigate to
https://docs.python.org/3/library/Functions.html. These are the pre-defined Functions, but since users have created many more, they're not the only ones available.
LenC“antidisestabLishmentarianism”), and the number 28 would return. [& File
-
Python 3.7.0 shell Edit
Shell
Debug
Options
Window
len(*antidisestablishmentarianism")
28
x
File
Help
Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)) on win32 'Type "copyright", "credits" or "license()" for more information. >>>
L& Python
G
(Inte
*
Edit
-
3.7.0 Shell
Shell
Debug
Options
Window
Python 3.7.0 (v3.7.0:lb9cc5093, 1)] on win32 Type >>> 28 >>>
“copyright”, "credits" or "license()" for len ("antidisestablishmentarianism”)
more
information.
RESTART: C:/Python Code/NameCount .py Enter your surname: Hayward Your name has 7 letters in it. >>> import math >>>
>>>
www.bdmpublications.com
oO
_ Hel Jun 27 2018, 04:06:47) [MSC v.1914 32 bit
x (Inte
dh>
Creating Functions
3 =o)
Additional Functions can be added to Python through modules. Python has a vast range of modules available that can cover numerous programming duties. They add functions and can be imported as and when required. For example, to use advnced Mathematics Functions enter:
a module, enter the name of the module, Followed by a Full stop, then the name of the Function. For instance, using the math module, since we've just imported it into Python, we can utilise the square root Function. To do so, enter:
import math
math. sqrtC16)
Once entered, you'll have access to all the Math module Functions.
As you can see, the code
A
Piren
«cops
362+
the
yon Samsara Leary
[B
+
Fite
2. Built-in Functions n
8
The Python mierpreter has.
number of funchons and types
butt imo
thet are
sways avaiable they are isted here
eiphebercal
ordor
Prthen Edit
2
7.3
To use a Function from
is
presented as module.function(data).
-
Snell
Shell
Debug
Options
Window
Python 3.7.0 (v3.7.G:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.i914 32 bit 1)] on win32 Type "copyright", "credits" or "license()" for more information. >>>
x
oO
Help
(Inte
len("antidisestablishmentarianism”)
28
>>>
RESTART: C:/Python Code/NameCount.py surname: Hayward Your name has 7 letters in it. >>> import math >>> math. sqrt (16)
Enter your
4.0
>>>
FORGING FUNCTIONS There are many different functions, created by other Python programmers, which you can import and you'll undoubtedly come across some excellent examples in the future. However, you can also create your own with the def command.
STEP
Choose File > New File to enter the editor, let's create a Function called Hello that will greet a
1
HeLlLloQ):
print
To modify it Further, delete the Hello(“David”) line, the last line in the script, and press Ctrl+S to save
the new script. Close the Editor and create a new file (File File). Enter the following:
user. Enter: def
STEP 3
rom HeLLo
C“HeLLlo
>
New
import HeLLoj
Hei lLoC*“David Press F5 to save and run the script. You'll see Hello in the Shell, type in Hello() and it’ll return the new Function.
STEP det
2
Let’s now expand the Function to accept a variable, the user's name for example. Edit your script to read:
HelLoCname):
print C“Hello”,
name)
Press F5 to save and execute the code.
What you've just done is import the Hello function From the saved Hello.py program, and then used it 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:
STEP 4
def add(a, This will now accept the variable name, otherwise it will print Hello David. In the Shell, enter: name=(“Bob”), then, Hello(name). Your function can now pass variables through it.
b)
return result Debug
Optent
Windom
key
Hep
eats
www.bdmpublications.com
BD
Conditions and 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 countdown. a
TRUE CONDITIONS Keeping conditions simple, to begin with, makes learning to program checking if something is TRUE, then doing something else if it isn’t. a new Python program that will ask the user to input a word, then check it to see if it’s a four-letter word or not. Start with File > New File, and begin with
STEP
Let’s create
1
the input variable:
word=input(“Please enter a four-letter word: Run 7
my twee scopyzignt®,
+
*credite™
BeeS098, dun 27 2010,
O4r06ra7) HEC
32
Bie Cince
_Opbent
Lense enter «
Window
Help
word:
enjoyable experience. Let’s start then by
Now we'll use an if statement to check if the word_ length variable is equal to Four, and print a Friendly
STEP 3
conformation if it applies to the rule: a four-letter word: “) word_lLength=Len(word) if word_Length == 4: print (word, “is a four-letter word. Well done.”)
word=input(“Please enter
“)
four-letter
a more
=P
or "1icensei)* for gore information.
The double equal sign (==) check if something something else. (& File
is
equal to
*Untitled*
Edit
Format
Run
Options
Window
Help
word=input ("Please enter a four-letter word: ") word_length=Len (word) if word_iength == 4: print (word, "is a four-letter word. Well done.*)
Now we can create a new variable, then use the len function and pass the word variable through it to get the total number of letters the user has just entered:
word=input(“Please enter
a
four-letter
word:
“)
word=input(“Please enter
word_Length=Len(word)
-
([@ “Untitled File
Edit
Format
Run
Options
Window
Help
word=input ("Please enter a four-letter word: ,word_length=len {word}
oO
The colon at the end of if tells Python that if this statement is true, do everything after the colon that’s indented. Next, move the cursor back to the beginning of the Editor:
STEP 4
x
word_lLength=Len(word) if word_Length == 4:
print
")}
Cword,
“is
a
a
four-letter
four-letter
word. Well
done.”
else: print (word, “is not
a
four-letter word.”)
[® *Untitied* File
Edit
Formet
Run
Options
Window
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
word:
“)
(Conditions
Press F5 and save the code to execute it. Enter
four-letter word in the Shell to begin with, you should have the returned message that the word is four letters. Now press F5 again, and re-run the program, but this time, enter a five-letter word. The Shell will display that it’s not a four-letter word. a
La
Pinon She
-
a
*
ee"
ox
wn 2° av18, 08 V6 47)
"higense
ty"
Pythan Word
IMEC V
Now expand the code to include other conditions. Eventually, it could become quite complex. We've added a condition for three-letter words:
word=inputC“Please enter a four-letter word: word_Length=Len(word) if word_Length == print (word, “is a four-letter word. Well
“)
4:
4:20
eoths,
and Loops
PLS 4a Ede (inte
for mare iaformariea,
done.”
Cose/vorsyane FY
elif
word_Length
3:
==
print (word, “is a three-letter word. Try again.”) else: print (word, “is not a four-Letter word.”)
eytnae Code/worsgame. EY reost
nay (en
oat
ok
vrimtecenoea, sun
2
2968
aaeaer47y
WHE
Lene a2 DAE
(tate
cave armen
Lie ae
ele ctrrer
abr on vanv2
tre
wereaats™
of
“License.” for
Tob
ae
more
antomerion.
ragame
LOOPS Although a loop looks quite similar to a condition, they are somewhat different in their operation. A loop wilt run through the same block of code a number of times, usually with the support of a condition.
STEP
(W-egcesse-
1
Tea Blan LC
ay
|
mies] eo) on
oe
this will check to see if something is TRUE, then run the indented code:
The For loop, is another example. For is used to loop over a range of data, usually a list stored as variables inside square brackets. For example:
STEP 3
“Dog
ords=| “Cat”,
for
word in words
OE
Famat
Bia
cptene
‘Unicorn
TL
mst
tree
and
x=L
The difference between if and while is that when while gets to the end of the indented code, it goes back and checks the statement is still true. In our example x is less than 10. With each loop, it prints the current value of x, then adds one to that value. When x does eventually equal 10 it'll stop.
STEP 2
STEP 4
The For loop can also be used in the countdown example by using the range Function:
The x=x+1 part isn’t needed here, because the range Function creates a list between the first and last numbers used.
www.bdmpublications.com
BD
Python Modules We've mentioned modules previously, using the Math module as an example, but since using modules is such a large part of getting the most from Python it’s worth dedicating a little more time to them.
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.
a to
Although good, the built-in Functions within Python are limited. The use of modules, however, allows us to make more sophisticated programs. As you are aware, modules are Python scripts that are imported, such as import math. L& Python File
Edit
3.7.0
=
Shelt
Shell
Debug
Options
Window
o
x
The result is an error in the IDLE Shell, as the Pygame module isn’t recognised or installed in Python. To install module we can use PIP (Pip Installs Packages). Close down the IDLE Shell and drop into command prompt or Terminal session. At an elevated admin command prompt, enter:
STEP 3
a
a
pip
Help
Python 3.7.0 (v3.7.0:ibf$cc$093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)] on win32 Type "copyright", "credits" or "license()" for more information.
install
>>> ampert math >>>
ip install pygame
|
5
Some modules, especially on the Raspberry Pi, are included by default; the Math module is a prime example. Sadly, other modules aren't always available. A good example on non-Pi platforms is the Pygame module, which contains many Functions to help create games. Try: import pygame. L& Python
3.7.0
File
Shel!
Edit
-
Shell
Debug
Options
Window
a
STEP 4 Start with
a search for CMD, via the Start button, right-click the result, and then click Run as Administrator. Linux and Mac users can use the Sudo command, with sudo pip install package.
(Inte
pokes teha eee areola Rca Peele Lee Ee ete Kc} 2017 Microsoft Corporation. All
math
WINDOWS
pygame
Traceback (most recent call last): File "", line 1, in import pygame ModuleNotFoundError: No module named 'pygame’ P>>
\system32>pip install
cE gs
rights reserved.
pygame
al Meha1L Id
Using cached pygame-1.9.3-cp36-cp36m-win32.whl
installing cellected packages: pygame Successfully installed pygame-1.9.3 >
www.bdmpublications.com
The PIP installation requires an elevated status due to it installing components at different locations.
x
Help
Python 3.7.0 (v3.7.0:ibf9ccS093, Jun 27 2018, 04:06:47) (MSC v.1914 32 bit 1)] on win32 Type "copyright", "credits" or "license{)* for more information. >>> im P>> Lm
pygame
(Inte
\WINDOWS
\system32>
dh>
Python Modules
STEP
Close the command prompt or Terminal, and relaunch the IDLE Shell. When you now enter import
5
pygame, the module will be imported into the code without any problems. You'll Find that most code downloaded, or copied, from the Internet will contain a module, mainstream or unique, and their absence is commonly the source of errors
in
execution.
_
GB Python 3.7.0 Shelt Edit
File
x
oO
Shell_Cebu
Python 3.7.0 {v3.7.0:1bf9ccS0S3, Jun 27 2018, 04:06:47) (MSC v.1914 32 bit on win32 Type "copyright", "credits" or "license()" for more information. >>> import pygame
(Inte
1))
yas:
import random import math
for I in range(5): printCrandom.randint(1, 25))
printCmath. pi) [@ File
pygame 1.9.4 Hello from the pygame community. https://www.pygame.org/contribute.html
Multiple modules can be imported within your code. To extend our example, use:
*md
-
Code/md number.py (3.7.0)* number py - C:/Python
Edit
Format
Run
Options
Window
oOo
xX
Help
import random import math
>>>
for
4 in range (5): print (random. randint (1, 25))
|prant (math.pi)|
The modules contain the extra code needed to achieve a certain result within your own code, with which we've previously experimented. For example:
import random Brings in the code from the Random number generator module. We can then use this module to create something like:
The result is a string of random numbers followed by the value of Pi, as pulled From the math
STEP 9
module using the print(math.pi) Function. You can also pull in certain Functions From a module by using the From and import commands, such as:
from random import randint
for i in range(5): printCrandint(1, 25))
for i in range(1@): printCrandom.randint(1, 25))
C& ‘rnd number.py C:/Python Codesrnd
File Edit
File
Format
Run
Options
Window
Help
2 in range
(10):
for
print (random. randint (1, 25})
This code, when saved and executed, will display ten random numbers From 1 to 25. You can play around
-
2
3.7
Surll
Shak
Debug
Opmant
Wandin
number py (3.7.0)*
Window
Help
i in range (5): print (randint (1, 25)}
This helps create a more streamlined approach to programming. You can also use: import module’,
STEP 10
import math as
for i in range(25): printCrandom.randint(1, 100) Fa
Options
nonetheless. Finally, modules can be imported as aliases:
import random
sinan
Run
which will import everything defined within the named module. However, it’s often regarded as a waste of resources, but it works
with the code to display more or less, and from a greater or lesser range. For example:
Fie
Format
from random import randint
import random
for
Edit
ou
m
print(m. pt) ebony
BB
Mel
Format
Spare 4
Of course, adding comments helps to tell others what's going on.
Paden
Dythan Run Upton
Window
Help
Fandom
canget261:
an (randem.randint Prine (1, 100))
[& File
“ma number.py
-
Edit
Format
import math as
Python Code/md number.py (3,7.0)" Run
Options
Window
Help
m
print (m.pi}
www.bdmpublications.com
BD
Python Errors It goes without saying that you'll eventually come across an error in your code, where
Python will declare 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, they're perfectly normal and 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.
a to
Code isn’t as fluid as the written word, no matter how good the programming language is. Python is
Thankfully Python is helpful when it comes to displaying error messages. When you receive an error in red ink from the IDLE Shell, it will define the error itself, along with the line number where the error has occurred. While in the IDLE Editor this is a little daunting For lots of code, text editors =i
certainly easier than most languages, but even it is prone to some annoying bugs. The most common are typos by the user, and while easy to find in simple dozen-line code, imagine having to debug multi-thousand line code.
aie
help by including line numbering.
qo
Oo
>> apples=10 >>> pirnt (apples} Traceback (most recent
27 2018,
"license(}" for
call last): File "", lane 1, in pirnt (apples) NameError: name ‘pirnt’ is not defined >>>
|
www.bdmpublications.com
a
x
Help
04:06:47) more
[MSC
v.1914 32 bit
information.
Syntax errors are probably the second most common errors you'll come across as a programmer. Even if the spelling is correct, the actual command itself is wrong. In Python 3 this often occurs when Python 2 syntaxes are applied. The
most annoying of these is the print Function. In Python 3, we use print(“words”), whereas Python2 uses print “words”. LB
(Inte
-
Python 3.7.0 Shell Edit
File
Shell
Debug
Options
Window
Python 3.7.0 (v3.7.0:lbfSccS093, Jun 27 2018, 04:06:47} [MSC v.1914 32 bit 1)] on win32 Type “copyright", "credits" or “license()" for more information. >>>
print"Hello world!§f
SyntaxError: invalid syntax >o>
|
ox
Help
(Inte
~
Conoo QE Pesky brackets are also a culprit of programming errors, especially when you have something like:
An excellent way to check your code step-by-step is to use Python Tutor’s Visualise web page, Found at
STEP 8
printCbaLanced_checkCinput()))
www.pythontutor.com/visualize.html#mode=edit. Simply paste your code into the editor and click the Visualise Execution button to
Remember that For every ‘(’ there must be an equal number of ‘)’.
run the code line-by-line. This help to clear bugs, and any
misunderstandings. 1
import sys
2
3edef balanced _check(data): 4 stack = []
characters = list(data)
5 6
for character in characters:
Te
reference = {
By 9
18 12 bs
if
13
character in reference. keys(): stack.append({ character}
14
15
ew ‘Tht
17
elif character in reference.values{) and Len(stack) > 6: char = stack.pop{)
18 19 20
else:
lis»
if
reference.get(char) return
1=
ster
one brung
ope
character:
"NO”
There are thousands of online Python resources, code snippets, and lengthy discussions across forums on how best to achieve something. While 99% of it is good code, don’t always be lured into copying and pasting random code into your editor. More often than not, it won't work and frustratingly, you won't have learned anything. oS
n~
cc Se edtaboo
Planning makes for good code. While a little old school, it’s good habit to plan what your code will do before sitting down to type it out. List the variables that will be
STEP 9
a
used, along with the modules, and write out a script for any user interaction or outputs.
You have a bare except clause; Le., try:
8
some
code()
except:
Vv
lean_vp() The problem with a bare except is that it will catch aif exceptions, including ones you really don’t want to be ignoring (like Keyboardincerrupt and SystemExid, It would be much beer 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 tine 200, yo
ave
Ay
this construction:
tor letter in range(len(chacen_word)}= Sf playcr_guess chosen_word[letter]: word quessed[letter] - player guess You're looping over the index variable, but also using the list elernent. It would be write:
for idx, letter in 4f player_guess
better to
enumerate (chosen_word)+ python CalcPi.py
enter the number of decimal places to calculate Pi to: 1600 =. 1415926535897 34207 66845359157829834676223326091570659889414549873766620940165910806611
34746868975779816037965556 013459959351 328617317661598 28082231 080441 973785312530S651521157470859338317744154596822745276277128465914181 337399225 3578411298808837824212679468963352921667694 151593493095842692658808012769960614706621700375020601 734423451! 3366196887 424309303278687 75560407147 230694 29813445 787466657 726444985596 298919860559636358984008947 138101161111956856848 705962579) 7 35 3987587601397 3328584999652664211902004 58889 344 '87255026356827 24402886 3568884 3735288982 506842338309905 740013758327 7017 849088913229585 2797 366101 31695950194 125393941465 384836 3666504 22641543877733760177071691424287443797178326263 307 3721044852592 24231626745266695227915782 3643188349561 7664885 226@7702179621858051987411481289519686123157537061674294211 272325228479818691718486735
www.bdmpublications.com
www.bdmpublications.com
Manipulating Data
Data is everything. gold or oil, and with it, you can elect presidents or topple governments, p
Find out the.secrets of the universe rod
y=
[CoM
aac
ey
a:
power, so, to get the most from code, you'll need to kno#fiow to
vollit use
and how to: manipulate it.
This section will introduce you to
bere ability to cope with data
.
and how it can be organised in your’ code. We look at how graphics.are
created and how to read and write data from other sources@nd oygput to
external files.
www.bdmpublications.com
Manipulating 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, which 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.
a
list is sequence of data values called items. You create the name of your list Followed by an equal
A
a
You can also access, or index, the last item in a list by using the minus sign before the item number [-1], or
oe
=f
sign, then square brackets and the items separated by commas; note that strings use quotes:
the second to last item with [-2], and so on. Trying to reference an item that isn’t in the list, such as [10] will return an error:
numbers = [1, 4, 7, 21, 98, 156] mythical_creatures - [“Unicorn”, “Balrog”, “Vampire”, “Dragon”, “Minotaur”]
mythical_creatures[-4]
GB
-
Python 3:70 Shall
File
Edit
Shell
Debug
numbers[-1]
Options
Window
Help
Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte Python 3.7.0 (v3.7.0:1b9cc5093, 1)] on win32 Type "copyright", "credits" or "License(}" for more information. >>> numbers = [{1, 4, 7, 21, 98, 156] = [{"Unicozn", "Balrog", "Vampire", "Dragon", "Minotaur" >>> >>>
-
G& Python 3.7.0 Shell
x
a
File
Shell
Debug
Gptions
Window
da
x
Help
Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte Python 3.7.0 (v3.7.0:lb9cc5093, 2)] on win32 Type "copyright", "credits" or "License(}" for more information. >>> numbers = (1, 4, 7, 22, 98, 156] = {"Unicorn", "Balrog", "Vampire", "Dragon", "Minotaur"] >>> mythical creatures >>> numbers
(1, 4, 7, 23, 98, 156] >>> 21 >>>
promica_crearures
Edit
numbers [3]
mythical_creatures [*Unicorn', *"Balrog', ‘Vampire’, ‘Dragon’, ‘Minotaur'}
>>> mythical_creatures{3] "Dragon" >>> numbers{-1] 156 >>> mnumbers{-2] 98
>>>
mythical creatures{-1j ‘Minotaur!
>>>
mythical creatures{-4}
‘Balrog’ >>>
Once you've defined your list, you can call each by referencing its name Followed by a number. Lists start the first item entry as 0, followed by 1, 2, 3, and so on.
Slicing is similar to indexing, but you can retrieve multiple items in a list by separating item numbers with a colon. For example:
STEP 2
For example:
numbers[1:3]
numbers
Will output 4 and 7, those being item numbers 1 and 2. Note that the returned values don’t include the second index position (as you would numbers[1:3] to return 4, 7 and 21).
To call up the entire contents of the list.
numbers[3]
21
To call the item third from zero in the list (21 in this case). [& File
-
Python 3.7.6 Shelt Edit
Shell
Debug
>>>
Options
Window
a
(Inte
on win.
\Type "copyright", “credits™ or “license()" for more information. >>> numbers = [1, 4, 7, 21, 98, 156] >>> mythical_creatures = ["Unicorn", "Balrog", "Vampire", "Dragon", "Minotaur") >>> numbers
(1, 4, 7, 21, 98, 156) >>> numbers[3) 121
>>>
mythical_creatures
[‘Unicorn', *Balrog', 'Vampire', ‘Dragon’, 'Minotaur'] >>> mythical_creatures[3} *Dragon" >>>
>>>
mythical _creatures[3}
"Dragon!
>>> numbers[-1]
Help
Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1
mythical creatures
(‘Unicorn', "Balrog', 'Vampire', 'Dragon', 'Minotaur’]
x
1sé
>>> numbers
mythical_creatures[-1]
*Minotaur' >>>
mythical _creatures[-4] "Balrog’
>>> mumbers[1: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
[-2]
98
>>>
Lists
STEP
You can update items within an existing list, remove items, and even join lists together. For example, to
5
everything =
numbers +
functions, for example, insert and pop are used to add, and remove, items at certain positions:
mythical_creatures
numbers.insert(4, 62)
Then view the combined list with:
Inserts the number 62 at item index 4. And:
everything [&
-
Python 3.7.0 Shen
File
Edit
Shell
Window
Options
Debug
o
ll,
4, 7, 21, 98, 156, ‘Unicorn’,
.pop(4)
Will remove it.
Help
mythical creatures
everything
numbers
x
Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte 1)7 on win32 Type "copyright", “credits” or “license()" for more information. >>> numbers = [1, 4, 7, 21, 98, 156] >>> mythical_creatures = [*Unicorn”, "Balrog", "Vampire", "Dragon", "Minotaur") >>> everything = numbers + >>>
You can view what can be done with lists by entering dir(list) into the Shell. The output is the available
STEP 8
join two lists we can use:
'Balrog', ‘Vampire’, 'Dragon', 'Minotaur’]
>>>
«
'_repr_', ‘_xeversed_', '_xmul_', '__setattr_'
educe_', '_reduce_ex_',
‘_setitem_’*, '_sizeof_', '_str_', '__subclasshook_'‘, ‘append’, ‘clear’, ‘copy’, 'count', "extend", ‘index', ‘insert’, ‘pop’, 'remove', 'reverse', ‘sort |
,
>>> numbers = >>> numbers
1,
[1, 4, 7, 21, 98, 156]
4, 7, 21, 98, 186}
>>> numbers.insert 62) (4, >>> numbers (1, 4, 7, 21, 62, 98, 156} >>> numbers. pop (4) 62
>>> numbers Ol, 4, 7, 21, 98, 186) >>> |
STEP6
Items can be added to a list by entering:
numbers=numbers+[2@1]
You also use the list Function to break a string down into its components. For example:
iyeeiskemm
LlistC“David”)
Or For strings:
mythical_creatres=mythical_creatures+[“Griffin”] Or by using the append function:
Breaks the name David into D, a, a new list:
v,
|,
d.
This can then be passed
to
name=ListC“David Hayward”)
mythical_creatures.append(“Nessie”)
name
numbers .append(278)
age=[44] user = user
>>> numbers fl, 4, 7, 21, 98, 156} >>> creatures
name + age
mythical
{'Unicorn’, “Balrog', 'Vampire', 'Dragon', 'Minotaur'}
Python 3.7.0 (v3.7.0:1bfScc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)] on win32 Type “copyright”, “credits"™ or “license()” for more information.
>>> numbers=numbers+ {201} >>> numbers {l, 4, 7, 21, 98, 156, 261] >>> mythical _creatures-mythical_creatures+["Griffin™] >>> _creatures
>>> list
{'Unicorn', ‘Balrog', 'Vampire', 'Dragon', ‘Minotaur', 'Griffin'} mythical_creatures. append ("Nessie") mythical creatures ('Unicorn', ‘Balrog', 'Vampize', 'Dragon', 'Minotaur', 'Griffin', 'Nessie']
>>> >>>
>>> numbers. append (278) >>> numbers
|
the item number:
del numbers[7] The second, by item name:
mythical_creatures. remove(“Nessie”) >>>
',
THY,
8,
He, Fat, tyt, tet, fat, txt, fat,
fat, tyt, twt, tat, txt, td'y
"dt,
°a%,
*
467
STEP 10
Based on that, we can create a program to store someone's name and age as a list:
name=inputC“What’s your name? “) Lname=ListCname) age=intCinputC“How old are you: “)) lLage=[age]
The combined name and age list is called user, which can be called by entering user into the Shell. Experiment and see what you can do.
Ui, 4, 7, 21, 98, 156, 201] >>> >>>
'Griffin'] 'Griffin', ‘Nessie'}
>>> numbers. append (278) >>> numbers
[l,
'
user = Lname + lage
mythical_creatures
[’Unicorn', Balrog’, *Vampire', ‘Dragon’, ‘*Minotaur'] >>> numbers=numbers+[201] >>> numbers
mythical_creaturea=mythical_creaturest["Griffin"] mythical creatures (VUnicorn’, ‘Balrog’, ‘Vampire’, ‘Dragon’, ‘Minotaur', >>> mythical append ("Nessie") >>> mythical_creatures {*Unicorn', “Balrog', ‘Vampire’, 'Dragon', ‘Minotaur',
U'D', tat, tw', Tat, "at, >>> age=[46] >>> user = name + age >>> user >>>
Removal of items can be done in two ways. The first is by
>>> name=List ("David Hayward") >>> name
[°D', tat, ‘wt,
4, 7, 21, 98, 156, 261, 278}
|
("David")
['D', ‘at, tw, ‘at, tat]
mythical
{l,
(Inte
4, 7, 21, 98, 156, 201, 278]
>>> del numbers {7] >>> numbers
172
{Bb
Pytnen
Fle
Fae
Stell
-
Soe Debug
Optiont
Window
ou
Fle
Help
Python 3.7.0 (v3.7.01ibéscesos3, Jum 27 2018, O4:06:47) [MSC v.1914 32 Bir (Inte 321 on wink? Type ‘copyright™, “credita™ or "license ()" for more information. De
RESTART: C:\Users\david\Documents\Python\ from your nape? Conan of Cimmerse flow old are yout 44 33> user cao tate ente tete Ht
tan
Git
Fermiat
Run
Option
Wandow
~
agening (input
("Mow
eld are you: *))
ages tage!
Pi\camelist py
user = inane + lage
ay
441
(ll, 4, 7, 21, 98, 156, 201] >>> mythical creatures. remove ("Nessie") >>> mythical_creatures {*'Unicorn', ‘Balrog’, ‘Vampire’, ‘Dragon’, 'Minotaur', ‘Griffin'] >>>
www.bdmpublications.com
Manipulating Data
Tuples Tuples are virtually 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 it’s perfect For storing Fixed data items.
THE IMMUTABLE TUPLE Reasons for having tuples vary depending on what the program is intended to do. Mostly a tuple is reserved For something special, but they're also used, as an example, in an adventure game where non-playing character names are stored.
STEP
A tuple
is created the same way as a list, but in this instance you use curved brackets instead of square
1
oy =f
tuple called NPC (Non-Playable Characters) containing the character name, and their combat rating, for an adventure game:
brackets. For example:
months=C“January”, “February”, “March”, “May” , months
Edit
“April”,
“June”)
NPC=[(“Conan”, 108),
Shell
C“Belit”, 80), C“Valeria”,
95)]
-
Python 3.7.0 Shell
[& File
You can create grouped tuples into lists that contain multiple sets of data. For instance, here we have a
one
Debug
Options
Window
a
x
Python 3.7.0 (v3.7.0:1lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1))] om win32 Type “copyright”, "credita™ or "License(}" for more information. >>> months=("January", "February", "March", “April*, “May”, "June™)
(Inte
>>> months
-
Python 3.7.6 Shell
[®
Edit
File
Help
Shelt
Debug
Options
Window
x
oO
Help
Python 3.7.0 {v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.19i4 32 bit 1)} on win32 Type "copyright", "credits" or “license()" for more information. >>> NPC=[("Conan", 100), ("Belit™, 80), ("Valeria"™, 95)]
(Inte
>>>
('danvary', ‘February’, ‘March’, ‘Apxil', 'May', ‘dJune’) >>>
As with lists, the items within a named tuple can be indexed according to their position in the data range:
STEP 2 months[@] months [5]
File
-
Python 3.7.0 Sheil
Edit
Shelt
Debug
Options
Window
x
('danuary', ‘February’, 'March', ‘April’, ‘May’, ‘dune')
>>> months [0]
‘January’
(Inte
‘June!
Edit
Shel)
Debug
("July")
months. append ("July")
‘tuple’ object
‘>>> NPC=({"Conan", >>> NPC
{(*Conan', 160), >>> NPC[O)
>>>
www.bdmpublications.com
has no attribute
‘append’
Options
Window
a
x
Help
Python 3.7.0 (v3.7.0:1lbf9cec5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 11)) on win32 ‘Type "copyright", "credits" or "license()™ for more information.
10
months. append
Traceback (most recent call last): File "", line 1, in
-
Python 3.7.0 Shell
(*Conan', 100) >>> NPC[O} (1)
>>> months [5]
>>>
Will display 100.
File
>>> months
AttributeError:
whole
NPC[@] [1]
[&
Oo
Help
Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)] on win32 Type "copyright", "credits" or "license()" for more information. >>> months=("January", "February", “March”, “April, “May*, “June™)
>>>
a
by entering NPC into the Shell, or they can be indexed according to their position NPC[0]. You can also index the
individual tuples within the NPC list:
And so on. However, any attempt at deleting, or adding, to the tuple will result in an error in the Shell. (&
Each of these data items can be accessed as
STEP 4
100), (*Belit®, 80), ("Valeria", 95)]
(‘Belit', 80), (*Valeria’,
95)}
bit (inte
It’s worth noting that when referencing multiple tuples within a list, the indexing is slightly different
from the norm. You would expect the 95 combat rating of the character Valeria to be NPC[4][5], however it’s not, it’s actually:
Cname,
3.7.0 Shell
File
Shell
Edit
Debug
Options
Window
a
[&
x
Edit
Shell
Debug
on win32z
‘Conan' >>> combat_rating 100 >>>
This means, of course, that the indexing Follows thus:
1,1
@,1
from the end of the data list. So, For our example, using the tuple with multiple data items, we would reference the Valeria character with:
2, 0 2,1
?
1
1, @
x
o
Help
Remember, as with lists, you can also index tuples using negative numbers, which count backwards
STEP 9
2
@
Window
>>> name
95
>>>
2,
Options
Python 3.7.0 (v3.7.0:1bf9ec5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte 1)] on win32 Type “copyright”, "credits” or “License()” for more information. >>> NPC={"Conan*, 100) >>> (name, combat_rating)=NFC
(Inte
Type "copyright", "credits" ox "license()" for more information. >>> NBC=[("Conan™, 100), ("Belit™, 80), ("Valeria", 95)]} >>> NPC(2) [1]
Q
-
Python 3.7.0 Shell
File
Help
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1934 32 bit
1))
combat_rating)=NPC
You can now check the values by entering name and combat_rating.
NPC[2] [1] L& Python
Now unpack the tuple into two c orresponding variables:
STEP 8
NPC[2][-@] [&
This, as you can imagine, gets a little confusing when you have a lot of tuple data to deal with.
-
Python 2.7.0 Shell Edit
File
Shell
Debug
Options
Window
Python 3.7.0 (v3.7.0:lbf9ccS093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit on win32 Type “copyright™, “credits” or “license(}" for more information.
1)]
>>> NPC(Oj[0}
"Conan’
|
>>> RPC=[("Conan", 100), >>> NEC(2] {-0}
x
a
Help
(Inte
{"Belit", 60), ("Valeria™, 95)]
"Valeria'
>>> NPC(O) [1] 106 >>> NPC(11 ("Belit', 80) >>> NPC{1J[0}
>>>
"Belit'
>>> NPC[1)(1} 80
>>> NPC(2}
('Valeria’, 35) >>> NPC[2} [0} ‘Valeria’
>>> NPC(2) [1] 95
>>>
Tuples though, utilise a Feature called unpacking, where the data items stored within a tuple are variables. First, create the tuple with two items (name and assigned combat rating):
STEP 10
STEP 7
highest and lowest values of a tuple composed of numbers. For example:
numbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99)
NPC=C“Conan”, 108) [& File
-
Python 3.7.0 Shell Edit
Shell
Debug
Options
Window
“credits™ or “license({)" for more information.
>>> NPC=("Conan", 100) >>>
The numbers can be integers and floats. To output the highest and lowest, use:
x
Help
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47} (MSC v.1914 32 bit
on wins2 |] Type "copyright",
a
(Inte
We can use the max and min Functions to find the
“
printC(maxCnumbers)) printCminCnumbers)) [B File
-
Python 3.7.9 Shell Edit
Shell
Debug
Options
Window
Qo
x
Help
Python 3.7.0 (v3.7.0: Ibf9$cec5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte 1)] on win32 Type "copyright", "credits" or "license(}" for more information. >>> numbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99) >>>
print (max (numbers) }
109.3 >>>
6.1
print (min (numbers) }
>>>
www.bdmpublications.com
|
>
Manipulating Data
Dictionaries Lists are extremely useful, but dictionaries in Python are by Far the more technical way of dealing with data items. Although they can be tricky to get to grips with at First, 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, but the Value can be any data item you like.
STEP
Let's say you want to create a phonebook in Python. You would create the dictionary name, and contain
1
the data in curly brackets, separating the key and value by Key: Value. For example:
a
As with lists and tuples, you can check the contents of a dictionary by calling the dictionary name; phonebook, in this example. This will display the data iterns you've entered in a similar Fashion to a list, which you're no doubt familiar with by now. =f
colon
phonebook={“Emma”: 1234, “Daniel”: 3456, “Hannah”: 6789}
[
-
Python 3.7.0 Shell Edit
File
Sheil
Debug
Options
Window
Fite oO
x
Help
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) (MSC v.1914 32 bit 1)] on win32 Type "copyright", "credits" or "license()" for more information. >>> phonebook={"Emma": 1234, "Daniel": 3456, "Hannah": 6789}
(Inte
>>>
'
a
Python 3.7.0 Shell Edit
Shell
Debug
Options
Window
x
Help
Python 3.7.0 (v3.7.0:1bf9cc5083, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)) on win32 Type "copyright", "credits™ or "license(}" for more information. >>> phonebook=("Emma": 1234, "Daniel": 3456, “Hannah”: 6789) >>> phonebook2={"David": "0987 654 321"} >>> phonebook {‘Emma': 1234, ‘Daniel’: 3456, 'Hannah': 6789)
(Inte
>>>
As with most lists, tuples, and so on, strings need to be enclosed in quotes (single or double), while integers can be left open. Remember that the value can be either a string, or an integer, you just need to enclose the relevant one in
[&
oe
quotes:
3.7.0
Shell
_
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 64:06:47) {MSC v.1914 32 bit 1)) on win32 Type "copyright", "credits" or "license()" for more information. >>> phonebook={"Emma": 1234, "Daniel": 3456, "Hannah": 6789} >>> phonebook2={“David' “O987 654 321%} >>> |
www.bdmpublications.com
phonebook[ “Emma” ]
phonebook[“Hannah”]
phonebook2={“David”: “0987 654 321”} [@ Python
The benefit of using a dictionary is that you can enter the key to index the value. Using the phonebook example From the previous steps, we can enter:
-
[Lm Python 3.7.8 Shell
o
x (Inte
Fite
Edit
Shell
Debug
Options
Window
Jun 27 2018, 04:06:47) [MSC v.1914 32 bit Python 3.7.0 (¥v3.7.0:lb9cc50S3, 1)) on win32 “credits” or Type "copyright", "license()" for more information. >>> phonebook=({"Emma": 1234, "Daniel": 3456, “Hannah”: 6789} >>> phonebook2={"David": "0587 654 321"} >>> phonebook {*Emma': 1234, ‘Daniel': >>> phonebook ["Emma”] 1234 >>> phonebook["Hannah"} 6785 >>>
o
x
Help
3456, 'Hannah': 6789}
(Inte
Dictionaries
STEP
Next, we need to define the user inputs and variables, one for the person’s name, the other for their phone number (we will keep it simple to avoid lengthy
Adding to a dictionary is easy too. You can include a new data item entry by adding the new key and
5
STEP 8
value items as such:
Python code):
phonebook[“David”] = “@987 654 321”
name=inputC“Enter name: “) number=intCinputC“Enter phone number:
phonebook
-
L& Python 3,7.0 Shell File
Edit
Shell
Window
Options
Debug
{’Emma’: 1234, "Daniel':
(} *Dictin.
Help
Python 3.7.0 (v3.7.0:ibfScec5083, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)] on win32 Type "copyright", “credits” or “license()" for more information. >>> phonebook=({"Enma": 1234, "Daniel": 3456, "Hannah": 6789} >>> phonebook2={"David": "0987 654 321") >>> phonebook
x
o
Format
Edit
File
-
david: Documents\Python\From Pi\Dictin.py (3.7.0)"
CAUsersi
-
py
(Inte
“))
Run
Options
Window
oOo
xX
_Help
[phonebook=t) name=input
name:
("Enter
number=int (input ("Enter
3456, ‘Hannah’: 6789}
") phone number:
*))
>>> phonebook[*Emma"] 1234 >>> phonebook ["Hannah"] 6789 >>> phonebook["David"] = "0987 654 321" >>> phonebook
ae
1234, "Daniel':
3456, 'Hannah': 6789, "David':
'0987 654 321'}
>>>
Note we've kept the number as an integer instead of astring, even though the value can be both an integer and a string. Now we need to add the user’s inputted variables to the newly created blank dictionary. Using the same process as in Step 5, we can enter:
And you can also remove items from a dictionary by issuing the del command followed by the
-
item's key the value will also be removed as well, since both work as a pair of data items:
del phonebook[“David”] [B
-
Python 3.7.0 Shell
File
Edit
Shell
Debug
Window
Options
a
phonebook[name] = number
x
Help
[LB Dictin.py
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)] on win32 Type “copyright”, "credits" or “license()" for more information. >>> phonebook={"Emma": 1234, "Daniel": 3456, "Hannah": 6789} >>> phonebook2={"David™: "0987 654 321") >>> phonebook {'Emma’: 1234, 'Daniel': 3456, *‘Hannah': 6789}
(Inte
File
-
C2.
Users\davidDocuments\Python\From Pi\Dictin.py (3.7.0)
Format
Edit
Run
Options
Window
Help
phonebook={}
") (input ("Enter phone number:
name=input ("Enter name:
™))
phonebook[name] = number
>>> phonebook{"Emma"]} 4
>>> 67839
phonebook {"Hannah"]
>>> phonebook["David"] = “0987 654 321" >>> phonebook
{'Emma’: 1234, 'Daniel': 3456, ‘Bannah': 6789, ‘David’:
>>> del phonebook{"David"] >>> phonebook
{'Emma’: 1234, 'Daniel':
‘0987 654 321'}
3456, *Hannah': 6789}
>>>
Taking this a step Further, how about creating a piece of code that will ask the user For the dictionary and value items? Create a new Editor instance, and start by key coding in a new, blank dictionary:
Now when we save and execute the code, Python will ask for name and a number. It will then insert those entries into the phonebook dictionary, which we can test by entering into the Shell:
phonebook={}
phonebook
[& File
-
Python 3.7.0 Shell Edit
Shell
Debug
Options
Window
(Inte
a
phonebook[“David”]
x
Help
Python 3.7.0 (v3.7.0:ibf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit |2)] on win32 Type “copyright”, “credits” or “license()™ for more information. >>>
a
STEP 10
«
IF the number needs to contain spaces you'll need to make it a string, so remove the int part of the input. LB File
phan
2)]
Bae
1
Lat then om
Shell
Debug
atte Uptions
Window
File_Fén format
tele.
3.7.0 (v4,7.011BESa86098, Jun 27 2018, 0470847) [HSC wanda
‘Type *copysight®,
“exedits”
or
>>>
“License (}"
seater,
Enter nane: David Enver phone number: 09676
for
more
information.
32 BLE
(Inte
“MM
Run
_Oppons
Window
namessnput("Entex namet
puabexangut{"kutex phone oumbes: *) phonebookinamel
(number
253 phonebook Chavsat: 9978) >oa 5876 phonebook ("Gavia")
ESTAR:
Eater mane: Bob Enter phone sunbers 0987 aoe
_Hedp!
phoachook()
$54 3221 9344
[40807 Got aaz2 s348e]7
www.bdmpublications.com
Manipulating Data
Splitting and oining 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 We'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(). ‘ With it, you're able to split apart a string of data,
STEP 1
based on the argument within the brackets. For example, here’s a string with three items, each separated by a space:
text="Daniel (Ge Python 3.7.0 File
Edit
Hannah Emma” =
Shell
Shell
Debug
Options
Window
Help
Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)] on win32 Type "copyright", “credits” or “license()" for more information. >>> text="Daniel >>>
*
oO
(Inte
Hannah Emma”
Note that the text.split part contains the brackets, quotes, then a space Followed by closing quotes and brackets. The space is the separator, indicating that each list item entry is separated by a space. Likewise, CSV (Comma Separated Value) content has a comma, so we would use:
STEP 3
February ,March, April ,May, June”
months=text.spLlitC%,”) months L&
Pether
File
-
27.2 Snell
Shell
Edit
Debug
Options
Window
x
oO
Help
Python 3.7.0 (v3.7.0:1bfScc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte 1)] on win32
“copyright”, “credits” or "license()”" for more information. >>> text="January, March, April, May, June” >>> months=text.split(",") >>> months
Type
('danuary’, 'February', ‘March’, *April', 'May', 'June'j
>>>
STEP2
We've previously seen how, using a name, we can split a string into individual letters as a list:
Now let’s turn the string into a list, and split the content accordingly:
names=text.splitc*
“)
name=ListC“David”) name
And enter the name of the new list, names, to see the three items. !
La File
|
a
Python 2.7.5 Shell Edit
Shell
Debug
Options
Window
x
Help
Python 3.7.0 (v3.7.0:lbfs9cc5093, dun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte 1)] on win32 Type "copyright", “credits” or "license()” for more information. >>> text="Daniel Hannah Emma® >>> names=text.split(" ") >>> names
["Daniel', 'Hannah', ‘Emma’ >>>
The returned value is ‘D’, ‘a’, ‘v’, ‘’, ‘d’. While it may seem a little useless under ordinary circumstances, it could be handy for creating a spelling game, for example. (& Python File
Edit
3.5.0
Debug
Options
Window
Python 3.7.0 (v3.7.0:1b9ccS0S3, 1)] on win32 Type "copyright", “credits” or >>> nameslist >>> name
("David")
('D, tat, tw,
>>>
www.bdmpublications.com
=
Shell
Shell
tae]
Bo
x
Help
Jun 27 2018, 04:06:47)
"license()" for
more
[MSC
v.1914 32 bit
information.
(inte
( The converse of the .split Function is join, where f separate items in a string, can join together to Form a word, orjust combination of items; depending on the program you're writing. For instance:
STEP 5
stop, or
a
alphabet=”” . joinc[“a” ; *b” ; oO” ; aq” ; a” alphabet
Edit
Shell
col Le
Options
Window
oF
Edit
(Inte
Shell
Debug
«
"a", "e*])
‘abcde’
>>>
form the name:
”.
together, and retained the list called
Ue
name, passing it through the join Function.
-
Shell
Debug
Options
Window
x
a
Edit
32
Shell
Debug
Options
Window
Python 3.7.0 (v3.7.0:1b9cc5093, 1)] on win32 Type "copyright", "credits" or
>>> title="conan the cimmerian”™ >>> title.capitalize() "Conan the cimmerian' >>> title.citle() ‘Conan The Cimmerian' >>>
Help
Python 3.7.0 (v3.7.0:lbf9ec5093, Jun 27 2018, 04:06:47) [MSC v.191 4)) on win32 Type "copyright", "credits™ or "License(}" for more information.
-
Python 3.7.0 Shell
Fife
Python 3.7.0 Shell Edit
There's some interesting functions you can apply to a string, such as .capitalize and .title. For example:
title. capitalized) title. titled
JoinCname)
We've joined the string back
File
Help
title=”"conan the cimmerian”
name
[&
Window
>>> text=" ".join(list) >>> text "Conan raised his mighty sword and struck the demon' >>> colours=["Red", "Green", “Blue"] >>> col=",".join (colours) >>> col "Red, Green, Blue! >>>
We can therefore apply join to the separated name we made in Step 4, combining the letters again to
name=”"
Options
Python 3.7.0 (v3.7.0:lbf9ccS093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel Type “copyright”, "credits" or "license()" for more information. >>> list=("Conan”, "raised", "his", "mighty", "sword", "and", "struck", "the", "d
xX
Help
Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) (MSC v.1914 32 bit 1)} on win32 Type "copyright", “credits” or “license()" for more information. >>> alphabet="".join(["a","b", "oc", >>> alphabet
Python 3.7.6 Shell
File
-
Debug
Full
ora
col=”,”.joinCcolours)
Python 3.7.0 Shell
File
have to be a space, it can also be a comma, hyphen, or whatever you like:
a
colours=[“Red”, “Green”, “Blue”]
])
This will display ‘abcde’ in the Shell. [&
and Joining Strings
4s with the split Function, the separator doesn’t
apalcesgee
!
>> namewlist ("David") >>> name
x
o
Help
Jun 27 2018, 04:06:47}
"license()" for
more
[MSC
v.1914 32 bit
(Inte
information.
UD, ta’, tv, "it, tay
>>> name="". (name) join >>> name
"David! >>>
A
a
A good example of using the join Function is when you have a list of words you want to combine into
STEP 10
sentence:
to check
List=[“Conan”, “raised”, “his”, “mighty”, “sword”, “and”, “struck”, “the”, “demon”] text=” “.join(list) text Note the space between the quotes before the .join Function (where there were no quotes in Step 6’s join). [& File
=
Python 3.7.5 shen Edit
Shell
Debug
Options
Window
Help
Python 3.7.0 (v3.7.0:4bf%ccS093, Jun 27 2018, 04:06:47) [MSC v.1914 32 Type “copyright®, “credits" or "license(}" for more information. >>> liste["Conan", "raised", "his", "mighty", “eword™, "and", 3>> terre" * join(tiat) >>> text ‘Conan raised his mighty svord ang struck the demon‘ >>>
bit (Intei)]
"struck", "the",
on win32
"demon™]
a
You can also use logic operators on strings, with the in and not in functions. These enable you
ifa string contains (or does not contain) a sequence
of characters:
message="Have a nice day” “nice” in message
in message “day” not in message “night” in message ”*bad” not
(&
Python
File
Edit
3.7.2
-
She
Shell
Debug
Options
Window
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) (MSC v.1914 32 bit 1)} on win32 Type “copyright”, "credits" ox "license()* for more information. >>> message="Have a nice day” >>> “"nice™
x
0
Help
(Inte
in
True >>> "bad" not in
True >>> "day" not in message
False >>> "night” False
in
message
www.bdmpublications.com
>
Manipulating Data
Formatting Strings As you work with data, creating lists, dictionaries, and objects you'll often want to print out the results. Merging strings with data is easy, especially with Python 3, as earlier versions of Pythons 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. This makes things easier to follow and, as with most coding, there are other ways to do things but this way is recommended.
a to
The basic Formatting in Python is to call each variable into the string using the curly brackets:
sy =f
number=10000
printC“{} of {} was a skilled mercenary, and thief too. He once stole {} gold from
name=”Conan”
is:
printC“The barbarian hero of the Hyborian Age {}”. format (name) Ge Python
3.7.0 Shell
File
Sheil
Edit
Debug
Options
Window
x
ad
string Formatting in a single print Function: ” 99
name="Conan
known as [&
Python
File
Edit
Debuq
Window
oa
Help
Python 3.7.0 (v3.7.0:lbfSec50$3, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type “copyright” "credits" or "license()* for more information. >>> name="Conan' >>> place="Cimmeria“ >>> print(*{} hailed from the North, in a cold land kmown as {}".format (name, place}) Conan hailed from the North, in a cold land known as Cimmeria >>>
Help
(intel))
on winsZ
There are many different ways to apply string formatting, some are quite simple, as we’ve shown you here, and others can be significantly more complex. It all depends on what you want from your program. A good place to reference frequently, regarding string Formatting, is the Python Docs webpage, found at https://docs.python.org/3.1/library/ string.html. Here, you will Find of help.
tons
cold land
Options
Window
STEP 4
gma tite
{}”.formatCname, place))
3.7.0 Sheil
Shell
a
Options
pro phint(*t) heiled f2um tbe Wurth, in a culd lend knuws aa place)) (1*.formet (name, Conan haaled from the North, in 2 cold land known as Cimmeria D3> numbere1ugv0 p> print{"{} of (} wea a akilled mercenary, and theif too. Me once atole {} gold from e merchanc.“. form place, number}) Conan of Cimmeria wan A Ski11e0 mercenary, ant cheif con. He nance arate 10000 gnid from a merchant.
{}".format (name})
in
Rehug
>>> name~*Conan* >>> placee*Cammeria*
Remember to close the print function with two sets of brackets, as you've encased the variable in one, and the print Function in another. You can include multiple cases of
from the North,
Shell
Hython 3.7.0 (v8.7. Uripfyeesuys, Jun 27 2018, U8:08r47) (HSC V.1N14 32 bat Type “copyriube", “credits” oz “License(Q)" fur more information.
(Inte
a0 =>
print(“{} hailed
Fait
File
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit L)] on win32 Type "copyright", "credits" or "license()" for more information.
place=”Cimmeria”
a
merchant.”.formatCname, place, number)
Help
>>> name="Conan”™ >>> print barbarian hero of the Hyborian Age is: ("The The barbarian hero of the Hyborian Age is: Conan >>>
We can, of course, also include integers into the mix:
oe
x
7.1.3. Format
a
Aneta
~
|
ae
an oncacnd deatng 14
cant
|
String Syntax
Theo
‘Th groan fro
oT
tees
~
11
Oy
eheeneera field obo a8
|
comsernce
Son
i,
z
!
fe
sem tre Forms Spectenanr
‘Tha ae fol_nams too ogra 0.7.2.
tart
eg we
wf
an 27g, 0are
iss
trans. (reges
www.bdmpublications.com
37
m
mmo
fat
Tho
Madarseige Seton.
Te peakine
scp
a's eto! aeofc) wcumbet
Dy
Co
pA
ening
Cane
NS a
a
of
ayRord
(el pat ser)
Ure
10°
8
wn
Bw
cambios tex postcnel wiguncal 2,
artery 0,1,
mide
a
25
and
iri
sheyword,
tel coc
doer nar sg_nae
Tha
kere De
apiront he rumercal
nad
By any
aa
of
tex
dna SATA
dh>
Formatting Strings
aaa)
Interestingly, you can reference a list using the string Formatting Function. You need to place an asterisk in front of the list name:
STEP
5
numbers=1, 3, 45, 567546, 3425346345 printC“Some numbers: {}, {}, {}, {},
Python3 7.0 Edit
File
printC“Hello {}.”.formatCname)
{}”.
Tile
Options
Window
2)]
x
oa
Help
Jun 27 2018, 04:06:47) (MSC v.1914 32 bit Python 3.7.0 (v3.7.0: 1lb9cc5093, 1)1 on win3z Type "copyright", “credits” or "License(}" for more information. >>> numbers*l, 3, 45, 567546, 3425346345
print ("Some
>>>
Some numbers:
numbers:
Shell
Uebug
Siptions
Fython 3.7.0 (v3.7.0:
-
Debug
Cart
-
sae
=o
Potnen
Ui
Shell
Shell
{}, {}, {}, {}, ()".format
1, 3, 45, 567546, 3425346345
(*numbers)
“)
name=inputC“What’s your name?
formatC*numbers)) [@&
You can print out the content of a user’s input in the same Fashion:
(Inte
>
on wind2
Window
1nESccsDea,
Tye “copyzight", “credics”
He
"License()” for
of
ons
Help
dun 27 2018, aai0bz47)
wore
FRSC
VISTA Sz
BoE
(inte
+
_Udd_Jermat
Run
Window
Options
Mel!
TAREeinput{-What’s your name? “) prant("Mello, ().*.fermac (aame))
information.
RESTART: C: Wnac's your name? David
Helle, Davia.
)
>>>
4S with indexing in lists, the same applies to calling a list using string Formatting. We can index each item according to its position (From 0 to however many are present):
And you can extend this simple code example to display the First letter in a person's entered name:
seexsge
numbers=1, 4, 7, printC“More numbers:
{3}, {@}, {2},
printC“The first Letter of your
-
Python 3.7.8 Shell Edit
Fite
Sheil
Debug
Options
Window
Python 3.7.0 (v3.7.0:1bf9cc5093, 1)] on win32 Type "copyright", "credits" or >>> numbers= 1, 4, 7, 9 >>> print ("More numbers: More numbers: 9, 1, 7, 4. >>>
x
a
Jun 27 2018, 04:06:47)
"license()" for
more
(3), {0}, {2}, (1}.".format
[MSC
v.1924 32 bit
(Inte
Lie
at
_eutere
And as you probably suspect, you can mix strings and integers in a single list to be called in the
“Belit”, “Valeria”,
print C“{@} is {3} years old. Whereas {1} years old.”.format(*characters))
faa
Help
€
You can also call upon a pair of lists, and reference them individually within the same print Function.
names=[“Conan”,
is {4}
Window
(Intel)]
“Belit”, “Valeria”]
Creating two lists. Now we can call each list, and individual items: Bo
Help
Python 3.7.0 (v3.7.0:1bf$cc5053, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit
printC“{@[0]} is {1[@]} years old. Whereas {0[1]} is {1[1]} years old.”.formatCnames, ages))
on
2
Type "copyright", "credits" or "license()™ 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. >>>
Window
ages=[25, 21, 22]
Options
Opbons
yt
your name
STEP 10
19, 27,
Python 3.7.0 Shell Debug
Run
Looking back at the code from Step 7, we can alter it with:
characters=[“Conan”,
Shell
Foompt
*hicease()™ for wore saforaation.
or
QESTART: C:.
20]
Edit
{Q}”.
Sinevs your maar? Cana
Format Function:
File
a
esranay €1 Gracy yout senet bovta
(*numbers))
felios conan, feet iecter of
[&
ep
Window
2)] on wind2 Tipe copyriaht®, "czeditat
information.
is
~
[Be rithen=
Help
name
formatC*Lname))
The
A
“)
Lname=ListCname)
{1}.”. formatC*numbers)) Gi
name=inputC“What’s your name?
printC“Hello {}.”.formatCname))
9
Lab Pethen
File
Fit.
270 Shell
=
Shell
Debig
Options
Window
a
Help
Python 3.7.0 (v3.7.0:1bf9ce5093, Jun 27 2018, 04:06:47) (MSC v.1914 32 bit ‘Type “copyright", “credits” or “license()" for more information. poo names=[“Conan", “Belic”, "Valezia®] >>> ages=[25, 21, 22) >>> Drink (FLO[N]} te C(O)) years old. wh - t0n yearn as Zo years old. whereas, Belat is Zs years old.
(Intel}]
on win32
format (names, ages))
[Sonam >>>
www.bdmpublications.com
Manipulating 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. Thankfully, acquiring the time and date is easy thanks to the Time module.
TIME LORDS The Time module contains Functions that help you retrieve the current system time, read the date from strings, format the time and date, and much more. First you need to import the Time module. It’s one that’s built-in to Python 3, so you shouldn’t need to
by entering:
drop into a command prompt and pip install it. Once it’s imported, we can call the current time and date with a simple command:
.
The output
Edit
Shell
Options
Window
‘time. struct_timeCtm_
to the time this book was written.
Help
Python 3.7.0 (v3.7.0:ibf9cc5033, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import time
(Inte
>>> time.asctime () "Thu Jun 20 09:51:18 2019' >>> +
displayed as such:
isdst=@)’; obviously dependent on your current time, as opposed
x
Debug
is
year=2019, tm_mon=9, tm_mday=7, tm_hour=9, tm_min=6, tm_sec=13, tm_wday=3, tm_yday=25@, tm_
Python 3:70 Shell
File
.
time. Local. timeQ)
import time time .asctime() Lb
You can see the structure of how time is presented
oe
=f
+
*
L& Python File
Edit
-
3.7.0 Shell
Shell
Debug
Options
Window
Python 3.7.0 (v3.7.0: 1bf9cc5093, 1))] on win32 Type "copyright", "credits" or >>> import time
|
x
oF
Help
Jun 27 2018, 04:06:47)
"license()" for
more
[MSC
v.1914 32 bit
(Inte
information.
>>>
time. localtime() time. struct_time(tm_year=2019, tm_mon=6, tm_mday=20, tm_hour=9, tm_min=52, tm_se tm_wday=3, tm_yday=17l, tm_iadst=1)
4 >>>
The time Function is split into nine tuples, these are divided up into indexed items, as with any other tuple, and shown in the screen shot below.
STEP 2
Index
Field
0
4-digit year
2016
1
Month
1to12
2
Day
1to 31
3
Hour
0 to 23
There are numerous Functions built into the Time module. One of the most common of these is sstrftime(). 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 we can use:
time. strftime( ‘%A’)
Values
Ge Python
3.7.0
File
Shell
|
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
8
Daylight savings
www.bdmpublications.com
to 366 (Julian day)
1, -1 means library determines
Debug
Options
time.strftime {'$A') ‘Thursday’
>>>
>>>
-1, 0,
Shett
Window
Help
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) {MSC v.1914 32 bit 1)) on win32 Type "copyright", "credits" or "license()" for more information. >>> import time
|
1
Edit
DST
(Inte
1}
Date and Time
STEP
We can also use the Time module to display the amount of time taken For an event to happen. For example, taking the above code, we can alter it slightly by including:
Naturally, this means you can incorporate various functions into your own code, such as:
5
STEP 8
|
ay
time. strftimeC“%a”) time. strftimeC“%B”) time. strftimeC“%b”) time. strftimeC“%H”) time. strftimeC*%H%M”>) L& Python
3.7.0 Shell
File
Sheil
Edit
start_time=time.time() And.
endtime=time.time()-start_time
Window
Options
Debug
x
logintime.py
«
Python\From
Window
Options
Pi\
vy
-
(3.7.0)
|
name:
")
time.strftime ("4B")
print ("\nWelcome",
tame. stxrftime ("*b")
print ("\nUser:", name, “logged in at", time.strftime ("%H:4M")) print ("It took", name, endtime, “seconds ko login to their account.*)
‘Jun!
("tH")
>>> time. stritime
os"
time. strftime ("$H$h")
x
ag
Help
import time
start_time=time.time(} login
‘June!
>>>
Run
endtime=time.time (}-start_time
‘The! >>>
CAUsers\davic\D
Format
name=input ("Enter
time.strftime ("ta")
>>>
Edit
File
(Inte
-
GB
Help
Jun 27 2018, 04:06:47) [MSC v1914 32 bit Python 3.7.0 (v3.7.0:1b9cc5093, 1)} on win32 ‘Type "copyright", "credits” or "license()™ for more information. >>> import time >>>
|
name)
|
‘agsst
Note the last two entries, with %H and %H%M, as you can see, these are the hours and minutes and as the last entry indicates, entering them as %H%M doesn't display the time correctly in the Shell. We can easily rectify this with:
STEP 6
.
time.strftimeC“%H :%M”)
[
-
Python 3.7.6 Shell Edit
File
Shell
a
x
The output will look similar to the screenshot below. ' The timer Function needs to be either side of the input statement, as that’s when the variable name is being created 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.
STEP 9
Debug
Window
Options
Help
(Inte
”
-
-
[a Python 3.7.0 Shell File
Python 3.7.0 (v3.7.0:ibfScc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)} on win32 Type "copyright", “credits” or “license()* for more information. >>> import time
-
"
Edit
Shell
Debug
Options
Window
a
x
Help
Jun 27 2018, 04:06:47) [MSC v.1914 32 bit Python 3.7.0 (v3.7.0: lb9cc5093, 1)] on win32 "credits" or Type "copyright", "license()™ for more information.
(Inte
|
>>>
RESTART: C:\Users\david\Documents\Python\From
Pi\logintime.py
>>> time. strftime ("*a") "Thu! >>> time. stritime ("$B")
Enter login
>>> time. strftime ("*b")
User: David logged in at 10:07 It took David 4.050173759460449 seconds to login to their account.
name: David
Welcome David
‘June'
‘Jun!
>>> time.strftime ("8") ‘097 >>> time. strftime ("%H&M")
>o>
|
"OS55" >>> time.strftime ("$H:4M")
*09:56°
>>>
This means you're going to be able to display either
anatase
occurred, such as a user entering their name. Try this code in the Editor:
import time name=inputC“Enter Login name: “) printC“Welcome”, name, “\d”) printC“User:”, name, “Logged in at”, time.
L&
strftimeC“%H : %M”)) az0
-
shee
Ct
Datu Optra
‘him ‘Pytmon
window
ab] ea winaz Type “soprrignes, “oredites of
momee b
wetoome Bavte
Perse zemsea an oe 20:00
a
x
Deemer He
CEOOMINTI
UM
“Licenae()” for
RESTART: 1
name bavi lancer Logie
Idoeye
Hay CE
Documental
ECCS
tat
heat Bean re Cease on _Oppons_andow Hee
semen
input
oy
Jpeiat (oyna Jerane(rnsaees",
same“)
login
"logged an ax”,
Shell
NAME
fame) name,
Edit
Debug
Options
Window
time ("AE
- This
a
bit (Inte
module provides various functions to manipulate time values.
Ur))
DESCRIPTION
There are two standard representations of time. 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
x
Help
Python 3.7.0 (v3.7.0:1lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 1)] on win32 Type “copyright", “credits” or “license()” for more information. >>> import time >>> help (time) Help on built-in module time:
peroreere
mare anformation,
Pytnen\Froe Pa\legiatane.py
_sorma
-
Python 3.7.6 Shell
File
Try to extend it Further to include day, month, year, and so on. 1D Pron
There’s a lot that can be done with the Time module, some of it is quite complex too — such as displaying the number of seconds since January 1st 1970. IF you want to drill down further into the Time module, then in the Shell enter: heLpCtime) to display the current Python version help File for the Time module.
STEP 10
the current time, or the time when something
(to represent fractions of seconds).
The Epoch is system-defined; on Unix, it is generally January The actual value can be retrieved by calling gmtime The other representation is a tuple of The tuple items are:
9
ist,
1970.
integers giving local time.
www.bdmpublications.com
{
Manipulating Data
Opening Files Python, you can read text and binary Files in your programs. This enables you to import data From one source to Python; handy if you have another program language running, that’s creating an output, and you want to analyse the results in Python. In
OPEN, READ AND WRITE Python, you create a File object, similar to creating a variable, only you pass in the file using the open() Function. Files are usually categorised as text or binary. In
Start by entering some text into your system's text editor. The text editor is preferable to a word processor, as word processors include background Formatting and other elements. In our example, we have the poem The Cimmerian, by Robert E Howard, and we've saved the file as poem.txt.
STEP
1
asked to be opened. We can now use the poem variable to read the contents of the file:
poem.
The
dark woods, masicing slopes of sombre hills; grey clouds” leaden everlasting arch;
Tre duaky streams Uhat flowed without JAnd
read()
Note than a /n entry in the text represents a new line, as we have used previously.
remeaber
The
IF you now enter poem into the Shell, you will get some information regarding the text file you've just
STEP 3
1
@ sound, the lone winds that whispered down the passes.
cugged peak and gazed, his shaded sau but the endless vista fill on
File
A
-
hill,
Edit
Shel}
Debug
Options
Window
a
x
Help
Python 3.7.0 (v3.7.0:ibf9cc5093, Jun 27 2018, 04:06:47) (MSC v.1914 32 bit 1}} on win32 Type "copyright", “credits” or “license()" for more information,
(Inte
("C:\\Users\\david\\Documents\ \poem. txt")
>>> poem=open >>> poem
>> poem=open("C:\\Users\\david\\Documents\\poem.txt"} >>>
print(poem, readQ)) Now, the /n entries are removed readable text. (& File
Help
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)) on win32 Type "copyright", "credits" or "license()" for more information.
IF
(Inte
*
in
favour of new lines and
-
Python 3.7.0 Sheil Edit
Shell
Debug
Options
Type "copyright", "credits"
Window
or
Help
"license()" for
more
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
endless vista - hill on hill, Slope beyond siope, each hooded like its brothers. Saw but the
It
www.bdmpublications.com
information.
>>> poam=open ("C:\\Users\\david\\Documents\ \poem. txt") >>> print (poem.read()) 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.
was
a gloomy
land tha’
oO
x
Opening Files
STEP
yaoi:
As with lists, tuples, dictionaries and so on, you're able to index individual characters of the text.
5
Extending this Further, you can use readlines() to grab all the lines of the text and store them as multiple lists. These can then be stored as a variable:
For example:
poem=openC(“C: \\Users\\david\\Documents\\poem. txt”)
read(5)
poem.
Lines=poem. readLlines()
Displays the first Five characters, while entering:
Lines [Q]
lines[1] lines[2]
read(5)
poem.
Will display the next Five. Entering (1) will display one character at a time.
Edit
File
Shell
Debug
File
-
[L& Python 3.7.0 Shell
Options
Window
L& Python
o
x
>>> poem=open ("C:\\Users\\david\\Documents\\poem. >>> read (5) poem. "I rem! >>> poem. read (5)
(Inte
Shell
Options
Debug
>>> lines [0] "I remember\n' >>> lines[1} ‘The dark woods, masking >>> lines[2]
txt")
‘ember!
"The grey clouds' leaden
>>>
>>>
sa
to
Similarly, you can display one line of text at a time by using the readline() Function. For example:
poem=openC“C: \\Users\\david\\Documents\\poem. poem. readLine()
poem.
Python
File
Edit
Debug
Window
everlasting arch; \n"
We can also use the for statement to read the lines of text back to us:
STEP 9
for lines in
Options
hills;\n’
poem=open(“C: \\Users\\david\\Documents\\poem. txt”)
Shell
Shell
slopes of sombre
a
poem:
print(lines)
x
-
Help
[&
Python 3.7.0 (v3.7.0:ibf9cc5093, Jun 27 2018, 04:06:47) (MSC v.1914 32 bit (Inte 1)J on win32 Type "copyright", “credits” or "license()}* for more information.
Fite
Python 3.7.0 Shell Edit
Shell
Options
Debug
Window
xremember\n'
x
a
Help
|
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)) on win32 Type “copyright”, "credits™ or “license()" for more information.
>>> poem=open ("C:\\Users\\david\\Documents\\poem.tzt"} >>> readline () poem. >>> poem. readline () ‘The dark woods, masking slopes of sombre >>>
(Inte
And, since this is Python, there are other ways to produce the same output:
readline()
3.7.0
x
Oo
Help
print(lines)
Will display the next line of text. [&
Window
for lines in lines:
txt”)
Will display the first tine of the text. And:
"I
-
3.7.9 Sheit
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.3914 32 bit 2)] on win32 Type “copyright”, "credits" or “license{}" for more information. >>> poem=open ("C:\\Users\\david\ \Documents\\poem. txt") >>> readlines () lines=poem.
Help
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:66:47} [MSC v.1914 32 bit 1)] on win3z Type “copyright”, “credits” oz "license()" for more information.
Edit
(Inte
|
>>> poemmopen ("C:\\Users\\devid\ \Documents\ \poem. txt”) >>> for lines in poem:
hills;\n'
print (lines) I remember The dark woods, masking slopes of sombre
Let's imagine that you wanted to print the text character at a time, as would an old dot matrix We can use the Time module mixed with what we've looked printer. at here. Try this:
As you may suspect, you can pass the readline() function into a variable, allowing you to call it again,
STEP 7
STEP 10
a
when needed:
poem=openC“C: \\Users\\david\\Documents\\poem. Line=poem. readlineQ)
txt”)
import time
Line [& File
poem=openC(“C: \\Users\\david\\Documents\\poem.
-
Python 3.7.0 Shell Edit
hills;
Shell
Debug
Options
Window
o
x
Help
Python 3.7.0 (v3.7.0:ibfScc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)] on win32 Type "copyright", "credits” or “license()™ for more information. >>> poem=open ("C:\\Users\\david\\Documents\\poem. txt") >>> Line=poem. readline () >>> line "I remember\n' >>>
(Inte
txt”)
read) for lines in lines: printClines, end=””) time.sleep(.15)
Lines=poem. *
The output is Fun to view, and easily incorporated into your own code. UD
Fie
eresreenn Féa
no
Format
ote,
arnt
Creaments-Bahon
veatcem 5 EH 7E
Ran
Options
Window
Help
mge{)" tor more anformaticn. RESTART: C2/O3ers/derrs To
remeaber rhe
Gack woods, masking slopes
of
ehat xhuspered
arching, niila ke
cn
vi
www.bdmpublications.com
Manipulating Data
Writing to Files Being able to read external Files within Python is certainly handy, but writing to a file can be even more useful. Using the write() Function, you're able to output the results of a program to a file, which you can then use to read() back into Python, or as a text File For perusal later.
WRITE AND CLOSE The write() Function is slightly more complex than read(). Along with the filename, you must also include an access mode that determines whether the File in question is in read or write mode.
STEP1
Start by opening IDLE and enter the following (obviously entering your own username location):
t=open(“C:\\Users\\david\\Documents\\text.txt”, “w?) This code will create a text File, called text.txt in write mode, 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 [&
Python
File
Edit
3.7.0
Shell
Debug
Options
Window
Qo
x
-
Python 3.7.0 Shell
Fite
Edit
Shell
Debug
109 >>> >>>
file. This gives us the foundation for some interesting possibilities, perhaps the creation of your own log file, or even the beginning of
t.writeC“You awake in a small, square room. A Single table stands to one side, there is a Locked door in front of you.”)
an adventure game. [& File
Note, the 109, it’s the number of characters you've entered. Python 3.7.0 Shell Edit
Shell
Debug
Options
Window
Oo
x
Help
Python 3.7.0 (v3.7.0:lbf98cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte 2)] on win32 Type “copyright”, “credits” or “License(}” for more information. >>> t=open("C:\\Users\\david\\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 >>>
|
«
Python 3.7.0 Shell Edit
Shell
x
oa
Debug
Options
Window
Help
Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte 2)] on win32 Type "copyright", "credits" or "License(}" for more information. >>> twopen("C:\\Users\\david\\Documents\\text.txc", "w"} >>> t.write("You awake in a small, square zoom. A single table stands to one sid e, there is a locked door in front of you.") 109 >>> >>>
t.cLose{}
-
Gb text Notepad
File
Edit
Format
a@
View
a
x
Help
in a small, square room. A single table stands to one side, there locked door in front of you.
You awake
www.bdmpublications.com
x
Oo
Help
IF you now open the text file with a text editor, you'll see that the line you created has been written to the
We can now write to the text file using the write() function. This works opposite to read(), writing lines instead of reading them. Try this:
File
Window
t.close()
STEP2
[&
Options
Python 3.7.0 (v3.7.0:1bf9ec5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte 1)) on win32 Type "copyright", "credits” or "License()” for more information. >>> t=open ("C:\\Users\\david\\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.")
(Inte
>>>
-
|
file itself. Part of the write() Function is that we need to commit the changes to the File, we can do this by entering:
(L&
Help
Python 3.7.0 (v3.7.0; lbf9cc5093, dun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)1 on win32 Type "copyright", ‘credits™ or "License(}" for more information. >>> teopen("C:\\Users\\david\\Documents\\text.txt", “w")
3
t.close()
it-so be careful.
-
Shell
a
However, the actual text file is still blank (you can check by opening it up). This is because you've written the line of text to the File object, but not committed it to the
STEP
is
~
Cwansors QB at the end of the original line, instead of wiping the File and creating a new one. For example:
We can pass variables to a File that we've created in Python. Perhaps we want the value of Pi to be written to a file. We can call Pi from the Math module, create new file, and pass the output of Pi into the new file:
t=open(“/home/pi/Documents/text.txt”,”a”)
import math
STEP
To expand this code, we can re-open the file using ‘a’, for access or append mode. This will add any text
5
STEP 8
a
printC“Value of Pi is: “,math.pi) printC“\nWriting to a file now...”)
t.writeC*\n”) t.writeC* You stand and survey your surroundings. On top of the table is some meat, and a cup of water. \n”) -
Python 3.7 2 Shell
[&
Edit
File
Shell
Debug
Options
Window
a
[a
writePitoFile.py
File
Edit
-
Run
Window
Options
x
Oo
Help
import math
x
print ("Value of Pi is:
Help
Python 3.7.0 (v3.7.0;lbf9cc5093, dun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte 2)] on win32 Type "copyright", "credits" or "License()}" for more information. >>> teopen("C:\\Users\\david\\Documents\\text.txt™, "w"} >>> t.write("You awake in a small, square room. A single table stands to one sid
-
C:/Users/david‘Documents:Python/wntePitoFile.py (3.7.0)
Format
print ("\niiriting to
a
°, math.pi) file now...")
|
e, there is a locked door in front of you.") 169 >>> >>> >>>
t.ciose{)
twopen("C:\\Users\\david\\Documents\\ctext.txt",
t.write("\n"}
"a"
1
t.write("You stand and survey your surroundings. On top of the table is some meat, and a cup of water.\n")
>>>
We can keep extending the text line by line, ending each with a new line (\n). When you're done, finish the code with t.closeQ), and open the file in a text editor to see the results:
t.writeC“The door is
Fie
Edit
We also need to create
made
Debug
Cotions
Window
209
(1:
\pecumenta\ \text
Remember to change your file location to your own particular
Kou auske In a |@
door
you. surroundings. Or
solid
with iron st
oak pefsonee!
D> Rawrites"Tne door 1x ange of AoLia OME WIEN iron straps, It*s Bolted from th ontaide, loeting you in. You are a priaoner'\n®} aM
There are various types of file access to consider using the open() Function. Each depends on how the file is accessed, and even the position of the cursor. For example, r+ opens a file in read and write, and places the cursor at the start of A
the file.
File
6
ea
Shel
Debug
Options
Windom
2,7.9 (v9.7.0rib9ee6093,
win
Help.
DoD pmopen tawrbte("Cz (Adventure 17
Da» proverto
more
\(Decumenca\ \eeze, cant, Game!\n\a")
information. *E+*)
Window
Options
_Help
[mport math
to a
math.pi)
%,
file
now...")
STEP 10
To finish, we can use string Formatting to call the variable and write it to the file, then commit the !
\
nus
tawzate(*You stena ena survey your surzouscings. Gn cop of che table 18 acme meet cup oF water.\n")
-
File
print ("Value of Pi is:
ext, mo)
-
-
*“writePitoFite.py C:/Users/david/Documents/Python/writePitoFile.py (3.7.0)"
small, square room. A sing)
locked door in front of You stand and survey your 2 cup of water. The eade is of locking you in. You are a
2
“EB Python 3.7.0 shel)
new file to write Pi to:
system setup.
{39> tecdoset)
do> cecpen teaweate"\ar)
a
t=open(“C:\\Users\\david\\Documents\\pi.txt”, “w”)
1elp
Python 9.7.0 (v3.7.0:1bfSceSO8S, Jun 27 2088. 08:08:47) (HSC v.19I4 32 bat (Inte ~ on win32 Type “copyright, “credita™ ox “License for more information. ()" tat", j>>> eecpen(MCr\ Waera\ Wdavid\ \Documenta\ (Doo Cwektet"¥ou weake 40a smell, aquare\text room. A ingle table stands ro one aad fe, there 2 @ locked door in front of you.*)
[pom
variable called pi, and assign it the
a
—
coer
Shell
a
value of Pi:
pi=math.pi
of solid oak with iron strips. It’s bolted from the outside, Locking you in. You are a prisoner! .\n”) t.close(Q) Deas
Now let's create
STEP 9
STEP 6
Bee Fae
tail
forena
View
As you can see From the results, you're able to pass any variable to
Help
Adventure Game! a
small,
As
You awakedoor In in Front square a locked of you.room. You stand end survey your surromdings a cup of water, The door is made of solid oak with tro locking you in. You are a prisonent
a File. Dares Fle
E6e
thot
Shel ebug
proms ‘Window Help
2018,
(+ —eeneee pesto: of Fa dex [Yedee
[Mracaag to a
fale
fare ¥.194 93 tae
ents
~
Fle F
Et
Fema fun Cpbora eb
Windom
wate
Ae
22
Help
fox more storm
eres 9.a4usezennaee799
now,
Of PA
Divi beaapod fe toe tome ew
Wale of 4
tas 3,
1".
Carmes
taal
Hap
LASSORS 989793
www.bdmpublications.com
Manipulating Data
exceptions As your code begins to Form and lengthen, you'll naturally come across some exceptional circumstances that are mostly 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. We can combat errors by creating conditions where exceptions may occur.
STEP
You can create an exception error by simply trying to divide a number by zero. This will report back
1
with the ZeroDivisionError: Division by zero message, as seen in the screenshot. The ZeroDivisionError part is the exception class, of which there are many.
-
(& Python 3.7.0 Shell Edit
File
Shell
Debug
Options
Window
oa
x
Help
Python 3.7.0 (v3.7.0:lbfsce5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bic (Inte 1)) on win32 Type "copyright", “credits” or “license()" for more information. >>> 1/0 Traceback (most recent call last): File “", line 1, in
i/o
ZeroDivisionError: >>>
division by
zero
We can use the functions raise exception to create our own error handling code within Python. Let's assume your code has you warping around the cosmos, too much, however, results in a warp core breach. To stop the game from exiting due to the warp core going supernova, we can create a custom exception: oe
=f
raise ExceptionC“warp core breach”)
[i
-
Python 3.7.0 Shell
File
Edit
Shell
Debug
Options
Window
a
x
Help
Python 3.7.0 (v3.7.0:1lbf$cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)] on win32 Type "copyright", “credits” or "license()* for more information.
(Inte
Exception("warp core breach") call last): File "", line 1, in raise Exception(*warp core breach") Exception: warp core breach >>> raise
|
recent |Traceback (most
>>>
a
=o,
Most exceptions are raised
automatically when Python comes across something that’s inherently wrong with the code. However, we can create our own exceptions that are designed to contain the potential error and react to it, as opposed to letting the code fail.
tip
be
reeration
abvecioaescoe
of: try, except, else, where the code is held within try, then if there's an exception do something, or do something else.
-
L& “Untitled Fite
Edit
Format
Run
Options
Window
Help
try:
Insert your operations here -----> except Exception 1: If there is an exception do this
-----:
Tf there is another exception do this else: If there is no exception, then do this
YarcodeBncodale scr DntoateTrenalaceErrer Depreeationmerst st
fast +
on+ +
symtanterning TeerRarning Boruretarning TeporeMerning Unboodemerning
Bytesteraing +
www.bdmpublications.com
To trap any errors in the code we can encase the potential error within a try: block. This block consists
= strecsritmerne:
Resoareettersing
>
o
x
Exceptions
For example, using the divide by zero error, we can create an exception where the code can handle the error without Python quitting due to the problem:
STEP
5
try:
Naturally, we can quickly fix the issue by changing the “r” read only instance with a “w" for write. This,
STEP 8
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
set of circumstances,
a=intCinputC“Enter the first number: “)) b=intCinputC“Enter the second number: “))
this case, a successful execution of the code.
in
ie
print(a/b)
WC
except ZeroDivisionError: printC“You have tried to divide by
else:
we, TETeELO” ‘eonaun
RESTART:
Etfors unable
zero!”)
no
RAL
0h
taemut
IN nee
12
Cpls
Wacko
Hay
oF CLiceRee()® For Moe LBtemMstion,
Savad\Docunwucs\PytHon\Tice PL\saoNptsen2.py C1\Couz9\ welve the Cote, Check permbsenenn,
peta:
Content Wratten te 1le
eewretally, Seve
wid
Documenta. Rate Pytheo\ a 3: ee fron mieremfully. day.
4 mow
PAexeepescaz.py
any.*
printC“You didn’t divide by zero. Well done!” Gi
-
Python 3.7.6 Shell Edit
Fite
Shell
Debug
Options
Window
Python 3.7.0 (v3.7.0: lb9cc5093, 1))] on win32 Type “copyright”, “credits” or
Fhe 64
oO
Fount
Weds 46 9
x
Help test, Yorw Norasd service will shectly cesusel
‘|
Help
Jun 27 2018, 04:06:47)
"license()" for
more
[MSC v.191
32
bit (Inte
information.
>>>
RESTART: C:\Users\david\Documents\Python\From Pi\exceptionl.py Enter the first number: 12 Enter the second number: 6 2.0 You didn't divide by zero. Well done!
int
>>>
RESTART: C:\Users\david\Documents\Python\From
Enter the first number: 12 Enter the second number: 0 You have tried to divide by zero!
a Finally: block, which works in a similar Fashion, but you cannot use else with it, Hint: You'll need to delete the textfile.txt File from your Folder.
LB exception! py CAUsers\david\Documents\Python\From Pi\exception| py (3.7.0)
Edit
Format
Run
Options
Window
Help
try:
try: txt = open C:\\Users\\david\\Documents\\textfile. txt” ; “r?) try: txt.writeC(“This is a test. Normal service will
a=int (input ("Enter the first number: *)) bint (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 tasks. Using an example From our previous tutorials, let's assume you want to open a file and write to it:
try: txt = openC“C:\\Users\\david\\Documents\\textfile. txt” ; “r) txt.writeC“This is a test. Normal service will shortly resume!” print C“Error: unable to write the file. Check permissions”)
else: print (“Content written to file successfully. Have a nice day.”)
txt.close()
user that the permissions are incorrect.
File
try:
txt
C:\Users'
Format
Edit
=
Run
As before an error will occur as we've used the “r” read-only permission. IF we change it to a “w”, then the code will execute without the error being displayed in the IDLE Shell. Needless to say, it can be a tricky getting the exception code right the first time. Practise, though, and you will get the hang of it. [&
david
Edit
Options
Help
open{"C:\\Users\\david\\Documents\\textfile.txt", "r") a test. Normal service will shortly resume!")
except IOError:
print ("Error: unable
to write the file.
else:
print ("Content written
to file
Shell
Debug
Options
Window
a
bit (Inte
>>>
RESTART: C:\Users\david\Documents\Python\From Error: unable to write the file. Check permissions
Pi\exception3 py
>>>
RESTART: C:\Users\david\Documents\Python\From Pi\exception3.py Content written to file successfully. Have a nice day. >>>
Edit
Check permissions")
successfully.
Have a
try?
Format
Run
Options
Window
Help
= open("C:\\Users\\david\\Documents\\textfile.txt"™,
try: txt.write ("This is a test.
finally:
print ("Content written
txt.close()
to
x
Help
Python 3.7.0 (v3.7.0:ibfScc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 1)J] om win32 Type “copyright”, “credits” or “license()" for more information.
File
Documents Python\From Pixexception2.py (3.7.0)
Window
-
Python 3.7.0 Shell
[& exception3. py CAUsers\david\Documents\Python\From Pi\exception3 py (3.7.0)
txt.write ("This is
txt.close ()}
permissions”)
File
Obviously this won't work due to the file textfile.txt being opened as read only (the “r” part). So in this case, rather than Python telling us we're doing something wrong we've created an exception, using the lOError class, informing the
ey exception2.py
shortly resume!” finally: print C“Content written to file successfully. Have a nice day.”) txt.closeQ) except I0Error: print C“Error: unable to write the file. Check
STEP 10
except I0Error:
-
You can also use
STEP 9
>>>
File
coe!
Pi\exceptionl.py
Normal service
file
will
successfully.
"w"™)
shortiy resume!") Have a nice
day.")
except I0Error!
print {"Error: unable to write the file.
Check permissions")
nice day.")
www.bdmpublications.com
Manipulating Data
Python Graphics While dealing with text on the screen, either as game or ina program, is perfectly Fine, there comes 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. a
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.
STEP
One of the best graphical modules to begin learning Python graphics is Turtle. The Turtle module is, as
1
The command turtle.circle(50) is what draws the circle on the screen, with 50 being the size. You can play around with the sizes if you like, going up to 100, 150, and beyond; you can draw an arc by entering turtle. circle(s@, 180), where the size is 50, but you're telling Python to only draw 180° of the circle.
STEP 3
the name suggests, based on the turtle robots used in many schools that can be programmed to draw something ona large piece of
paper on the floor. The Turtle module can be imported with:
import turtle. (&
Python
File
Edit
3.7.0
-
Shelt
Shell
Debug
Options
Window
x
oO
Help
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) (MSC v.1914 32 bit 1)} on win32 Type "copyright", "credits" or "license()" for more information. >>> import turtle
(Inte
/
>>>
STEP 2 import
Let's begin by drawing a simple circle. Start File, then enter the following code:
a
New
turtle
The last part of the circle code tells Python to keep 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: gescemme
turtle
turtle.circle(5@)
import
turtle.getscreen()._root.mainLloop()
printC“Drawing a square...”
As usual press F5 to save the code and execute it. This will open up a new window and the ‘Turtle’ will drawa circle.
for t in range(4):
Lh
Goch
=A
de
Dict
turtle. forward(100) turtle. LeftC9@)
turtle.getscreen()._root.mainloop() You'll notice we've inserted
a
loop to draw the sides of the square.
seanni)® for mare Aatornarien,
earere tere (90)
9
www.bdmpublications.com
an Tate Gps
-
a
*
Python Graphics
STEP
To add some colour, we can add a new line to the Square code:
5
Now let’s get the code by importing the pygame module:
yu Sor:
import pygame
turtle. color(“Red”)
pygame
.initC)
And we can even change the character to an actual turtle by entering:
img =
turtle. shapeC“turtle”)
white = (255, 255, 255) = 900 h = 452
Bee
phos
Gly
Tan
Fas
Format
Cetens
Wedow
jh vu tems
img
—
aczeen.
rarele. forwesa i100)
)
-_rooe mainioae
()
STEP 9
complex, as you begin to master the way it works. Enter this example:
turtle import * colorC‘red’, ‘yellow’)
pygame>> import calendar >>> for name tr calendar.month_nane:
print
n
Help
bit (Intel)]
on win32
(name)
January February
Interestingly we can also list the number of days in month by using a simple For loop:
STEP 6
a
import calendar
cal=caLlendar.TextCalendarCcalendar. SUNDAY) for i in cal.itermonthdays(2019, 6): printdi) se *“daysinmenth.py Edit
File
Format
C".Users\.david\
Run
Options
import calendar cal=open(“C:\\Users\\david\\Documents\\cal .html”, “w’)
c=caLlendar.HTMLCalendar(Ccalendar. SUNDAY) cal.write(c.formatmonth(2019, 1))
Documents\Python\From Pi\daysinmonth.py (:
Window
The Calendar module also allows us to write the Functions in HTML, so that you can display it ona website. Let’s start by creating a new file:
Help
cal.close()
This code will create an HTML File called cal, open it with and it displays the calendar for January 2019.
import calendar
cal=calendar.TextCalendar (calendar .SUNDAY) for in cal.itermonthdays (2019, 6): print (i)
i
Me
FE crseversstecmeniens
67
You can see that code produced some zeros at the beginning, this is due to the starting day of the
-
\[@ Python 3.7.0 Shell i
|File
Edit
Shell
Debug
Options
Window
Help
Oo
21
15 16
17
223 2
Opbons
Window
Ilelp
incr
\\Doeza\\david\ \Doounenta\\car-neay! e~calendar. ETMLCalendar (calendar. SUNDAY} (2019, 1)}
O
@
=
1839
2526
2930
STEP 10
week, Sunday in this case, and overlapping days From the previous month. So, the counting of the days will start on Saturday 1st June 2019 and will total 30 as the output correctly displays.
fun
calendar
ay nen
WUR
13:14
A
Tormat
browser
cal.vrite cal.close()(.formatmonth
Jawaary 2019 SanMonTeoWedThuFriSat
20
Edt
ame IEE
D RetinAisersidaid/Oocsll
a
Of course, you can modify that to display a given year as a web page calendar:
import calendar
year=intCinputC“Enter the year to display as x
a
“))
webpage:
cal=open(“C:\\Users\\david\\Documents\\cal .html”, “w’) cal. .writeCcalendar .HTMLCaLendarCcalendar .MONDAY) . formatyear(year))
cal.close()
This code asks the user for a year, then creates the necessary webpage. Remember to change your File destination.
» 5
DOM
7a Mw
ip202k DN
DOM
18
25 26
2 www.bdmpublications.com
85
Using Modules
S Module The OS module allows you to interact directly with the built-in commands Found in your operating system. The commands can vary, depending on the OS on which you're running the module, 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. We can start the OS module with some simple functions to see how it interacts with the operating system environment that Python is running on. IF you're using Linux, or the Raspberry Pi, try this:
STEP
1
import os
The Windows output is different as that’s the current working directory of Python, as determined by the system. As you suspect, the os.getcwd() Function is asking Python to retrieve the Current Working Directory. Linux users will see something along the same lines as the Raspberry Pi, as will
STEP 3
macO$S users.
home=os .getcwd()
printChome)
-
Python 3.5.2 Shell
+,
File Edit Shel Debug Options Window Help
autem Bile
Edit
RRC
Est
C
Python 3.5.2 (default, Nov 17 2016, 17:65:23) [GCC 5.4.8 26168689) on Linux Type “copyright”, "credits" or "License{)" for more information. >>> import os >>> home=os.getcwd()
Shell Debug Qpticns Window Help
Python 3.5.3 (default, Sep 27 2018, 17:25:39} (Gec 6.3.0 26176516] on linux Type “copyright”, "credits" or "license()" for more information. >>> import Os
>>>
)
>>>
The returned result, From printing the variable home, is the current user’s home folder on the system. In Step 1 that’s /home/pi, it will be different depending on the user name you login as, and the operating system you use. For example, Windows 10 would output: C:\Users\david\AppData\,
-
UB Python 3.7.5 Shell Edit
Shell
Debug
Options
Window
Python 3.7.0 (v3.7.0:lb$cc5093, 1)] on win32 Type "copyright", "credits or >>> import og
browser=os.system(‘start chrome’) Qa
x
"license()" for
see
Wom
Help
dun 27 2018,
Another interesting element to the OS module is its ability to launch programs that are installed in the host system. For instance, if we wanted to launch the Chromium Web Browser from within a Python program we can use the command:
import os
Local\Programs\Python\Python37-32.
File
print (home)
/home/david
>>> homesos.getcwd{ >>> print (home) fhome/pi. 22>
04:06:47) more
[MSC
v.1914 32 bit (Inte
sl
Help
093, Jun 27 2016, O4r06242) (MSC 7.1914 32 Bax (Ince
~
e
&
fom Far
From!
information.
>>> home=os.getewd (} >>> print (home)
C:\Users\david\AppData\Local\Programs\Python\ Python37-32 >>>
Goo ‘Seach Goagie
a owone
a
86
www.bdmpublications.com
of
type
a
URL
v tome |
a
QB The os.system() Function is what allows interaction with external programs you can even call up previous Python programs using this method. You will obviously need to know the full path and program File name For it to work successfully. However, you can also use the Following: —
import os
os.system(‘ ‘start feed/music”’)
chrome
//www. youtube .com/
Being able to manipulate directories, or folders if you prefer, is one of the OS module’s best Features. For example, to create a new directory you can use:
STEP 8
import os os.mkdirC*C:\\BDM\\NEW”) This creates a new directory within the specified Directory (C\BDM\), named according to the object in the mkdir Function (C\BDM\NEW).
ate 10m
STEP 9
You can also rename any directories you've created by entering:
import os os.renameC(“C:\\BDM\\NEW”, “C:\\BDM\\OLD”) To show that the OS module works roughly the same across all platforms, we need to specify the name of the app according to the OS on which you're working. For example, on a Raspberry Pi you would enter:
import os os.system(‘chromium-browser
Or delete them...
import os os.rmdirC*C:\\BDM\\OLD”) a
‘eae eine
Chick excess
3S
Deophice (Team
DOWIOID
we
IOS
-
BOM
(3 Fyn 2090
“http://
Fie
"
ae
marc
BD wWoepen
bdmpublications.com/”’)
=
"F} Documnenes
FO Commtoeds ab
Muie
_€&t
Shel
Options
Debuy
9
fled
s 90:
\
("C1
ODEN
\
WERTW
*
AEN) ANFRY,
(7c: 1 (BOKoL0"f *Ct\\EH ALON)
jename
mak
x
Window
Jun 27 ZL, OF:OG:eT) (NSC V-ADLE 32 BEE Pytncn 3.7.0 (v9.7.0: iDENCCHU93, 35] on wand2 + or “Lacensecn for moce sntormation. Ftwwe "copyesans*,
\uoRe\
Another module that goes together with OS is shutil. We can use the Shutil module, together with OS and time, to create a time-stamped backup directory, and copy files into it:
STEP 10
import os,
anlar
Note, in the previous step’s example the use of single and double-quotes. The single quotes encase the entire command, and launching Chromium, whereas the double quotes open the specified page. You can even use variables to
open webpages:
import os
a=(‘start
chrome
“http: //www.google.co.uk”’)
os.system(a)
shutil,
time
t=str(time. strftimeC“%Y -%m-%d %H-%M”)>) #Path to root_src_dir = r’C:\\BDM\\Documents\\’ the source directory root_dst_dir = ‘C:\\Backup\\’ + t #Path to the backup directory for src_dir, dirs, files in os.walk(Croot_src_dir): dst_dir = src_dir.replace(root_src_dir, root_ dst_dir, 1) if not os.path.exists(Cdst_dir): os.makedirs(Cdst_dir) for file_ in files: src_file = os.path.join(src_dir, file_) dst_file = os.path.joinCdst_dir, file_) if os.path.exists(Cdst_file): os.remove(dst_file) shutil.copyCsrc_file, dst_dir) print(“>>>>>>>>>>Backup complete>> import random >>> [st=["David", 46, "Avengers", 3245.32, *Pi*, True, 3.14, "Python"] >>> rnd=random. choice >>> print (rnd)
(Inte
>>> random. shuffle >>> print (lst)
(1st)
(Pit, 3.14, ‘Avengers’,
printC“Tails:”, output[“Tails”]) fornia
La
Tot
fae
3.14
(1st)
°
Shel
~
Gonent
Debug
Window
RESTART: Heads: 5022
Tatiar
ou
Docunenta\ Pythoa\ trom
~
Pi\headrtasis
Zis
Yauia: 204l
["David', 'Avengers', 3245.32, True, 'Pi', 3.14, 'Python',
grant
Henan: 3006 Tatler 4596
46}
>>>
\Usera\davta\Docuneors\Pychon\From
Opbems
Wind
™
Help
STania"203 td)
range(aoovon=
a an
output pant
Headat 4459
C2
Ru
ovinelast (output. .keye
py
46A8,
nesTaRT:
sheet dang: Becuments Python. Trem
furmnet
ine sct ransom 4
RESTART: C:\Uaeza\david\Docuneata\Pythoa\From Pi\beadstaila.py
*Python', ‘David', True, 46, 3245.32)
kt
roe
Bie (Tace
B7
epee
revere
Ub
Hep
Fychen 3.7.0 (wa.7-Oelbraaesos3, Sun 37 3018, O408047) NEE w.I914 296 68 wa032 Type “oopysight™, “caedita™ of *Licanset}" for acre information.
(1st)
>>> random. shuffle >>> print (1st)
output [Lrandom. choiceCcoin)]+=1
x
Qa
[random. choice {ocdn) Joe1 »
(cueade:*, ("Hesda™| (Taalas", output ovepue*tasae"]),
Pi\headarat la py
RESTART: C:\Uaers\auris\Documencs\Pychon\ P1\headscai}s.py Prom
Meage: «nay Taita: 5072 1
Sais
C:\Usere\davia\Docunents\Pychon\froe
Pi\needsteils py
Using shuffle, we can create an entirely random list of numbers, for example, within a given range:
import random
Llst=[[i] for I in range(2@)] random. shuffleC1Lst)
Here's an interesting piece of code. Using a text file containing 466 thousand words, we can pluck
STEP 10
printCLst) Keep shuffling the list, and you'll have from 0 to 20 every time.
a
different selection of items
generated number of words from the file (text File Found at: https://github.com/dwyl/english-words):
a user
import random [&d Python 3.7.0 Shell
File
Edit
Shell
Debug
Options
Window
Help
Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47} [MSC v.1914 32 bit 1)} on win32 Type "copyright", "credits" or "license()" for more information. >>> import random >>> lat=[{i] for i in range (20)} >>> random. shuffle >>> print (1st)
(Inte
printC“\nUsing a 466K English word text file I can pick any words at random.\n”) wds=intCinputC“\nHow many words shall I choose?
(1st)
(81, [19], [13], (17), [10], [5], [1], [12], [3], [9], [2], [16], [0], [18],
1, (143, (223, >>>
print(“>>>>>>>>>>Random Word Finder>> >>> from >>>
tkinter
import
or
The first line Focuses on the newly created window. Click back into the Shell and continue the other lines.
x
oa
Help
“license()" for
more
(inte
«
Python 3.7.0 (v3.7.0:lbf$cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit
information.
*
52d do
Although it’s not recommended to import everything from a module using the asterisk, normally it won't window, ' enter:. anyy harm. : Let’s begin byby creating 9 a basic GUI gin
wind=Tk()
File
~
Python 3.7.0 Shett
Edit
Shell
Debug
Options
Window
.
from
.
import tkinter tkinter import *
oO
Pittkintercodel py (3.7.0)
-
as
tk
x
Help
(Inte
def clickQ): printC“You just clicked me!”) btn[“command” @
tkintercodel.py Edit
Format
-
]=click
C:\Users'\davidsDacuments’Python\From Run
Options
Window
import tkinter as tk from tkinter import *
btn=Button () ben. pack()
btn["text”)="Hello everyone!" def click(}: print ("You just clicked me!*) ben{"command"]*click
www.bdmpublications.com
New File:
btn[“text”]="Hello everyone!”
File
90
a
Then add some button interactions:
Python 3.7.0 (v3.7.0: lbf9ccS093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)} on win32 Type "copyright", “credits™ or "lice: se()" for more information. >>> import tkinter as tk >>> from tkinter import * >>> wind=Tk() >>>
We can combine the above into
btn=ButtonC) btn. pack()
This creates a small, basic window. At this point, there’s not much else to do but click the X in the corner to close the window. [&
(Inte
1)}] on win32 Type "copyright", “credits™ or "license()}" for more information. >>> import tkinter as tk >>> from tkinter import * >>> btnsButton() >>> brn.pack(} >>> btn["text"J="Hello everyone!” >>>
Help
Oo
x
Tkinter Module
Save and execute the code from Step 5, anda window will appear with ‘Hello everyone!’ inside. IF you click the Hello everyone! button, the Shell will output the text ‘You just clicked mel’. It’s simple, but shows you what can be achieved with a few lines of code. File
Edit
Shell
Debug
Options
Window
Help
Python 3.7.0 {(v3.7.0:lbf9ce5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit 1)} on win32 Type "copyright", "credits" or "license()" for more information. >>> import tkinter as tk >>> from tkinter import *
(Inte
btn=Button ()
>>> >>> >>> >>>
btn.pack()
btn["text"]="Hello
e
RESTART: C:\Users\david\Documents\Python\From
>>> You just clicked me! You just clicked me! You just clicked me! You just clicked me!
We can create radio buttons too. Try:
yu Sor:
tkinter import
from
root = TkQ) v = IntVarQ
LabelCroot, root.titleC(“Options”), text=”””Choose preferred Language:”””, justify = LEFT, padx = 20).packQ) RadiobuttonCroot, text="Python”,
a
padx = 20,
Pi\tkintercodel.py
. packCanchor=W)
o
RadiobuttonCroot,
x
text="C++”,
Hello everyone!
padx = 20,
variable=v,
STEP6
We can also display both text and images within a Tkinter window. However, only GIF, PGM, or PPM
formats are supported. So Find an image, and convert it before using the code. Here’s an example using the Raspberry Pi logo:
tkinter import
*
value=2) .packCanchor=W)
mainloop() And we can create check boxes, with buttons, and output to the Shell:
oi
root = TkQ) Logo = PhotoImageCfile=”C: \\Users\\david\\DownLoads\\
from
wl = LabelCroot, root.titleC“Raspberry
def var_statesQ):
PiLogo.gif”)
Pi”),
The Raspberry Pi Foundation is a UK-based charity that works to put the power of computing and digital making into the hands of people all over the world. We do this so that more “””
content =
people are able to harness the power of computing digital technologies for work, to solve problems that matter to them, and to express themselves creatively. “”” and
LabelCroot,
justify=LEFT,
padx = 10,
text=content) .pack(side=”Left”) root .mainlLoop()
Sais
The previous code is quite weighty, mostly due to the content variable holding a part of Raspberry Pi’s About page, from the company website. You can obviously change the content, the root.title, and the image to suit your needs. Leer
Lacemerese File
Edit
Format
Run
Ukimter
ae
Python from
os
Option:
Window
Br
esneeeznaes peed
TkO)
world.
Label
(roe,
textucontent) -pack (sides -mataloop() @
printC“Warrior: %d,\nMage:
%d”
%
Cvari1.getQ),
var2.getC))) LabelCroot, root.titleC(“Adventure Game”), text=">>>>>>>>>>Your adventure role 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 basic_math.py window is left open.
+
( Create Your Own Modules Back to the basic_math.py window, at the top of the
utilise the newly created Function definitions:
*
from minimath import
if
This will import the Function definitions as module. Press F5 to save and execute the program, and see it in action. a
Python Shell
Ld
choice == ‘1’: printCtimestwo(num1))
elif
choice == ‘2’: printCtimesthreeCnum1))
elif
choice == ‘3’: printCsquareCnum1))
3.7.0
0
shel
Cot
Fae
Pythin 3.7.8 (v3.7.0: 1bFSra:hO8a, dun
27 2018,
04:06:47)
(MSC
v.1914
92
m
We
on wind2
2))
Type "copyright",
“credits”
oz
“licensc{}" for
moze
Finally, we can now create a range of if statements to determine what to do with the number, and
STEP 9
code enter:
information,
minimath inp
(timeatwot2)) print
print
(timenthiee(3}) (square(4)) (power
(5,3))
elif
>I
choice num2 =
==
‘4’:
intCinputC“Enter second number:
“))
printCpower(Cnum1, num2))
else: printC“Invalid input”)
& *testmath. - G/Users/david/Documents/Python/testmath.py (3.7.0}* py
Fite
Format
Edit
Run
Options
from minimath import
We can now make the programa little more advanced, by utilising the newly created module to
printC“Select operation. \n”)
choice = input ("\nEnter choice (1/2/3/4):*)
printC“1.Times by two”) printC“2.Times by Three”) printC“3.Square”) printC“4.Power of”)
numl =
print (timestwo (num1)) elif
(1/2/3/4):”)
+
chutee (37279709)
'3':
==
'4':
int(input ("Enter second
number:
"))
(power (numl, num2))
print ("Invalid input”)|
|
Now we can add the user input to get the number the code will work on:
STEP 8 numl =
=
print
of")
taenter
1.f choice num2
fquare*)
input
'2':
print (square (numl))
Print i*Select operation. \n"} print Dy two! (*1.Times peat (*2 Times by Three") (*4.fower
==
choice =
-
chotce
choice
print (timesthree (numl1)})
(7.0) Ud testrmath gy Citsers/demd/DocumentyPythorvtestmath py
(93
int (input ("\nEnter number: "))
if choice =
choice = inputC“\nEnter choice
ant
Help
print ("Select operation.\n")} print("1.Times by two") print ("2.Times by Three") print ("3.Square") print ("4.Power of")
its Full. Let’s include some user interaction. Start by creating a basic menu from which the user can choose:
Print
Window
*
intCinputC“\nEnter number:
“))
This will save the user-entered number as the variable num1.
ie *testmath, py File
Edit
-
Note that for the last available options, the Power 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.
STEP 10
Ci‘Users/david/Documents/Python/testmath.py (3. 7.0)*
Format
Run
Options *
Window
Help
"from Minimath import
print ("Select operation.\n")} Print ("L.Times by two") print ("2.Times by Three”) Print ("3.S5quare™) print ("4.Power of} choice = input ("\nEnter choice [(1/2/3/4):"} numl = int (input
("\nEnter number: *)) meer canoe
1/2946
mates moet § (ents? second cwbert 4
a3
3
_
—_ www.bdmpublications.com
97
98]
Index
www.bdmpublications.com
66]
Woo'suo}esI}qndwipq
mmm
Pulm J04 SOR Bebe
gs
CEN
Giessadau
wa
melee emeltm
lt
elle)
ay} Je SYOO} UOIZAS SIYL
AT
Tt h roe alter arab aol a2eds dy] pue UONeINpe ‘Hulyueq
VPM
RNR
Tm let
‘suoieoidde ‘suiajsAs Buneiado EY) Ren Lm Lm Ell tales) reo)
]Njysamod pue uaidijjo ue sl ++5
pelt tele LR PiU) ele) ay
eo
MEM CL LU aM
B]QeJISAP JO SWJa] UI ‘NOA JOJ PyJOM Mau a]OYM e suado ++ Ul apod 0}
oT: Bes ete os
ee
Be
Olt
JO S$Q>eW ‘smopuIM Buisn 3J,noA
Const)
AE TUe TUT [oN to wae pel tcon) JHOK dn samod nok uayM NOA jo yuo
Ltt
Mie Meola lost| STE mode to) BurwwesBosd Buizewe ue si ++5
BD
Introducing C++
Why C++? C++ is one of the most popular programming languages available today. Originally called C with Classes, the language was renamed to C++ in 1983. It’s an extension of the original C language, and is a general purpose object-oriented (OOP) environment. C EVERYTHING Due to both the complexity of the language and its power and performance, C++ is often used to develop games, programs, device drivers, and even entire operating systems. Dating back to 1979, the start of the golden era of home computing, C++, or rather C with Classes, was the brainchild of Danish computer scientist Bjarne Stroustrup, while working on his Ph.D thesis. Stroustrup’s plan was to Further the original C language, which had been widely used since the early seventies.
C++ proved to be popular among the developers of the 80s, since it was a much easier environment with which to get to grips, and, more importantly, it was 99% compatible with the original C language. This meant that, beyond the mainstream computing labs,
regular people who didn’t have access to the mainframes and large computing data centres could use it.
C++’s impact in the digital world is immense. Many of the programs, applications, games, and even operating systems are coded
using C++. For example, all of Adobe’s major applications, such as Photoshop, InDesign and so on, are developed in C++. You will Find
that the browser you use to surf the Internet is written in C++, as well as Windows 10, Microsoft Office, and the backbone to Google’s search engine. Apple’s macOS is written largely in C++ (with some other languages mixed in depending on the Function), and the likes of NASA, SpaceX, and even CERN use C++ For various applications, programs, controls, and umpteen other computing tasks. As well as being an easier addition to the core C language, C++ is also extremely efficient and performs well across the board. This higher level of performance over other languages, such as Python, BASIC and such, makes it an ideal development environment for modern computing; hence the aforementioned companies using it so widely.
C++ code is much Faster than other
programming languages.
wide
Teh
Beis
Jace
11
Bet Bet
AsPrime ~
false;
hreak:
“This as
4
prime number":
19 not a prime number
x fioks
x
ASearchveass Line
stele)
www.bdmpublications.com
Hessage
x
Acer x) Qaatin
x P
wuld messages
x)
Acoothekweate
x A Oathedesteresse:
>
Why C++?
- Visual Studio Community 2017 (15.0.26223.1)
Installing
Individual components
Workloads
Language packs
Windows (3)
|
|
Summary
Universal Windows Platform development MBM) Create applications for the Universal Windows Platform with C#, V8, JavaScript, or optionally C++.
IEEE
[my |
|
-NET desktop development
v Desktop development with C...
Build WPF, Windows Forms and console applications using the NET Framework,
included
|
|
v
Desktop development with C++
te
Visual C++ core desktop features
Optional
VC++ 2017 v14} toolset (x86,x64) C++ profiling toois
Build classic Windows-based applications using the power of the Visual C++ toolset, ATL and optional features like MFC and...
Windows 10 SDK (10.0.14393.0) Visual C++ tools for CMake Visual C++ ATL support
Web & Cloud (4)
Windows 8.1 SDK and UCRT SDK
ASP.NET and web development Build web applications using ASP.NET, ASP.NET Core, HTML, JavaScript, and CSS,
\ I
Windows XP support for C++
Azure development Azure SDK. tools, and projects for developing cloud apps and creating resources.
MFC and ATL support (x86 and x64)
C++/CU support Clang/C2 (experimental) Standard Library Modules
Data storage and processing Connect, develop and test data solutions using SQL Server, Azure Data Lake, Hadoop or Azure ML
development
)_Nodeds Build scalable network applications
using Nodejs, an asynchronous
event-driven JavaScript runtime. |
|
@
the By continuing, you agree to the :cerse for Visual Studio editior you selected, We also offer the
ability to download other software wth Visual Studio. This software is ‘icensed separately, as set ‘out in the 3rd Party Notices or in its accompanying license, By contiruing, you also agree to those licenses.
Mobile & Gaming (5)
Microsoft's Visual Studio is a great, free environment in which to learn C++.
C++ puts the developer in a much wider world of coding. By mastering C++, you will find yourself being able to develop code for the likes of Microsoft, Apple and so on. Generally, C++ developers enjoy a higher salary than programmers of some other languages, and, due to its versatility, the C++ programmer can move between jobs and companies without the need to re-learn anything specific.
You will discover, as you become a more advanced coder, that many of the developers in various coding jobs around the world tend to use pre-designed development engines. For example, when creating games, the likes of Bethesda, the team behind Oblivion and Skyrim, utilise 3D game engine called The Creation Engine. This enables a
the team to quickly create animations, characters, items, terrains, rooms, and just about everything else you'd see in the game. The
engine itself has been modified to make the most of the current graphics card hardware, and computer or console processing power. These engines are mostly written in C++, and when making
improvements to the engine, or when creating a new game, if the developers want to add something that the engine can’t do, they will use C++ to create the new content or link between two
different engines. The end result, of course, is game that contains the latest graphical technology, while being seamlessly bound together with some pretty clever C++ coding. a
Getting to use C++ is quite easy, all you need is the right set of tools in which to communicate with the computer in C++, and you can start your journey. A C++ IDE is free of charge, even the immensely powerful Visual Studio From Microsoft is freely available to download and use. You can get into C++ from any operating system, be it macOS, Linux, Windows, or even mobile platforms. So, to answer the question of Why C++, the answer is because it’s Fast, efficient, and developed by most of the applications you regularly use. It's cutting edge, and a Fantastic language to have mastered.
Indeed, the operating system you're using is written in C++.
Windows 10
Mac
debian
ubuntu www.bdmpublications.com
Introducing C++
C++ is one of the top programming languages in the industry. It’s quick, powerful, and used by nearly every major tech and gaming company in the world. Here’s some interesting Facts about the rather wonderful C++. e
.
C++ is one of the
eeeeoeoeceonseeoeeeoneeoneeen
Mp
e NASA, CERN, MICROSOFT, |
&
IN
ANIMATION PROCESSES.
C++ has influenced other
3D ANIA ATION, MOD ELLING,
programming languages, such as C# and Java.
ULATIONS
AND
ua,
development of all kinds of technical and commercial software.
ORACLE, PAYPAL, LINKEDIN, AMAZON AND THE MILITARY USE C++.
C++ IS USED F REQUENTLY
CI
predominant programming \anguages for the
AL L UTILISE C++. |
Alot of the Linux operating system is coded ing C++, therefore youc ‘ould say that most oft e world’s Internet ho sting servers are availabl e thanks to C++.
SUPERCOMPU ING USES C++ CODE TO CALCULATE VASTAMOUNTS OF DATA, INCLUDI NG THE NASA-BASED SUPERCOMPU’ ING FARM THAT RUNS SIMULATIONS F THE UNIVERSE. :
www.bdmpublications.com
0
/
More then 70% of all
esa]
,tadng/sknown as (HFT), and the software
O°
responsible is written in C++ to make use of its high speed.
Onn =
Google, Quora, Stack
Ss =
Exchange, eduCBA,
StackOverflow, stackShare,
= =
AppDynamics
g
C++ Facts & Figures
The Xbox
operating system . uses C++ as its backbone.
Gaming is one of the biggest users of C++. It handles the complexities of 3D games, supports multiplayer options, and enables intensive CPU and
z
sS
Sy
Many database applications are built using C++, such as MySQL, it’s also used by Wikipedia, Yahoo and YouTube,
Google Chrome, Mozilla’s Firefox, and even Microsoft's Edge web browsers are coded in C++.
GPU hardware Functions. i CH
Oth
used in computer networking as the main code behind the
Programmable Logic Controller, connecting servers, processors, other ardware, an owen
Windows 95, 89, 2000, XP, 7, 8.1 and 10, as well as Microsoft Office, use C++ as the backbone programming language of choice.
vabdles,
PERCENTILE SALARY FOR A UK-BASED C++ DEVELOPER IS
1
20,000
MRI scanning machines and Computer Aided Design all use C++ to help with the enhanced imagery produced by these systems.
oe
s =
\
Sources: ITJobsWatch,
AN
“Uy,
Adobe's
z= stable of products ge
%
are developed using C++.
2 53
my
The Unreal 4 Engine, which is coded in C++, is used For hundreds of games, including Fortnite.
es
Basse
FLIGHT CONTROL SYSTEMS IN MODERN AIRCRAFT, INCLUDING MILITARY AIRCRAFT, USE C++.
www.bdmpublications.com
eek]
Will Need C++ SETUPS As most, if not all, operating systems have C++ at their core, it stands to reason that you can learn to program in C++ no matter what OS you're currently using.
|_|
COMPUTER
Unless you fancy writing out your C++ code by hand on a sheet of paper (which is something many older coders used to do), then a computer is an absolute must have component. PC users can have any recent Linux distro or Windows OS, Mac users the
latest macOS.
|_|
*
Conate
gw
appietion iis We,
eppeennt
Project
torent
AN IDE
As with Python, an IDE is used to enter and execute your C++ code. Many IDEs come with extensions and plugins that help make it work better, or add an extra level of Functionality. Often, an IDE will provide enhancements depending on the core OS being used, such as being enhanced for Windows 10.
tet
elasonld
Publ ce!
ueabewuiegtigg Ww
:
op
‘Cipatonost
a
|_|
COMPILER
A compiler is
program that will convert the C++ language into binary that the computer can understand. While some IDEs come with a compiler built in, others don’t. Code::Blocks is our favourite IDE that comes with a C++ compiler as part of the package. More on this later.
|_|
a
TEXT EDITOR
Some programmers much prefer to use a text editor to assemble their C++ code before running it through a compiler. Essentially you can any text editor to write code, just save it with a .cpp extension. However, Notepad++ is one of the best code
text editors available.
| _] INTERNET ACCESS oe
deme
arog
Encosng
Yew
6
namespace sed?
sad -
Bi De
While it’s entirely possible to learn how to code on a computer that’s not attached to the Internet, it’s extraordinarily difficult. You will need to install the relevant software, keep it up to date, install any extras or extensions, and look For help when coding. All of which require access to the Internet.
wectorer
>a2
liste (
we He
5
Range baned for owe
[| TIME AND PATIENCE
Yes, as with Python, you're going to need to set aside significant time to spend on learning how to code in C++. Sadly, unless you're a genius, it’s not going to happen
overnight, or even a week. A good C++ coder has spent many years honing their craft, so be patient, start small and keep learning. 104
www.bdmpublications.com
You Will Need
(Equipment
OS SPECIFIC NEEDS C++ will work in any operating system, however, getting all the necessary pieces together can be confusing to some OS specifics For C++.
As we've mentioned previously, good IDE is Microsoft's Visual Studio. However, a better IDE and compiler is Code::Blocks, which is regularly kept up to date with a new release twice a year, or so. Otherwise Windows users can enter their code in Notepad++ then compile it with MinGW — which Code::Blocks uses.
Linux users are lucky in that they already have a compiler and text editor built into their operating system. Any text editor
will allow you type out your C++ code, when it’s saved with .cpp extension, use g++ to compile it. Cede cpg
Wen
Sears
Dpoe®Aas
Touts
a
a
-Huvcuments
Qccurmerts Help
van
ag
RASPBERRY
PI
TANG
The Raspberry Pi’s operating system is Raspbian, which is Linux based. Therefore, you're able to write your code out using a text editor, then compile it with g++ as you would in any other Linux distro.
Mac owners will need to
download and install Xcode to be able to compile their C++ code natively, Other options for the macOS include Netbeans, Eclipse or Code::Blocks. Note: the latest
Code::Blocks isn’t available For Mac due to a lack of Mac developers. mee
eee
ee
eee
Cee
RE
PEPE See UC ECS
Cee ee eee
fort
newcomer, Here's
WINDOWS
LINUX
Fie
a
FCC
Project Liporer
meyeee.
=o
+
New
Go tate Open 0 hae Window
index
‘uild Configurations
Target
‘ulld
Projeet
Cheae Project
Remove trom Cantext cs
—
—e
———
.
— —_———
‘ Goagie Configure Properties Resource Configurations.
MacBook Air
www.bdmpublications.com
ate)
Introducing C++
How to Set Up C++ in Windows Windows users have a wealth of choice when it comes to programming in C++. There are loads of IDEs and compilers available, including Visual Studio From Microsoft. However, in our opinion, the best C++ IDE to begin with is Code::Blocks.
CODE::BLOCKS Code::Blocks is a free C++, C and Fortran IDE that is feature rich and easily extendible with plugins. It’s easy to use, comes with a compiler and has a vibrant community behind it too.
te
Start by visiting the Code::Blocks download site, at www.codeblocks.org/downloads. From there, click on the ‘Download the binary releases’ link to be taken to the latest downloadable version For Windows.
a0
When you've located the File, click on the Sourceforge.net link at the end of the line and a download notification window appears; click on Save File to start the download and save the executable to your PC. Locate the downloaded Code::Blocks installer and double-click to start. Follow the on-screen instructions to begin the installation.
a
Code::Biocks
a HOU Fo
OTE:
aca
wat
Cree
(i
rte Nes
ane
ht eters
Chasggteg
Thr
he
ners
ay
a
Ratna
ko
1a
MELA
x
tte
mo
ns
oetane pat
Sana
pte
Welcome to CodeBlocks Setup
he
vn Zadensses heared a
0
and
Say
ne! Dabian reppin he
em
ant ned
Famn
pny Shes ete
don
4
ned ney
ne
Setup will guide you through the installation of CodeBlocks.
It is recommended that you dose ail other applications before starting Setup. This will make it possible to update relevant system files without having to reboot your computer. Click Next to continue.
There you can see, there are several Windows versions available. The one you want to download has mingw-setup.exe at the end of the current version number. At te time of writing this is: codeblocks-17.12mingw-setup.exe. The difference is that the mingw-setup version includes a C++ compiler and debugger from TDM-GCC (a compiler suite).
Once you agree to the licencing terms, a choice of installation options becomes available. You can opt smaller install, missing out on some of the components but we
STEP 4
STEP 2
for
a
recommend that you opt for the Full option, as default.
|
lode
cEloubs
-
instalation
Choose Components
AAyyrtown
xP
vita 70.21
Choose which features of CodeBlocks you want to install. 10:
codeblocks 17.12 setup.oxe
30 Dae:
codeblocks 17.12 setup nonadmin.oxo
0 Oe
codeblocks-17. 12-nosetup zip
0 Dee
codeblocks-17. 12mingw-setup.exe
30 Dee
Paabhorks-17 TPmungwnnnetup
:
71p
codabineks-1/ T2mmgw_tortran-selap exe
3M
WOTE The codellocks-17 12-selup.exe fie includes Code Blocks with all plugins. The codeblucks-17.12-selup-ionadmin.exe fle is provided NOTE: Tho codablocks-17. 12mingw-sstup.oxa file inckides adcitonaty the GCC/G+-+ compiler and GOB
debugger from
for
Dee
Check the components you want to install and uncheck the components you don't want to install. Click Next to continue.
Select the type of install: Or, select the optional components you wish to instal:
[Ful:
everything All plugins, all tools, just
3-4]
Default install
Contrib
conven
lc:
TOM GCC (vorsion 6.1.0. 32 be,
(Toa. ccc). NOTE The codeblocks-17 12{nargw}nosetup.cip fles ave provided “installahon” yau are on your awn
iunsure, please use codeblocks-t7, $2magwselup.exe!
alel-)
www.bdmpublications.com
fur commenience
ty users that aw allvigic against installers,
Hower,
i wil not allow Description
Space required: 253.4 MB
Position your mouse aver 4 component ta see its
x
to Set Up C++ in Windows
(How
Next choose an install location For the Code::Blocks files. It's your choice but the default is generally sufficient (unless you have any special requirements of course).
When you click Next, the install begins; when it’s finished a notification pops up asking you if you want start Code::Blocks now, so click Yes.
a
There’s
a lot you can do in Code::Blocks, so you need to dig in and find a good C++ tutorial to help you get the most from it. However, to begin with, click on File > New > Empty File. This creates a new, blank window for you to type in.
STEP 8
Wi -unteteat - CosesBiocts
Ae
Voew
Search
17.12
Propet Gold Cebu
fortmn
wmih
Took
Tooke Plugins
Deyiincts Settings Help
D
Create shortcut: C:
Extract: gdbinit, Output folder:
Roaming Mic osoft\Windows\Start Menu Programs
G5
a
Blocks Installation
Coden
@
Ness Shaederinan dutgram
Do you want to run Code::Blocks now?
Create shortcut: C: Users\david AppData Roaming Microsoft\Windows\Start Menu'P... Nullsoft Install Systen
STEP 6
3.02.1
The First time Code::Blocks loads it runs an
autodetect for any C++ compilers you may already have installed on your system. IF you don’t have any, click on the first detected option: GNU GCC Compiler and click the Default button to set it as the system’s C++ compiler. Click OK when you're ready to continue. Compilers auto-detection
oO
Note: After auto-detection, at least
Select
you
one
ee
favourite default:
x
compier’s master path is still empty and therefore invalid.
re nes
master path Inter inthe
STEP 9
In
the new window, enter the following:
#include
Int maind t //My first C++
program
Std: :cout
“ot found ‘ound
1
wot
found
2 3
iot found
4
Not found
‘
compiler com
332) Compiler
5
Not found
2
"ot found
*
8
diy Bal
taxat Coe prog ceeak
Save as and save the code witha .cpp extension (helloworld.cpp, for example). Code::Blocks changes the view to colour code according to C++ standards. To execute the code, click on the Build and Run icon
types. Again, we would recommend you opt For the last choice, to associate Code::Blocks with every supported file type.
along the top of the screen. It’s a green play icon together with yellow cog.
Saystsivaee
etatie
A
aaa
Code::Blocks
6
asrenity not the defeut application for
De you
want
‘You
aways change sasoastore fran
can
Oe
sett as defeat?
Cit
Testine ay
vource Mes.
the eneronment setungs biter.
everyinng nee tia an
‘Ore lee Otter,
be
a
-
°
ite
STEP 10
every tary onsets
(rt ask tt
agen
ent est)
assnciate Code: Boda with C/C++ fhe types
Biter, senccete
Code:
toc
wit every augported type fndudiny project fee
from
otter
IDE)
Ca]
www.bdmpublications.com
atiyd
How to Set Up C++ ona Mac To start C++ coding on a Mac you need to install Apple’s Xcode. This is a Free, Full Featured IDE that’s designed to create native Apple apps. However, it can also be used to create C++ code relatively easily.
XCODE Apple's Xcode is primarily designed For users to develop apps for macOS, iOS, iPadOS, tvOS and watchOS applications in Swift or Objective-C, but you can use it For C++ too. Start by opening the App Store on your Mac, Apple Menu > App Store. In the Search box enter Xcode and Return. There will be many suggestions Filling the App Store press window but it’s the first option, Xcode, that you need to click on. dy
Weta
Cage
crane
Acoae
seaty
ae Seroot
= a 1B
tor
tr Xe
2200
orssetearson
Lat
ree Susp
oo
manone
‘
ae Senoot
oreo
ox
om
mortars
aisfood
=
ond
pea ws
|_| os
=
angperara wre ter
an
= an
Tebiviseees oe
= code)
Une =
om
tor
20
Keo
te ent
om
om
We Coren cornet
7
be
fos]
oD
Som
®e
o
7
1 Aree
Search
When you're ready, click on the Get button which then turns into ‘Install App’. Enter your Apple ID and Xcode begins to download and install. It may take some time depending on the speed of your Internet connection.
STEP 3
a
Rene er
fra]
ee :
|
anaes Fe
Take a moment to browse through the app’s information, including the compatibility to ensure you have the correct version of macOS. Xcode requires macOS 10.12.6 or later to install and work.
When the installation is complete, click on the Open button to launch Xcode, Click Agree to the licence terms and enter your password to allow Xcode to make changes to the system. When you've done that, Xcode begins to install additional components.
Xcode
gf Totes visse
wens
‘pepe ino,
Xcode and Apple SDKs Agreement PLEAGE BCROLL
OFTWARE OF
DOWN AND
nvelopes reed to create areat 2s19n, coding testing, and cet
READ ALL OF THE FOLLOWING TERMS.
SERVICES.
APPLE APPLE. ANO
OF
THIS
A!
IF YOU AQAEE
THE TERMS AND CONDITIONS, CLICK’ OR INC "AGREE" BY COWNLOADING,
Save...
TO BE BOUND
‘OR
Disagree
BY ALLey
COPYING
ANY
Agree
Pers
a
uaihes
ng aos easier and
More
9.2
ale)
www.bdmpublications.com
Pen,
(
The next step asks where to create a Git Repository for all your Future code. Choose a location on your Mac, or a network location, and click the Create button. When you've done all that, you can start to code. The left-hand pane details the Files used in the C++ program you're coding. Click on the main.cpp file in the list.
With everything now installed, including the additional components, Xcode launches, displaying the version number along with three choices and any recent projects
STEP
How to Set Up C++ ona Mac
STEP 8
5
that you've worked on; although for a Fresh install, this shows blank.
I
7
>
on
be
Rene OH 0ECWceeeges
Reem
alone
tommenarive
.
ne
Page
nme
meron
Cepepmmmtend
Omran
sere
. Paecronn
ha No Recent Projects
ae ce
‘Sein
Explore new ideas
quickly and
Clone
an
Mee
Ort
Ba
bate
Deereeens Tage
Apple Watch or
are
mein Qonen
Peo sine
Apple TY.
See
existing project
Siart working on something from an SCM repository.
ssa
em
teneunt
a
eceneteme
weersen
toe
+ Show this window when Xcode launches
Serpe
Open another project...
Start by clicking on Create New Xcode Project; this opens a template window from which to choose the platform you're developing code for. Click the macOS tab, then the Command Line Tool option and Finally, Next to continue.
You can see that Xcode has automatically completed a basic Hello World program for you.
oS
Fillin the various fields but ensure that the Language option at the bottom is set to C++. Simply choose it from the drop-down list. When you've Filled in the fields, and made sure that C++ is the chosen language, click on the Next button to continue.
The differences here are that the int main () Function now contains multiple Functions and the layout is slightly different. This is just Xcode utilising the content that’s available to your Mac.
project:
Team;
Organization Nama:
When you want to run the code, click on Product > Run. You may be asked to enable Developer Mode
STEP 10
on the Mac; this is to authorise Xcode to perform Functions without
needing your password every session. When the program executes, the output is displayed at the bottom of the Xcode window. 008
new
cee
as
oe
Choose options for your
iB
5
teens
“oe
a
easily.
Create anew Xcode project
pz
nme
Prevtaiening Paria bane Remtied
~
.
Get started with a playground
Create an app for iPhone, iPad, Mac,
aoncarers etcmrem
Ded hat hemt.
'
Version 9.2 (90400)
(S|
enanenbareet
La onl aseeneal
Welcome to Xcode [a]
fe
themeoO
*
Goce
meme
Guim
ec
“
BCs
tegen
bern Cos
5
remap
Reacnes
to
Add account... David Hayward
Organization identifier:
www.bdmpublications.com
109
Introducing C++
How to Set Up C++ Linux
In
great C++ coding environment. Most Linux distros already have the essential components preinstalled, such as a compiler. The text editors are also excellent For entering code into, including colour coding. There’s also tons of extra software Linux is
a
e
available to help you out.
LINUX++
For this example, we're using a Fresh installation of Linux Mint. However, these also work if you're using Ubuntu or any other Debian-based Linux OS.
a to
The First step with ensuring Linux is ready For your C++ code is check the system and software are
up to date. Open a Terminal and enter: sudo apt-get update && sudo apt-get upgrade. Press Return and enter your
password. These commands updates the entire system and any installed software.
File
View
Edit
Search Terminal s ~ §
ee
eee
sudo
AMazingly, that's it. Everything is all ready for you to start coding. Here’s how to get your first C++ program up and running. In Linux Mint the main text editor is Xed can be launched by clicking on the Menu and typing Xed into the search bar. Click on the Text Editor button in the right-hand pane to open Xed. epseaciee
Help
apt-get update
&
[sudo] password for david: Jj
Most Linux distros come preinstalled with all the necessary components to start coding in C++. However, it’s always worth checking to see if everything is present, so still within the Terminal, enter: sudo apt-get install
build-essential
and press Return. IF you have the right components, nothing is installed but if you're missing some then they are installed by the command. david@mint-mate Edit
File
View
Search « je
Terminal §
sudo
lists...
~
Help
apt-get install build-essential
rade,
@
to newly
eget
oon
Am earcias serene] MEG
rteroemeeraie
F
Uenrens Docume?
In Xed, or any other text editor you may be using, enter the lines of code that make up your C++ Hello World program. To remind you, its:
STEP 4
#include
int main() { //My first C++ program
std::cout
.
If not, see
code you're entering, including placing a closing speech mark as soon as you enter the First. Don’t Forget the semicolon at the end of the line; this is one of the most important elements to a C++ program and we'll tell you why in the next section. For now, move the cursor down to the closing curly bracket and press Return.
i)
F#include
int main()} {
}
Just as before, Code::Blocks auto-completes the
STEP 9
|) x]
1
int main(}
i
I
Notice that Code::Blocks has automatically created corresponding closing curly bracket a couple of lines below, linking the pair, as well as a slight indent. This is due to the structure of C++ and it’s where the meat of the code is entered. A
a
Now enter:
//My first C++ program we
|
std::cout
Now click on the Run icon, the green play button. A command line box appears on your screen the words: Hello, world}, followed by the time it’s taken —_ displaying see a group of icons: a yellow cog, green play button andacog/play to execute the code, and asking you press a key to continue. Well button together. These are Build, Run, Build and Run functions. done, you just compiled and executed your First C++ program. IF your code is looking similar to the one in our screenshot, then look to the menu bar along the top of the screen. Under the Fortran entry in the topmost menu you can
cke 17.12
yect
Build
Fortran
Debug
mals
wexSmith
)
Start here
L
|
*helloworkLcpp
=
Tools
BS x
STEP 4
Tools+
Plug
#include
t
18
}
going on:
cout view. txt notepad.exe view.txt
echo. File
Now, create a batch File that displays the contents of any directory and post it as a text file to the user's screen. Add the Following to the list.bat batch File:
STEP 3
File >
list.txt
list. on
-ivtepag
Edit
Format
View
Help
off
cls dir “ci\"
echo.
type
> List.txt List.txt
echo. echo Hello, XUSERNAME%. echo From the list, which directory would you set /p view= (enter as c:\directory) dir “Xview%" > view. txt notepad.exe view. txt
522
Save and execute the batch file. Within the
command prompt you can see the contents of all the Files and directories From the root of the C:\ drive; and as any user under Windows has permission to see this, there’s no UAC elevated privileges required.
like to
view?
What's happening here is the batch file asks the user to enter any of the directories displayed in the list it generated, in the form of ‘e:\directory’. Providing the user enters a valid directory, its contents are displayed as a text File. We created the view variable here along with %HOMEPATH%, to store the input and the text file.
STEP 4
SoBe dein Cer
slipVR
a
Directory of c:\ dey
Aes
dene apa e
Pas
e
craeusnay Cielp
Adora
Perflogs Program rue
a
Files
aeRO
|
CoB)
veteng tr avtve Time
Serial
bas
no.
Label.
Nonben $< $E47-ABEF
cae
Ss
cates
cae
Al
wb v
8 8
6,912 $1241
BOM
ee
BOL
Loge
:\Users\david\Documents\Batch Fi 206,692 tog 6,912 Etcape ser
Escape
162
www.bdmpublications.com
( It’s always a good idea, when creating text Files for the user to temporarily view, to clean up after
yourself. There’s nothing worse than having countless, random text Files cluttering up the file system. That being the case, let's clear up with:
STEP 8
Instead of left clicking on the Command Prompt result, as you did the First time you opened it,
right-click it and from the menu choose Run as Administrator. There is a risk that you could damage system Files as the Administrator but as long as you’re careful and don’t do anything beyond viewing directories, you will be okay.
cls del /Q view.txt del /Q list.txt echo ALL files deleted. System clean. Bier Fe
|
Ede
ae els
View
Format
Help
Filters
~
Best match
off
=
> Iist.cxt List.txt
Gir “cr\" echo.
echo Hello, SUSERMOMES. ‘echo From the which directory would you set /p view (enter as c:\directory)
list,
dir “AviewX”
like to
view?
els
Se
del JQ view.txt del /Q list.txt
All files deleted.
Command Prompt
Cs Run as administrator
>
view. txt notepad.exe view. txt
echo
@
nereoss
|
type
with Variables
Playing
(1 Open file location
System clean.
&
the Files without any user input or notification. The Final message informs the user that the files are removed.
Pin to taskbar
—4
The additions to the batch File simply clear the command prompt window (using the cls command) and delete both the view.txt and list.txt files that were created by the batch file. The /Q flag in the del command means it deletes
STEP 6
>
ap Pin to Start
This action triggers the UAC warning message, asking you if you're sure you want to run the Windows command prompt with the elevated Administrator
STEP 9
GE Command Prempt
privileges. Most of the time we wouldn't recommend this course of action: the UAC is there to protect your system. In this case, however, click Yes.
User Account Control
Do you want to allow the following program to make changes to this computer? Windows Command Processor Program name: Verified publisher: Microsoft Windows
STEP 7
Depending on how DQ
@
(¥)
Filters
Yes
show details
is
your system configured, you may not get any directory information at all or message stating Access Denied. This is because the UAC is blocking access to
Bestmatch Command Prompt
a
protected areas of the system, like c\Windows or C:\Program Files.
Therefore, you need to run the batch File as an Administrator. Click the Windows Start button and enter CMD again.
Change when these notifications appear
Desktop BPP
Search suggestions
Pa
d-
See web results
>
With the UAC active, the command prompt looks a little different. For starters, it’s now defaulting to the C\WINDOWS\system32 folder and the top of the windows is
STEP 10
labelled Administrator. To run the batch file, you need to navigate to the Batch Files directory with: cd \Users\USERNAME\Documents\
Batch Files. To help, press the Tab key to auto-complete the directory names. Ge Administrator; Command Prompt
ikea
t
tem32>cd “\Users\david\Documents\Batch
Files"
Ss
www.bdmpublications.com
Wey)
Introducing Windows 10 Batch Files
)
Batch File Programming It’s the little additions we can make to a batch file that help it stand out and ultimately become more useful. While the Windows graphical interface is still king, the command
line can
just as much, and this is where batch Files come into their own.
do
SEARCHING FOR FILES Here’s an interesting little batch File that you can easily extend For your own use. It asks the user for a File type to search for and displays the results. We are introducing a couple of new commands into the mix here but we think they're really useful.
Create @echo
a
new batch file called seek.bat and in it put:
cls
off
color
2
echo Please enter the type of file you want to search for (MP3, DOC, JPG for example) echo. -
Notepad
Edt
Format
Ad seek File
@echo
2
echo Please enter the type of file you want to search for (MP3, DOC, JPG for example)
echo. set /p ext= where /R
c:\
*.%ext% > found.txt
notepad.exe found.txt View
cls
Help
off
color
cls color
off
@echo
cls color
Now let's extend the seek. bat batch File:
a
2
echo Please enter the type of
file
you want
to search for (MP3,
DOC, IPG
for exemple)
echo.
del /Q found.txt aBernsen Ue mat lgeche
=—
13%
ne
off
jets
[solor
2
lacho fecno. Pieese enter the type of
file
you
went tu
EEBrch
for (WS,
DC,
206
for
axmple)
set Jp wrte
[niece 7K c:\ *.KexeS > Found. rotepad.ene found. tet
txt
eolor
[ft
a0
ot,
The new command in this instance is color
(Americanised spelling). Color, as you already assume, changes the colour of the command prompt display. The color attributes are specified by two hex digits, the First corresponds to the background colour of the Command console and the second to the Foreground, and can be any of the Following values:
10 fowndneee
Another new command, Where, looks For a specific file or directory based on the user’s requirements. In this case, we have created a blank variable called ext that the user can enter the file type in, which then searches using Where and dumps the results in a text File called Found.txt. Save and run the batch file. we aa bat fern ldecho
0O=Black
68=Grey
1=Blue 2=Green 3=Aque
9 = Light Blue
4 = Red
5=Purple 6=Yellow’
7=White
A2=Light Green B=Light Aqua C = Light Red D
=Light Purple = E Light Yellow F=6right White
‘color
vom
Hay
2
echo Plesse enter the type of
echo.
‘|
off
file
you want ta search
for
(92, DX,
at
296
for exemple)
mo
s\Suamer JAWALK THE TOW - Shut Up and ‘samme? 18 Rede
“The Wladbe
Could You Se
(Live)
Morty
003
mys
Loved
.
sat Matdarsier, wal
Sete
1
Stardting.p3
One Love People Get Reody.op3 TL Shot the eS t4 Vole.mg3 Wateing 32. Hedeaption Song, mp3
Natlers\Oh,
6
‘Sathity +
Nes Le\BOb
www.bdmpublications.com
Maren
id:Poste\Sob Manley 2 The Wallers\O1. Ix this Love.ap Metlers\02 Ho Woman We Coy
:\Uvers\davtd
ay)
DancelMpMonverter rt ].ap?
Grey,
Recley
&
The
My
03
Shard Sout.apd
Exc ep) Meblers\i6. Jamming Puniy Reggae Party.ap}
( Batch File Programming CHOICE MENUS Creating a menu of choices is a classic batch file use and a good example to help expand your batch File programming skills. Here’s some code to help you understand how it all works.
STEP
1
command in
Rather than using a variable to process a user’s response, batch Files can instead use the Choice conjunction with an ErrorLevel parameter to make a
menu. Create a new File called menu.bat and enter the Following:
@echo
cls
off
@echo
ErrorLevels are essentially variables and the /M switch of Choice allows a descriptive message string to be displayed. Extend this menu with something new: eeeieyemme
cls
off
echo.
choice
/M “Do you want
if errorlevel if errorlevel
2
to continue? Y/N”
echo
echo.
goto N goto Y
1
echo Please choose a
directory.
echo.
goto End:
echo Press
1
for c:\Music
echo. echo Press 2
for c:\Documents
echo. echo Press 3 for
c:\Pictures
echo. echo Press 4
for c:\Videos
echo. echo Running the code produces an error as we've called a Goto command without any reference to it in the exactly that, goes to a specific line in the batch Finish the File with the following and run it again:
file.
Goto does
file.
oN
echo.
choice /C 1234
if if if if
errorlevel errorlevel errorlevel errorlevel
0 Sto)
echo You chose No. Goodbye.
goto End
4 goto Videos 3 2
1
goto Pictures goto Documents goto Music
Now add the Goto sections:
rY
:Videos
echo.
cls
echo You chose Yes. Hello
CD %HOMEPATH%\Videos
>
echo You are now
End sereces
Borers j
iad
Fae
quero
3s
in the Videos directory.
goto End
Format
:Pictures
Yee etn
of
cls
7
[chatce “De 2you want vo comtinue? ¥/M" Af errorlevel goto errorlevel 1 gate ¥ este ted
1
=
%HOMEPATH%\Pictures echo You are now in the CD
~
acho.
Jacho You chose Ho. Goodbye,
Wi Corman
smipms
Pictures directory.
goto End
Prompt
:Documents
cls CD %HOMEPATH%\Documents
The output from your choice is different depending on whether you pick Y or N. The :End part simply signifies
STEP 3
echo You are now in the Documents
directory.
goto End :Music
the end of the file (also known as EOF). Without it the batch file runs through each line and display the Y response even if you enter N; so it’s
cls
important to remember to follow your Goto commands.
CD %HOMEPATH%\Music
echo you are now
in the Music directory.
goto End IDo
You
you want to
cantinue? V/N [¥,N]
2M
:End
chose Ha. Goodbye.
Hello \Documen
‘id\Documen
STEP 6
When executed, the batch file displays menu and with a
each choice the code changes directory to the one the
user entered. The %HOMEPATH% system variable will enter the currently logged in user's Music, Pictures and so directories, and not anyone else's.
www.bdmpublications.com
165
Introducing Windows 10 Batch
Files)
Loops and Repetition Looping and repeating commands are the staple diet of every programming language, including batch file programming. For example, you can create a simple countdown or even make numbered Files or directories in the system.
COUNTERS Creating code that counts in increasing or decreasing number sets is great for demonstrating loops. With that in mind, let’s look at the If statement a little more, alongside more variables, and introduce the Else, Timeout and eof (End of File) commands. Start by creating a new batch file called count.bat. Enter the Following, save it and run:
oe
off
@echo
The count.bat is rough way of demonstrating a loop; a better approach would be to use a For loop. Try this example instead:
a
a
off
cls
@echo
set /a counter=0
for /L
:numbers
set /a counter=%counter%+1 if %counter% ==100 (goto :eof) else Cecho
%%n
in (1,1,99)
do echo %%n
[2 fecno off for ML Xin
$0
(1,1,989
do
core Ver
%counter%)
timeout /T 1 /nobreak > nul goto :numbers BD
count
File
Edit
@echo
cls
-
Netepadd
Format
View
Help
of f
set fa counter=0 :numbers
set fa counter=%counter%+1 if %counter% =-10@ (goto :ecf) else (echo Xcounter%) timeout /T 1 /nobreak > nul goto :numbers
Breaking it down, there’s For, then the /L switch, which handles a range of numbers. Then the parameter labelled as
STEP 4
STEP 2
The count. bat code
starts at number one and counts, scrolling down the screen, until it reaches 100.
The Timeout command leaves a one second gap between numbers and the
Cemmand Prempt
-
count
%%n to denote
a
number. Then
the in (1,1,99) part, which tells the statement how to count, as in
1
(start number),
1
(steps
to take), 99 (the end number).
The next part is do, meaning DO whatever command is after.
Else statement continues
until the counter variable
equals 100 before going to the eof (End Of File), thus closing the loop.
:\Users\david\Documents\Batch Fi
www.bdmpublications.com
(
There are different ways of using the For loop. In this example, the code creates 26 directories, one for each letter of the alphabet, within the directory c\test which the batch File makes using the MD command:
You can include the pause between the numbers easily enough within the far simpler For loop by
STEP 8
adding multiple commands after the Do For loop. The brackets and ampersand (&) separate the different commands. Try this:
@echo off FOR %*F
off
@echo
for /L
in (1,1,99) nul)
%%n
/nobreak >
do Cecho %%n &
timeout /T
Loops and Repetition
INCabcdefghijyklmnopgqr
1
s,t,u,v,w,x,y,Z)
C:\test\%%F)
DO Cmd
B count- Hotepad fama FOR XXF IN
Yon
(a,b,,4,,f,8,h,41,9,K,1,0,9,0,0,0,%,5,t,U,V,WyX,¥,2)
8 |
One of the great time saving uses of batch files is to create multiple, numbered files. Assume that you want twenty five text Files within a directory, all numbered fom 1 to 25. A For loop much like the previous example does the trick:
STEP 6
off
@echo
for /L
in (1,1,25)
%%n
do copy nul %%n.txt
(14,25)
do
coy
rub
Setet
C:\tost\XXxF}
Command Frempt
Loops can be powerful and extremely useful elements ina batch file. While creating 26 directories may not sound too helpful, imagine having to create 1,000 users on a network and assign each one their own set of unique directories. This is where a batch file saves an immense amount of time.
STEP 9
Thue ‘gecho for fA Bho tn
DO (md
>t
i
+
>
Oate mocinet
a
Forepettem Sy
¥ +
it Temtonw onttin
>
ah
mre
»
1
+
>
Mey
Oocements
BF
de
Donstonds
>
pte
»
ven
>
181)
CvavROIN
ie
ae
See
Tyre
faethe ‘fetohtee
a
Htone
3s
retoe
ae
a owareerss
1
Yo
tach ieg 7tat
Name
fea rastate
Fy
Pete etait:
he
a
dn de
Fite
fy Cason,
toler
Hele
ie
fant
ide
>
+
>
anlar
you open Windows Explorer, and navigate to the Batch Files directory where you're working from,
off
for /L
2
ae rae
#%n
eo +
Ommences
cd
Dewentam
>
a
too
omone
miner
Pwo
ae
Should you ever get stuck when using the various commands within a batch file, drop into the command prompt and enter the command followed by a question
switch. For example, for /? or if
/2.
You get an on-screen help File
detailing the commands’ use. For easier reading, pipe it to
For
in (1,1,25)
/?
>
a
text file:
forhelp.txt
do copy nul User%%n.txt -
bore out
a
teen
STEP 10
IF
you can now see 25 text files all neatly numbered. OF course, you can append the file name with something like user1.txt and so on by altering the code to read:
@echo
bene
0
x
e
a
Taare
=e
mn
Flee
Die
tat
EDet oped soa Jeet oasecy
9) Docmens ww
F
Oreo
othe
Wem
See cee
Set et Sewer
Brien
ucioes a renmeny
Ota 4
ener
en
aa Been geet Dawn
Boer
www.bdmpublications.com
aC
y4
Creating
Batch File Game
a
off
@echo
Cls istart set /a score=0 set /a question=0
‘Hereisibrie ma
oti)
ihe mi
loading screen in a separate batch File and save it as screens.bat (For example). Then, from the main game batch file, you can load it at the beginning of the file
with the ‘call’ command Followed by colour to reset the game’s colours:
WED
Select Command Prompt - tereent
set /p
q
name= What
is your
name?
‘menu
cls echo.
SHO
EEE ERIK ER ER EEE EREREREREEERE
kk
ww
Make up your own questions but how about also including an introductory or loading screen? Make your
@echo off Cls Call screens.bat color :start set /a score=0 set /a question=0 cls set /p name= What is your
cls
echo. echo Welcome echo. echo Press 1 echo. echo Press 2 echo. echo Press Q echo.
tname%
to the super-cool trivia game.
to get started
for instructions to quit KEKE REREEREREERERER
SCHOO
xk
choice /C 129
if errorlevel if errorlevel if errorlevel
3 2 1
goto :eof goto Instructions goto Game
:Instructions
cls name?
echo.
CHO echo.
KRKRIRKR HAAR ER ERR ER
echo The
instructions
KIA
are simple. Answer
the
questions correctly. echo.
I RIK IK
CIO pause
cls
goto menu :Game
set /a question=%tquestion%+1
cls if %question’
==5 (goto end)
else (echo you
are on
question %question$) echo. echo get ready for the question... echo. timeout /T 5 /nobreak > nul if tquestion% ==5 (goto end) else (goto %question%) iL
cls echo. OCHO
4
echo.
IRI AIR IRE
ERR IR ERE
e e echo Your current score is %score% echo. echo HKKKK KK KEKE KERR RE echo. echo. echo Question %question’. echo. echo Which of the following version of Windows
is the
best?
echo. echo A. Windows echo. echo B. Windows echo. echo C. Windows echo. choice /C abc
if errorlevel if errorlevel if errorlevel
3
2
1
10
ME
Vista
goto wrong goto wrong goto correct
72
cls
echo.
SCH
FEKKKKAKKKKKKERKEKEKEREEEEKKEKE
echo. echo Your current score is %score% echo. KK KKK KIRKE REE echo echo. echo. echo Question %question%’. echo. echo Which of the following version of Windows most stable? echo. echo A. Windows 10 echo. echo B. Windows 95 echo. echo C. Windows ME echo. choice /C abc if errorlevel 3 goto wrong if errorlevel 2 goto wrong
if errorlevel
1
is the
goto correct
33
cls
echo. SCHOO
REKKKKAKKKKKKEKKRKKKEREEKREKRKE
echo. echo Your current score echo. SCHOO
is
%score%
FEKKKKAKKKKKKKEKEKEKEREEERERKK
echo. echo. echo Question %question’. echo. echo Which of the following Windows version
latest?
echo. echo A. Windows 10 echo. echo B. Windows 98 echo. echo C. Windows 7 echo. choice /C abe
is the
( if errorlevel if errorlevel if errorlevel
Creating a Batch File Game
goto wrong goto wrong goto correct
3
2 1
els echo. echo HIKKKK KERIKERI REKREREREREIEERER echo. echo Your current score is %score% echo. SCHOO KAKKKKKAEKARKKKKKEEKEKEKEEKREEEEREE
echo. echo. echo Question %questions echo. echo Which of the following Windows uses DirectX 12? echo. echo A. Windows 10 echo. echo B. Windows 3.11 echo. echo C. Windows XP echo. choice /C abc if errorlevel 3 goto wrong if errorlevel 2 goto wrong
if errorlevel
goto correct
1
:Wrong
els
echo HEKKKKEKEKEKEKEKEEEEE echo. echo WRONG!!!! echo. OCHO KAKKKKKKKKKKKKKKKE
set /a score=%score%-1 pause goto :game
:correct
cls echo KEKKKKEKREKKEREKEKKK echo. echo CORRECT. YIPEE!!! echo. echo HEKKKEKEKEKREKEKEEEEE set /a score=%score%tl pause
goto :game end
cls ERERERERE
KE KEK echo echo. echo Well done,
%tname%,
you have answered
all the
questions echo. echo And your final score echo. echo $score% echo.
CTO
RR RHI
I
is....
HI HI
IRI
choice
/M “play again? Y/N” if errorlevel 2 goto :eof if errorlevel 1 goto start
www.bdmpublications.com
169
( coding Projects
& Ideas
This section features some Fantastic coding projects and ideas that you can use in your own code. Want to add
something a little extra to your code? How about creating a loading screen, TIANS)
ASCII characters?
There’s code here to track the in real-time, and we even look.bas at some retro coding, using BBC Micro BASIC, to give you a better understanding of how other forms:of code come together and work.
2...
There are always more ideas to code,
www.bdmpublications.com
Passing Variables to
hon
A ogra
iggy UE (vont
EINRKO
a
agra
(3 4 (M
at
fo}
ace)
THE WINDOWS WAY
script...
It
os.environ[ ‘name’ ]
printC“Your
is... “,
name
n)
L& batpy1.py - C:/Users/david/Documents/Python/BatPy/batpy| py
python batpy1.py echo
=
n
name=What is your name? echo Let’s try and pass this to a Python
set /p
worked!!
Format
Edit
File
Run
Options
Window
-
(3.7.0)
a
*
Help
import os
os.environ['name'] batpy1.bat Edit
@echo
a
Notepad
Format
View
name is...
", n)
Help
of F
set /p name-What echo
print ("Your
Let's try
is
re
File
-
oe
|
oo
ep
import os
off
@echo
abd
new text file and enter the Following:
a
a
Con ’=< 0
the batpy Folder, create
Now open Python and create a New File. Enter the following code:
STEP 3
ene
Let's begin by creating a sample Folder within your Python directory; call it batpy, for example. Within
ONE
a
>
=e
The two systems use slightly different ways to accomplish the same task; Windows is slightly easier (by a single command) so we'll start with that.
your name?
this to
and pass
a
Python
script...
python batpy1.py a
It worked!
1
1
New
8 Tan & mm
Python
»
Baty
BE
i
@ Name
Date masified
Type
Fl batpy!
TWDUATIIUDSE
«Windows Baten Fike
bap)
18/DU2019 0843
Python Fite
[&
BOM
Ckganse>
2
Baty
folder
Using Tet Fit t*
BF Drepber (Teatn
49 >
Python
»
vy
Bethy
&
Search
=a
Aer
Bars
Name
bat!
Varad:
Date eascdtied
TBOL2O9 AGES
ype Python Fite
@
‘use
1B
Tj Using Text Flest
3F Dropbox (Team Bt
Tern BOM
This PC
Me
Objects @ Detttop
OneDrive
GM
thes PC
DB wovyects
JB) Documents
>
E
Mi
ow
z
[BaF
Fneerhng
ANSI
-
Save
Desttop
(2) Documents
.
Saveas type: AllFiles
A Hide Folders
»
PiProjects Weat
B30
se
GoogleDive # Passing
Documents
»
Tet
Onedrive
Fe
ThisPC
New folder
a
+
Oryaive
Documents
=i
.
ecoint
|
Buthon
sythion batpyl. ty byl PY
It worked! !
eg
[pavers
set /p name-What is your name? thic tno echo Let‘s try and
echo
9
code as batpy1.py.
mone
a
of
Bt
ae
echo
te name: ESM
Save at type.
Cancel
A
bide Feleers
Python
tes Save
oneal
L.
» ae:
Vv
a
ie 4
_i
Os
Ww
7
y wa oa
E | Q
i)
TL Tuy
gy og To
a”
*
828°"
eanOba
.
,
oy
recap: we
o
ahd
a
j
rece
a
7
aslo)
have a batch file called batpy1.bat,
variable called name. It'll then print to the screen a message, then run the Python code, and finally print “It worked!!”. The Python code, called batpy1.py, uses the OS module to call os.environ[‘name’], stored as n. It'll then print the value of n after a
a
system
message. . ete
seat
“Dievwye- enet Fie Gat Feet nee leecns
Drop
intoaWidows command
prompt and
navigate to the Folder Batpy. To run
a
Windows
batch file, simply enter the command:
batpy1.bat Enter your name as instructed and the reply will be passed to Python, then back to the batch file to end. Ben
Fe
BY
ne
-
which asks the user their name and stores the info as
me
oR.
ee
Bee Dor wt eS ate. pee
«
Help
off
set fo onmectbat 1s your same? Let's try and past this to
Jecho
python
Bateyl
a
Python
script...
Py
Jacho Te workedt!
THE LINUX WAY Linux's version of passing variables to Python is slightly different, just because it’s Linux! It’s easy, though, and here’s how it’s done.
agle}
Start by opening your Favourite Linux text editor, and entering the following:
import os
#1/bin/bash echo -n “Hello, what read firstname
is
“ your name?
n
*batpy.sh (~/Documents/batpy
ie
export firstname
Cae
Mew
Search
Tori
Documents
@@uwiesees:xoda
python3 ./batpy1.py
#1
Help
Qi}
= os.environ[ ‘firstname’
printC“Your
stews
name
is... “,
“It worked!!!”
“hatpyt.py -shome/david/Documents/hatpy/batpy1.py(3.67)"
firstnane
python3 ./batpy1.py
n)
-
5
File Edit Format Run Options Window Help OS
export:
]
Save the Python code as batpy1.py.
/binioash
fo
echo echo echo -n echo
Now create a new Python file, and enter the following:
n
=
ry
os.environ[' firstname’ ]
print(’Your
name
is... °,
ny
echo echo
|
echa -n “Tt worked?!”
o a
Y w
Drop into a Terminal session and make a new directory called batpy (mkdir batpy). Save the Bash script as batpy.sh, and from the Terminal enable the script as executable with: chmod +x batpy.sh.
STEP 2
Back in the Terminal, enter: ./batpy.sh to run the Bash script. As you can see, the results are the same as in Windows. The major differences are making the Bash script executable, and adding the export Firstname command to the Bash file. In Linux, you need to export system variables before they can be accessed by the subsystem, in this case the Python code.
i i V4
david@david-Mint: -/Documents/batpy Terma’
ep
Retro Coding |
THE GOLDEN ERA OF CODE
THE BEEB
Sed
The problem with BASIC is that there were so
8
many different versions available,
rH
A A
across multiple 8-bit platforms,
3 is
with each
3
i
rs
RS
x P|
i)
aN
6
*
ms
BS
a
Sait:
PHEN
having its own unique elements on top of th ecore
BASIC Functions. The 3ASIC that was
packaged with the Co different to that on the ZX Spectrum, or the Atari
‘can
“ah, ls PRINT “FAH
BBC BASIC was used on the Acorn BBC Micro range of computers,
While it may seem a little counterproductive to learn how to code ina language that’s virtually obsolete, there are some surprising benefits to
utilising the MOS 6502-based processor technologies. It was one of the quickest examples of BASIC and, thanks to an inline assembler, it was also capable of allowing the developers of the time to write code for
getting your hands dirty with a bit of retro coding. Firstly, learning old code will help you build the structure of code as, regardless of whether it
different processor types, such as the Zilog Z80 — a CPU present in the ZX Spectrum, as well as many arcade machines.
language that was developed yesterday, or Forty years ago, code still demands strict discipline to work correctly. Secondly, everyday coding is
a
elements such as loops, sub routines and so on are a great visual aid to learn in older code, especially BASIC. Lastly, it’s simply good fun.
The easiest retro language to play around with is, without doubt, BASIC. Developed back in the mid-sixties, BASIC (Beginner's All-Purpose Symbolic Instruction Code) is a high-level programming language whose design was geared toward ease of use. Ina time when computers were beginning to become more accessible, designers John Kemeny and Thomas Kurtz needed a language that students could get to grips with, quickly and easily. Think of BASIC as a distant relation to Python.
processor that’s used in virtually every Android phone and tablet, as well as smart TVs, set top boxes and so on. The BBC Micro was born ina
but it was the BBC’s Computer Literacy Project (the BBC Micro) that was chosen, due to its ruggedness, upgradability, and potential for education. Asaresult, the BBC Micro, or the Beeb as it’s affectionately known, became the dominant educational computer throughout the 80s.
BEEBEM Naturally, you could scour eBay and look for a working BBC Micro to play around on, and it'll be a lot of Fun. However, for the sake of playing
around with some retro code, we'll use one of the best BBC Micro emulators available: BeebEm.
nai
BeebEm was originally developed For UNIX in 1994 by Dave Gilbert and later ported to Windows. It is now developed by Mike Wyatt and Jon Welch, who maintain the Mac port of the emulator, and is therefore available For Windows 10, Linux and macOS, as well as other platforms. using Windows 10, simply navigate to http://www.mkw. me.uk/beebem/index.html, and download the BeebEM414.exe that’s IF you're
F
displayed in the main screen. 4
i
Sh
SAM
JONATAWNEOYONG
The BBC Micro was designed and built by Acorn Computers—a company that is historically responsible For the creation of the ARM CPU - the
time when the UK government was looking for a countrywide computer platform to be used throughout education. Different companies bid,
GOING BASIC
ON
home computers, due to the differing hardware of each system. However, it’s widely recognised that one of the ‘best’, and possibly most utilised, form oF BASIC from the 80s was that of BBC BASIC.
BBC BASIC also has some interesting built-in Features, such as the value
BeebEm - BBC Micro and Master 128 Emulator
of Pl:
-F
circle
“ r Input “Enter the radius: 3@ let area = PI*r*r 40 print “The area of your circle 2@
5@ Download version 4.14 for Windows: Becbl
Area of a
1 REM
2 CLS
is: “;
area
print
eve
As you'll notice, variables with a dollar ($) represent strings, nothing after Once downloaded, launch the executable and Follow the on-screens instructions to install it. Linux users can Find the installation files, as well as Full instructions, at: http://beebem-unix.bbcmicro.com/download.
html. MacOS users can get everything they need From: http://www.
g7jjf.com/.
the variable, or a hash (#) represent Floating point decimals; a
whole integer has a % character, and a byte has an ampersand (8).
The single quotes after the Print on line 50
BBC BASIC
indicate a blank line, one
Once installed and powered up, BeebEm will display the default BBC system start-up, along with a couple of beeps. Those of you old enough to
BBC Computer 32K
for each tick, while REM
[elke lan Oat)
on line
BASIC
have been in a UK school in the 80s
Da
BASIC, we use line numbers to determine which line of code run in sequence. For example, to print something to screen we'd enter: In
print “hello”
BASIC >10 PRINT “HELLO”
Once you've typed the above in, press Enter and then type:
aa Pa
run
isa comment,
Needless to say, there's a lot you can learn, as well as having Fun, with BBC BASIC. It’s a rainy day project and something that's interesting to
will certainly recall this setup.
1®@
1
and thus ignored by the BASIC compiler.
show the kids — this is how we rolled back in the 80s, kids! There are a number of sites you can visit to learn BBC BASIC, such as http://archive.retro-kit.co.uk/bbc.nvg.org/docs.php3.html. See what you can come up with using BBC BASIC, or other BASIC types for
different systems, and let us know what you've created.
aad
We can of course expand the code to
OTHER SYSTEMS
include variables, multi-line print statements and so on:
“Hello, what’s your
10 Input 28 print 30 print
“
“Hi,
n$
“ I
hope
name?
“
n$
you’re well today.”
rere eee eee ee eee eee eee
Ov
1 CLS
Type RUN to execute the code, you can also type LIST to view the code you've entered.
HI, DAVID
Pe
I HOPE
YOU'RE WELL TODAY.
aE 1
CLS
10 INPUT "HELLO, WHAT'S YOUR NAME? "
As you can see, variables are handled
in much the same way as Python, a print statement on its own displays a blank line, and CLS clears the screen ~as used in conjunction with the OS module in Python and when running
Windows. We're also able to do some maths work, and play around with variables too: 1 CLS 1@
input “how old are you?
2@
print
40
if if
5@
print
30
a > 40 a < 4@
“a
print “You’re over 4@ years old.” print “You’re under 4@ years old.”
Naturally, you don’t have to look to the BBC Micro to play around with some retro code. IF you grew up witha
Commodore 64, then you can always try VICE, the C64 emulator. Likewise, the ZX Spectrum has a slew of great
emulators available for every modern system to play around on. In fact, you can probably find an emulator for virtually
every 8-bit or 16-bit machine that was produced over the years. Each has their own unique perspective and coding
nuances, so Find a few and see what you can create.
Ler
Text Animations bo
THE FINAL COUNTDOWN
andso onto 10.
phe
te sethe ee
a ei
ihe
It'll take some time, but it’s worth it in the end.
Of course,
you can always take a different approach and design the numbers yourself.
The next step of the process is to initialise the code settings and start
~ & “
O
the countdown:
#Initialise settings
start = 10 message = “>
ws
") >")
404040404 v40407)
3
33333333:
222222 12222222: 2
333333353333333
")
nin)
The code in its entirety can be viewed from within our Code Repository: https:// bdmpublications.com/ code-portal, where you're free to copy it to your own Python IDLE and use it as you see Fit. The end effect is quite good and it'll be worth adding to your own games, or presentations, in Python.
BB Command Premet - p:thor
8
es
To extend the code, or make it easier to use, you can always create the number Functions in their own Python code, call it Count.py For example, then import Count at the beginning of anew Python File called Countdown.py, along with the OS and Time modules:
hee
avy
import os import time import count
input(“Press Enter to launch rocket...”
bee
a date worm
*e@SOES tan 1 O88,
count.seven() elif counter ==
ROLLING DIE Aside from the rocket animation, together with its countdown, another fun bit of text-based animation is that of a rolling dice. a great animation to include in an adventure game, where the player rolls to see what their score is compared to that of an enemy. The highest roller wins the round and the losers’ health drops as a result. It’s an age-old combat sequence, used mainly in the Dungeon and Dragons board games and Fighting Fantasy novels, but it works well.
Arolling dice can be
6:
count.six()
elif counter
elif elif
==
5:
66 0~G--
count.five() counter == 4: count. four() counter == 3: count.three() counter == 2: count. two() counter == 1: count.one()
The code you'll need to animate
Cergreu tees
distanceFromTop = 20
ow
while True: os.system(‘cls’ if os.name
==
ee
II
print(®
II
print(*
AN os.name
distanceFromTop -= 1 if distanceFromTop
Now create a folder
in
your Python code directory
on your computer (call it Test, for now), and open either Notepad for a Windows 10 computer, or, if you're using Linux, then the currently installed text editor. Click on the Select & Copy
button at the bottom of the ASCII Generator webpage, and paste the contents into the text editor.
Open up Python and create a New File. We're going to need to import the OS and Time modules for this
STEP 4
example, followed by a line to clear the screen of any content. If you're using Windows, then you'll use the CLS command, whereas it’s Clear For Linux. We can create a simple if/else statement to handle the command.
L&
*test.py
File
Edit
2
xt
-
C\Users\davicl Documents\Python\ Test\test.py (3.7.0)"
Format
Run
Options
Window
Help
os, time
os.system('cls' 1f
og.name
= ‘nt’
else ‘clear')
i
De
a «3,
9)
Os
§
at atiY
iets ert a w FT TOSg JU yal.
"wa :
oa
oS
Dy
Gat
he fp ae:
ee
TotO9*notbeauszeBoO* ae — re
one
Next we need to create a list of the names of the
Here's the code in full:
text Files we want to open, and then we need to
import os, time
open them for display in the Terminal.
filenames = frames = []
for
name
os.system(‘cls’ if
[“1.txt”, “2.txt”]
filenames = frames = []
in filenames:
with openCname, “r”, encoding="utf8”) as frames .append(f .readlines())
mun
ma
f:
for
os.name
[“1.txt”,
«2
==
‘nt’ else ‘clear’)
txt]
name in filenames: with openCname, “r”, encoding="utf8”) as
f:
frames .append(f .readlines()) r
for
in range(1@): for frame in frames: printC”. joinCframe)) time.sleep(1) 1
Pe. systemt
Kalenemes =
frames = veer
1%
[1 17
fre eutenameere, enaodingenuernny sranop append {texeaalioes))
4
os.system(‘cls’ if
ft
‘clear’)
os.name
==
‘nt’ else
Note from the loop within the code, we've used the same CLS and Clear if/else statement as before. Again, if you're running on Windows then the OS module will use the CLS command, ‘ELSE’ if you're using Linux or a Mac, the Clear command will work correctly. IF you want, you could use a Try/
STEP 9
We've used the UTF8 standard when opening the text files, as ASCll art as text, within a text File, often requires you to save the file as UTF compliant- due to the characters used. Now we can add a loop to display the files as 1.txt, then 2.txt, creating the illusion of animation while clearing the screen after each File is displayed. oS
Lee
Fe
;a
; bi
(>>
print (n)
Hangman:
~
8
init
def
(self,word):
self.word = word
self.missed_letters = [] self.quessed_letters = [] guess (self, letter): af letter in self.word and letter
def
(range(1, 11))
fh, 2, 3, 4, 5, 6, 7,
ofa
class Hangman: def guess(self, letter):
RESTART: C:\Users\david\Documents\Python\Space Invaders.py
>>> |
x
Help
Python 3.6.2 (v3.6.2:5fd33bS, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit on win32 Type "copyright", “credits” or “license(}™ for more information.
colon to the end
And so on. The colon is what separates the code, and creates the indents to which the following code belongs to.
to 10.
1
a
not
in
self.guessed_letters:
guessed_letters. append (letter) un self.word and letter not
9, 16)
>>>
in
self.missed_letters.append (letter) return return
def
hangman_won
if
CASE SENSITIVE
False
True
hangman_over (self): return self.hangman_won{) cr
def
(len(self.missed_letters)
==
6)
(self):
*_' not
return
self.missed_letters:
in
self.hide word(}: True
False
def hide_word(self):
Python is a case sensitive programming language, so you will need to check any variables you assign. For example, Lives=10 is a different variable to lives=10, calling the wrong variable in your code
fox letter in self.word: if letter not in self.gquessed_letters: +="
else: rtn +=
can have unexpected results.
return
letter
rtn
le Python 2.62 Shell |
File
Edit
Shell
Debug
Options
Window
Help
|
Python 3.6.2 on
wins?
(w3.6.2:5fd33b5, dul
Type "copyright", "credits™ 33> Lives=10 y>> lives=49 33> Print 10 4
or
§
2017, 04:14:3
"license{)}™
for
mor
(Lives, lives}
OPERATORS Using the wrong operator is also a common mistake to make. When you're performing a comparison between two values, for example, you need to use the equality operator (a double equals, ==). Using a single equal (=) is an assignment operator that places a value toa variable (such as, lives=10). 2
c=i1d
3
d=
4
b
10
==
5
BRACKETS Everyone forgets to include that extra bracket they should have added to the end of the statement. Python relies on the routine having an equal amount of closed brackets to open brackets, so any errors in your code could be due to you Forgetting to count your
brackets; including square brackets.
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,} Brint {} print ("Letters Guessed: ',} for letter
Erint
be=5
2
in self.guessed_ letters: Print [{letterz,}
{}
c
#false because
da
terae
5
net
equal te 10 equal te 19
ig
because 13 is
OPERATING SYSTEMS Writing code for multiple platforms is difficult, especially when you start to utilise the external commands of the operating system. For example, if your code calls for the screen to be cleared, then For Windows you would use cLs. Whereas, For Linux you need to use clear. You need to solve this by capturing the error and issuing it with an alternative command.
#
Code to
detect
error
for using
a
different
OS
run=1
while (run==1):
try: os.system(‘'clear')
except OSError:
os.system('cls') print (*\n>>>>>>>>>>Python
3
File Manager bool;
ty
Hees
1+
Call python from module and recene output ,
({noreturn]] virtual veid fee() everride;
hanchan «c2A de it by hand tut
othe Inga
Lam creeng
A
s
a
__Pfhion function error problom
My 1tonal shan ratuk
“Foo: T must be floating point")
fjoo
Newsletters.
Users
Top
rm
@b16;
template struct Foo {
iC
anaes
StackExchange”
LINE
thet pope? oe
pipe she
ha werd
i
Where Next?
GOING MOBILE
PORTFOLIOS
The mobile market is a great place to test your coding skills and present any games or apps you've created. IF your app is good, then who knows, it could be the next great thing to appear on the app stores. It’s good learning experience nevertheless, and something worth considering.
IF you've learned how to code with an eye for a developer in job the future, then it’s worth starting to build up an online portfolio of code. Look at job postings and see what skills they require,
a
then learn and code something with those skills and add it to the portfolio. When it comes to applying, include a link to the portfolio.
DP Google Play
My Work Want to sce more examples?
Sate. Shy
Chronicled.org
Bihra che
Sea account
ay
maoscognors
Reser
anyones
ay ome Wy
ecoony Peay
Puree Gus
Gawnauk @|
ONLINE LEARNING
TEACH CODE
Online courses are good examples of where to take your coding skills next, even if you start From the beginner level again. Often,
Can you teach? If your coding skills are spot on, consider approaching a college or university to see if they have need For a programming language teacher, perhaps a part-time or evening course, If not teaching, then consider creating your own YouTube how to code channel.
an online course follows a strict coding convention, so if you're self taught then it might be worth seeing how other developers lay out
their code, and what’s considered acceptable.
Learn to code interactively, for free.
C++ Programming
IN ONE ‘Sagn
up
Log
In
VIDEO
060
foe
hp
natant Mam
Whal people think programming is vs. how it actually is swe
aga
Choose a username I
Your amail ackdrexs
Choose » password
tm
nota robot
ee
SHARE CODE
HARDWARE PROJECTS
Get sharing, even if you think your code isn’t very good. The criticism, advice and comments you receive back help you iron out any issues with your code, and you add them all to your checklist. Alternatively your code might be utterly amazing but you won’t know unless you share it.
Contributing to hardware projects is great resource for proving your code with others and learning From other contributors. Many of the developer boards have postings for coders to apply to for hardware a
projects, using unique code to get the most from the hardware that’s
being designed.
Share Code in Real-time with Developers An online code editor for interviews, troubleshooting, teaching & more.
www.bdmpublications.com
ex)
Black Dog Media
at) Master Your Tech
To continue learning more about your tech visit us at:
www.bdmpublications.com FREE Tech Guides
: Apple iPhone, Lee) Mac, MacBook & Watch
ro
Lightroom
iPione
Gaerne
bdmpublications Buy our Photoshop guides and download tutorial images for free!
Cx jane
Galaxy Guidebook mar
iomoyson
ge
reas a5
Simply sign-up and get creative.
BDM's Manual Series Teh Edition
-Black Dog Media Limited (BDM) lames ..
Ayshford Karl Linstead bin Drew, Martin Smith, Lena Whitaker uss Ware, David Hayward lison Drew Mark
Printed and bound in Great Britain by: Acorn Web Offset Ltd Newsstand distribution by: Seymour Distribution Limited 2, East Poultry Avenue London EC1A 9PT
International distribution by: Pineapple Media Limited www.pineapple-media.com Digital distribution: Readly AB, Packetmags, Zinio, Cafeyn, Magzter and promotional opportunities contact: For all advertising [email protected] INTERNATIONAL LICENSING Black Dog Media has many great publications and all are available For ticensing worldwide. For more information go to: www.brucesawfordlicensing.com; email: [email protected] telephone: 0044 7831 567372
Copyright
2020 Black Dog Media. All rights reserved.
Editorial and design are the copyright Papercut Limited and are reproduced under licence to Black Dog Media. No part of this
BDM’s Manual Series is an independent publication and as such does not necessarily reflect the views or opinions of the
publication may be reproduced in any Form, stored ina retrieval system, or integrated into any other publication, database, or
producers contained within. This publication is not endorsed or associated in any way with The Linux Foundation, The Raspberry
commercial programs, without the express written permission of the publisher. Under no circumstances should this publication and its contents be resold, loaned out, or used in any form by way of
trade without the publisher's written permission. While we pride ourselves on the quality of the information we provide, Black Dog Media Limited reserves the right not to be held responsible for any
Foundation, ARM Holding, Canonical Ltd, Python, Debian Project, Lenovo, Dell, Hewlett-Packard, Apple, Microsoft and Samsung orany associate or affiliate company. All copyrights, trademarks and registered trademarks For the respective Pi
companies are acknowledged. Relevant graphic imagery reproduced with courtesy of Lenovo, Hewlett- Packard, Dell,
mistakes, or inaccuracies, found within the text of this publication. Due to the nature of the software industry, the publisher cannot guarantee that all tutorials will work on every version of Raspbian
Samsung, FUZE Technologies Ltd, and Apple. Additional images contained within this publication are
OS. It remains the purchaser's sole responsibility to determine the suitability of this book and its content For whatever purpose.
reproduced under licence from Shutterstock.com. Prices, international availability, ratings, titles and content are
Images reproduced on the front and back covers are solely for design purposes and are not representative of content. We
subject to change. All information was correct at time of print. Some content may have been previously published in other
advise all potential buyers to check listing prior to purchase For confirmation of actual content. All editorial opinion herein is that
of the reviewer as an individual and
not representative of the publisher or any of its affiliates. Therefore, the publisher holds no esponsibility in regard to editorial opinion and content. is
volumes or BDM titles. We advise potential buyers to check the suitability of contents prior to purchase.
Black Dog Media Limited (BDM) Registered in Engtand & Wales No: 5341514
i
The Complete
The Complete
Mac
|
Nikon
Manual
1
Manual
The Complete
Outdoor Photography
Manual
* The Complete
The Complete
MacBook
Photography
Manual
|
The Complete
Photoshop
The Complete
Raspberry Pi
Manual
Expert Tutorials to Improve Your Skills
Sone;(}
. The Complete
Lightroom
Ady
The Complete
macOS
Catalina Manual
—=
Expert Tutorials to Improve Your Skills
The Complete
Samsung Gala Manuel
The Complete
Python &
Windows 10 Manual
Photoshop
Elements
C++
: Manual
Expert Tutorials to Improve Your Skills
The Complete
The Complete
‘=gj
Expert Tutorials
to
Improve Your Skills
The Complete
macOS
Big Sur Manual.
Expert Tutorials to Improve Your Skills
iPad OS 14
Go Deep with Apple’s OS!
Jigswd