Professional Documents
Culture Documents
The Complete
|||{» |
Manual
Master programming and
improve your i,
9)5
guides
\& t ip s y
Linux & C++skills
iPhone MacBook
User Manual
iPad
& iO S £ The essential step-by-step guide to
MacBook and macOS Sonoma User Manual &iPadOSE
User Manual
•essential step-by-
User Manual
The Com plete The C o m plete The C o m plete The C o m plete The C o m plete
W in d o w s 11
User Manual Galaxy
Samsung Google Chromebook
User Manual
W h a ts A p p
Manual
The essential step-by-step manual User Manual Master your Chromebook and
Google's Chrome OS
The essential step-by-step
to mastering Microsoft's Windows 11
Manual " Googles amailng tree apps /owwX
720
manual to mastering
your WhatsApp
1essential step-by-step manual ta using your
\ GOIDtS j
^ MASTERPYTHONPROGRAMMING LINUX,PYTHON&C++CODING < ,■$ LEARNPYTHON&C++CODING </> ^ PROGRAMUNUX,PYTHON&C++ <j > RASPBERRYPi5, Pi4,400&PICO gj
* The C o m plete i S' The Co m plete [ The Com plete The Co m plete * The C o m plete
V
The Com plete The Complete The Com plete The Complete The C o m plete
In s t a g r a m Internet [W in d o w s 1 0 1 Home Cloud
User Manual
essential step-by-step manual to mastering
Security User Manual
The essential step-by-step guide
Networking Computing
K A *■>■■A'l I ■ to mastering Microsoft's Windows 10
,— operating system Manual Manual
89Oi The essential step-by-step manual to using cloud
\ 'EES? Qjg-„
Keep yourself
secure and
your data
safe onl'ne
3 Popercut
For a full list of titles available please visit:
w w w .pclpublications.com
The Complete
SJPopercut
w w w .p clp ub licatio n s.com
6 ) Coding Foundations * 3 4 ) Coding with C++
8 Being a Programmer 36 Your First C++Program
10 A Brief History of Coding 38 Compile and Execute
12 Choosing a Programming Language 40 Using Comments
14 Creating a Coding Platform 42 Variables
44 Data Types
[ 1 6 ) Introducing C++ 46 Strings
48 C++ Maths
18 Why C++?
50 User Interaction
20 C++ Facts & Figures
22 Equipment You Will Need
24 Structure of C++ Code 5 2 ) Introducing Python
26 How to Set Up C++ in Windows
54 Why Python?
28 How to Set Up C++ on a Mac
56 What Can You Do with Python?
30 How to Set Up C++ in Linux
58 Python in Numbers
32 Other C++ IDEs to Install
60 Equipment You Will Need
62 Getting to Know Python
64 How to Set Up Python in Windows
66 How to Set Up Python in Linux
68 Python on the Pi
50 Complete Programs
Over 20,000 lines of code
Visit: www.pclpublications.com/exclusive
Please note: Sign up is required to download
8 Being a Programmer
10 A Brief History of Coding
12 Choosing a Programming Language
14 Creating a Coding Platform
Being a Programmer
Programmer, developer, coder, they're all titles For the sam e occupation, som eone w ho
creates code. W hat they're creating the code For can be anything From a video gam e
to a critical element on board the International Space Station. H ow do you become a
program m er though?
how Far to take before the bedroom coder was a thing of the past and huge teams of
designers, coders, artists and musicians were involved in making a single
game. This of course led to the programmer becoming more than simply
your coding someone who could fashion a sprite on the screen and make it move at the
press of a key.
adventure!" Naturally, time has moved on and with it the technology that we use.
Flowever, the fundamentals of programming remain the same; but what
exactly does it take to be a programmer?
# in c lu d e < s t d io . h >
# i n c lu d e < d o s . h > The single most common trait of any programmer, regardless of what
# in c lu d e < s t d lib . h >
# i n c lu d e < c o n i o . h>
v o id g e tu p ()
they're doing, is the ability to see a logical pattern. By this we mean
{ someone who can logically follow something from start to finish and
t e x t c o l o r ( B L A C K );
te x tb a c k g ro u n d (1 5 ); envisage the intended outcome. While you may not feelyou’re such a
c lr s c r ();
w in d o w (1 0 , 2 , 7 0 j 3 ) ; person, it is possible to train your brain into this way of thinking. Yes, it
c p r in t f ("P re s s X to E x it , P r e s s S p a c e t o D u m p ");
w in d o w (6 2 ,2 ,8 0 j3 ); takes time but once you start to think in this particular way you will be able
c p r i n t f ("S C O R E : " ) ;
w in d o w (1 , 2 5 , 8 0 , 2 5 ) j to construct and follow code.
f o r ( i n t x = 0 ;x < 7 9 ;x + + )
c p r in t f ( " n " ) ;
t e x t c o l o r ( 0);
} Second to logic is an understanding of mathematics. You don't have to be
i n t t,sp e e d = 4 0 ; at a genius level but you do need to understand the rudiments of maths.
v o i d d s ( i n t jum p=0)
Maths is all about being able to solve a problem and code mostly falls under
s t a t ic in t a = l;
the umbrella of mathematics.
i f (ju m p = = 9 )
t=9;
e l s e if(ju m p = = 2 )
Being able to see the big picture is certainly beneficial for the modern
e ls e t+ + ;
window(2i 1 5 - t J18J25 ); programmer. Undoubtedly, as a programmer, you will be part of a team
c p r in t f( ”
c p r in t f( " M AO n /l/l/lM ") j of other programmers, and more than likely part of an even bigger team
c p r in t f( " nnn n n n n n
c p r in t f( ” juin/i/irinn of designers, all of whom are creating a final product. While you may only
c p r i n t f C /i Mjum/innn
c p r i n t f ( “ J1/1M MJUUU1J1J1MMM be expected to create a small element of that Final product, being able to
c p r i n t f ( " n/iJiJi/iJiJwiJiJiJi n
c p r in t f ( “ rw iuuuum n understand what everyone else is doing will help you create something
i f (jump==l || jump==2){
c p r in t f(" /l/in rui ") j that’s ultimately better than simply being locked in your own coding cubicle.
c p r in t f( ” JIM JIM ”)j
} e ls e i f ( a — 1)
s
\
c p r in t f(" n/utn nnn Finally, there's also a level of creativity needed to be a good programmer.
c p r in t f( ” JIM
a=2; Again though, you don't need to be a creative genius, just have the
>
e ls e i f ( a = = 2 )
s
imagination to be able to see the end product and how the user will interact
\
c p r in t f( ” ruiM nji with it.
c p r in t f(" •);
a = l;
}
c p r in t f ( " "); There is of course a lot more involved in being a programmer, including
d e la y (s p e e d );
;5 > learning the actual code itself. Flowever, with time, patience and the
57 v o id o b j ( )
58 C determination to learn, anyone can become a programmer. Whether
Being able to follow a logical pattern and you want to be part of a triple-A video game team or simply create an
see an end result is one of the most valued automated routine to make your computing life easier, it's up to you how
skills of a programmer. far to take your coding adventure!
During the Second World War, From the 1970s, the development of the likes of C, SQL, C with
there significant advances Classes (C++), MATLAB, Common Lisp and more came to the
were made in programmable fore. The '80s was undoubtedly the golden age of the home
machines. Most notably, the computer, a time when silicon processors were cheap enough
cryptographic machines used for ordinary folk to buy. This led to a boom in home/bedroom
to decipher military codes coders with the rise of 8-bit machines.
used by the Nazis. The Enigma
was invented by the German
engineer Arth ur Scherbius
but was made famous by Alan
Turing at Bletchley Park's
codebreaking centre.
1990s-Pre se n t Day
COIB 7E CO 79
Choosing a
Programming
Language
It would be impossible to properly
explain every program m ing language in
a single book of this size. New languages
and ways in which to 'talk' to a computer
or device and set it instructions are being
invented alm ost daily; and with the
onset oF quantum computing, even more
complex m ethods are being born. Here
is a list oF the more com m on languages
along with their key Features.
SQL SQL stands For Structured Query Language. SQL is a standard language
For accessing and manipulating databases. Although SQL is an ANSI
(American National Standards Institute) standard, there are diFFerent versions oF
the SQL language. However, to be compliant, they all support at least the major
commands such as Select, Update and Delete in a similar manner.
igi python python Python is a widely used high level programming language used
for general purpose programming, created by Guido van
Rossum and first released in 1991. An interpreted language, Python has a design
philosophy that emphasises code readability and a syntax that allows programmers
to express concepts in Fewer lines of code. This can make it easier For new
programmers to learn.
C Features. It was designed with a bias toward system programming and embedded,
resource-constrained and large systems, with performance, efficiency and Flexibility
oF use as its design highlights.
RUBY Ruby 'sa language of careful balance. Its creator, Yukihiro "Matz"
W Matsumoto, blended parts of his Favourite languages (Perl, Smalltalk,
a Eiffel, Ada and Lisp) to Form anew language. From its release in 1995, Ruby has
drawn devoted coders worldwide. Ruby is seen as a Flexible language; essential
parts of Ruby can be removed or redefined, at will. Existing parts can be added to.
Creating a Coding
Platform
The term 'Coding Platform' can signify: a type of hardware on which you can code,
a particular operating system, or even a custom environm ent that's pre-built and
designed for easy gam e creation. In truth it's quite a loose term, as a Coding Platform
can be a mixture of all of these ingredients, it's simply down to which program m ing
language you intend to code in and w hat your end goals are.
f rom d}ango.contrlb.auXE.decorator* Coding can be one of those experiences that sounds fantastic,
from <i}ango.cotVtrib.admin.vims.decorator* >
but is often confusing to tackle. A fter all, there's a plethora
from django.core.exceptions Ob^ectboerHi
of languages to choose from, countless apps that will enable
from diaogo.http import KttpResponseforbiddea
from d}ango.cootrip.autP import authenticate, you to code in a specific, or range, of languages and an equally
from d}ango.contrib.auth.mode\* tmport User huge amount of third-party software to consider. In addition, by
accessing the Internet, you will discover that there are countless
from diango.core.paqinator import Paginator coding tutorials available for the language in which you've decided
from diango.core.urVresoVvers import reverse you want to program, alongside even more examples of code. It's
from diango.conf import settings all a little too much at first.
from diango.db.models import Q, Sum. Win, Couo
The trick is to slow down and, to begin with, not look too deeply
from diango.contrib import messages
from datetime import date, timedetta into coding. Like all good projects, you need a solid foundation
on which to build your skillset and to have all the necessary tools
import re
available to enable you to complete the basic steps. This is where
from .modets import * creating a coding platform comes in, as it will be your learning
foundation while you begin to take your first tentative steps into
the wider world of coding.
"There are some errors, p\ease
one MCC.Cli.GE
HARDWARE SOFTWARE
You will need access to the Internet to download, install and Over time, you may find yourself progressing from the
update the coding development environment, alongside a mainstream development environment and using a collection
computer with Windows 10, macOS, or Linux, installed. You of your own, discovered, tools to write your code. It's all
can use other operating systems, but these are the 'big three' personal preference in the end and as you become more
and you will find that most code resources are written with experienced, you will start to use different tools to get the
one, or all, of these in mind. job done.
Windows 10 is the most widely used operating system in the A virtual machine is a pieceoFsoFtware that allows you to install a
world, so it's natural that the vast majority oF coding tools are Fully working operating system within the conFines oF the soFtware
written For MicrosoFt’s leading operating system. However, itselF. The installed OSwillallocateuser-deFined resources From the
don't discount macOS and especially Linux, host computer, providing memory, hard drive space etc., as well as
sharing the host computer's Internet connection.
macOS users enjoy an equal number oF coding tools to their
Windows counterparts. In Fact, you will probably Find that a The advantage oF a virtual machine is that you can work with
lot oFproFessional coders use a Mac over a PC, simply because Linux, For example, without it aFFecting your currently installed
oF the Fact that the Mac operating system is built on top oF host OS. This means that you can have Windows 10 running and
Unix (the command-line OS that powers much oF the world's launch your virtual machine client, boot into Linux and use all
Filesystems and servers). This Unix layer lets you test programs the Functionality oF Linux, while still being able to use Windows.
in almostany language without using a specialised IDE.
THE RASPBERRY PI
18 Why C++?
20 C++Facts & Figures
22 Equipment You Will Need
24 Structure of C++Code
26 Flow to Set Up C++in Windows
28 Flow to Set Up C++on a Mac
30 Flow to Set Up C++in Linux
32 Other C++IDEs to Install
Why C++?
C++ is one of the m ost popular program m ing languages available today. Originally
called C with Classes, the language w as renamed to C++ in 1983. It's an extension of
the original C language, and is a general purpose object-oriented (OOP) environment.
C E V E R Y T H IN G
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 using C++. For example, all of Adobe's majorapplications, such as
computing, C++, or rather C with Classes, was the brainchild of Photoshop, InDesign and so on, are developed in C++. You will find
Danish computerscientist Bjarne Stroustrup, while working on that the browser you use to surf the Internet is written in C++, as
his Ph.D. thesis. Stroustrup’s plan was to further the original C well as Windows 10, Microsoft Office, and the backbone to Google's
language, which had been widely used since the early seventies. search engine. Apple's macOS is written largely in C++ (with some
other languages mixed in depending on the function), and the likes
C++ proved to be popular among the developers of the 80s, since of NASA, SpaceX, and even CERN use C++ for various applications,
it was a much easier environment with which to get to grips, programs, controls, and umpteen other computing tasks.
and, more importantly, it was 99% compatible with the original C
language. This meant that, beyond the mainstream computing labs, As well as being an easieraddition to the core C language, C++ is
regular people who didn't have access to the mainframes and large also extremely efficient and performs well across the board. This
computing data centres could use it. higher level of performance overother languages, such as Python,
BASICand such, makes itan ideal development environment for
C++'s impact in the digital world is immense. Many of the programs, modern computing; hence the aforementioned companies using it
applications, games, and even operating systems are coded so widely.
Why C++?
W indows (3)
Summary
U niversal W indows Platform developm ent .N ET desktop developm ent
v D esktop developm ent with C...
■ m Create applications fo r the Universal Windows Platform with C *. Build WPF, Windows Forms and console applications using the
VB, JavaScript o r optionally C++. .N ET Framework. Included
'a Build classic Windows-based applications using the power of the H VC++ 2 0 1 7 v141 toolset (x86,x64)
Visual C++ toolset, A TI, and optional features like MFC and... n C++ profiling tools
Q Windows 10 SDK (10.0.14393.0)
Q Visual C++ tools for CMake
Q Visual C + + ATL support
Web & Cloud (4)
□ Windows 8.1 SDK and UCRT SDK
/ 'T \ \ ASP.NET and web developm ent Azure developm ent f l Windows X P support for C++
V j Bui l d web applications using ASP.NET, ASP.NET Core, HTML, Azure SDK, tools, and projects for developing cloud apps and l~l MFC and ATL support (x&6 and x64)
JavaScript, and CSS. creating resources.
□ C++/CU support
M Clang/C2 (experimental)
l~| Standard Library Modules
Node.js developm ent Data storage and processing
Q By continuing, you agree to die license for the
LP ^ J Build scalable network applications using Node.js, an asynchronous r —j Connect, develop and test data solutions using SQL Server, Azure
Visual Studio edition you selected. We also offer the
event-driven JavaScript runtime. Data Lake, Hadoop or Azure ML.
ability to download other software with Visual
Studio. This software is licensed separately, as set
out in the 3rd Party Notices or in its accompanying
license. By continuing, you also agree to those
M obile & Gam ing (5) licenses.
C++ puts the developer in a much wider world oF coding. By improvements to the engine, or when creating a new game, if
mastering C++, you will find yourself being able to develop code for the developers want to add something that the engine can't do,
the likes of Microsoft, Apple and so on. Generally, C++ developers they will use C++ to create the new content or link between two
enjoy a higher salary than programmers of some other languages, different engines. The end result, of course, is a game that contains
and, due to its versatility, the C++ programmer can move between the latest graphical technology, while being seamlessly bound
jobs and companies without the need to re-learn anything specific. together with some pretty clever C++ coding.
You will discover, as you become a more advanced coder, that many Getting to use C++ is quite easy, all you need is the right set of tools
of the developers in various coding jobs around the world tend to in which to communicate with the computer in C++, and you can
use pre-designed development engines. For example, when creating start your journey. A C++ IDE is free of charge, even the immensely
games, the likes oF Bethesda, the team behind Oblivion and Skyrim, powerful Visual Studio from Microsoft is freely available to
utilise a 3D game engine called The Creation Engine. This enables download and use. You can get into C++ from any operating system,
the team to quickly create animations, characters, items, terrains, be it macOS, Linux, Windows, or even mobile platforms.
rooms, andjustabout everything else you'd see in the game. The
engine itself has been modified to make the most of the current So, to answer the question of Why C++, the answer is because it’s fast,
graphics card hardware, and computer or console processing efficient, and developed by mostoF the applications you regularly
power. These engines are mostly written in C++, and when making use. It's cutting edge, and a Fantastic language to have mastered.
one of the s
predominant
programming
languages for the
development of all
kinds of technical
NASA, CERN, and commercial
MICROSOFT,
software.
ORACLE, PAYPAL,
LINKEDIN, AMAZON AND
THE MILITARY USE C++.
C++ IS U SED FR EQ U EN T LY
IN ANIM ATION P R O C ESS ES .
3D ANIMATION,
MODELLING,
ANDSIMULATIONS
A LL UTILISE C++.
A lot of the
Linux operating
system is coded
using C++, therefore
you could say that most
of the world's Internet
hosting servers are
available thanks to C++.
THE
C++ is
used in computer
networking as the
main code behind the
Programmable Logic Most of Adobe’s
PERCENTILE SALARY stable of products
Controller, connecting FOR A UK-BASED C++ are developed
servers, processors, other DEVELOPER IS using C++. ^
£120,000
MRI scanning
machines and
Windows 95, 98, 2000, Computer Aided Design The Unreal 4 Engine,
XP, 7,8.1 and 10, as well as all use C++ to help with which is coded in C++,
Microsoft Office, use C++ the enhanced imagery is used For hundreds
as the backbone programming produced by these oF games, including
language of choice.
systems. Fortnite.
PROCESSING ^
TECHNOLOGIES
U s e 'c + M s
WEL^AS
ADVANCED
m is s il e
SV5TEMS
FLIGHT CONTROL SYSTEMS IN
MODERN AIRCRAFT, INCLUDING
MILITARY AIRCRAFT, USE C++.
EquipmentYou
Will Need
You don't need to invest a huge am ount of m oney in order to learn C++, and you
don't need an entire computing lab at your disposal either. Providing you have a fairly
m odern computer, everything else is freely available.
C + + SETU PS
As most, if not all, operating systems have C++ at their code, it stands to reason that you can learn to program in C++ no
matter what OS you're currently using.
_J COM PUTER
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.
_ J A N ID E
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 enhancements For Windows 10.
_ J C O M P IL E R
A compiler is a program that converts 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 partoF the
package. More on this later.
□ T E X T E D IT O R
Some programmers much preFer to use a text editor to assemble their C++ code
before running it through a compiler. Essentially, you can use any text editor to write
code, just save it with a .cpp extension. However, Notepad++ is one of the best code
text editors available.
_ J IN T E R N E T A C C E S S
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.
_ J T IM E A N D P A T IE N C E
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 in a
week. A good C++ coder has spent many years honing their craFt, so be patient, start
small and keep learning.
OS SPECIFIC NEEDS
C++ will work in any operating system; however, getting all the necessary pieces together can be conFusing to a newcomer. Here's
some OS speciFics For C++.
LINUX WINDOWS
Linux users are lucky in that they already have a compiler and As we've mentioned previously, one good IDE is Microsoft's
text editor built into their operating system. Any text editor Visual Studio. However, a better IDE and compiler is
will allow you to type out your C++ code, when it's saved with Code::Blocks, which is kept regularly up to date with a new
a .cpp extension, use g++ to compile it. release twice yearly, or so. Otherwise, Windows users can
enter their code in Notepad++ then compile it with MinGW -
which Code::Blocks uses.
<4 p -v*
S H l ► C«*~. • .4 . -6
RASPBERRY PI MAC
# IN C L U D E < C + + IS A C E !>
As you learn the basics of programming, you will begin to understand the structure oFa program. The commands may be
diFFerent, butyou will start to see how the code works.
C++ # IN C L U D E
The structure of a C++ program
File Edit View Search Tools Documents Help
Danish student Bjarne can look complex, but once you
Stroustrup invented C++ in get Familiar with ityou'll begin to
D © Pi IT*- W y. ip e
1979, as a part of his Ph.D. see how it flows. Every C++ code
thesis. Initially C++ was called begins with a directive, #include
C with Classes, which added <>. The directive instructs the |C**| *newcode,cpp X
features to the already popular pre-processor to include a
C programming language section of the standard C++ #include <iostream>
while making it a more code. For example: #include
user-friendly environment. <iostream> includes the
iostream header to support
Bjarne Stroustrup, inventor input/output operations.
of C++.
IN T M A IN () *newcode.cpp (~/D
V
int main() initiates the File Edit View Search Tools Documents Help
declaration of a function, which
is a group of code statements
under the name 'main'. All
£1 © < lP 6
5 Q
,
C++ code begins at the main
function, regardless of where 10 * * 1 +newcode.cpp X
it lies within the main body oF
the code. #include <iostream>
int main()
£) © K l S B 0 .5 .
[cfj *newcode.cpp X
Ic"i *newcode.cpp X
# in c lu d e <iostream>
#include <iostream>
int mainO
i n t m a in O {
{ / / My f i r s t C++ program!
// My f i r s t C++ program! s t d ::c o u t « (" H e llo W orld!\n")
STD OUTPUTS
In C++, STD means Standard. It’s a part of the Standard Namespace Leading on, ("Hello World!") is the part that we want to appear on
in C++, which covers a number of different statements and the screen when the code is executed. You can enter whateveryou
commands. You can leave the std part out of a code, but it must be like, as long as it's inside the quotation marks. The brackets aren’t
declared at the start with: using namespace std. needed, but some compilers insist on them. The \n part indicates a
new line is to be inserted.
▼ *neweode.cpp (-/Documents)
File Edit View Search Tools Documents Help
Ic’i *newcode.cpp X
# in c lu d e <iostream>
// My first C++ program!
using namespace s t d ; std::cout « ("Hello World!\n")|
int mainO
{
/ / My f i r s t C++ program!
COUT ; AND}
In this example we're using cout, which is a part of the Standard Finally you will notice that lines within a function code block
Namespace - hence why it's there, as you're asking C++ to use it from (except comments) end with a semicolon. This marks the end of
that particular namespace. Cout means Character OUTput, which the statement, and all statements in C++ must have one at the end
displays, or prints, something to the screen. If we leave std: : out we or the compiler will fail to build the code. The very last line has the
have to declare it at the start of the code; as mentioned previously. closing brace to indicate the end of the main Function.
c" rvewcode.epp X
* i i i elude <iosi least*
£1 © Di *■* «* (□ C <1 9: 'in t mainO
(
// My f i r s t C li program!
std::cout « ( "Hello world’Vn"):
ItTI *newcode,cpp X
# in e lu d e <iostream >
i n t m a in O
{
/ / My f i r s t C++ program!
s t d : rcout |
How to Set Up
C++ in Windows
W indow s users have a wealth of choice when it com es to program m ing in C++. There
are loads oP IDEs and compilers available, including Visual Studio Prom MicrosoPt.
However, in our opinion, the best C++ IDE to begin with is Code::Blocks.
C O D E ::B L O C K S
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.
Start by visiting the Code::Biocks download site, at When you've located the File, click on the
www.codeblocks.org/downloads. From there, click SourceForge.net link at the end oF the line and a
on the 'Download the binary releases' link to be taken to the latest download notiFication window appears; click on Save File to start
downloadable version For Windows. 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.
There you can see, there are several Windows Once you agree to the licencing terms, a choice oF
versions available. The one you want to download installation options becomes available. You can opt
has mingw-setup.exe at the end oF the current version number. At For a smaller install, missing out on some oFthe components but we
the time oF writing this is: codeblocks-17.12mingw-setup.exe. The recommend that you opt For the Full option, as deFault.
diFFerence is that the mingw-setup version includes a C++ compiler
I C o d e ::B lo clcs Installatio n
and debugger From TDM-GCC (a compiler suite).
C h o o s e C o m p o n e n ts
Windows XP / Vista / 7 18.x /10: Choose which features o f CodeBlocks you w ant to install.
1
File
codeblocks-17 12-setup.exe 30 Dec! Check the components you w ant to install and uncheck the components you don't w ant to
codeblocks-17 12-setup-nonadmin exe 30 Dec: install. Click N ext to continue.
codeblocks-17.12-nosetup.zip 30 Dec:
Select the type o f install: Full: All plugins, all tools, ju st everything V
codeblocks-17 12mingw-setupexe 30 Dec;
O r, select the optional ] - 0 D e fa u lt in s t a ll
codeblocks-17 12mingw-nosetup zip 30 Dec:
components you wish to
- ] - 0 Contrib Plugins
codeblocks-17 12mingw_fbrtran-setup exe 30 Dec: install:
0 C ::B C B P 2 M a k e
NOTE: The codeblocks-17 12-setup.exe file includes Code Blocks with all plugins. The codeblocks-17 12-setup-nonadmin.ex file is provided for conven •0 C ::B C C T e s t
NOTE The codeblocks-17.12mingw-setup.exe file includes additionally the GCC/G++ compiler and GDB debugger from TDM-GCC (version 5.1.0. 32 bit. 0 C ::B Share Config
(TDM-GCC)
0 C ::B Launcher
V
NOTE: The codeblocks-17.12(mingw)-fl’osetup zip files are provided for convenience to users that are allergic against installer1 However, it will not allow I m .- „ ... ^ .. „ ..
Description
If unsure, please use codeblocks-17 12mingw-setup.exe! Space required: 2 53.4 MB Position your mouse over a component to see its
Next choose an install location for the Code::Blocks There's a lot you can do in Code::Blocks, so you need
files. It'syourchoice but the default isgenerally to dig in and find a good C++ tutorial to help you
sufficient (unless you have any special requirements of course). get the most from it. However, to begin with, click on File > New >
When you click Next, the install begins; when it’s finished a Empty File. This creates a new, blank window for you to type in.
notification pops up asking you if you want start Code::Blocks now,
# 'Untitted2- CoderBlocta17.12
so click Yes.
Output folder: C
Created uninsta
Output folder: C ________. _ _ __ enuV^ro...
C reate shortcut: C:VJsersyiavid\AppData fo a m in g ydicrosoft\WindowsVStart M e n u ^ ...
The first time Code::Blocks loads it runs an In the new window, enter the following:
autodetect for any C++ compilers you may already
have installed on your system. If you don't have any, click on the tinclude <iostream>
first detected option: GNU GCC Compilerand click the Default
Int main ()
button to set it as the system's C++ compiler. Click OK when you're
ready to continue.
{
//My first C++ program
Compilers a u to -d etectio n □ X
Std::cout « "Hello World!\n";
Note: After auto-detection, a t least one compiler's master path is still empty and therefore invalid.
!
Inspect the list below and change the compiler's master path later in the compiler options.
Select you favourite default compiler here: Notice how Code::Blocks auto-inserts the braces and speech quotes.
Compiler Status A Set as default
N 1cit■ ^.fcdb 17.12
GNU GCC Compiler Detected Pile Edit Vwv. Scorch Propel Md Debuj fortran loots Toot- PIujvb OrvyBecb Sdtajs Help
i a 0 * * 4 «*;# ► ii D i^ a r
f * f » » M 1* ‘
Starthire ‘ UnWcdJ
• Projects biflidcJs rtes 1 1 Unelude viescjew'
Q Workspace
; c -o r ,
5 {
6 //My fin e Co-o peojram
The program starts and another message appears Click File > Save as and save the code with a
informing you that Code::Blocks is currently not .cpp extension (helloworld.cpp, for example).
the default application for C++ files. You have two options, to leave Code::Blocks changes the view to colour code according to C++
everything as it is or allow Code::Blocks to associate all C++ file standards. To execute the code, click on the Build and Run icon
types. Again, we would recommend you opt for the last choice, to along the top of the screen. It's a green play icon together with a
associate Code::Blocks with every supported file type. yellow cog.
O MO,leaveeverylhmgasit«
O No. leeveevtrytfmg*Jit8 (butaskme»gannexttime)
O fes, esssMteCode wthC/C+*He types
(5)fes. associateCodeiiBocksKithevery snowted tyce(ndudngGroiectAlesfromotter IDEs}
XCODE
Apple's Xcode is primarily designed For users to develop apps For macOS, iOS, tvOS and watchOS applications in SwiFt or
Objective-C, but we can use it For C++ too.
Start by opening the AppStore on your Mac, Apple When you're ready, click on the Get or cloud icon
Menu > App Store. In the Search box enter Xcode, bu tton which wi ll insta ll the Xcod e a pp. En ter your
and press Return. There will be many suggestions filling the App Apple ID, and Xcode will begin to download and install. It may take
Store window, but it's First option, Xcode, that you need to dick on. some time depending on the speed oFyour Internet connection, as
Xcode is in excess oF 11GB.
Take a moment to browse through the app's When the installation is complete, click on the Open
information, including the compatibility to ensure button to launch Xcode. Click Agree to the licence
you have the correct version oF macOS. Xcode requires macOS terms, and enteryour password to allow Xcode to make changes
10.12.6 or later to install and work. to the system. When you've done that, Xcode will begin to install
additional components.
With everything now installed, including the The next step asks where to create a Git Repository
additional components, Xcode will launch displaying For all your Future code. Choose a location on your
the version number along with three choices and any recent projects Mac, o ra network location, and click the Create button. When
that you've worked on-although fora Fresh install, this will be blank. 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.
Start by clicking on Create New Xcode Project, this You will notice that Xcode has automatically
opens a template window to choose which platform completed a basic Hello World program For you.
you're developing code For. Click the macOS tab, then click the The differences here are that the int main () Function now contains
Command LineTool option. Click Next to continue. multiple Functions and the layout is slightly different. This is just
Xcode utilising the content that’s available to your Mac.
© ffi □
App Document App Same m c ... ui „
H ‘e I I I %
Framework * Library
Bundle
Cancel
Fill in all the fields, but ensure that the Language When you want to run the code, click on Product >
option at the bottom is set to C++. Simply choose Run. You may be asked to enable Developer Mode
it from the drop-down list. When you've Filled in the Fields, and on the Mac, this is to authorise Xcode to perform Functions without
made sure that C++ is the chosen language, click on the Next needing your password every session. When the program executes,
button to continue. the output will be displayed at the bottom of the Xcode window.
L IN U X + +
There are many different versions of Linux available, for this example we're using one of the more popular distributions: Linux
Mint. However, these steps will work in any Debian-based Linux.
The first step with ensuring Linux is ready for your Amazingly, that's it. Everything is all ready foryou
C++ code is check the system and software are to start coding. Here’s how to get your first C++
up to date. Open a Terminal and enter: sudo apt-get update program up and running. In Linux Mint the main text editor is Xed
&& sudo apt-get upgrade. Press Return and enter your can be launched by clicking on the Menu and typing Xed into the
password. These commands updates the entire system and any search bar. Click on the Text Editor button in the right-hand pane to
installed software. open Xed.
ir---------
File Edit View Search Terminal
david@mint-mate - S sudo apt-get update
Help
Most Linux distros come preinstalled with all the In Xed, or any other text editor you may be using,
necessary components to start coding in C++. enter the lines of code that make up your C++ Hello
However, it's always worth checking to see if everything is present, World program. To remind you, it's:
so still within the Terminal, enter: sudo apt-get install
iinclude <iostream>
build-essential and press Return. If you have the right
components, nothing is installed but if you're missing some then int m a i n ()
they are installed by the command.
{
When you've entered your code, click File > Save As Before you can execute the C++ file you need to
and choose a folder where you want to save your compile it. In Linux it's common to use g++, an open
program. Name the file as helloworld.cpp, or any other name just as source C++ compiler and as you're now in the same folder as the
long as it has .cpp as the extension. Click Save to continue. C++ file, go to the Terminal, enter: g++ helloworld.cpp and
press return.
david@mii
File Edit View Search Terminal Help
david@mint-mate -/Documents g++ helloworld.cpp
david@mint-mate -/Documents
Name, helkworldipd
S3 desktop
pfrfnrte py
GUlTest.py
a* Pictures
L a Videos
The first thing you can see is that Xed has There will be a brief pause as the code is compiled
automatically recognised this as a C++ file, since the by g++ and providing there are no mistakes or
file extension is now set to .cpp. The colour coding is present in the errors in the code you are returned to the command prompt. The
code and if you open up the file manageryou can also see that the compiling of the code has created a new file. If you enter Is into the
file's icon has C++ stamped on it. Terminal you can see that alongside your C++ file is a.out.
w davidt?
File Edit View Search Terminal Help
david@mint-mate '/Documents $ g++ helloworld.cpp
david@mint-mate -/Documents S Is
a.out helloworld.cpp
david@mint-mate -/Documents $
With your code now saved, drop into the Terminal The a.out file is the compiled C++ code. To run the
again. You need to navigate to the location of code en te r:. /a. out and press Return. The words
the C++ file you've just saved. Our example is in the Documents 'Hello World!' appears on the screen. However, a.out isn't very friendly.
folder, so we can navigate to it by entering: cd Documents. To name it something else post-compiling, you can recompile with:
Remember, the Linux Terminal is case sensitive, so any capitals must g++ helloworld.cpp -o helloworld. This creates an output
be entered correctly. file called helloworld which can be run with: ./helloworld.
david@mint-mate ~7Doci
File Edit View Search Terminal Help
File Edit View Search Terminal Help david@ m int-m ate -/Documents S ./ a .o u t
H e llo W orld!
david<Bmint-mate ~ s cd Documents david@ m int-m ate -/Documents S g-w- h e llo w o rld .c p p -o h e llo w o rld
david@ m int-m ate -/Documents S ./ h e llo w o r ld
david@mint-mate ~/Documents s § H e llo W orld!
david@ m int-m ate -/Documents S
DEVELOPING C++
Here are ten great C++ IDEs that are worth looking into. You can install one or all oF them iFyou like, but Find the one that
works best For you.
Eclipse is a hugely popular C++ IDE thatoFfers CodeLite isa Free and open source IDE that's
the programmer a wealth oF Features. It has a regularly updated and available For Windows,
great, clean interface, is easy to use and available For Windows, Linux and macOS. It’s lightweight, uncomplicated and extremely
Linux and Mac. Head over to www.eclipse.org/downloads/to powerful. You can Find out more information as well as how to
download the latest version. IF you're stuck, click the Need Help link download and install it at www.codelite.org/.
For more inFormation.
rt- A ll * - e - i f - e - ■%-»- 0 - 0 - 4 - am
: § | . {, I - ■ •
The GNAT Programming Studio (GPS) is a powerful Another popular choice is NetBeans. This
and intuitive IDE that supports testing, debugging is another excellent IDE that's packed with
and code analysis. The Community Edition is free, whereas the Features and a pleasure to use. NetBeans IDE includes project based
Pro version costs; however, the Community Edition is available For templates For C++ that give you the ability to build applications with
Windows, Mac, Linux and even the Raspberry Pi. You can Find it at dynamic and static libraries. Find out more a twww.netbeans.org/
www.adacore.com/download. Features/cpp/index.html.
_■ Makefile
B Makefile
config.h
conflg.log
config.log
• config.status
Makefile
stamp-til
i-i+1:
Makefile.am
Makefiie.am.ix
Mukefite.in
Bloodshed Dev C++, despite its colourful name, Ultimate++ is a cross-platform C++ IDE that boatsa rapid
is an older IDE that is For Windows systems only. development oF code through the smart and aggressive
However, many users praise its clean interface and uncomplicated use of C++. For the novice, it's a beast of an IDE but behind its
way of coding and compiling. Although there’s not been much complexity is a beauty that would make a developer's knees go
updating For some time, it's certainly one to consider iF you want wobbly. Find out m oreatwww.ultimatepp.org/index.html.
something different: www.bloodshed.net/devcpp.htmL
HELLO, W O R L D !
It's traditional in programming For the First code to be entered to output the words 'Hello, World!' to the screen. Interestingly,
this dates back to 1968 using a language called BCPL.
We're going to use Windows 10 and the excellent At the moment it doesn't look like much, and
IDE Code::Blocks For the rest oF the C++ code and it makes even less sense, but we'll get to that
tutorials in this book. Begin by launching Code::Blocks. When open, in due course. Now click on File >Save File As. Create or Find a
click on File > New > Empty File or press Ctrl+ShiFt+N on the keyboard. suitable location on your hard drive and in the File Name box, call
it helloworld.cpp. Click the Save as type box and select C/C++ Files.
Click the Save button.
H **.«*•' -ofcibrhl-V
PigeSIVMirFte
O Owpbm BT
' ‘ J, iaaiwk Scut ' C u t ) > rMJmnugn ’l (OtMAlM ' CnO«J,V.!. .« « « «. '.dm* ■ ClCtl
Now you can see a blank screen, with the tab You can see that Code::Blocks has now changed
labelled *Untitled1, and the number one in the top the colour coding, recognising that the File is now
leFt oF the main Code::Blocks window. Begin by clicking in the main C++ code. This means that code can be auto-selected From the
window, so the cursor is next to the number one, and entering: Code::Blocks repository. Delete the #include <iostream> line and
re-enter it. You can see the auto-select boxes appearing.
tinclude <iostream>
H I *helloworld.cpp - Code::Blocks 17.12
Ml -U ntitled l - C od tu Blo cks 17.12 File Edit View Search Project Build Debug Fortran wxSm ith Tools Tools-*- Plugins DoxySloi:
File Edit View Search Project Build Debug Fortran w xSm ith Tools Tools+ Plugins DoxyE
c s ( a . H 9 i ^ = * | s s » » i a ®i|i □ - E3 i ►
> =»| R> B S B I -t + /“ *< -] v| | • k
- * f* R* F5 » /•**<! IS «+ -H • k » Management
* h ellow orld.cpp X |
Management
P r o je c ts Symbols
Q W orkspace
1 0 0
0
0 1 1 1
10 1
111 0 0
0 1 0 0
0 0 1 0 0 0 0 1 1 0 1
D 1 o 1 1 0 0
Coding & Programming
1 0 1 0 o o
0 111 o ooo l 0 o0 0 0 0 11 1 0 0 1 0 0 1
Your First C++ Program
Auto-selection oF commands is extremely handy and Note again the colour coding change. Press Return at
cuts out potential mistyping. Press Return to get to the end oF the previous step's line, and then enter:
line 3, then enter:
std::cout « "Hello, world!\n";
int raain()
1 IS ft ft I Q , f t ; ® B
Note: there's no space between the brackets.
\ » * i /** * < i a m i ^ : *H • K ; & |v | o
,* X
Start here X *helk>workl.cpp X |
__
r * |/** *< |M [f] |^> * k : iles ►
1 #include <iostream>
X 2
Start here X * h e llo w o rld .c p p X
3 i n t m a i n ()
► 1 #in c lu d e < io s tr e a m > 4 EM
2 5
Notice that Code::Blocks has automatically created That's all you need to do For the moment. It may
a corresponding closing curly bracket a couple oF not look terribly amazing but C++ is best absorbed
lines below, linking the pair, as well as a slight indent. This is due to in small chunks. Don't execute the code at the moment as you need
the structure oF C++ and it's where the meat oF the code is entered to look at how a C++ program is structured First; then you can build
Now enter: and run the code. For now, click on Save, the single Floppy disc icon.
File Edit View Search Project Build Debug Fortran wxSmith Tools Tools* Plugins DoxyBlocks Settii
nr ! q a a t i o. | m * a I a ®i|; @ + :1
« * | r * *< | @ |$] | ^ ; H * k
Management X
X *helk>world.cpp X Start here X “ helloworld.cpp X
Projects Symbols Files ►
#include <iostreaoa> ( J Workspace 2
3 i n t m a in l)
!
i n t m a in () 4 R (
5 /,m- n » t c « program
1 {
6
7
std::c o n t « " H e llo , w o r ld !\ n ” ; 0 0
L>
8 0
0 1 1 l
0 1
1 1 1
0 1
0 0 0 10 1 0 1 c oo o0 0 1 0 10 1 o 1 0 0 0 0
0 0 0 i o () 1 1 0 1 o Oil 1 1 o o 1 1 1 1 l 1 o 1
Coding & Programming
0 1 0 0 1 0 0 i )0 0 1 0 1 111 0 0
Ollio 0 0 0 0 1 0 l 0 o 0 0 1 0 0 1 1 1 1 1 0 O i l 1 0
Coding with C++
G R E E T IN G S F R O M C++
Compiling and executing C++ code From Code::Blocks is extraordinarily easy; it's just a matter oF clicking an icon and seeing
the result. Here's how it's done.
Open Code::Blocks, iFyou haven't already, and Start by clicking on the Build icon, the yellow cog.
load up the previously saved Hello World code you At this point, your code has now been run through
created. Ensure that there are no visible errors, such as missing the Code::Blocks compilerand checked Forany errors. You can see
semicolons at the end oF the stdccout line. the results oF the Build by looking to the bottom window pane. Any
messages regarding the quality oF the code are displayed here.
m ’ helloworld.cpp - Code;;Blocks 17,12
File Edit View Search Project Build Debug Fortran wxSmith Toots Tools* Plugins DoxyBlocks Settings
iFyour code is looking similar to the one in our Now click on the Run icon, the green play button.
screenshot, then look to the menu bar along the top A command line box appears on your screen
oF the screen. Under the Fortran entry in the topmost menu you can displaying the words: Hello, world!, followed by the time it's taken
see a group oF icons: a yellow cog, green play button and a cog/play to execute the code, and asking you pressa key to continue. Well
button together. These are Build, Run, Build and Run Functions. done, you just compiled and executed your First C++ program.
ocks 17.12
££ * a I # ► % O Q
i n t m a in ( )
Pressing any key in the command line box closes it, Create a deliberate error in the code. Remove the
returning you to Code::Blocks. Let's alter the code semicolon From the cout line, so it reads:
slightly. Under the #include line, enter:
cout « "Hello, world!\n"
using namespace std;
Start here X * helloworld.cpp X
Then, delete the std:: part oF the Cout line; like so:
1 ^include <iostream>
cout << "Hello, world\n";
2 using namespace std;
3
4 int m a i n ()
5 Fpit
6 //My first C++ p r o g r a m
7 c o u t << "Hello, world!\n"
3
9
10
11
12
In order to apply the new changes to the code, you Now click the Build and Run icon again to apply the
need to re-compile, build, and run it again. This time, changes to the code. This time Code::Blocks refuses
however, you can simply click the Build/Run icon, the combined to execute the code, due to the error you put in. In the Log pane at
yellow cog and green play button. the bottom oF the screen you are informed oF the error, in this case:
Expected before token, indicating the missing semicolon.
Buna Deeug Fonrin iwstwm Toon took* piugmt DMyBJoiB smmgt H«p
2i i t ; © ► 4 -0 g g ; ► 4= c: V u a ! SJ ■ i V matnOrht
1r •< -J vl : • h !» ~ * 2 + to \ - .1 - - - ■ ! ° K ^ I s C II
Starthere hcHoworld.cpp
>*P*a« «td;
Ju st as we mentioned in the previous pages, you Replace the semicolon and under the cout line,
don't need to have stdccout if you already declare enter a new line to your code:
using namespace std; at the beginning oF the code. We could have
Cout << "And greetings from C++!\n";
easily clicked the Build/Run icon to begin with but it's worth going
through the available options. You can also see that by building and The\n simply adds a new line under the last line oF outputted text.
running, the file has been saved. Build and Run the code, to display your handiwork.
Using Comments
While com m ents may seem like a minor element to the many lines of code that
combine to make a game, application or even an entire operating system, in actual Pact
they're probably one oP the m ost important Factors.
T H E IM P O R T A N C E O F C O M M E N T IN G
Comments inside code are basically human readable descriptions equalling zero is something that drastically changes the program for
that detail what the code is doing at that particular point. They don't the user, such as, they've run out of lives, then it certainly needs to
sound especially important but code without comments is one of commented on.
the many frustrating areas of programming, regardless of whether
you're a professional or just starting out. Even if the code is your own, you should write comments as if you
were going to publicly share it with others. This way you can return
In short, all code should be commented in such a manner as to to that code and always understand what it was you did or where it
effectively describe the purpose of a line, section, or individual wasyou went wrong or what worked brilliantly.
elements. You should get in to the habit of commenting as much as
possible, by imagining that someone who doesn't know anything Comments are good practise and once you understand how to add a
about programming can pick up your code and understand what it's comment where needed, you soon do it as if it's second nature.
going to do simply by reading your comments.
DEFB 26h, 30h,32h,26h,30h,32h,0,0 , 32h,72h,73h,32h,72h, 73h,32h
In a professional environment, comments are vital to the success DEFB
DEFB
60h, 61h, 32h, 4Ch, <5DA, 32h, 4Ch, 99h, 32h, 4Ch, 4Dh, 32h, 4Ch, 4Dh
32h,4Ch,99h,32h,5Bh,5Ch,32h,56h,57h,32h,33h,OCDh, 3 2 h , 3 3 h
of the code and ultimately, the company. In an organisation, many DEFB 34h , 3 2 h f33h,34h,32h,33h,OCDh,32h,40h,41h,32h,66h, 6 7 h , 6 4 h
DEFB 66h,67h,32h,72h,73h,64h,4Ch,4Dh,32h,56h,57h,32h,8 0 h , O C B h
programmers work in teams alongside engineers, other developers, DEFB 19h,80h,0 , 1 9h,80h,81h,32h,SOh,OCBh,OFFh
TS58C:
hardware analysts and so on. If you're a part of the team that's DEFB 80h,72h,66h,60h,56h,66h,56h,56h,51h,60h,51h,51h,5 6 h , 6 6 h
DEFB 56h,56h, SOh, ?2h, 66h, 60h, S6h, 66h, 56h, 56h, 51h, 60h, Slh, Slh
writing a bespoke piece of software for the company, then your DEFB 56h, 56h,56h,56h,80h,72h,66h,60h,56h,66h,56h,56h,5 1 h , € 0 h
DEFB Slh,51h,56h,66h,5€h,56h,SOh,72h,66h,60h,56h,66h,5 6 h , 4 0 h
comments help save a lot of time should something go wrong, and DEFB 56h, 66h,SOh,66h,56h,56h,56h,56h
another team member has to pick up and follow the trail to pinpoint ; Game restart point
the issue. START: XOR A
LD (SHEET),A
LD (KEMP) ,A
Place yourself in the shoes of someone whosejob it is to find out LD (DEMO),A
LD (B845B),A
what's wrong with a program. The program has in excess of 800,000 LD (BB458),A
LD A, 2 ;Initial lives count
lines of code, spread across several different modules. You can soon LD (NOMEN),A
LD HL,T845C
appreciate the need fora little help from the original programmers SET O, (HL)
LD HL,SCREEN
in the form of a good comment. LD DE,SCREEN+1
LD BC,17FFh ;Clear screen image
LD (HL),0
The best comments are always concise LDIR
LD HL,OAOOOh ;Title screen bitmap
and link the code logically, detailing what LD DE,SCREEN
LD BC,4096
happens when the program hits this line LDIR
LD HL,SCREEN + 8Q0h + 1*32 + 29
or section. You don’t need to comment on LD DE,MANDAT+64
LD C,0
every line. Something along the lines of: if CALL DRWFIX
LD HL,0FCQOh ;A t t ributes fox the last room
x==0 doesn't require you to comment that if x LD DE,ATTR ; (top third)
LD BC,256
equals zero then do something; that's going LDIR
LD HL,09E00h ;Attributes for title screen
to be obvious to the reader. However, if x LD BC,512 ; (bottom two-thirds)
LDIR
LD BC, 31
DI
XOR A
R8621!
IN E, (C)
OR E
DJNZ R8621 ??-03
AND 20h
JR NZ,R 8 6 2 F ;$+07
LD A, 1
LD (KEMP) ,A
R862F:
LD IY,T846E
CALL C92DC
JP NZ,L8684
XOR A
LD (EUGHGT),A
Using the Hello World code as an example, you can Be careful when commenting, especially with block
easily comment on different sections of the code comments. It’svery easy to forget to add the closing
using the double forward slash: asterisk and forward slash and thus negate any code that falls inside
the comment block.
//My first C++ program
cout « "Hello, world!\n"; - Start here X ‘helk»world.cpp X
1 ^include <iostream>
2 using namespace std;
1 # i n c l u d e <iostreain> 3
4 int main()
2 using namespace s t d ; 5 E3 i
6
3
7 cout « "Hello, world!\n";
4 int m a i n f ) 8 cout « "And greetings from C++";
9
/• T h i t rnm m pnr r~*n
5
6
^ 10
11
12 without the need to add more slashes
7 coat « "Hello, worl d ! \ n " ; 13
14 Sm & « "This line is now being ignored by the compiler!";
8 15
16
9 17
10 18
19
11 20
12
_1 _
However, you can also add comments to the end Obviously if you try and build and execute the
of a line of code, to describe in a better way what's code it errors out, complaining of a missing curly
going on: bracket'}' to finish off the block of code. If you've made the
error a few times, then it can be time consuming to go back and
cout << "Hello, world!\n"; //This line outputs the
rectify. Thankfully, the colour coding in Code::Blocks helps identify
words 'Hello, world!'. The \n denotes a new line.
comments from code.
Note, you don't have to put a semicolon at the end of a comment.
This is because it's a line in the code that's ignored by the compiler.
You can comment out several lines by using the If you're using block comments, it's good practise
forward slash and asterisk: in C++ to add an asterisk to each new line of the
comment block. This also helps you to remember to close the
/* This comment can
comment block off before continuing with the code:
cover several lines
without the need to add more slashes */ /* This comment can
* cover several lines
Ju st remember to finish the block comment with the opposite
* without the need to add morS slashes */
asterisk and forward slash.
4 int m a i n ()
5 Hi
5
6
^
cout. « "Hello, world!\n";
7 coat « "Hello, world!\n"; 3 cout c< "And greetings from C++\n";
8 coat « "And greetings from C++"; 9
10
9
11 cover several lines
10 /* This comment can 12
11 cover several lines 13
12 wit ho it the need to add. more slashes 14
15 cout « "This line is now being ignored by the compiler!\n";
13
16
14 17
15 18
Variables
Variables differ slightly w hen using C++ as opposed to Python. In Python, you can
simply state that 'a' equals 10 and a variable is assigned. However, in C++ a variable has
to be declared with its type before it can be used.
T H E D E C L A R A T IO N O F V A R IA B L E S
You can declare a C++ variable by using statements within the code. There are several distinct types of variables you can
declare. Here's how it works.
Open up a new, blank C++ file and enter the usual You can build and run the code but it won't do
code headers: much, other than store the values 10 and S to the
integers a and b. To output the contents of the variables, add:
#inclucte <iostream>
using namespace std; cout « a;
Starthere X V a r ia b le s ,t p p X |
cout « "\n";
int main() 1 ♦include ciostreano
cout << b; using namespace std;
{ 2
3
The c o u t « "\n"; part
4 int m a i n ()
simply places a new line 5
between the output of 6 E3<
7 int a;
10 and 5.
8 int b;
9
10 a = 10;
11 b = 5;
12
13 cout << a;
14 cout << "\n” ;
15 cout << b;
16
17 >
18
Start simple by creating two variables, a and b, with Naturally you can declare a new variable, call it
one having a value of 10 and the other 5. You can result and output some simple arithmetic:
use the data type int to declare these variables. Within the curly
int result;
brackets, enter:
result = a + b;
int a;
Start here X *Variables.cpp X cout << result;
int b;
1 ♦include <iostream> Insert the above into the code as per the screenshot.
a = 10 2 u s ing n a m espace std;
b = 5; 3
Start here X Variables.cpp X |___
4 int m a i n ()
#include ciostreano
5 □sing namespace std;
€ Be int main ()
F l C:M)sers\david\Documents\C» *\Variables.e
7 int a;
Pc •ocess returned 0 (0x0) execution time ; 0.045 :
3 int b; •ess any key to continue.
int b;
9
infc result;
10 a = 10;
a = 10;
11 b = 5; b =5;
12
13 cout « result;
14
You can assign a value to a variable as soon as you The previous step creates the variable StartLives,
declare it. The code you've typed in could look like which is a global variable. In a game, for example,
this, instead: a player's lives go up or down depending on how well or how bad
they're doing. When the player restarts the game, the StartLives
int a = 10;
returns to its default state: 3. Here we've assigned 3 lives, then
int b = 5;
subtracted 1, leaving 2 lives left.
int result = a + b;
#include <iostream>
using namespace std;
auto pi = 3.141593;
Specific to C++, you can also use the following int raainf)
to assign values toa variable as soon as you
{
declare them:
double area, radius = 1.5;
int a (io;
area = pi * radius * radius;
int b (5) ,
cout « area;
Then, from the C++ 2011 standard, using curly brackets:
}
int result (a+b);
• 1 -- — • ‘ i' -- 1
— r —
Start here X Variables, cpp X 1 Start here X Variables.cpp X
1 ♦ I n c l u d e < io s t r e a m >
2 u s i n g n a m e sp a ce s t d ;
1 ♦include <iostreara>
l i l C:\Users\dsvicf\Documeirts\C-n-\Vanables.exe
3 2 u s in g n am espace s t d ;
4 i n t m a in ( ) 15
}r o c e s s re tu rn e d 0 (0 x 0 ) e x e c u t i o n t im e : 6 .0 3 8 s
3 a u to pi = 3.141593;
5
6 P r e s s a n y ke y t o c o n t in u e . 4
7 i n t a (10) ; 5 i n t m a i n ()
8 i n t b (5),-
9 i n t r e s u l t C a + b ); 6
10 7 E3<
11 cout « r e s u lt ;
12
S d o u b le area, radius = 1.5;
13 } 9
14
10 area = pi * radius * radius;
11
12 cout « area;
13
14 >
Data Types
Variables, as w e've seen, store information that the program m er can then later call up,
and manipulate if required. Variables are simply reserved m em ory locations that store
the values the program m er assigns, depending on the data type used.
#include <iostream>
using namespace std;
double PI = 3.141592653589793238463;
int m a i n ()
{
cout « PI;
i
1 #inclnde ciostrearrD-
2 using namespace s td;
3 1 double PI = 3.141592653589793233463;
4
5 int icainQ
6 ^
7 cout << PI;
8
These basic types can also be extended using the following modifiers:
9 }
Long, Short, Signed and Unsigned. Basically this means the modifiers
10 Ll
can expand the minimum and maximum range values for each data
type. For example, the intdata type has a default value range of
-2147483648 to 2147483647, a fair value, you would agree. ■ C:\Users\david\DocumentsVC++\DataTypes,exe
Now, if you were to use one of the modifiers, the range alters: 3.14159
Process returned 0 (0x0) execution time 0.054 s
Unsigned int = 0 to 4294967295 Press any key to continue.
Signed int = -2147483648 to 2147483647
Short int = -32768 to 32767
Unsigned Short int = 0 to 65,535 Build and run the code and as you can see the output is only
Signed Short int = -32768 to 32767 3.14159, representing cout’s limitations in this example.
Long int = -2147483647 to 2147483647
You can alter the code including the aforementioned cout.precision
Signed Long int = -2147483647 to 2147483647
function, for greater accuracy. Take precision all the way up to 22
Unsigned Long int = 0 to 4294967295
decimal places, with the following code:
Naturally you can getaway with using the basic type without the
#include <iostream>
modifier, as there's plenty of range provided with each data type.
using namespace std;
Flowever, it's considered good C++ programming practise to use the
double PI = 3.141592653589793238463;
modifiers when possible.
int m a i n ()
There are issues when using the modifiers though. Double
{
represents a double-floating point value, which you can use for
cout.precision(22);
This is mainly due to the conversion From binary in the compiler
cout << PI;
and that the IEEE 754 double precision standard occupies 64-bits
oFdata, oFwhich 52-bitsare dedicated to the signiFicant(the
signiFicant digits in a Floating-point number) and roughly 3.5-bits
are taken holding the values 0 to 9. IFyou divide 53 by 3.5, then you
Start here X DataTypes.cpp X arrive at 15.142857 recurring, which is 15-digits oF precision.
SI C:\Users\david\D ocuments\C++\DataTypes,exe
B . 141592653589793115998
Process returned 0 (0x0) execution time : 0.047 s
Press any key to continue.
Again, build and run the code; as you can see From the command
line window, the number represented by the variable PI isdiFFerent
to the number you've told C++ to use in the variable. The output
reads the value oF PI as 3.141592653589793115998, with the
numbers going awry From the FiFteenth decimal place.
Calculator — □ X
#include <iostream>
using namespace std;
= Sc ie n tific s> typedef int metres;
int main()
y 10* lo g Exp M od
t CE C <3 —
TT 7 8 9 X
This code when executed creates a new int data type called metres.
Then, in the main code block, there's a new variable called distance,
n! — which is an integer; so you're basically telling the compiler that
4 5 6
there's another name Forint. We assigned the value 15 to distance
± and displayed the output: distance in metres is 15.
1 2 3 +
It might sound a little conFusing to begin with but the more you use
— C++ and create your own code, the easier it becomes.
c ) 0 -
Strings
Strings are objects that represent and hold sequences of characters. For example, you
could have a universal greeting in your code 'W elcom e' and assign that as a string to be
called up w herever you like in the program.
ST R IN G T H E O R Y
There are different ways in which you can create a string of characters, which historically are all carried over from the original
C language, and are still supported by C++.
To create a string you use the char function. Open a Build and run the code, and 'Welcome' appears
new C++ file and begin with the usual header: on the screen. While this is perfectly fine, it's
not a string. A string is a class, which defines objects that can be
#include <iostream>
represented as a stream of characters and doesn't need to be
using namespace std;
terminated like an array. The code can therefore be represented as:
int main ()
#include <iostream>
{ using namespace std;
} int main ()
{
char greet[] = "Welcome";
cout « greet « "\n";
it's easy to confuse a string with an array. Here's an In C++ there's also a string function, which works in
array, which can be terminated with a null character: much the same way. Using the greeting code again,
you can enter:
#include <iostream>
using namespace std; #include <iostream>
using namespace std;
int main ()
int main ()
{
char greet [8] = { 'W' , 'e' , '1', 'c' , 'o', 'm',
V' , ' \ 0' } ; string greet = "Welcome";
cout « greet « "\n"; cout « greet « "\n";
finclude <io3tream>
n s i n g n a m e s p a c e std;
int main ()
There are also many different operations that you Ju st as you mightexpect, you can mix in an integer
can apply with the string function. For instance, to and store something to do with the string. In this
get the length of a string you can use: example, we created int length, which stores the result of string.
size() and outputs it to the user:
#include <iostream>
using namespace std; #include <iostEeam>
using namespace std;
int main ()
int main ()
{
string greet = "Welcome"; {
cout « "The length of the string is: int length;
cout « greet.size() « "\n"; string greetl = "Hello";
string greet2 = ", world!";
string greet3 = greetl + greet2;
1 #include <iostreara> length = greet'3 .siz.ej );
2 using namespace std;
3
4 int main ()
cout « "The length Of the combined Strings
5 is: " << length « "\n";
6 EEH
7 string greet = "Welcome”;
}
8 cont « "The length of the string is:
S cout << greet.size(> << "\n";
10
11 >
12 Using the available operations that come with the
string Function, you can manipulate the contents oF a
string. For example, to remove characters from a string you could use:
You can see that we used greet.size() to output the
#include <iostream>
length, the number of characters there are, of the
using namespace std;
contents of the string. Naturally, if you call your string something
other than greet, then you need to change the command to reflect int main ()
this. It's always string name.operation. Build and run the code to see
{
the results.
string strg ("Here is a long sentence in a
* C:\Users\david\Documents\C++\Strings,ece
string.");
The length of the string is: 7
cout « strg « '\n';
int main ()
It's worth spending some time playing around with
{
the numbers, which are the character positions
string greetl = "Hello";
in the string. Occasionally, it can be hit and miss whether you get it
string greet2 = ", world!";
right, so practice makes perfect. Take a look at the screenshot to see
string greet3 — greetl + greet2;
the result of the code.
cout << greet3 « "\n";
H j C:\User5\david \D ocu menls\C-t-+\Strin gs. exe
}
Here i s a long sentence in a s tr in g .
X
Start here X Strings.cpp X
Here i s a sentence in a s tr in g .
Files ► Here i s sentence in a s tr in g .
2 a s in g namespace std; Here i s a s tr in g .
3
4 Int m a i n ()
5
Process returned 0 (0x0) execution time : 0.0S1 s
e FEH Press any key to continue.
7 string greetl = "Hello";
8 string greet2 = ", world!";
S string greet3 = greetl + greet2;
10
11 coat « greet3 « "\n";
12
13 >
14
C++ Maths
Program m ing is mathematical in nature and as you m ight expect, there's plenty oF
built-in scope For som e quite intense maths. C++ has a lot to oFFer som eone w h o's
implementing mathematical m odels into their code. It can be extremely complex or
relatively simple.
C++ = MC2
The basic mathematical symbols apply in C++ as they do in most other programming languages. However, by using the C++
Math Library, you can also calculate square roots, powers, trig and more.
C++'s mathematical operations follow the Multiplication and division can be applied as such:
same patterns as those taught in school, in that
#include <iostream>
multiplication and division take precedence overaddition and
using namespace std;
subtraction. You can alter that though. For now, create a new File
and enter: int main ()
{
#includs <iostream>
float numbers = 100;
using namespace std;
numbers = numbers * 10; // This multiplies 100
int main ()
by 10
{
float numbers = 100; cout « numbers « "\n";
numbers = numbers + 10; // This adds 10 to the numbers = numbers / 10; // And this divides
initial 100 1000 by 10
i l l C:\U5ers\david\Documents\C++\Maths.exe i l l CAUsers\david\Document5\C++\Maths,exe
110 1000
100 100
Process returned 0 (0x0) execution time : 0.043 s Process returned 9 (0x0) execution time : 0.050 s
Press any key to continue. Press any key to continue.
The interesting maths content comes when you call Calculating powers of numbers can be done with:
upon the C++ Math Library. Within this header are
dozens of mathematical functions along with further operations. #include <iostxeam>
Everything from computing cosine to arc tangent with two #include <cmath>
parameters, to the value of PI. You can call the header with: using namespace std;
Start by getting the square root of a number: Here we created a float called number with the
value of 12, and the pow(variable, power) is where
the calculation happens. Ofcourse, you can calculate powersand
#include <iostream>
square roots without using variables. For example, pow (12, 2)
tinclude <cmath>
outputs the same value as the first cout line in the code.
using namespace std;
int main ()
{
double area, radius = 1.5;
User Interaction
There's nothing quite as satisfying as creating a program that responds to you. This
basic user interaction is one of the m ost taught aspects of any language and with it
you're able to do much more than simply greet the user by name.
HELLO, D A V E
You have already used cout, the standard output stream, throughout our code. Now you're going to be using cin, the standard
input stream, to prompt a user response.
Anything that you want the user to input into the The cin command works in the opposite way from
program needs to be stored somewhere in the the cout command. With the first cout line you're
system memory, so it can be retrieved and used. Therefore, any outputting ’What is your age' to the screen, as indicated with the
input must first be declared as a variable, so it's ready to be used by chevrons. Cin uses opposite facing chevrons, indicating an input. The
the user. Start by creating a blank C++ file with headers. input is put into the integer age and called up in the second cout
command. Build and run the code.
I C:\Users\david\Documents\C++\userinteraction.exe
tinclude <iostream>
■ j The data type of the variable must also match the using namespace std;
type of input you want from the user. For example,
int main ()
to ask a user their age, you would use an integer like this:
{
tinclude <iostream> string name;
using namespace std; cout « "what is your name: ";
cin » name;
int main ()
{ cout « "\nHello, " << name « ". I hope you're
int age; well today?\n";
cout « "what is your age: ";
}
cin » age;
Starthere X *userinteraction.cpp X |
1 #include <iostream>
2 using namespace std;
3
4 Int main ()
5 EpH
6 int age;
7 cout << "what is your age:
8 cin » age;
5
10 cout <<"\nYou are " << age « " years old.\n";
11
12 }
13
The principal works the same as the previous code. While cin works well for most input tasks, it does
The user's input, their name, is stored in a string, have a limitation. Cin always considers spaces as a
because it contains multiple characters, and retrieved in the second terminator, so it’s designed Forjust single words not multiple words.
cout line. As long as the variable 'name' doesn't change, then you Flowever, getline takes cin as the First argument and the variable as
can recall it whereveryou like in your code. the second:
#include <iostream> i
using namespace std;
int main ()
{
int numl, num2;
cout « "you entered " « numl << " and " <<
num2 « "\n"; Build and execute the code, then enter a sentence
with spaces. When you're done the code reads the
number oF characters. IFyou remove the getline line and replace it
with cin » mystr and try again, the result displays the number oF
characters up to the First space.
• C:\UsersVdavid\DocumentsVC++\userinteraction.oe
Enter a sentence:
BDM Publications Python and C++ fo r Beginners
/our sentence is : 45 characters long.
54 Why Python?
56 What Can You Do with Python?
58 Python in Numbers
60 Equipment You Will Need
62 Getting to Know Python
64 How to Set Up Python in Windows
66 How to Set Up Python in Linux
68 Python on the Pi
m n m iin j n M I l|F|
W vQ I
V
m % 1 \ % m m m m\ \ m\ S
H I lllllilllU !M lu H II
Why Python?
There are many different program m ing languages available for the modern computer,
and som e still available for older 8 and 16-bit com puters too. Som e of these languages
are designed for scientific work, others for mobile platforms and such. So w hy choose
Python out o f all the rest?
PYTHON POW ER
Ever since the earliest home computers were available, enthusiasts, users and proFessionals have toiled away until the wee
hours, slaving over an overheating heap of circuitry to create something akin to magic.
These pioneers oF programming carved their way into a new Regardless oF whether you use an Android device, iOS device, PC,
Frontier, Forging small routines that enabled the letter A to scroll Mac, Linux, Smart TV, games console, MP3 player, GPS device built-in
across the screen. It may not sound terribly exciting to a generation to a car, set-top box o ra thousand other connected and 'smart'
that's used to ultra high-deFinition graphics and open world, multi appliances, behind them all is programming.
player online gaming. However, Forty-something years ago it was
blindingly brilliant. All those aForementioned digital devices need instructions to tell
them what to do, and allow them to be interacted with. These
Naturally these bedroom coders helped Form the Foundations For instructions Form the programming core oF the device and that core
every piece oF digital technology we use today. Some went on to can be built using a variety oF programming languages.
become chieF developers For top soFtware companies, whereas
others pushed the available hardware to its limits and Founded the The languages in use today diFFer depending on the situation, the
billion pound gaming empire that continually amazes us. platForm, the device's use and how the device will interact with its
environment or users. Operating systems, such as Windows, macOS Python was created over twenty six years ago and has evolved to
and such are usually a combination of C++, C#, assembly and some become an ideal beginner's language For learning how to program a
Form oF visual-based language. Games generally use C++ whilst web computer. It’s perfect for the hobbyist, enthusiast, student, teacher
pages can use a plethora of available languages such as HTML, Java, and those who simply need to create their own unique interaction
Python and so on. between either themselves or a piece of external hardware and the
computer itself.
More general-purpose programming is used to create programs,
apps, software or whatever else you want to call them. They're Python is Free to download, install and use and is available For Linux,
widely used across all hardware platforms and suit virtually every Windows, macOS, MS-DOS, OS/2, BeOS, IBM i-series machines, and
conceivable application. Some operate Faster than others and some even RISC OS. It has been voted one of the top Five programming
are easier to learn and use than others. Python is one such general- languages in the world and is continually evolving ahead of the
purpose language. hardware and Internet development curve.
Python is what's known asa High-Level Language, in that it 'talks' So to answer the question: why Python? Simply put, it's Free, easy to
to the hardware and operating system using a variety ofarrays, learn, exceptionally powerful, universally accepted, effective and a
variables, objects, arithmetic, subroutines, loops and countless superb learning and educational tool.
more interactions. Whilst it's not as streamlined as a Low-Level
Language, which can deal directly with memory addresses, call
stacks and registers, its beneFit is that it's universally accessible 4.0 L E T p y = 15
7 0 FO R W=1 T O 1 0
and easy to learn. 71 CLS
7 5 L E T b y = XN T IR N D * 2 3 )
8 0 L E T b x =0
I//file: Invoke.java 9 0 F O R d =1 T O £ 0
import java.lang.reflect.*; 1 0 0 P R IN T R T p x , p y ; " U ”
1 1 0 P R I N T R T bx , by j " o "
1 £ 0 I F I N K E Y $ = " p " T H E N L E T p y = P
y + 1
1 3 0 I F I N K E Y $ = ” Q ‘‘ T H E N L E T p y = P
class Invoke { y - 1 U
public static void main( String [] args ) { 1 3 5 F O R n =1 T O 1 0 0 : N E X T n
try { 1 4 0 I F p y <£ T H E N L E T p y =£
Class c = Class.forNameC args[0] ); 1 5 0 I F p y > 27 T H E N L E T p y = 2 7
Method m = c.getMethodC args[l], new class 1 S 0 L E T b x = bx +1
[] { } ) ; 1 8 5 P R IN T R T b X - l , b y ; " "
object ret = m.invokef null, null ); 1 9 0 N E X T d
System.out.pri ntln( 2 0 0 I F ( b M - 1 ) =p y T H E N L E T £ = S + 1
"Invoked static method: " + args[l] 2 1 0 P R IN T R T I 0 , l 0 ; " s c o r e = " ; s
2 2 0 F O R V =1 T O 1 0 0 0 : N E X T V
+ " of class: " + args[0] 3 0 0 N E X T W
+ " with no args\nResults: " + ret );
} catch ( ClassNotFoundException e ) { 0 O K , 0 : 1
// Class.forNameC ) can’t find the class
} catch ( NosuchMethodException e 2 ) {
// that method doesn't exist BASIC was once the starter language that early
} catch ( illeaalAccessException e 3 ) {
// we don't nave permission to invoke that 8-bit home computer users learned.
method
} catch ( invocationTargetException e4 ) {
// an exception ocurred while invoking that p r i n t (H A N G M A N [0])
System.out.pri ntln(
"Method threw an: " + e4 . while (attempts != 0 and in w o r d _ g uessed):
guessedletters.append(playerguess)
Python's ability to create highly readable code, within a small set You'll find lots of examples of this, where Python is acting behind
of instructions, has a considerable impact on our modern digital the scenes. This is why it's such an important language to learn,
world. From being an ideal first programmers' choice through to
being able to create interactive stories and games; from scientific
applications through to artificial Intelligence and web-based Beautiful is b etter th a n ugly.
e»
Explicit is better than implicit.
applications, the only limit to Python is the imagination of the Sim p le is b etter than com plex.
Com plex is b etter tha n com plicated.
person coding in it. Flat Is better than nested,
S p a rse is b etter than dense.
Readability co un ts.
It's Python's malleable design that makes it an ideal language for Sp ecial c a s e s a re n ’t special enough to b reak the rules.
Although p racticality b eats purity.
many different situations and roles. Even certain aspects of the E rro rs should n e v e r p a ss silently.
U nless exp licitly silenced .
coding world that require more efficient code still use Python. For In the face o f am biguity, refu se th e tem ptation to g ue ss.
example, NASA utilises Python both as a stand-alone language Th ere should be o n e - and preferab ly only one -o b v io u s w ay to do it.
Although th a t w ay m ay not be o bvious a t first u n le ss yo u 're Dutch.
and as a bridge between other programming languages. This way, Now is b etter than n ever.
Although n e v e r is often b etter tha n “ rig h t* now.
NASA scientists and engineers are able to get to the data they I f the im plem entation is h ard to exp la in , it's a bad idea.
need without having to cross multiple language barriers; Python I f the im plem entation is e a s y to e xp la in , it m ay be a good idea.
N am espaces are one honking g reat id ea — le t's do m ore o f those?
fills the gaps and provides the means to get the job done.
BIG DATA
« T o ,.
Big data is a buzzword you're likely to have come across in the last couple of years.
• ir r o r
Basically, it means extremely large data sets that are available for analysis to reveal
patterns, trends and interactions between humans, society and technology. Of course,
it’s not just limited to those areas, big data is currently being used in a variety of
industries, from social media to health and welfare, engineering to space exploration = False
HIRRORjp
and beyond. x * F a ls e
= F a ls e
L_* - T ru e
Python plays a substantial role in the world of big data. It's extensively used to analyse
huge chunks of the available big data and extract specific information based on what
the user/company requires from the wealth of numbers present. Thanks to an
impressive set of data processing libraries, Python makes the act of getting to the data,
in amongst the numbers, that counts and presenting it in a fashion that's readable and
useable for humans.
There are countless libraries and freely available modules that enable fast, secure and
more importantly, accurate processing of data from the likes of supercomputing clusters.
For example, CERN uses a custom Python module to help analyse the 600 million collisions
per second that the Large Pladron Collider (LHC) produces. A different language handles
the raw data, but Python is present to help sift through the data so scientists can get to the
content they want without the need to learn a far more complex programming language.
4 0 Minecraft Launcher
Although you won’t find too many triple-A rated games coded
Spotify, for example, uses Python based code,
using Python, you may be surprised to learn that Python is used as
among other things, to analyse your musical
an extra on many of the high-ranking modem games.
habits and offer playlists based on what you've
listened to in the past. It’s all clever stuff and
The main use of Python in gaming comes in the form of scripting,
moving forward, Python is at the forefront of
where a Python script can add customisations to the core game
the way the Internet will work in the future.
engine. Many map editors are Python compatible and you wilt also
come across it if you build any mods for games, such as The Sims.
r i <d
«
«
Coding & Programming
Introducing Python
There’s a
lot to like ab o u t
Python, but don’t ju st
take our word for it. Here are
som e amazing facts and figures
surrounding one of the most popular
programming languages of recent years.
PYTH O N AND
LIN UX S K ILLS
A R E TH E THIRD
As of the end of 2023, Disney Pixar uses Python
Python was the most M OST P O P U LA R in its Renderman software
discussed language on I.T. S K IL L S IN to operate between other
the Internet. graphics packages.
TH E UK.
1
*
7 5 % )
^
# % 9 0 f 7 5 %)
OVER 75% OF 90% OF ALL IT’S ESTIMATED
RECOMMENDED FACEBOOK POSTS THAT OVER 75% OF
CONTENT FROM NETFLIX ARE FILTERED NASA'S WORKFLOW
IS GENERATED FROM THROUGH PYTHON- AUTOMATION
MACHINE LEARNING - CODED MACHINE SYSTEMS ON BOARD
CODED BY PYTHON. LEARNING. THE I.S.S. USE PYTHON.
PYTHON SKILL-BASED
16,000 POSITIONS ARE THE
ftfffttt
m tm i MOST SOUGHT-AFTER
There are over 16,000 Python jobs
posted every six months in the UK. JOBS IN THE UK.
Python Data Science is Google is the top Data Science, Blockchain New York and San
thought to become the company for hiring Python and Machine Learning Francisco are the top
most sought-after job in developers, closely are the fastest growing Python developer cities
the coming years. followed by Microsoft. Python coding skills. in the world.
EquipmentYou
Will Need
You can learn Python with very little hardware or initial financial investment. You
don't need an incredibly powerful com puter and any software that's required is
freely available.
W H A T W E 'R E U SIN G
ThankFully, Python is a multi-platForm programming language available For Windows, macOS, Linux, Raspberry Pi and more. IF
you have one oF those systems, then you can easily start using Python.
□ COM PUTER
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 eithera 32
or 64-bit processor, an Apple Mac or Linux installed PC.
_ J A N ID E
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.
□ T E X T E D IT O R
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.
_ J IN T E R N E T A C C E S S
Python is an ever evolving environment and as such new versions often introduce
new concepts or change existing commands and code structure to make it a more
efficient language. Having access to the Internet will keep you up-to-date, help you
out when you get stuck and give access to Python's immense number of modules.
_ J T IM E A N D P A T IE N C E
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 timesand other times the code will Flow like water. Understand you're learning
something entirely new, and you will get there.
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
FUZE PROJECT
BOOKS
n 2 r * l* * ~ '*
Col°ur Guides
'MPublia,;on!.
3 Popercut t-
’"timremcl,
Coding & Programming
</>] Introducing Python
PYTHON POW ER
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.
The Python Software Foundation, a non-profit organisation devoted Made up from over 5 Petabytes of data, spread across a
to both furthering and improving Python, currently develops the ton of hard drives, Python helped science to unveil the first
language. The foundation's purpose is to "promote, protect, and image of a black hole.
advance the Python programming language, and to support and
facilitate the growth of a diverse and international community of
Python programmers." As a side 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
The structure of Python code has been designed to flow easily, image of a black hole was released, the supermassive black hole in
allowing those who are just beginning to code to follow it without the galaxy called M87, located roughly 55 million light years away.
too much difficulty. Yet, despite its ease of use, Python is regularly Thanks to the collaboration of over 200 scientists, using an array of
used throughout a number of industries in real-world scenarios. telescopes spanning the world (called the Event Horizon Telescope
Project), the combined power of the telescopes formed an
Big Data and Al are the two fastest growing Python-backed impressive five petabytes of data, spread across tens of hard drives
technologies at the moment. Big Data is simply a modern term weighing in at nearly one ton. Five petabytes, by the way, equates
used to describe huge to around 5,000 years’ worth of MP3 files. Once all those hard drives
amounts of data, were gathered together and shipped to a central supercomputer
such as sequences cluster, the team then used Python to painstakingly stitch together
of numbers collated all the fragments of data from the five petabytes to finally form the
during a day's worth of most talked about astronomic event of the decade.
trading on the Stock
Exchange. Python Al, if you're not familiar with the term, stands for Artificial
code is used to dig Intelligence. Although we're still a long way off from the visionary
into the voluminous stories of Arthur C. Clarke, Al is fast becoming one of the most
collection of numbers, influential technologies of our modern age. Rather than controlling
and then feed back robots, the Al that Python drives is designed to create autonomous
with reports on the ways of interacting with people online. For example, when you
highs and lows, what's search for something on the Amazon website you will usually notice
trending, and so on. that similar products start to appear, whether within Amazon itself,
PYTHON 3 VS PYTHON 2
In a typical computing scenario, Python is complicated somewhat by the existence of two active versions of the language:
Python 2 and Python 3.
You need to be careful when you look up Python code online, although
jgi python there are countless websites that offer quick tutorials, code snippets
About Downloads DocunterVlotion Community Success Stones News fventS and support-and 99% of these site are a great help to those starting
out with Python - a lot of the sites haven't been updated for some
ngfunctions. time, and as such use Python 2. If you enter Python 2 code into the
Python 3 IDLE, the chances are it won't work due to incompatibilities
between the older version and the newer. Python 2 is good, but
6 9 Python 3 is better. You can obviously spend time converting the
Python 2 code into version 3, but, to begin with, it's best to make sure
that the code you're looking at is for the Python 3 libraries. Don’t
Python 3 is the best option to
worry, though, all the code in this book is designed for Python 3, and
download, or update to.
that includes all the sub versions from Python 3.1 to the latest 3.x.
Python 3 is the newest release of the programming language.
However, if you dig a little deeper into the Python site and investigate Python 3's growing popularity has meant that it's now prudent to start
Python code online, you will undoubtedly come across Python 2. learning to develop with the new features and begin to phase out the
Crucially, although you can run Python 3 and Python 2 alongside previous version. Many development companies, such as SpaceX and
each other, it's not recommended. Always opt for the latest stable NASA, use Python 3 for snippets of important code.
release, as posted by the Python website. You will find, when using
macOS or Linux, that Python 2 is already installed. This is because However, support for Python 2 is set to end on January 1st 2020, but
both these operating systems utilise elements of code necessary to this doesn't mean it’ll be the last you see of it. Many Linux distros use
the core functionality of the OS. Linux users tend to be better off, Python 2 libraries, as does macOS, and to be fair, for the developers
as most distributions package the latest version of Python 3 out-of- to transfer the existing Python 2 content to Python 3 may take more
the-box, whereas macOS often has Python 3, it's usually an older time than they have available, i.e. before the start of 2020. It's likely
version. Microsoft doesn't use any Python code for its core Windows then, that we will still be seeing Python 2 long after it has had the Final
systems, which is why you won’t find Python inherent to Windows and nail hammered into its coffin-in fact, expect to see that cut-off date
therefore need to install it from scratch. extend further into the future.
Despite the fact that many people find the targeting of Python lets you access
advertising intrusive, or even an invasion of privacy, you have to all the power of a
admit that the code technology behind it all is rather impressive. computer in a language
With some very clever techniques, a Python developer is able that humans can
to create a machine thinking script that not only displays items, understand. Behind all
news stories, books, other websites and ideas relating to what this is an ethos called
you've searched for, but it can also predict what you may be "The Zen of Python".
interested in looking for in the future. Another element to This is a collection of 20
consider, with regards to Al, is that Python code can be used to software principles that
$
help a computer learn how to do something more efficiently. In influences the design of
the case of neural networks in Al, the Python code is designed the language. Principles The Zen of Python, as
to return a result, then, as the code is run over and over again, include "Beautiful is seen when entering:
the Al portion will begin to learn how to obtain a more accurate better than ugly" and import this, into the
result, or do the maths behind the code quicker. It all depends on "Simple is better than Python IDLE.
what the developer wants from their Al Python code. comnlex." Tvne: WIBWM
| into Python and it will display all the principles.
How to Set Up
Python in Windows
W indow s users can easily install the Python programming language via the main Python
Downloads page. While most seasoned Python developers may shun W indow s as the
platform of choice for building their code, it's still an ideal starting point for beginners.
IN ST A L L IN G P Y T H O N 3.X
MicrosoFt Windows doesn’t come with Python pre-installed as standard, so you're going to have to install it yourselF manually.
ThankFully, it's an easy process to follow.
Start by opening your web browser to www.python, Choosing the Customise option allows you to
org/downloads/. Look For the button detailing the speciFy certain parameters, and while you may
Download link for Python 3.x. Python is regularly updated, changing stay with the deFaultsit's a good habit to adopt as sometimes (not
the last digit For each bug Fix and update. ThereFore, don't worry iF with Python, thankFully) installers can include unwanted additional
you see Python 3.7.0, or more, as long as it's Python 3, the code in Features. On the First screen available, ensure all boxes are ticked
this book will work Fine. and click the Next button.
e* python
Optional Features
About Downloads Documentation Community Success Stories News E'l 0 Documentation
Installs the Python documentation file.
D o w n lo a d t h e la t e s t v e r s io n f o r W in d o w s 0 pip
Installs pip. which can download and install other Python packages.
W w \ ! J! 0 td/tk and IDLE
Looking for Python with a different OS? Python for Windows,
Installs tkinter and the IDLE development environment
Unux/UNIX, Mac OS X, Other
Want to help test development versions of Python? Prereleases, 0 Python test suite
Docker images Installs the standard library test suite.
Looking for Python 2.7? See below for specific releases
Ji 0 py launcher 0 for all users (requires elevation)
nuthnn
Click the download button For version 3.x, and save The next page oF options include some interesting
the File to your Downloads Folder. When the File is additions to Python. Ensure the Associate File with
downloaded, double-click the executable and the Python installation Python, Create Shortcuts, Add Python to Environment Variables,
wizard will launch. From here you'll have two choices: Install Nowand Precompile Standard Library, and Install For All Users options are
Customise Installation. We recommend opting For the Customise ticked - these make using Python later much easier. Click Install
Installation link, and that the Add Python 3.x to PATH option is ticked. when you're ready to continue.
& Python 3.9.0 (64-bit) Setup & Python 3.9.0 (64-bit) Setup X
c»
0 Create shortcuts for installed applications
^ Install Now
C:\Users\dav idVAppDataVLocaf\Prograrm\Python\Python39 0 Add Python to environment variables
You may need to confirm the installation with the If you now click on the Windows Start button again,
Windows authentication notification. Simply click and this time typeCMDyou'll be presented with
Yes and Python will begin to install. Once the installation is complete the Command Prompt link. Click it and you'll be at the Windows
the final Python wizard page will allow you to view the latest release command line environment. To enter Python within the command
notes, and follow some online tutorials. line, you need to type: python and press Enter.
Setup w as successful
See what’s new in this release, or find more info about u sin a
r * Python on Windows.
p y th o n
for
w in d o w s Close
Windows 10 users will now find the installed The command line version of Python works in much the
Python 3.x within the Start button Recently Added same way as the Shell you opened inStep 7; note the
section. The first link, Python 3.x (64-bit) - or 32-Bit (more on that three left-facing arrows (»>). While it's a perfectly fine environment,
in a moment) - will launch the command line version of Python it’s not too user-friendly, so we'll leave the command line for now. Enter
when clicked (more on that in a moment). To open the IDLE, type exit () to leave, and close the Command Prompt window.
IDLE into Windows start.
I Command Prompt
Microsoft Windows [Version 10.0.19041,610]
Best match (c) 2020 Microsoft Corporation. All rights reserved.
Apps
Jb Uninstall
Clicking on the IDLE (Python 3.x 64-bit) link will There are two versions of the latest Python
launch the Python Shell, where we’ll begin our available, 32-Bit and 64-Bit. Essentially, the 64-Bit
Python programming journey. Don't worry if your version is version of Python allows you to utilise more than 4CB of memory.
newer, as long as it's Python 3.x our code will work inside your While this is great for users with a lot of memory, and memory hungry
Python 3 interface. processes, it's not an essential feature of Python. However, the 32-bit
version may provide more compatibility with existing modules.
[ £ Python 3.9.0 Shell - □ X
File Edit Shell Debug Options Window Help
Python 3.9.0 tcags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on Win32
Type "help", "copyright", "credits” or "licensed" for more information.
How to Set Up
Python in Linux
While the Raspberry Pi's operating system contains the latest, stable version of Python,
other Linux distros don't come with Python 3 pre-installed. IP you're not going down
the Pi route, then here's how to check and install Python Por Linux.
P Y T H O N P E N G U IN
Linux is such a versatile operating system that it's oFten diFficult to nail down just one-way of doing something. DiFFerent
distributions go about installing software in different ways, so For this particular tutorial we will stick to Linux Mint.
First you need to ascertain which version of Python Once the update and upgrade completes, enter:
is currently installed in your Linux system. To begin python3 — version again to see if Python 3.x is
with, drop into a Terminal session from your distro's menu, or hit the updated, or even installed. As long as you have Python 3.x, you're
Ctrl+Alt+T keys. running the most recent major version, the numbers after the 3.
indicate patches plus further updates. Often they're unnecessary,
david@david-Mint: - but they can contain vital new elements.
File Edit View Search Terminal Help I FL[e Edit View Search Terminal Help
has been updated with the latest versions, enter: sudo apt-get File Edit View Search Terminal Help
d a v id @ d a v id -M in t : S sudo a p t -g e t i n s t a l l b u i l d - e s s e n t i a l c h e c k in s t a l l
update && sudo apL-geL upgrade to update the system. Reading package l i s t s . . . Done
B u ild in g dependency tre e
Reading s t a t e in f o r m a t io n . . . Done
d a v id e d a v id - M in t : - b u i l d - e s s e n t i a l i s a lre a d y th e newest v e r s io n ( 1 2 .4 u b u n t u l) .
The fo llo w in g NEW packages w i l l be i n s t a l l e d
File Edit View Search Terminal Help c h e c k in s t a l l
0 to upgrade, 1 to new ly i n s t a l l , 0 to remove and 3 not to upgrade.
david@david-Mint:-$ python --version Need to ge t 9 7 .1 kB o f a r c h iv e s .
Python 2.7.15rcl A f t e r t h i s o p e ra t io n , 438 kB o f a d d it io n a l d is k space w i l l be used.
david@david-Mint:-$ python3 --version Do you want to c o n tin u e ? [Y/n] y
Python 3.6.7
david@david-Mint:-$ sudo apt-get update && sudo apt-get upgrade
[sudo] password for david: |_____________________________________
Open up your Linux web browser and go to the For the GUI IDLE, you'll need to enter the following
Python download page: https://www.python.org/ command into the Terminal:
downloads. Click on the Downloads, followed by the button under
sudo apt-get install idle3
the Python Source window. This opens a download dialogue box,
choose a location, then start the download process. The IDLE can then be started with the command: idle3. Note, that
IDLE runs a different version to the one you installed from source.
37.2
da vid @ d a vid -M in t: -/ D o w n lo a d s/ P yth o n - .
Python on the Pi
IF you're considering on which platForm to install and use Python, then give som e
thought to one oF the best coding bases available: the Raspberry Pi. The Pi has many
advantages For the coder: it's cheap, easy to use, and extraordinarily Flexible.
THE POW ER O F PI
While having a Far more powerful coding platForm on which to write and test your code is ideal, it's notoFten Feasible. Most oF
us are unable to jump into a several hundred-pound investment when we're starting oFF and this is where the Raspberry Pi can
help out.
While having a Far more powerful coding platForm on which to kits available will provide the Pi with a pre-loaded SD card (with the
write and test your code is ideal, it's not often feasible. Most of us latest Raspbian OS), a case, power socket and cables, this is a good
are unable to jump into a several hundred-pound investment when idea as you could, with very little effort, leave the Pi plugged into the
we're starting oFF and this is where the Raspberry Pi can help out. wall under a desk, while still being able to connect to it and code.
The Raspberry Pi is a fantastic piece of modern hardware that The main advantage is, of course, the extra content that the
has created, or rather re-created, the Fascination we once all had Raspberry Pi Foundation has included out of the box. The reason
about computers, how they work, how to code and Foundation for this is that the Raspberry Pi's goal is to help educate the
level electronics. Thanks to its unique mix of hardware and custom user, whether that’s coding, electronics, or some other aspect of
software, it has proved itself to be an amazing platform on which to computing. To achieve that goal the Pi Foundation includes different
learn how to code; specifically, using Python. IDEs for the user to compile Python code on; as well as both Python
2 and Python 3, there's even a Python library that allows you to
While you're able, with ease, to use the Raspberry Pi to learn to communicate with Minecraft.
code with other programming languages, it's Python that has been
firmly pushed to the Forefront. The Raspberry Pi uses Raspbian as There are other advantages, such as being able to combine Python
its recommended, default operating system. Raspbian is a Linux code with Scratch (an Object-Oriented programming language
OS, or to be more accurate, it's a Debian-based distribution of developed by MIT, For children to understand how coding works) and
Linux. This means that there's already a built-in element of Python being able to code the GPIO connection on the Pi to further control
programming, as opposed to a Fresh installation of Windows 10, any attached robotics or electronics projects. Raspbian also includes
which has no Python-specific base. However, the Raspberry Pi a Sense HAT Emulator (a HAT is a hardware attached piece of
Foundation has gone the extra mile to include a vast range of circuitry that offers different electronics, robotics and motorisation
Python modules, extensions and even examples, out of the box. projects to the Pi), which can be accessed via Python code.
So, essentially, all you need to do is buy a Raspberry Pi, follow the
instructions on how to set one up (by using one of our excellent Consequently, the Raspberry Pi is an excellent coding base, as well
Raspberry Pi guides found at www.bdmpublications.com) and you as a superb project foundation. It is for these, and many other,
can start coding with Python as soon as the desktop has loaded. reasons we've used the Raspberry Pi as our main Python codebase
throughout this title. While the code is written and performed on a
Significantly, there's a lot more to the Raspberry Pi, which makes Pi, you're also able to use it in Windows, other versions of Linux and
it an excellent choice for someone who is starting to learn how to macOS. If the code requires a specific operating system, then, don't
code in Python. The Pi is remarkably easy to set up as a headless worry; we will let you know in the text.
node. This means that, with a few tweaks here and there, you're able
to remotely connect to the Raspberry Pi From any other computer,
Everything you need to learn to code with Python is
or device, on your home network. For example, once you've set up
included with the OS!
the remote connectivity options, you can simply plug the Pi into the
power socket anywhere in your house within range of your wireless IP ^ B ^ Q ^[Se"MHATEmul»lotl ^ :v- 'ir-r-.:- ^ [PylhoiJ53SMI)
HE I
router. As long as the Pi is connected, you will be able to remotely Cdu:si'<>r > t y vr.-tuwa-ra
access the desktop from Windows or macOS as easily as if you were ^ off*# I r* rynon3<iDiQ
(y) Scratch
sitting in front of the Pi with a keyboard and mouse. 5 Graphics • Scratch2
f A«*JS5TV« > mSeos#K4TEmulator
Using this method saves a lot of money, as you don’t need another
keyboard, mouse and monitor, plus, you won't need to allocate
sufficient space to accommodate those extras either. If you're pushed
for space and money, then for around £60, buying one of the many
PI 4-EVER!
RASPBIAN BUSTER
In short, what you see in this book will work with the Raspberry Pi
4,5 and Raspbian Buster!
Once set up, you can remotely connect to the Pi’s desktop You can even test connected hardware with Python
from any device/PC. remotely, via Windows.
ST A R T IN G P Y T H O N
As when learning anything new, you need to start slow. You can pick up the pace as your experience grows, but For now, let’s
just get something appearing on the screen. Don’t worry, you'll soon be coding like a pro!
■ S H j Click on the Windows Start button, and start typing For example, in the Shell enter: 2+2
'idle’. The result will be the currently installed AFter pressing Enter, the next line will display the
version oF the Python IDLE on your system. You can Pin it to the answer: 4. Basically, Python has taken the 'code' and produced the
Start For convenience, otherwise simply click the icon to launch the relevant output.
Python Shell.
Li Python 3.7.0 Shell □ X
File Edit Shell Debug Options Window Help
Python 3.7.0 (v3.7.0:lbfScc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bi t (Intel)]
“ "1” 32
>»l
The Shell is where you can enter code and see the The Python Shell acts very much like a calculator,
responses and output oF code you've programmed since code is basically a series oF mathematical
into Python. This is a kind oF sandbox, iFyou will, where you're able interactions with the system. Integers, which are the inFinite
to try out some simple code and processes. sequence oF whole numbers, can easily be added, subtracted,
multiplied, and so on.
Python 3.7,0Shell - □ X
File Edit Shell Debug Options Window Help
Qfc Python 3.7.0Shell — O X
Python 3.7.0 (v3.7.0:lbfScc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on Win32
Type "copyright", "credits" or "licensed" for more information. File Edit Shell Debug Options Window Help
i Python 3,7,0 <v3.7,0;lbf9cc50S3, Jun 27 2018, 04:0«7TT) [MSC v7l914 32 "bit (Intel)] on Win32
Type "copyright", "credits" or "licensed" for more information.
2+2
» > 8+6
234S3+645545522
645568975
» > 98778642342-12343
98778629999
» > 1287437*43534
56047282358
While that's very interesting, it's not particularly The Python IDLE is a configurable environment. IF
exciting. Instead, try this: you don't like the way the colours are represented,
then you can always change them via Options > Configure IDLE, and
print("Hello everyone!")
clicking on the Highlighting tab. However, we don't recommend that
Just enter it into the IDLE as you've done in the previous steps. as you won’t be seeing the same as our screenshots.
L# Python 3.7.0Shell - □
File Edit Shell Debug Options Window Help File Edit Shell Debug Options Window Help
Python 3.7.0 (v3.7.0:Ibf9ec5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)) on Win32 Python 3.7.0 (v3.7.0:Ibf9cc5093, Jun 27 2018, 04:06:47) (MSC v.1914 32 bit (Intel)] i
Type "copyright", "credits" or "license()" for more information. Type "copyright", "credits" or "licensee)" for n : information.
14 14
23453+645545522 » > 23453+645545522
645568975 645568975 bfc Settings
» > 98778642342-12343 > » 98778642342-12343
98778629999 98778629999 Fonts/Tabs Highlights Keys Generi
» > 1287437*43534 » > 12 87437" 43534 Custom Highlighting Highlighting Theme
56047282358 56047282358
» > print("Hello everyone:’ » > print ("Hello every* Select:
Hello everyone! Choose Color for: ® a Built-in Theme
I
Normal Text
This is a little more like it, since you've just produced As with most programs available, regardless of the
your First bit oF code. The Print command is Fairly operating system, there are numerous shortcut
self-explanatory, it prints things. Python 3 requires the parentheses keys. We don't have room For them all here, but within the Options
as well as quotes in order to output content to the screen, in this > Configure IDLE and under the Keys tab, you'll see a list of the
case the 'Hello everyone!' bit. current bindings.
You'll have noticed the colour coding within the The Python IDLE is a power interface, and one
Python IDLE. The colours represent different that's actually been written in Python using one
elements oF Python code. They are: of the available GUI toolkits. If you want to know the many ins and
outs For the Shell, we recommend you take a few moments to view
Black - Data and Variables B lu e -U se r Functions
https://docs.python.Org/3/library/idle.html, which details many oF
Green-Strings Dark Red - Comments
the IDLE's Features.
Purple-Functions Light Red - Error Messages
O rang e- Commands
P LA Y IN G W IT H P Y T H O N
As with most languages, computer or human, it's all about remembering and applying the right words to the right situation.
You're not born knowing these words, so you need to learn them.
Ifyou've dosed Python 3 IDLE, re-open it as you You'll notice that instead of the number 4, the
did in the previous page. In the Shell, enter the output is the 2+2 you asked to be printed to the
familiar following: screen. The quotation marks are defining what's being outputted
to the IDLE Shell, to print the total of 2+2 you’ll need to remove
print("Hello")
the quotes:
>»
As predicted, the word Hello appears in the Shell You can continue as such, printing 2+2, 464+2343
as blue text indicating output from a string. It's and so on to the Shell. An easier way is to use a
fairly straightforward, and doesn’t require too much explanation. variable, which is something we will cover in more depth later. For
Now try: now, enter:
print("2+2") a=2
b=2
[jjt 1hc-n SheI
File Edit Shell Debug Options Window Help
lift Python 3,7.0 Shell
Python 3.7.0 (v3.7.0:lbf9ccS093, Jun 27 2018, 04:06:47) [MSC v.1514 32 bit (Intel)]
Win32 File Edit Shell Debug Options Window Help
Type "copyright", "credits” or "license ()" for more information. Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)]
» > print ("Hello") W in32
Hello Type "copyright", "credits" or "license ()" for more information.
» > print ("2+2") » > print ("Hello")
2+2 Hello
»> » > print ("2+2 ")
2+2
» > print (2+2)
0
1
1 0 0
0
0 1 1 1
10 1 ) )
111 0 0
0 1 0 0 1 0
0 0 1 0 1 0 0 0 1 0 1 0 1 » 10 0 0 0 1 1 1 0 1
0 0 1 1 1 1 i 1 ° 10 1 o 0 0
goding & Programming
0 o 0 1 0 1 11 0 0 1 0 1 0 1 1 0 0
0 1 1 1 o ooo o 0 0 0 1 o 0 1 11 l1 oo 0 1 1 0 1
Your First Code
What you have done here is assign the letters a Now let's add a surname:
and b two values: 2 and 2. These are now variables,
surname="Hayward"
which can be called upon by Python to output, add, subtract, divide
print(surname)
and so on, For as long as their numbers stay the same. Try this:
We now have two variables containing both a first name and a
print(a)
surname, and we can print them independently.
print(b)
The output oF the last step displays the current IF we were to apply the same routine as beFore,
values oFa and b individually, as essentially you've using the + symbol, the name wouldn't appear
asked them to be printed separately. iFyou want to add them up, correctly in the output in the Shell. Try it:
you can use the Following:
print(name+surname)
print(a+b)
We need a space between the two, deFining them as two separate
This code takes the value oF both a and b, adds them together, and values and not something you mathematically play around with.
outputs the result.
You can play around with diFFerent kinds oF variables In Python 3 we can separate the two variables
together with the Print Function. For example, we with a space by using a comma:
could assign variables For someone's name:
print(name, surname)
name= " David"
Alternatively, you can add the space yourselF:
print(name)
print(name+" "isurname)
G | Python 3.7,0Shell
As you can see, the use oF the comma is much neater.
File Edit Shell Debug Options Window Help
Pychon 3.7.0 (v3.7. 0:lbf9cc5053, Jun 27 2018, 04:06:47) [MSC v.1514 32 bit (Intel)) Congratulations, you've just taken your First steps into the wide
Win32
Type "copyright", ’credits" or "licensed" ^or more information. world oF Python.
» > print ("Hello")
Hello
» > print ("2+2")
0 2+2 [<& Python 3.7.0 Shell
> » print (2+2)
4 File Edit Shell Debug Options Window Help
» > a=2 Python 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
» > b=2 1)] on Win32
» > print (a)
Type "copyright", "credits" or " l i censed" f°r more information.
2 >>> name="David"
»> print (b)
1 2 >>> p r i n t (name)
» > print (a+b) David
_ 1 4
» > name=" David.”
» > surname*"Hayward"
>>> p r i n t (surname)
0 1 DavidHayward
0 0 0 1 0 1 0 1 0 o o o 0 0 0 1 i 0 1 » 1 0 0 0 0 0 0 1
0 0 0 l o () 1 1 0 1 0 0 1 1 1 o 0 i 1 1 1 1
Coding & Programming
0 1 0 0 1 0 0 1 i 0 0 0 () o o 1 0 1
O i i i o 0 0 0 0 1 0 1 0 o 0 0 1 0 0 ii o 0 0 1 l 10 10
Coding w ith Python
E D IT IN G C O D E
You will eventually reach a point where you have to move on From inputting single lines oF code into the Shell. Instead, the
IDLE Editor will allow you to save and execute your Python code.
First, open the Python IDLE Shell. When it's up, dick As you can see the same colour coding is in place in
on File > New File, this will open a new window with the IDLE Editor as it is in the Shell, enabling you to
Untitled as its name. This is the Python IDLE Editor, and within it, you better understand what's going on with your code. To execute the
can enter the code you need to create your future programs. code, however, you need to first save it. Press F5 and you'll have a
Save...Check box open.
u ti --
The IDLE Editor is, for all intents and purposes, a Click on the OK button in the Save box, and select a
simple text editor with Python features, colour destination where you'll save all your Python code.
coding and so on. You enter code as you would within the Shell, so The destination can be a dedicated foldercalled Python, oryou can
taking an example from the previous tutorial, enter: just dump it wherever you like. Remember to keep a tidy file system,
though, it'll help you out in the future.
print("Hello everyone!")
Enter a name foryourcode, 'print hello' For Let's extend the code and enter a Few examples
example, and click on the Save button. As soon From the previous tutorial:
as the Python code is saved, it's executed and the output will be
a=2
detailed in the IDLE Shell; In this case, the words 'Hello everyone!'.
b=2
name="David"
surname="Hayward"
print(name, surname)
print (a+b)
IFyou press F5 now, you'll be asked to save the File again, as it's been
modiFied From beFore.
This is how the vast majority oF your Python code T H IFyou click the OK button the File will be overwritten
j l
will be conducted. Enter it into the Editor, hit F5, with the new code entries, and executed; with the
save the code, and look at the output in the Shell. Sometimes things output in the Shell. It's not a problem with just these Few lines, but
will diFFer, depending on whether you've requested a separate if you were to edita larger File overwriting can become an issue.
window, but essentially that's the process and, unless otherwise Instead, use File > Save As From within the Editor to create a backup.
stated, this is the method we will use.
(jf!r "print hello.py - C:/Python Code/print hello.py (5.7.0)*
U Python 3.7.0 Shell □ X File Edit Format Run Options Window Help
File Edit Shell Debug Option Window Help New File Ctrl+N
Python 3.7.0 (v3.7.0:lbf9eeS093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte Open... Ctrl+O
1)] on Win32
Type "copyright", "credits" or "license()" for more information.
Open Module... Alt+M
»> Recent Files ►
= ============= = = RESTART: C:/Python Code/print hello.py = =========== = = = Module Browser Alt+C
Hello everyone!
»> Path Browser
Save Ctrl+S
Save As... Ctrl-*-Shift-*- S
Save Copy As... Alt+Shift+S
Close Alt+ F4
Exit Ctrl+Q
iFyou open the File location oF the saved Python Now create a new File. Close the Editor, and open
code, you'll notice that it ends in a .py extension. a new instance (File > New File From the Shell).
This is the deFault Python filename, any code you create will be Enter the Following, and save it as hello.py:
whatever.py, and any code downloaded From the many Internet
a="Python"
Python resource sites will be .py. Just ensure that the code is written
b="is"
For Python 3.
c="cool!"
print(a, b, c)
COMMAND TH E 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 Now you're at the command line, we can start
routine automatically included all the necessary Python using the command python and pressing
components to allow the execution oF code outside of the GUI the Enter key. This will put you into the command line version of the
IDLE; in other words, the command line. To begin with, click on the Shell, with the familiar, three right-facing arrows as the cursor (»> ).
Windows Start Button, and type: cmd.
As you did when launching the Python IDLE, From here you're able to enter the code you've
click on the returned result from the search, the looked at previously, such as:
Command Prompt App. This will launcha newwindow, w itha black
a=2
background and white text. This is the command line, also called a
print(a)
Terminal in macOS, Linux, and Raspberry Pi operating systems.
As you can see, it works exactly the same.
» > print(a)
Now enter exit () to leave the command line From within the same folder as the code you're going
Python session, and return back to the command to run, enter the following into the command line:
prompt. Enter the folder where you saved the code from the
python hello.py
previous tutorial, and list the available files within; you should see
the hello.py file. This will execute the code we created, which to remind you is:
ic:\Users\david>python
Python 3.7.0 (v3.7.0:lbf9ccS093, 3un 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] (
Type "help", "copyright", "credits" or "license” for more information.
» > a=2
i»> print(a)
2 j Com mand Prompt
>» e*it()
C :\Users\david>ed\ C:\Python Code>python hello.py
Python is cool!
jc:\>cd "Python Code"
C:\Python Code>
If you've previously used Python 3 on a Mac or Linux, and This isn’t an issue with Windows, as it doesn't use any Python
subsequently the Raspberry Pi, you may be a little confused as libraries other than the ones installed by the user themselves
to why the Windows version of Python uses the command line: when actually installing Python. When a Windows user installs
python, instead of python3. Python, the installation wizard will auto-include the command line
instance to the core Windows PATH variable, which you can view by
The reason behind this is that UNIX-like systems, such as macOS entering: path into the command line. This points to the python,
and Linux, already have Python libraries pre-installed. These older exe file required to execute Python code from the command line.
libraries are present because some of the macOS and Linux system
utilities rely on Python 2, and therefore installing a newer version We don't recommend you install both Python 2 and Python 3
of Python, and thus altering the executable name, could have dire within Windows 10; naturally, you can if you want, but realistically,
consequences to the system. 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
As a result, developers decided that the best approach for macOS rename one of the Python versions names; as they will be installed
and Linux systems would be to leave the command line ‘python’ in different folders and both use python.exe as the command line
as exclusive Python 2 use, and newerversions of user-installed executable. It's a little long-winded, so unless there's a dire need to
Python would be 'python3‘. have both versions of Python installed, it's best to stick to Python 3.
C :\Users\david>path
P A T H=C:\ProgramData\Oracle\lava\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C
:\Windows\system32;C :\Windows;C :\Windows\System32\Wbemj C :\Windows\System32\WindowsPowerShell\vl.0 \ ; C :\Program Files (x86
)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DALjC:\Pr
pgram Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Comp
onents\IPT;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\WINDOWS\system32;C:\WINtX)WS;C:\WINDOWS\System32\Wbe
mjC:\WINDOWS\System32\WindowsPowerShell\vl.0\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files\PuTTY\;C:\WIND
bws\System32\OpenSSH\;C:\Program Files\NVIDIA Corporation\NVIDIA N vDLISR;C:\Users\david\AppData\Local\Programs\Python\Py
phon37-32\Scripts\;C:\Users\david\AppData\Local\Programs\Python\Python37-32\;"C:\Users\david\AppData\Local\Microsoft\Win
dowsApps; C:\Users\david\AppData\local\Programs\Python\Python36-32w; ; C :\Users\david\AppData\Local\Microsoft\WindowsApps
C :\Users\david>
Open up the GUI version of Python 3, as mentioned You can use all [ + Python 3.7,0 Shell
you can use either the Shell or the Editor. For the the customary File Edit Shell Debug Options W indow
Python 3.7.0 (v 3 .7.O :lbf9cc5093,
time being, we're going to use the Shell. If you've opted to use a Mathematical operations: divide, 1)] on Win32
third-party text editor, note thatyou need to get to the IDLE Shell multiply, brackets and so on. Type "copyright", "credits" or "I
> » 2+2
for this part of the tutorial. Practise with a few, for example: 4
» > 54356+34553245
|_^r Python 3.7,0 Shell — □ X 1/2 34607601
» > 99867344*27344434221
File Edit Shell Debug Options Window Help 6/2
2730821012201179024
Python 3.7.0 (v3.7.0:Ibf9cc5093, Jun 27 2018, 0-4:06:47) [MSC v.1914 32 bit (Inte
1 )] o n W in 3 2
2+2*3 > » 1/2
0.5
Type "copyright", "credits" or "license()" for more information. (1+2)+(3*4)
>» >» 6/2
3.0
> » 2+2*3
8
>» (l+2>+(3*4>
15
»>
Using Comments
W hen writing your code, the Plow, what each variable does, how the overall program
will operate and so on, is all inside your head. Another program m er could Follow the
code line by line, but w hen the code starts to hit thousands oP lines, things get a little
diPPicult to read.
#CO M M EN TS!
A method 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.
We'll start by creating a new instance of the IDLE Re-save the code and execute it. You'll see that the
■ Editor (File > New File), and then create a simple output in the IDLE Shell is still the same as before,
variable and print command: despite the extra lines being added. Simply put, the hash symbol (#)
denotes a line of text the programmer can insert, to inform them
a=lO
and others of what's going on, without the user being aware.
print("The value of A is,", a)
Python 3.7.0 Shell — □ X
Save the Pile, and execute the code.
File Edit Shell Debug Options Window Help
Python 3.7.0 (v3.7.0:lbfScc5093, Jun 27 2018, 04:06:47) [MSC v.1514 32 bic (Inte
[j|r Comm ents.py - C:/Python Code/Com m ents.py (3.7.0) 1)] on Win32
Type "copyright", "credits" or "license()" for more information.
File Edit Format Run Options W indow Help >»
==================== RESTART: C:/Python Code/Comment3 .py ====================
a=10 The value of A is, 10
p r i n t ( "The value of A is,", a) >»
==================== RESTART: C:/Python Code/Comments.py ====================
The value of A is, 10
>»
Running the code will return the line: The value of Let's assume that the variable A we've created is
A is, 10 into the IDLE Shell w indow-which is what the number of lives in a game. Every time the player
we expected. Now let's add some of the types of comments you'd dies, the value decreases by 1. The programmer could insert a
normally see within code: routine along the lines of:
File Edit Format Run Options W indow Help # Set the start value of A to 1C
# Set the start value of A to 10 a=10
a=10
# Print the current value of A
iprint("The value of A is,”, a )
0 # Print the current value of A
p r i n t ("The value of A is,", a )
a=a-l
p r i n t ("You*ve just lost a l i f e !r
p r i n t ("You n ow have", a , "lives left!") 0 0
0
0 1 1 1
10 1 ) 0
1 1 1 0 0
0 1 o |_____________ 0
0 0 1 0 1 0 « 0 0 1 o~ io o 10 0 0 0 1 1 1
110 1 o ii o 1 1 1 1 0 1 0 1 o 0 0
goding & Programming
0 0 1 0 1 0 10 1 0 0 0 1 1 0
0 111 o ooo i o 0 0 0 1 0 0 111 1 o o 0 1 1 1
Using Comments
While we know that the variable A denotes number Inline Comments are comments that follow a
of lives and the player hasjust lost one, a casual section of code. Take our examples from above,
viewer, or someone checking the code, may not know. Imagine fora instead of inserting the code on a separate line, we could use:
moment that the code is twenty thousand lines long, instead of just
a=10 # Set the start value of A to 10
our seven. You can see how handy comments a re.
print("The value of A is,", a) # Print the current
L& Python 3.7.0 Shell - □ X value of A
File Edit Shell Debug Options Window Help a=a-l # Player lost a life!
Python 3.7.0 <v3.7.0:Ibf5cc5053, Jun 27 2018, 04:06:47) [MSC v.1514 32 bit (Inte
1)] on Win32
print("You've just lost a life!")
Typ e "copyright", "credits" or "license()" for more information. print("You now have", a, "lives left!") # Inform
>»
= = = = = = = = = = = = = = RESTART: C:/Python Code/Comments.py = = = = = = = = = = = = = = = = player, and display current value of A (lives)
The value of A is, 10
»>
============= = = = = = = RESTART: C:/Python Code/Comments.py ============ = = ====== [_£ "Comments.py - C:/Python Code/Gomments.py (3.7.0)' — □ X
The value of A is, 10 File Edit Format Run Options Window Help
»> a=10 t Sec che scare value of A co 10
==== = = = = = = == = == RESTART: C:/Python Code/Comments.py == = = = = = = = = =
print("The value of A is,", a) t Print the current value of A
T he value of A is, 10 a=a-l it Player lose a life E
You've just lost a life! print("You've just lost a life!")
You n ow have 9 lives left! print("You now have", a, "lives left!") ♦ Inform player, and display current of A (lives)]
»>l
Essentially, the new code together with comments The comment, the hash symbol, can also be used to
could look like: comment out sections oF code you don't want to be
executed in your program. For instance, if you wanted to remove
# Set the start value of A to 10
the First print statement, you would use:
a=10
# Print the current value of A # print("The value of A is,", a)
print("The value of A is,", a)
# Player lost a life! |j^f *C o m m e n ts.p y - C:/Pyth on C o de./Com m en ts.py (3.7.0)*
a=a-l File Edit Form at Run O p tio n s W in d o w Help
# Inform player, and display current value of A # Set the start value of A to 10
(lives) a=10
print("You've just lost a life!") # Print the current value of A
print("You now have", a, "lives left!") # print ("The value of A is,", a)|
# Player lost a life!
a=a-l
[A -Comm.nB.py-. C:/Python Codc/Conun'rb.py (3.7®* — □ X
File Edit Format Run Options Window Help
# Inform player, and display current of A (lives)
t Sec che start value of A to 10 print("You1ve just lost a life!")
a=10
# Print che current value of A
print("You now have", a, "lives left!")
print("The value of A is,”, a)
# Player lost a life!
a=a-l
t Inform player, and display current of A (lives)|
print("You1ve just lost a life!")
print("You now have", a, "lives left!")
You can use comments in different ways. For You also use three single quotes to comment
example, Block Comments are a large section of out a Block Comment, or multi-line section of
text that details what's going on in the code, such as telling the code comments. For them to work, place them before and after the areas
reader which variables you're planning on using: you want to comment:
0 0 0 10 10 1 1 oi oooooo i
0
1
o
o
0
o
o
Ol l i o 0 0 0 0 10 1 o00 0 1 00 1111 i o o 0 1 i 10 0 0 1
Coding w ith Python
V A R IO U S V A R IA B L E S
We'll be working with the Python 3 IDLE Shell in this tutorial. IFyou haven't already, open Python 3 or close down the previous
IDLE Shell to clear up any old code.
In some programming languages, you're required As we've seen previously, variables can be
to use a dollar sign to denote a string, which is a concatenated using the plus symbol between the
variable made up of multiple characters, such asa name of a person. variable names. In our example, we can use: print (name +
In Python this isn't necessary, so, for example, in the Shell enter: " + title) .The middle part, between the quotations, allows
name="David Hayward" (useyourown name, unless you're also us to add a colon and a space. As variables are connected without
called David Hayward). spaces, we need to add them manually.
File Edit Shell Debug Options Window Help File Edit Shell Debug Options Window Help
Python 3.7.0 (v3.7.0:Ibf9cc5093, Jun 27 201S, 04:06:47) [MSC v.1914 32 bit (Inte Python 3.7.0 (V3.7.0:lbfScc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)
1)] on Win32 ] on Win32
Type "copyright", "credits" or " l i c e n s e O " for more information. Type "copyright", "credits" or "license()" for more information.
> » name=" David Hayward" » > name*"David Hayward"
> » print (name) » > print (name)
D a vid Hayward David Hayward
> » type (name)
l <class 1str*>
» > title="Descended from Celts"
>>> p r i n t (name + ": " + title)
David Hayward: Descended from Celts
»>
on 3.7,0 Shell
You can check the type of variable in use by issuing We can also
File Edit Shell Debug Options Window Help
the type () command, placing the name of the combine variables Python 3.7.0 (v3.7.0: lbf9cc50S3, Jun ;l
variable inside the brackets. In our example, this would be: within another variable. For ] on Win32
Type "copyright", "credits" or "licen:
type (name). Add a new string variable: title="Descended example, to combine both name > » n a m e="David Hayward"
» > print (name)
from Celts". and title variables into a new D avid Hayward
» > type (name)
variable, we use: Cclass ’s t r ^
[j& Python 3.7.3 Shell
» > tit!e="Descended from Celts"
File Edit Shell Debug Options Window Help character=name + » > p r int (name + " + title)
Python 3.7.0 (v3.7.0:Ibf5cc5093 Jun 27 2018, 04:06:47) [MSC ’ ,1914 32 bit (Intel) D avid Hayward: Descended f r o m Celts
] on Win32 title >>> character=narae + ■: " + title
Type "copyright", "credits" or "license()" for more infoxmati( » > print (character)
» > name="David Hayward" D avid Hayward: Descended fro m Celts
> » print (name)
Then output the content of the » > age=46
David Hayward new variable as: » > type (age)
» > type (name) cclass ’int'>
cclass 1str'> I »>
> » title="Descended from Celt print (character)
»>
age=44
Type (age)
0 1 1
10 1 Which, as we know, are integers.
111 0 u
0 0
A A A
0 0 1 0 1 0 1 0 o 1 0 0 10 0 0 0 0 1 1
o 1 1 1 0 10 1 0 0 0
Coding & Programming
o 0 1 0 o1 0 C 1 0 1 1
0 111 o ooo 1 0 00 1 0 111 1
1 oo 0 1 l 1 0 0 1
Working with Variables
However, you can't combine both strings and This presents a bit of a problem when you want
integer type variables in the same command as you to work with a number that's been inputted by
would a set of similar variables. You'll need to turn one into the the user, for example, as age + 10 is both a string variable and an
other, or vice versa. When you do try to combine both, you'll get an integer, it won’t work. Instead, you need to enter:
error message:
int(age) + 10
print (name + age)
This will TypeCast the age string into an integer that can be
] on Win32
Type "copyright", "credits" or "license()" for more information.
worked with.
» > name="David Hayward"
» > print (name)
L # Python 3.7.0 Shell - □ ~ ~ xl
David Hayward
» > type (name) File Edit Shell Debug Options Window Help
<class 'str’> Python 3.7.0 (v3.7.0:Ibf5cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
» > title="Descended from Celts" 1)] on Win32
> » print (name + ": " + title) Type "copyright", "credits" or "license()" for more information.
David Hayward: Descended from Celts > » age=input ("How old are you? ")
» > character=name + ": " + title
How old are you? 46
» > print (character)
> » type (age)
David Hayward: Descended from Celts <class 'str’>
» > age=46
» > age + 10
» > type (age)
Traceback (most recent call l a s t ) :
<class •i n t ‘>
File "<pyshell#2>", line 1, in <module>
» > print (name+age)
age + 1 0
Traceback (most recent call l a st):
TypeError: can only concatenate str (not "int") to str
File "<pyshell#S>", line l r in <module>
> » int (age) + 10
print (name+age)
56
TypeError: can only concatenate str (not "int") to str
>» »>
This is a process known as Typecasting. The Python The use of Typecasting is also important when
code is: dealing with floating pointarithmetic; remember:
numbers that have a decimal point in them. For example, enter:
print (character + " is " + str(age) + " years
old.") shirt=l9.99
Alternatively, you can use: Now enter: type (shirt) and you'll see that Python has allocated
the number as a 'float', because the value contains a decimal point.
print (character, "is", age, "years old.")
L i Python 3.7.0 Shell
Notice again that in the last example, you don't need the spaces
i File Edit Shell Debug Options Window Help
between the words in quotes, as the commas treat each argument Python 3.7.0 (v3.7.0:lbf9cc5053, Jun 27 2018, 04:06:47) [MSC v.1514 32 bit (Inte
to print separately. 1)] on Win32
Type "copyright", "credits" or "license()" for more information.
» > shirt=19.99
David Hayward: Descended fro m Celts » > type (shirt)
>>> age=46 <class 'float'>
>>> type(age) >»
<class ’i n t 1>
> » print (name+age)
Traceback (most recent call l ast):
File "<pyshell#9>", line 1, in <module>
print (name+age)
TypeError: can only concatenate str (not "int") to str
> » print (character + " is " + str (age) + " years old.")
David Hayward: Descended fro m Celts is 46 years old.
>>> print (character, "is", age, "years old.”)
David Hayward: Descended fro m Celts is 46 years old.
>»
Another example of Typecasting is when you ask When combining integers and floats Python
for input from the user, such as a number, for usually converts the integer to a float, but should
example, enter: the reverse ever be applied, it's worth remembering that Python
doesn't return the exact value. When converting a float to an
age= input ("How old are you? ")
integer, Python will always round down to the nearest integer,
All data stored from the Input command is stored as a string variable. called truncating; in ourcase instead of 19.99, it becomes 19.
File Edit Shell Debug Options Window Help File Edit Shell Debug Options Window Help
Python 3.7.0 (v3.7.0:lbf9cc5Q93, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte Python 3.7.0 (v3.7.0:lbfScc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
1)] on Win32 1)] on Win32
Type "copyright", "credits" or "license()" for more information. Type "copyright", "credits" or "license))" for more information.
» > age=input ("How o ld are you? ") > » shirt=19.99
H o w old are you? 46 > » type (shirt)
> » type (age) cclass 1float'>
<class 'str‘> > » int (shirt)
»> 19
>» 0 0
0
i
1 1 1 0 0
J 4 0 1 0
10 1 oToooood l
O
" 0 1 0 1 0 1 0 1 o
o
o
0 0 1
000 1 0 1 o 0 1 1 1 o 0 i 1 1 1 1
Coding & Programming
0 0 1 0 0 i 1 0 0 0 0 o 0 1 0 1 1 1
0 1 1 1 0 000 1 o0 0 0 1 o 0 1 i oo 0 1 i
i 10
Coding with Python
User Input
W e've seen som e basic user interaction with the code From a Few oF the examples
earlier, so now would be a good time to Focus solely on how you get inFormation From
the user, then store and present it.
U S E R F R IE N D L Y
The type of input you want From the user will depend greatly on the type oF program you're coding. A game, For example, may
ask For a character's name, whereas a database can ask For personal details.
K C R S I IF it's not already, open the Python 3 IDLE Shell, Now that we have the user's name stored in a
■ U S a n d start a New File in the Editor. Let's begin with couple oF variables, we can call them up whenever
something really simple, enter: we want:
Save and execute the code, and, as you no doubt Run the code and you'll notice a slight issue, the
suspected, in the IDLE Shell the program will ask Full stop aFter the surname Follows a blank space.
Foryour First name, storing it as the variable firstname, Followed by To eliminate that, we can add a plus sign instead oF the comma in
your surname; also stored in its own variable (surname). the code:
1 0 0
0
0 1 1 1
10 1
11 0 0
o 0 0
A A A «
0 1 0 1 0 1 0 O lo 1 0 o 1 0 0 0 0 1 1 1
o 1 1 1 1 0 0
goding & Programming
0 01 0 1 0 0 0
0 111 o ooo 1 o o0 0 1 0 0 111 0 0 11 1 0 0 1
User Input
You don't always have to include quoted text within Whatyou've created here is a condition, based on
the input command. For example, you can ask the the user's input. In short, we're using the input
user their name, and have the input in the line below: 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
print("Hello. What's your name?")
unhindered. If, however, they entera name other than David, the
name=input ()
guard challenges them to a fight.
(_■& *Userlnput.py - C:/Python Code/Userlnput,py (3.7.0)* — □ X
li^hon 3.7.0Shell - □ X
File Edit Format Run Options Window Help File Edit Shell Debug Options Window Help
The code from the previous step is often regarded As you learned previously, any input from a user
as being a little neater than having a lengthy is automatically a string, so you'll need to apply a
amount of text in the input command, but it's not a rule that's set in TypeCast in order to turn it into something else. This creates some
stone, so do as you like in these situations. Expanding on the code, interesting additions to the input command. For example:
try this:
# Code to calculate rate and distance
print("Halt! Who goes there?") print ('"'Input a rate and a distance")
name=input() rate = float (input ("Rate : ") )
(jjr *Userlnput.py - C:/Python Code/Userlnput.py (3.7.0)* — O X \Jjfr ’ Userlnput.py - C:/Python Code/Userlnput.py (3.7.0)* — □ X
File Edit Format Run Options Window Help File Edit Format Run Options Window Help
p r i n t ("Halt! Who goes there?”) # Code to calculate rate and distance
n a m e = i n p u t () p r i n t ("Input a rate and a distance")
rate = f l o at(input("Rate: "))|
It's a good start to a text adventure game, perhaps? And to finalise the rate and distance code, we can add:
Now we can expand on it, and use the raw input
distance = float (input ("Distance: ") )
from the user to flesh out the game a little:
p r i n t ( " T i m e , (distance / rate))
if name=="David":
Save and execute the code, and enter some numbers. Using the
print("Welcome, good sir. You may pass.")
float(input element, we've told Python that anything entered is a
else:
Toating point number rather than a string.
print("I know you not. Prepare for battle!")
) “ 2‘0 0 0
1 )
0
0 1 1 1
10 1
1 1 1
0 1 i> (
0 0 0 1 0 1 0 0 o 0 0 1 1 0 1 o 1 0 0 0 0 0 0 1 1 0 1
000 1 0 110 1 o o i 1 1 i
Coding & Programming
0 0 0 1 0 0 0 1 0 1 1 1
0 1 1 1 0 0 0 0 00 0 0 1 0 M i l l 00 11 o i 0
Coding w ith Python
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.
FUN KY FUNCTIONS
A Function is a command thatyou enter into Python in order to do something. It's a little piece oF selF-contained code that
takes data, works on it, and then returns the result.
It's not only data that a Function works on. Functions You can pass variables through Functions in much
can do all manner oF useFul things in Python, such as the same manner. Let's assume you want the
sort data, change items From one Format to another, and check the number oF letters in a person's surname, you could use the Following
length or type oF items. Basically, a Function is a short word Followed code (enFer the text editor For this example):
by brackets. For example, len(), list(), or type().
name=input ("Enter your surname: ")
USr ‘ Python 3.7.0 Shell* - □ X count=len(name)
File Edit Shell Debug Options Window Help print ("Your surname has", count, "letters in
Python 3.7.0 (v3.7.0:lbf9cc50S3, Jun 27 2018, 04:06:47) [MSC v.1514 32 bit (Inte
1)] on Win32 it.")
Type "copyright", "credits" or "license()" for more information.
» > len()| Press F5 and save the code to execute it.
A Function takes data, usually a variable, works on Python has tens oF Functions built into it, Far too
it depending on what the Function is programmed many to get into in the limited space available here.
to do, and returns the end value. The data being worked on goes Flowever, to view the list oF built-in Functions available to Python
inside the brackets, so iFyou wanted to know how many letters 3, navigate to https://docs.pytFion.Org/3/library/Functions.html.
are in the word antidisestablishmentarianism, then you'd enter: These are the pre-deFined Functions, but since users have created
len ("antidisestablishmentarianism"), and the num ber28 many more, they're not the only ones available.
would return.
[ j j i Python 3.7.0 Shell — □ X
Python 3.7.0 Shell — □ X File Edit Shell Debug Options Window Help
Python 3.7.0 (v3.7.0:lbf9cc5053, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
| File Edit Shell Debug Options Window Help
1)1 on Win32
Python 3.7.0 (v3.7.0:lbfScc50S3, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte Type "copyright", "credits" or "license()" for more information.
1)] on Win32 >>> l e n ("antidisestablishmentarianism")
Type "copyright", "credits" or "license()" for mo r e information. 28
» > len ("antidisestablishmentarianism") >»
28 ==================== RESTART: C:/Python Code/NameCount.p y == = =========== ======
»> Enter your s urname: Hayward
Your name has 7 letters in it.
> » import math
> »
■ T H jJ ' Additional Functions can be added to Python To use a Function From a module, enter the name oF
through modules. Python hasa vast range oF the module, Followed by a Full stop, then the name
modules available that can cover numerous programming duties. oF the Function. For instance, using the math module, since we've
They add Functions and can be imported as and when required. For just imported it into Python, we can utilise the square root Function.
example, to use advanced Mathematics Functions enter: To do so, enter:
Once entered, you'll have access to all the Math module Functions. As you can see, the code is presented as module.function(data).
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.
Choose File > New File to enter the editor, let's To modify it further, delete the Hello("David") line,
create a Function called Hello that will greet a the last line in the script, and press Ctrl+S to save
user. Enter: the new script. Close the Editor and create a new file (File > New
File). Enter the following:
Press F5 to save and run the script. You'll see Hello in the Shell, Press F5 to save and execute the code.
type in Hello() and it’ll return the new function.
T R U E C O N D IT IO N S
Keeping conditions simple, to begin with, makes learning to program a more enjoyable experience. Let's start then by
checking if something is TRUE, then doing something else iF it isn’t.
Let's create a new Python program that will ask the Now we'll use an if statement to check if the word_
user to input a word, then check it to see iF it's a length variable is equal to Four, and printa Friendly
Four-letter word or not. Start with File > New File, and begin with conformation if it applies to the rule:
the input variable:
word=input("Please enter a four-letter word: ")
word=input("Please enter a four-letter word: ") word_length=len(word)
if word_length == 4:
print (word, "is a four-letter word. Well done.")
[jjf ’ Untitled* — □ X
Now we can create a new variable, then use the len K H B The colon at the end of if tells Python that if this
m
Function and pass the word variable through it to statement is true, do everything after the colon
get the total number of letters the user has just entered: that's indented. Next, move the cursor back to the beginning of
the Editor:
word=input("Please enter a four-letter word: ")
word length=len(word) word=input("Please enter a four-letter word: ")
word length=len(word)
[«|i 'Untitled* — □ X
if word length — 4:
File Edit Format Run Options Window Help
w o r d = i n p u t ("Please enter a four-letter word: ") print (word, "is a four-letter word. Well
word_length=len(word)
done .")
else:
print (word, "is not a four-letter word.")
U|r 'Untitled* — □ X
Press F5 and save the code to execute it. Enter Now expand the code to include otherconditions.
a four-letter word in the Shell to begin with, you Eventually, it could become quite complex. We've
should have the returned message that the word is four letters. added a condition for three-letter words:
Now press F5 again, and re-run the program, but this time, enter a
word=input("Please enter a four-letter word: ")
five-letter word. The Shell will display that it’s not a four-letter word.
word length=len(word)
if word length 4:
print (word, "Is a four-letter word. Well
done.")
elif word_length =— 3:
print (word, "is a three-letter word. Try again.")
else:
print (word, "is not a four-letter word.")
u IA : o«weCoo, *.•
tit. Edit SMI 9*6-49 Option* Window M*lp Edit M M Sen Option, m , Hdp
5>}H! «in32 IV>' J“ * “ *** **■ **■ ’ ’ ** 611 ■ Jits itniTn*l*Mtie*dl
Typ. -copyright", "cr*dlt»" ar for » r * .nfar-arlan. *v,<i_i,„gth. — •;
■ ........................... RESTART; C:/Python r.y ................................ t-ord length — S;
pclet (word. * u V arH>l(IXei n M i Try again. *|
print iwora, *M not • tour letter voro.-|
n r
LOOPS
Although a loop looks quite similar to a condition, they are somewhat different in their operation. A loop will run through the
same block of code a number of times, usually with the support of a condition.
Let's start with a simple while statement. Like if, The for loop, is another example. For is used to
this will check to see if something
's s / y /iss sTRUE,
s s s s s s sthen
s s f/ s run
s s s s jj J i loop over a range of data, usually a list stored as
the indented code: variables inside square brackets. For example:
'Untitled' Dcbuij Opliuaiv Window Help nit Hit femm Run Opiipni Window
I Python 3.7,0 (v3.7.0:ibf6ec5053, Jun 27 2013, 04:0fi:47> [MS2 v.ISH 32 bit (Inc
File Edit Format Run Options Window Help 1) ] on Win32
•••••••••••••••••••••••••••••••••••••••••••••••••••a*
The difference between if and while is that when The for loop can also be used in the countdown
while gets to the end of the indented code, it goes example by using the range function:
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.
The x=x+1 part isn’t needed here, because the range function
creates a list between the first and last numbers used.
- RESTART: 0:/Pyr.hnn Ci-xWlrvnpl .py - File Edrt Shell Debug Option. Window Help_____________
Python Modules
W e've mentioned modules previously, using the Math module as an example, but since
using modules is such a large part of getting the m ost Prom Python it's worth dedicating
a little more time to them.
M A S T E R IN G M O D U L E S
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.
Although good, the built-in Functions within Python The result is an error in the IDLE Shell, as the
are limited. The use oF modules, however, allows us pygame module isn't recognised or installed in
to make more sophisticated programs. As you are aware, modules Python. To install a module we can use PIP (Pip Installs Packages).
are Python scripts that are imported, such as import math. Close down the IDLE Shell and drop into a command promptor
Terminal session. At an elevated admin command prompt, enter:
Python 3.7.0 Shell — □ X
File Edit Shell Debug Options Window Help pip install pygame
Python 3."7,0 (v3,7.0:lbfScc5Q93, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit <Inte
1)] on Win32
Type "copyright", "credits" or "license 0 " for more information. S B C o m m a n d P ro m p t
» > impor _ mat h
>»1
C:\Users\david>pip install pygame
Some modules, especially on the Raspberry Pi, are The PIP installation requires an elevated status due
included by deFault; the Math module is a prime to it installing components at diFFerent locations.
example. Sadly, other modules aren't always available. A good Start with a search For CMD, via the Start button, right-click the
example on non-Pi platForms is the Pygame module, which contains result, and then click Run as Administrator. Linux and Mac users can
many Functions to help create games. Try: import pygame. use the Sudo command, with sudo pip install package.
C :\WINDOWS\system32>
Close the command prompt orTerminal, and re Multiple modules can be imported within your code.
launch the IDLE Shell. When you now enter import To extend our example, use:
pygame, the module will be imported into the code without any
import random
problems. You'll find that most code downloaded, or copied, from
import math
the Internet will contain a module, mainstream or unique, and their
absence is commonly the source oFerrors in execution. for I in range(5):
print (random.randint ( 1 2 5 ) )
[i|r Python 3.7.0 Shell — □ X
print (math.pi)|
The modules contain the extra code needed to The result is a string of random numbers followed
achieve a certain result within your own code, with by the value of Pi, as pulled from the math
which we've previously experimented. For example: module using the print(math.pi) function. You can also pull in
certain functions from a module by using the from and import
import random
commands, such as:
Brings in the code from the Random number generator module. We
from random import randint
can then use this module to create something like:
for i in range(5):
for i in range(10):
print(randint(1, 25))
print(random.randint(1, 25))
’ ’ id number.py - C:/Python Cade/md numberpy (3.7.0)' — □ X
L # ’ Untitled’ — □ X
File Edit Format Run Options Window Help
File Edit Format Run Options Window Help
from random import randint
import random
This code, when saved and executed, will display ten This helps create a more streamlined approach to
random numbers from 1 to 25. You can play around programming. You can also use: import module*,
with the code to display more or less, and from a greater or lesser which will import everything defined within the named module.
range. For example: Flowever, it's often regarded as a waste of resources, but it works
nonetheless. Finally, modules can be imported as aliases:
import random
import math as m
for i in range(25):
print(random.randint(1, 100)) print(m.pi)
print (xn.pi)
96 W h a t is a B a tc h File ?
98 G e t tin g S t a r t e d w it h B a tc h F ile s
100 G e t tin g an O u t p u t
102 P la y in g w it h V a ria b le s
104 B a tc h F ile P ro g ra m m in g
106 L o o p s an d R e p e titio n
.BAT M A N
A Windows batch File is simply a script File that runs a series oF commands, one line at a time, much in the same Fashion as a
Linux script. The series oF commands are executed by the command line interpreter and stored in a plain text File with the .BAT
extension; this signiFies to Windows that it's an executable File, in this case, a script.
Batch files have been around since the earliest versions oF Microsoft line in turn, loading programs that would activate the mouse or
DOS. Although not exclusively a Microsoft scripting file, batch files optical drive into the memory areas assigned by the Config.sys file.
are mainly associated with Microsoft's operating systems. In the
early days, when a PC booted into a version of DOS (which produced The DOS user of the day could opt to create different Autoexec,
a simple command prompt when powered up), the batch file was bat files depending on what they wanted to do. For example, if
used in the form of a system file called Autoexec.bat. Autoexec, they wanted to play a game and have as much memory available
bat was a script that automatically executed (hence Autoexec) as possible, they'd create a Config.sys and Autoexec.bat set of files
commands once the operating system had finished dealing with the that loaded the bare minimum of drivers and so on. IF they needed
Config.sys file. access to the network, anAutoexec.bat file could be created to
Batch files are plain text and often created using Notepad. However, if you're working in the command prompt with
elevated privileges to begin with, as the Administrator, then
the UAC won’t question the batch File and continue regardless
of what files are being deleted.
The Autoexec.bat was the first such file many users came across in
S I Command Prompt - testl
their PC-based computing lives; since many had come from a 16-bit
or even 8-bit background; remember, this was the late eighties
and early nineties. The batch file was the user's primary tool for
************************
automating tasks, creating shortcuts and adventure games and ********* * H ELLO ! *
translating complex processes into something far simpler. ik********** ************************
************* **********
* ***** * ******
Nowadays however, a batch file isn't just For loading in drivers and * ***** * ****
such when the PC boots. You can use a batch file in the same way * ******* «** **
* * ***** * * *
as any other scripting language File, in that you can program it to * * ***** * *
ask for user input and display the results on the screen; or save to ***************
***************
a file and even send it to a locally or network attached printer. You ***************
can create scripts to back up your files to various locations, compare ***************
date stamps and only back up the most recently changed content as ***************
***************
well as program the script to do all this automatically. Batch files are ***************
remarkably powerful and despite them not being as commonly used ***************
**** *** ****
as they were during the older days of DOS, they are still there and *** ** ***
can be utilised even in the latest version oF Windows 10; and can be ** * **
as complex or simple as you want them to be. * *
A N E W BATCH
Throughout this section on batch Files we're going to be working with Notepad, the command prompt and within a Folder
called 'Batch Files'. To begin with, let's see how you get to the Windows command prompt.
: : \users\davia>cd Documents
t :\Users\david\Documents>
P
1 cmd|
1
Click on the search result labelled Command Prompt The prompt should change and display \
(Desktop App) and a new window pops up. The Documents>; this means you're in the Documents
Command Prompt window isn't much to look at to begin with but directory. Now, create a new directory call Batch Files. Enter:
you can see the MicrosoFt Windows version number and copyright
md "Batch Files"
inFormation Followed by the prompt itselF. The prompt details the
current directory or Folder you're in, together with your username. You need the quotations because without them, Windows creates
two directories: Batch and Files. Now change directory into the
] Command Prompt newly created Batch Files.
M ic r o s o ft Windows [V e r sio n 10.0.1 62 9 9.4 02 ]
( c ) 2017 M ic r o s o f t C o rp o r a t io n . A l l r i g h t s re se rv e d . cd Batch Files
:\U s e r s \ d a v id >
You won't need the quotes to change directories.
I QB ommand Prompt
Now thatyou have the directory set up, where you Back at the command prompt window, enter:
store your batch Files, here is how you can create d ir / w again to list the newly created Test.bat File.
one. Leave the command prompt window open and dick on the By the way, the /w part oF dir/w means the files are listed across
Windows Start button again. This time enter Notepad and click on the screen as opposed to straight down. Enter d i r if you want
the search result to open the Notepad program. Notepad is a simple (although you need more Files to view) but it's considered easier to
text editor but ideal For creating batch scripts with. read with the /w Flag.
.] [..] T e st.bat
1 F ile ( s ) 30 bytes
2 D l r ( s ) 129,865,961,472 bytes fre e
To create your First batch File, enter the Following To execute the batch File you've just created, simply
into Notepad: enter its name, Test, in the command prompt
window. You don't need to add the .bat part, as Windows recognises
0echo nff
it as an executable File, and the only one with that particular name in
echo Hello World!
the current directory. Press return and see how you're greeted with
By deFault, a batch File displays all the commands that it runs Hello World! in the command prompt.
through, line by line. What the @echo oFF command does is turn
SB
that Feature oFF For the whole script; with the (at) sign to apply
C:\Users\david\Docuroents>md "Batch Files"
that command to itself.
C:\Users\david\Documents>cd "Batch Files”
C:\Users\david\Docunvents\Batch Files>dir/w
3 Untitled - Notepad Volume in drive C has no label.
Volume Serial Number Is 8E47-ABFF
File Edit Format View Help
@echo o f f Directory of C:\Users\david\Documents\Batch Files
echo H e llo W o rld! [.] [..] T e st.b at
1 File(s) 30 bytes
2 Dir(s) 129,865,961,472 bytes free
C:\Users\david\DocumentsVBatch Files>Test
Hello World!
C:\Users\david\Documents'\Batch Files>
■f > This PC > Documents > Batch Files Remember to save each new change to the batch File.
Organise » New folder
V Dropbox (Team Bl
Team BDM
A OneDrive
■ This PC
^ 3D Objects
■ Desktop
[HI Documents
Filename: |
Save as type All Files
Getting an O u tp u t
While it's great having the command prom pt w indow display what you're putting after
the echo command in the batch file, it's not very useful at the moment, or interactive
for that matter. Let's change up a gear and get som e output.
INPUT, O U T P U T
Batch Files are capable oF taking a normal Windows command and executing it, while also adding extra options and Flags in to
the equation.
Let’s keep things simple to begin with. Create a new You have no doubt noticed that there is no
batch File called 'dirview.bat', short for Directory indication that the batch file worked as there's
View. Start with the @echo off command and under that add: no meaningful output on the screen. However, if you now open
Explorer and browse to c : \Users\YOURNAME, remembering to
dir "c:\users\YOURNAME\Documents\Batch Files" >
substitute y o u r n a m e with your Windows username, and double
c :\users\YOURNAME\dirview.txt
click the dirview. t x t file, you can see the batch file's output.
Substitute YOURNAME with your Windows username.
_ j dirview - Notepad
The new line uses the dir command to list the If you want to automate the task of opening the
contents of the directory Batch Files, in your Home text file that contains the output, add the following
directory, dumping the output to a text file called dirview. t x t in line to the batch file:
the root oF your Home directory. This is done, so that the Windows
notepad.exe c:\users\YOURNAME\dirview.txt
UAC doesn't require elevated permissions, as everything is in your
own Home area. Save and run the batch file. Save the file and once again run from the command prompt. This
time, it creates the output and automatically opens Notepad with
the output contents.
2 dirview - Notepad
File Edit Format View Help
@ecFio off
dir "c:\users\david\Documents\Batch Files" > c:\users\david\dirview.txt
notepad.exe c :\users\david\dirview.txt
Create a new batch File and call it name.bat. Start This is extremely useFul iFyou want to create a
with the 0echo off command, then add the unique, personal batch File that automatically runs
Following lines: when a user logs into Windows, Using the deFault systems variables
that Windows itselF creates, you can make a batch File that greets
set /p name= What is your name?
each user:
echo Hello, %name%
0echo off
Note: there's a space aFter the question mark. This is to make it look
neater on the screen. Save it and run the batch File. echo Hello, %USERNAME%.
echo.
1— — echo Thanks for logging in. Currently the network
1 File Edit Format View Help
giecho o f f
is operating at 100%% efficiency,
s e t /p nam e- What i s y o u r name? echo.
e ch o H e l l o , %name%
echo Your Home directory is located at: %HOMEPATH%
S I Command Prompt echo The computer name you're logged in to is:
: \ U s e r s \ d a v id \ D o c u m e n t s \ B a t c h F ile s> n a m e
%COMPUTERNAME%
What i s y o u r name? D a v id
T e l lo , D a v id echo.
C : \ U s e r s \ d a v id \ D o c u m e n t s \ B a t c h F i l e s >
; 3 nanic-Notepad
feche off
echo Thanks for logging in. Currently the network i s operating at 10CKC efficiency.
The set/p name creates a variable called name,
echo Your Hone directory i s located at: SHOMEPATHX
with the /p part indicating that an '=prompt string' echo The coaputer name you're logged in to is: JSC0MPUTERNAME5S
C : \ U s e r s \ d a v i d \ D o c u m e n t s \ B a t c h F ile s > n a m e
H e l lo , d a v id .
T h a n k s f o r l o g g i n g i n . C u r r e n t l y t h e n e t w o rk i s o p e r a t in g a t 130% e f f ic ie n c y .
Y o u r Home d i r e c t o r y i s l o c a t e d a t : \ U s e r s \ d a v i d
The c o m p u te r name y o u 'r e l o g g e d i n t o i s : WINDOWS
0echo off
notepad c :%HOMEPATH%\user.-txt
The > outputs to a new File called user.txt, while the » adds the
lines within the File.
U SIN G M O R E V A R IA B L E S
Here's a good example of mixing system and environmental variables with some oFyour own creation, along with a number oF
external Windows commands.
Create a new batch File called list.bat and start it oFF Now, create a batch File that displays the contents
with the @echo off command. Begin by clearing oF any directory and post it as a text File to the user's
the command prompt screen and displaying a list oF the current screen. Add the Following to the list.bat batch File:
directories on the computer:
echo Hello, %USERNAME%.
els echo From the list, which folder would you like to
dir "c:\" > list.txt view?
type list.txt set /p view= (enter as c:\folder)
echo. dir "%view%" > view.txt
notepad.exe view.txt
~J list- Notepad
File Edit Format View Help
3 list - Notepad
@echo o f f
File Edit Format View Help
e ls (Secho o ff
d ir " c :\ " > l i s t . t x t
typ e l i s t . t x t | els
echo.
d ir " c : \ " > l i s t . t x t
type l i s t . t x t
echo.
echo Hello, %USERNAME%.
echo From the l i s t , which d irectory would you lik e to view?
se t /p view= (enter as c :\d ire c to ry )
d ir ”%vievi%" > view .txt
notepad.exe view .txt
^
Save and execute the batch File. Within the What’s happening here is the batch File asks the user
command promptyou can see the contents oF all to enter any oF the directories displayed in the list it
the Files and directories From the root oF the C:\ drive; and as any generated, in the Form oF 'c:\directory'. Providing the user enters a
user under Windows has permission to see this, there's no UAC valid directory, its contents are displayed as a text File. We created
elevated privileges required. the view variable here along with %HOMEPATH%, to store the input
and the text File.
Q Command Prompt
Directory of c :V
k :\Users\david\Documents\Batch Files>
It's always a good idea, when creating text files Instead of left clicking on the Command Prompt
For the user to temporarily view, to clean up after result, as you did the First time you opened it,
yourself. There's nothing worse than having countless, random right-click it and from the menu choose Run as Administrator. There
text files cluttering up the file system. That being the case, let's is a risk that you could damage system files as the Administrator
clear up with: but as long as you’re careful and don't do anything beyond viewing
directories, you will be okay.
els
del /Q view.txt
del /Q list.txt
echo All files deleted. System clean. Filters V
e D @
e ls
dir "e:\" > list.txt
type list.txt Command Prompt
echo H e llo , 3PJ5ERNAMES.
echo From the l i s t , which d ire c to ry would you l ik e to view?
se t /p view - (enter a s c :\d ire c t o ry ) ^ 0 Run as administrator
notepad.exe vie w .txt
els Se
del /Q vie w .txt
del /Q l i s t . t x t
Open file location
echo A l l f i l e s deleted. System clean.
>-
-te Pin to Start
da Pin to taskbar
The additions to the batch file simply clear the
command prompt window (using the els 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
the files without any user input or notification. The final message
This action triggers the UAC warning message,
informs the user that the Files are removed.
asking you iFyou're sure you want to run the
Windows command prompt with the elevated Administrator
privileges. Most of the time we wouldn't recommend this course
[All files deleted. System clean.
'c:\Users\david\Documents\Batch Files>
of action: the UAC is there to protect your system. In this case,
however, click Yes.
Depending
on how _
B D © Filters N /
your system is configured,
Best match
you may not get any
directory information g || Command Prompt
at all or a message a Desktop app
This is because the UAC yP c m d - See web results > With the UAC active, the command prompt looks
is blocking access to a little different. For starters, it's now defaulting
protected areas of the to the C:\WINDOWS\system32 folderand the top of the windows is
system, like c:\Windows labelled Administrator. To run the batch file, you need to navigate to
or C:\Program Files. the Batch Files directory with: cd \Users\USERNAME\Documents\
Therefore, you need to Batch Files. To help, press the Tab key to auto-complete the
run the batch File as an directory names.
Administrator. Click the
Windows Start button and
enter CMD again. Microsoft Windows [Version 10.0.16299.402]
(c) 2017 Microsoft Corporation. All rights reserved.
©
C :\WINDOWS\system32>cd "\Users\david\Documents\Batch Files
C :\Users\david\Documents\Batch Files>
1
■■ yP cm d
S E A R C H IN G F O R 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 Now let's extend the seek.bat batch File:
into the mix here but we think they're really useFul.
Create a new batch File called seek.bat and in it put: 0echo off
els
0echo off
color 2
els
echo Please enter the type of file you want to
color 2
search for (MP3, DOC, JPG for example)
echo Please enter the type of file you want to
echo.
search for (MP3, DOC, JPG for example)
set /p ext=
echo.
where /R c:\ *.%ext% > found.txt
3 seek ■ Notepad
notepad.exe found.txt
File Edit Format View Help els
@echo o ff
color
e ls
co lo r 2 del /Q found.txt
echo Please enter the type o f f i l e you want to search fo r (MP3, DOC, DPG fo r example)
echo.
Fit* idri Fvnul Vi*. Mp
The new command in this instance is color Another new command, Where, looks For a speciFic
(Americanised spelling). Color, as you already file or directory based on the user's requirements.
assume, changes the colour oF the command prompt display. The In this case, we have created a blank variable called ext that the user
color attributes are speciFied by two hex digits, the first corresponds can enter the File type in, which then searches using Where and
to the background colour of the Command console and the second dumps the results in a text File called Found.txt. Save and run the
to the Foreground, and can be any oF the Following values: batch File.
0 = Black 8 = Grey
1 = Blue 9 = Light Blue
2 = Green A = Light Green
3 = Aqua B = Light Aqua
4 = Red C = Light Red
5 = Purple D = Light Purple
6 = Yellow E = Light Yellow
7 = White F = Bright White
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.
Rather than using a variable to process a user's ErrorLevels are essentially variables and the /M
response, batch files can instead use the Choice switch of Choice allows a descriptive message string
command in conjunction with an ErrorLevel parameter to make a to be displayed. Extend this menu with something new:
menu. Create a new File called menu.bat and enter the following:
0echo off
@echo off els
els echo.
choice /M "Do you want to continue? Y/N" e c h o ----------------------------------------------
if errorlevel 2 goto N echo.
if: errorlevel 1 goto Y echo Please choose a directory,
goto End: echo.
echo Press 1 for c:\Music
echo.
i f trrorLtvel 1 Y
echo Press 2 for c:\Documents
echo.
echo Press 3 for c:\Pictures
echo.
echo Press 4 for c:\Videos
echo.
e c h o ----------------------------------------------
Running the code produces an error as we've called choice /C 1234
a Goto command without any reference to it in the if errorlevel 4 goto Videos
file. Goto does exactly that, goes to a specific line in the batch file. if errorlevel 3 goto Pictures
Finish the file with the following and run it again: if errorlevel 2 goto Documents
if errorlevel 1 goto Music
:N
echo.
echo You chose N o . Goodbye. Now add the Goto sections:
goto End
:Y :Videos
echo. els
echo You chose Yes,
. Hello CD %HOMEPATH%\Vi decs
echo You are now In the Videos directory,
:End
goto End
:Pictures
els
CD %HOMEPATH%\Pictures
echo You are now in the Pictures directory,
goto End
:Documents
els
CD %HOMEPATH%\Documents
echo You are now in the Documents directory,
The output from your choice is different depending on
goto End
whetheryou pickYorN .The:End part simply signifies
the end of the file (also known as EOF). Without it the batch file runs :Music
through each line and display the Y response even if you enter N;so it’s els
important to remember to follow your Goto commands. CD %HOMEPATH%\Music
echo you are now in the Music directory,
( S i C om m and Prom pt - menu ■ m enu - m enu - menu - menu
goto End
Do you want to continue? Y/N [YJN]?N :End
You chose No. Goodbye.
You chose Yes. Hello When executed, the batch File displays a menu and with
C :\Users\david\Documents\Batch Files>
each choice the code changes directory to the one the
C :\Users\david\Documents\Batch Files>
user entered. The %HOMEPATH% system variable will enter the currently
logged in user's Music, Pictures and so directories, and not anyone else’s.
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 oFFile) commands.
Start by creating a new batch File called count.bat. The count.bat is a rough way of demonstrating a
Enter the following, save it and run: loop; a better approach would be to use a For loop.
Try this example instead:
§echo off
els 0echo off
set /a counter=0 for /L %%n in (1,1,99) do echo %%n
:numbers
set /a counter=%counter%+l
if %counter%. -=100 (goto :eof) else (echo
%counter%)
timeout /T 1 /nobreak > nul
goto :numbers
31count - Notepad
File Edit Format View Help
(jSecho o f f
e ls
s e t /a counter=0
: numbers
se t /a counter=%counter%+l
i f %counter% ==100 (go to :e o f) e ls e (echo %counter%)
tim eout /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
The count, (SB Command Prompt - count
%%n to denote a number. Then
bat code 1 the in (1,1,99) part, which tells
starts at number one and 2
the statement how to count,
counts, scrolling down the
4 as in 1 (start number), 1 (steps
screen, until it reaches 100. 5
to take), 99 (the end number).
The Timeoutcommand 6
7 The next part is do, meaning DO
leaves a one second gap S whatever command is after.
between numbers and the Q
Else statement continues 10
11
until the counter variable 12
equals 100 before going to 13
the eoF (End OF File), thus 14
15
closing the loop. 16
17
18
19
20
You can include the pause between the numbers There are different ways of using the For loop. In
easily enough within the Far simpler For loop by this example, the code creates 26 directories, one
adding multiple commands after the Do For loop. The brackets and for each letter of the alphabet, within the directory c:\test which the
ampersand (&) separate the different commands. Try this: batch file makes using the MD command:
39 Command Prompt
One of the great time saving uses of batch files is to Loops can be powerful and extremely useful
create multiple, numbered Files. Assume that you elements in a batch file. While creating 26
want twenty five text files within a directory, all numbered from 1 to directories may notsound too helpful, imagine having to create
25. A For loop much like the previous example does the trick: 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
@echo off
amount of time.
for /L %%n in (1,1,25) do copy nul %%n.txt
ifyou open Windows Explorer, and navigate to the Should you ever get stuck when using the various
Batch Files directory where you're working from, commands within a batch file, drop into the
you can now see 25 text files all neatly numbered. Of course, you command prompt and enter the command followed by a question
can append the File name with something like userl .txt and so on by switch. For example, for/? or if/?. You get an on-screen help file
altering the code to read: detailing the commands' use. For easier reading, pipe it to a text file:
:1
cls
echo.
echo ******************************
echo.
e
P C
*1 v
Creating a Batch File Game
:3 set /a score=%score%+l
els pause
echo. goto :g ame
e c h o ******************************
echo. rend
e c h o Y o u r c u r r e n t s core is %score% els
echo. echo ******************************
e c h o ****************************** echo.
echo. echo W e l l done, %name%, y o u h a v e a n s w e r e d all the
echo. que s t i o n s
e c h o Q u e s t i o n %question%. echo.
echo. echo A n d y o u r final score i s __
e c h o W h i c h o f the f o l l o w i n g W i n d o w s v e r s i o n is the echo.
latest? echo %score%
echo. echo.
e c h o A. W i n d o w s 10 echo ********************************
echo. choice /M "play again? Y/N"
e c h o B. W i n d o w s 98 if errorlevel 2 goto reof
echo. if errorlevel 1 goto s tart
e c h o C. W i n d o w s 7
echo.
c hoic e /C a b c
W h y Linux?
For many of its users, Linux m eans freedom. Freedom from the walled-gardened
approach o f other operating systems, freedom to change and use the O S as you please
and freedom from any form of licensing or payment. There's a lot more to Linux than
you may think.
The First thing we need to address is that there is no basic operating Linux works very diFFerently to Windows or macOS. Fora start, it's
system called Linux. Fundamentally, Linux is the operating system Free to download, Free to install on as many computers as you like,
kernel, the core component oFan OS. When talking about Linux we Free to use For an unlimited amount of time and free to upgrade
are, in Fact, reFerring to one oF the many distributions, ordistros, and extend with equally Free programs and applications. This Free to
that use the Linux kernel. No doubt you've heard oF at least one oF use element is one of the biggest draws for the developer. While a
the current popular distros: Ubuntu, Linux Mint, Fedora, openSUSE, Windows license can cost up to £100 and a Mac considerably more,
Debian, Raspbian... the list goes on. Each one oF these distros oFFers a user, be they a developer, gamer, orsomeone who wants to put an
the user something a little diFFerent. While each has the Linux kernel at older computer to use, can quickly download a distro and get to work
its core, they oFfera different looking desktop environment, diFFerent in a matter of minutes.
pre-loaded applications, different ways in which to update the system
and get moreapps installed and a slightly diFFerent look and Feel Alongside the free to use aspect comes a level of freedom to customise
throughout the entire system. Flowever, at the centre lies Linux, which and mould the system to your own uses. Each of the distros available on
is why we say, Linux. the Internet have a certain 'spin', some offer increased security, a fancy-
A O B * | - #include--:stdio.
§include <iostream> #include^ :conio.
#include<
wine lude<graphics.h>
int main!) #include<stdlib.h>
#include<
#include<math.h>
#include<dos.h>
//My first C++ program #include^t ime.h»
std::cout « "Hello World!\n' void slinelint,int,int,int,int,int,float,int,int);
void hlinefint,int,int,int,int,int,float,int,int);
void mline(int,int,int,int,int,int,float,int,int);
void grid(int,int,int,int);
void mainO
{
int gd=DETECT,gm,maxx,maxy,midx,midy;
int
sincolor=4,soutcolor=0,hincolor=l,houtcolor=L,mincolor=12,moutcolo
int bakcolor=!.4;
int gcolor=0 ,grad=3;
d a v id @ m irt -m a te -/ D o c u m e n ts
float thita,X,Y,h, File Edit View Search Terminal Help
initg raph(&gd,&gm,
davidgmint-mate Documents s ./helloworla
maxx=getmaxx(); Hello World!
m a x y= g e tm a x y( ) ; davidomint-mate -/Documents S
midx=maxx/2 ;
midy=maxy/2 ;
float phi=3.142 3,deg ree,dh,dm;
int rad=125;
int HX.HY,MX,MY,SX,SY,ML=rad-25.SL=rad-20,H L= rad-25;
char strElO];
helioworld.epp cleardevice();
setfillstylel1 ,bakcolor);
Emacs Tutorial L e a m b a sic keystrc circlelmidx.midy,rad-10 );
Emacs Guided Tour O ve rview of E m a c s floodfill(midx,midy,15);
U :% % - *GNU Em acs* 11% L 3 ( Fun< setfillstylel 1 ,1 );
circle(midx,midy,rad+1 0 );
floodfill(midx+rad+3,midy,15);
for(thita= ’0+45;thita<« !6Q+13S;thita-thita+(18G/( ))
Another remarkable advantage for those looking to learn how to code (Pdebian Mandriva is la e k w a r e
LINUXMINT-LINUXMINT.COM
By far the most popular Linux distro (distribution) is Linux Mint. In fact, it’s recommended that you spend at least some time trying
Mint began life back in 2006, as an alternative to the then, most different environments and even different distros, to see which
popular distro, Ubuntu. Although based on Ubuntu's Long Term suits you and your computer best.
Support build, Linux Mint took a different direction to offer the
user a better overall experience.
Linux Mint has three main desktop versions available with each
new version of the core OS it releases. This may sound confusing
at first, but it's quite simple. Currently, Linux Mint uses the
Cinnamon Desktop Environment as its flagship model, although
MATE and Xfce models are also available.
UBUNTU-UBUNTU.COM
The second most popular distro available is Ubuntu: an ancient
African word meaning 'humanity to others'. Ubuntu's popularity
has fluctuated over its fourteen-year life. At one time, it was
easily the most used, Linux-based operating system in the
world, sadly, some wrong choices along the way with regards
to its presentation, along with some unfavourable and
controversial elements involving privacy, saw it topple from the
number one spot. and it's a little heavy on system resources (especially if you plan
to install it on an older computer).
That said; Ubuntu has since made amends and is slowing crawling
its way back up the Linux leader board. The latest versions of Ubuntu, for all its faults, is a good Linux distro to start
the OS use the GNOME 3 desktop environment, it's impressive experimenting with. It's a clean interface, easy to use and install
although it can be a little confusing for former Windows users and offers the user the complete Linux experience.
I do exactly that, but it's not ideal for beginners. Ubuntu and
Mint both offer an easier installation path and come with Meanwhile, openSUSE attempts to cover both bases.
software packages that will help you get started. OpenSUSE Leap is a rock-solid system. It's developed openly
by a community, along with SUSE employees. They develop
Arch, on the other hand, is a more 'bare bones' affair. It is an enterprise-level operating system: SUSE, which powers the
committed to free software and its repositories contain over London Stock Exchange, amongst other things. It is designed
1 1 50,000 apps to install. You can also install multiple Desktop for mission critical environments where 'there is no scope
environments and use them as you would with any other distro. for instability'. If you find all that too sensible, openSUSE
Tumbleweed is a rolling release with all the latest features and
Arch is a distro for when you're more experienced with Linux. the occasionalcrash.
You start with nothing more than the command line and from
there: you manually partition your hard drive, set where the openSUSE is a highly respected Linux distribution and many
installation files will go, create a user, set the OS locale and of its core contributors work on the Linux Kernel, LibreOffice,
install a desktop environment, along with the apps you want. Gnome and other key Linux areas. In short: openSUSE is where
you’ll find the pros hanging out.
The advantage, For all this hard work, is a distro that you've
created. This means your Arch distro won’t come with all
the unnecessary files and apps that other distros have pre
installed; it's custom made foryou, by you.
II
. 1 RASPBERRY PI DESKTOP - RASPBERRYPI.ORG/DOWNLOADS/RASPBERRY-PI-DESKTOP
No doubt you've heard of the different programming languages and
Raspberry Pi? It's hard not to have, as li^ ra c p be rry: S neofetch educational resources.
jr
_ ,metSSSSSgg. p i§rasp be rry
this remarkable, tiny computer has .gS5SSSS£5S55«SSP.
,gSSP ........... “Y SS.". OS: Debian GNU/Linux 9 .6 (s tr e t c h ) x86_64
, SSP’ 's s s . Model: V irtu a lB o x 1 .2
taken the technology world by storm ,SSP , ggs.
, SP "1
$Sb:
SSS
Kernel: 4 . 9 ,0-8-amd64
Uptime: 2 minutes
Originally, Raspbian was exclusive to
d S' SSP Packages: 1499
since it was introduced six years ago. Shell: bash 4.4.12 the Pi hardware, as the Raspberry Pi
Resolu tio n : 1280x600
DE: LXDE uses an ARM processor to power it.
ia
VH: Openbox
Theme: Adwaita [GTK3]
There are several aspects to the Ic on s: Adwaita [GTK3] Flowever, the Raspberry Pi Foundation
Term inal: lxte rm in al
Raspberry Pi that make it such a CPU: In t e l 15-660DK (2 ) 0 3.5GHz
GPU: V irtu a lB o x G raphics Adapter has since released a PC version of
Memory: 83MB / 2G04HB
sought-after piece of the computing Raspbian: Raspberry Pi Desktop.
world. For one, it's cheap, costing
around £25 for, what is essentially, As with the Pi version, Raspberry Pi
Equipm entY ou
Will Need
The system requirements for successfully installing Linux M int on to a PC are
surprisingly low, so even a computer that's several years old will happily run this distro.
However, it's worth checking you have everything in place before proceeding.
MINTY INGREDIENTS
Here’s what you'll need to install and run Linux Mint as we work through this book. You have several choices available, so take
your time and see which works best for you.
SYSTEM REQUIREMENTS
The minimum system requirements For Linux Mintare as Follows:
CPU 700MHz
RAM 512MB
Monitor 1 0 2 4 x 7 6 8 resolution
Obviously the better the system you have, the betterand quicker
the experience will be.
USB INSTALLATION
You can install Linux Mint onto your computer via USB or
DVD. We'll look into each a little later on, but iF you're already
Familiarwith the process (or you're thinking oF USB and just
gathering the hardware you'll need), then you're going to
need a minimum 4GB USB Flash drive/stick to contain the
Linux Mint ISO.
MAC HARDWARE
Although Linux Mint can be installed onto a Mac, there's a
school of thought that recommends Mac owners use a virtual
environment, such as VirtualBox or Parallels; and why not,
macOS is already a splendid operating system. If you're looking
to breathe new life into an older Mac, make sure it's an Intel
CPU model and not the Power-PC models. However, be aware,
it’s not as pain-free as installing on to a PC.
VIRTUAL ENVIRONMENT
Installation to a virtual environment is a favourite method of
testing and using Linux distros. Linux Mint works exceedingly
well when used in a virtual environment, more on that later.
There are many different virtual environment apps available,
however VirtualBox, from Oracle, is one of the easiest. You can
get the latest version from w ww .virtualbox.org.
Vi rtualBox
Coding & Programming
Coding on Linux
First locate the ISO image of Linux you've already - iT lJ I Right-click the Linux ISO and from the menu select
downloaded. In Windows 7, 8.1 and 10 computers, Burn Disc Image. Depending on the speed of the PC,
you'll usually find this in the Downloads folder unless, when saving it may take a few seconds before anything happens. Don't worry too
it, you've specified a different location. much, unless it takes more than a minute, in which case it might be
worth restarting your PC and trying again. With luck, the Windows
Name Disc Image Burner should launch.
it Quick access
J linuxmint-19.1-cinnamon-64bit
y Dropbox (Team EDM) M o unt
& Share
© CD Drive (E:) HiSuite
Open with
Network
Open with WinRAR
Add to archive...
Arlrl + n " 11 r* ii v m i n f - 1 Q 1 - n n n a m n n -foA In 1f~ rar"
Next, inserta recordable DVD disc into your With the Windows Disc Image Burner dialogue box
computer's optical drive. After a few seconds, while open, click on the 'Verify disc after burning' tick
the disc is read, Windows will display a pop-up message asking you box, followed by the Burn button. The process should take a few
what to do with the newly inserted disc, ignore this as we're going minutes, depending on the speed of your PC's optical drive. Once
to use the built-in image burning function. it's complete, it will run through the verification stage and when
done, the optical drive should auto-eject the disc foryou.
Disc burner
Status
Burning disc image to recordable disc,..
09:45 | Cancel ~|
A® Cl») 18/01/2019
Rufus 3.0.1304 X
When you're ready, click on the Start button at
D riv e P ro p e rtie s ------------------------------ the bottom oF the RuFus app. This may open up
Device
First, open up a web Ubuntu 13.04 ITS amd64 (G:) (3G8]
another dialogue box asking you to download and use a new version
browser and go to Boot selection oFSysLinux. SysLinux is a selection oF boot loaders used to allow a
https://rufus.akeo. ubuntu-18,04-desktop-amd64.iso v (0 SELECT modern PC to access and boot From a USB Flash drive. It is necessary,
ie/. Scroll down the Partition scheme Target system
so if asked, click on 'Yes' to continue.
MBR BlOSorUEFI
page a little and you'll
v Show advanced drive properties
come to a Download
Fo rm at O p tio n s ------------------------------- This image uses Syslinux 6.03/20151222 but this application only
heading, under which Volume label includes the installation files for Syslinux 6.03/2014-10-06.
you'll see the latest [ Ubuntu 18.04 LTS amd&4
1 device found
Flash drive (iF not, just Statu s Please select the mode that you w ant to use to write this image:
remove and reinsert). READY (•) Write in ISO Image mode (Recommended)
Q W rite in DD Image mode
© 0 5 ® CLOSE
OK Cancel
1 devicefound
0 Rufus 3.4.1430 X
B JS H S g : At First glance the RuFus interface can look a little
confusing, don’t worry though, it's really quite D rive P ro p erties --------------------------------
Device
simple. To begin with, click on the SELECT button next to the ’Disk The Linux ISO is now
Linux Mint 19.1 Cinnamon 64-bit (F:) [4.1GB]
or ISO Image (Please select)' pull-down menu. This will launch a being transferred to Boot selection
Windows Explorer window From where you can locate and select the USB Flash drive. The linuxmint-19.1-cinnamon-64bit.i50 v- @ SELECT
the Linux ISO. process shouldn't take Partition scheme Target system
MBR v j BIOS or UEFI
too long, depending on
J v Show advanced drive properties
SOpn,
the speed oFthe USB
Form at O ption s ------------------------
device and the PC. During
Volume label
fume OatmoMml Type Sut
the process, you may Find | Linux Mint 19,1 Cinnamon 64-bit
PrLiUvn.theme r.r, „ ^ Vo,
4 .0 . Rufus will auto-open the File system Cluster size
v Showedvtnteddintptopartin FAT32 ~j 4096 bytes (Default)
USB drive in Windows
<*ci v Show advanced format options
Explorer, don't worry you
F«!«iyttem CHmwi sin Status
ta n . . . . «*j rn tru o ix u n ■ » ! can minimise or close it
READY
Status -------------------------------------------- if you want. Click on the
Close button once the © (D 2 US | START ] CLOSE
® 0 = lia CLOSE Flitmane ISOIn.nn
process is complete.
---- '
' Using image: linuxmint-19.1-cinnamon-64bit.iso
Installing Linux on a PC
M o st Linux distros come as a Live Environment. This m eans you can boot into an actual,
fully working distro straight from the D V D or USB you’ve just created. Let's see how
that w orks and how you go about installing Linux from there.
UEFI BIOS
The UniFied Extensible Firmware Interface (UEFI) is used to identiFy hardware and protect a PC during its boot-up process. It
replaces the traditional BIOS, but can cause issues when installing Linux.
Insert your DVD or USB Flash drive into your PC and, With UEFI turned to Legacy mode, there are now
if you haven't already, shutdown Windows. In this two ways oF booting into the Live Environment. The
instance, we're using the USB boot media but the process is virtually First is via the BIOS you're already in. Locate the Boot Sequence and
identical. Start the PC and when prompted press the appropriate change the First boot device From its original setting, usually Internal
keys to enter the BIOS or SETUP; these could be, For example, F2, PIDD or similar, to: USB Storage Device For the USB media option; or
Del or even F12. DVD Drive, For the DVD media option.
A There are diFFerent versions oFa UEFI BIOS, so Alternatively use the Boot Option Menu. With this
■ ■ ■ ■ V covering them all would be impossible. Whatyou're option, you can press F12 (or something similar)
looking For is a section that details the Boot Sequence or Boot to display a list oF boot media options; From there, you can choose
Mode. Flere you’ll have the option to turn oFF UEFI and choose the appropriate boot media. Either way, you can now Save and Exit
Legacy, or disable Secure Booting. Most distros work with UEFI but the BIOS by navigating to the Save & Exit option and choosing Save
it can be a tricky process to enable it to boot. Changes and Exit.
INSTALLING LINUX
Once the Live Environment has booted, you will see the option to install the distro to your computer. Have a look around and
when you're ready, look For the Install option on the desktop.
Providing you're connected to the Internet (if not, BeFore the installation process begins, you're asked
then do so now) and you're in the Live Environment, iF the choice you made regarding the erasure oF the
start the installation process by double-clicking on the Install Linux hard drive is correct. This is your last chance to back out. IF you're
Mint icon on the desktop. Other distros will display their own name, oF certain you don’t mind wiping everything and starting again with
course, but the process is the same. Click Continue when you're ready. Linux Mint, click Continue. iFyou need to back up your Files remove
the Linux disc/USB, reboot, back up and start again.
While the installation process is very similaracross Eventually you will be asked to set up your Linux
most Linux distros, some oFFer diFFerent questions username and password. Enteryour Name to begin
during the installation. Generally, the questions aren’t too diFFicult, or with, then Computer Name - which is the name used to identify
technical, butsomesuch as'Installing third-party soFtware...'can be it on the network. Next, choose a Username, Followed by a good
confusing. In this case, you can click Continue, but if you're unsure, Password. You can tick the Login Automatically option, but leave
have an Internet-connected device available to ask any questions. the Encrypt Home Folder option For now.
When installing a new operating system it's The installation process can be quick and there may
recommended that you wipe the old OS, replacing it be more questions to answer, or it may simply start
with the new. When you reach this stage of the installation process, installing Linux based on your previous answers. Either way, you will
ensure the 'Erase diskand install Linux...' option isselected. NOTE: end up being asked to Continue Testing the Live Environment, or
This will completely wipe Windows 10 from your computer; make Restarting to use the newly installed OS. IF you're ready to use Linux,
sure you have backups of all your personal files and data. then click Restart Now.
Installing a Virtual
Environm ent
A Virtual Environment is a simulated com puter system. Using a Virtual Machine, you
can mimic a standard PC and install an entire operating system on it w ithout affecting
the one installed on your computer. It’s a great way to test and use Linux, while still
having W indow s 10 as your main OS.
GOING VIRTUAL
Using a Virtual Machine (VM) will take resources From your computer: memory, hard drive space, processor usage and so on.
So make sure you've got enough of each before commencing.
We're using VirtualBox in this instance, as it's one of With the correct packages downloaded, beFore
the easiest virtual environments to get to grips with. we install anything, we need to make sure that the
Enterwww.virtualbox.org and dick on ‘Download VirtualBox'. This computer you're using is able to host a VM. To do this, reboot the
will take you to the main download page. Locate the correct host computer and enter the BIOS. As the computer starts up, press the
for your system: Windows or Mac - the Host is the current installed Del, F2, or whichever key is necessary to Enter Setup.
operating system and click the link to begin the download.
Award Modular BIOS vB.OOPG, An Energy Star Ally
Copyright CC) 1984-99, Award Software, Inc.
Next, while still at the VirtualBox download page, As each BIOS is laid out differently, it’s very difficult
locate the VirtualBox Extension Pack link. The to assess where to look in each personal example.
Extension Pack supports USB devices, as well as numerous other However, as a general rule oF thumb, you're looking For Intel
extras that can help make the VM environment a more accurate Virtualisation Technology, or simply Virtualisation, usually within
emulation of a Teal' computer. the Advanced section of the BIOS. When you've located it, Enable it,
save the settings, exit the BIOS and reboot the computer.
D o w n lo a d V irtu a lB o x
Hire you *w find linkstovirtuelBox tWnnesera Ire source co
:= « . E i Cl d) a
Advanced Monitor
VirtualBox binaries
ftaek •ifv.ancedx CPU Confljurat
If you're lookingfor thel«e« VMwWwi6,0 packages,si
II you're lookingtor thelatest VirtualBox 5.2 packages,si
VirtualBox 6.1.16 platform packages
VirtualBox 6.1.16 Oracle VM VirtualBox Extension Pack Active Processor cores Disabled
Enabled
■ 'All supported platforms Limit CPUID Maximum
Supportfor USB2.0 endUSB3.0 devices. VirluolBc
(PutL). Measetnitall tile SemeVWSKKIActoAWMp,
FXiBraiie Dlsutiie Rli
VirtualBox 6.1.16 Software Developer Kit (SDK)
With the computer back up and running, locate When installing VirtualBox, your network
the downloaded main VirtualBox application and connection will be disabled for a very brief
double-click to begin the installation process. Click Next to continue, period. This is due to VirtualBox creating a linked, virtual network
when you're ready. connection so thatany VM installed will beable to access the
Internetand your home network resources, via the computer's,
already established, network connection. Click Yes, then, Install to
begin the installation.
W a rn in g :
N e tw o rk In te rfa ce s
The default installation location of VirtualBox You'll probably be asked by Windows to accept a
should satisfy most users, but if you have any special security notification, dick Yes for this and next
location requirements, click on the 'Browse' button and change the you may encountera dialogue box asking you to trust the
install folder. Also, make sure that all the icons in the VirtualBox installation from Oracle, again, dick yes and accept the installation
feature tree are selected and none of them have a red X next to of the VirtualBoxapplication. When it's complete, click finish to
them. Click Next to move on. start VirtualBox.
Click on the Icons in the tree below to change the way features will be installed.
This section can be left to the defaults, should you With VirtualBox up and running, you can now
■ ■ ■ H ^ F wish. It simply makes life a little easier when dealing install the VirtualBox Extension Pack. Locate the
with VMs, especially when dealing with downloaded VMs, as you downloaded add-on and double-click. There may be a short pause
may encounter in the future. Again, clicking Next will move you on while VirtualBox analyses the pack, but you'll eventually receive a
to the next stage. message to install it; click Install to begin the process, scroll down
the next screen to accept the agreement and click 'I Agree'.
Oracle VM VirtualBox 6.1.16 Setup X
C usto m Se tu p
Installing Linux in a
Virtual Environm ent
With Oracle's VirtualBox now up and running, the next task is to create the Virtual
Machine (VM) environment into which you will install Linux. This process w on't affect
your currently installed operating system, which is w hy a V M is a great choice.
CREATING THE VM
There are plenty oF options to choose From when creating a VM. For now though, we'll setup a VM adequate to run the
excellent Linux Mint, and perForm well.
K E H S B ’: With VirtualBox open, click on the New icon in the The next section will deFine the amount oF system
top-middle oF the right-hand panel oF the app.This memory, or RAM, the VM has allocated. Remember
will open the new VM Wizard. this amount will be taken From the available memory installed in
yourcomputer, so don't give the VM too much. For example, we
have 8GB oF memory installed and we're giving 2GB (2048MB) to
the VM. When you're ready, click Next to continue.
In the box next to Name type Linux Mint, and This section is where you'll start to create the virtual
VirtualBox should autom atically choose Linux as hard disk that the VM will use to install Mint on to.
the Type and Ubuntu (64-bit) as the Version, iF not then use the The deFault option, ‘Create a virtual hard disk now', is the one we're
drop-down boxes to select the correct settings (remem ber Mint using. Click Create to move on.
mainstream is based on Ubuntu). Click Next when you're ready
to proceed.
The pop-up window that appears after clicking After clicking Create the initial setup of the VM is
Create is asking you what type of virtual hard disk complete; you should now be looking at the newly
you want to create. We're going to use the default VDI (VirtualBox created VM within the VirtualBox application. Before you begin though,
Disk Image) in this case, as the others are often used to move VMs click theSettings button from the top of the right-hand panel, and within
from one VM application to the next. Make sure VDI is selected, and the General section click the Advanced tab. Using the pull-down menus,
click Next. choose 'Bidirectional' for both Shared Clipboard and Drag'n'Drop.
The question of whether to optfor Dynamically or Follow that by clicking on the System section,
Fixed sized virtual hard disks may come across as being then the Processor tab. Depending on your CPU
somewhat confusing to the newcomer. Basically, a Dynamically Allocated allocate as many cores as you can without detriment to your host
virtual hard disk is a more flexible storage management option. It won't system; we've opted for two CPUs. Now click on the Display section,
take up much space within your physical hard disk to begin with either. slide the Video Memory up to the maximum, and tick 'Enable 3D
Ensure Dynamically Allocated is selected, and click Next. Acceleration'. Click OK to commit the new settings.
The virtual hard disk will be a single folder, up to the B S H jr M Click on the Start button and use the explorer
size you state in this section. button in the 'Select Start-up Disk’ window; the
Ensure the location of the virtual hard disk, on your computer, has explorer button is a folder with a green arrow. Click Add in the new
enough free space available. For example, we've used a bigger pop-up window, to locate the downloaded ISO of Mint; and click
storage option on our D:\drive, named it Linux Mint, and allocated Open to select the ISO. Now click the Start button to boot the VM
25.S0CB of space to the virtual hard disk. with the Linux Mint Live Environment. You can now install Linux as per
the standard PC installation requirements.
Getting Ready to
Code in Linux
Coding in Linux mostly happens in the Terminal or the Com m and Line. While it can be a
scary looking place to begin with, the Terminal is an extremely powerful environment.
Before you can start to code, it's best to master the Terminal.
TAKING COMMAND
The command line is at the core of Linux and when you program with it, this is called scripting. These are self-contained
programs designed to be run in the Terminal.
The Terminal is where you begin your journey What you currently see in the Terminal is your login
with Linux, through the command line and thus name followed by the name of the computer, as you
any scripting From. In Linux Mint, it can be accessed by clicking on named it when you First installed the OS on to the computer. The
the Menu Followed by the Terminal icon in the panel, or entering line then ends with the current Folder name; at first this is just a tilde
'Terminal' into the search bar. (~), which means your Home folder.
The Terminal will give you access to the Linux The flashing cursorat the very end of the line is
Mint Shell, called BASH; this gives you access to where your text-based commands will be entered.
the underlying operating system, which is why scripting is such a You can begin to experiment with a simple command, Print Working
powerful language to learn and use. Everything in Mint, and Linux Directory (pwd), which will output to the screen the current folder
as a whole, including the desktop and GUI, is a module running from you're in. Type: pwd and press Enter.
the command line.
david@davii
File Edit View Search Terminal Help
david@dav±d-mint - t pwd
/home/david
da vid(ada v i d - m i n t - $
All the commands you enter will work in the same The list of available Linux commands is vast,
manner. You enter the command, include any with some simply returning the current working
parameters to extend the use of the command and press Enter to directory, while others are capable of deleting the entire system in
execute the command line you've entered. Now type: uname -a an instant. Getting to know the commands is part
and press Enter. This will display information regarding Linux Mint. of learning how to script. By using the wrong command, you could
In scripting, you can use all the Linux command-line commands end up wiping your computer. Type compgen -c to view the
within your own scripts. available commands.
HERE BE DRAGONS!
There's an urban myth on the Internet that an employee at Disney Pixar nearly ruined the animated movie Toy Story by
inadvertently entering the wrong Linux command and deleting the entire system the film was stored on.
Having access to the Terminal means you're Therefore it's always a good idea to work in the
bypassing the GUI desktop method of working Terminal using a two-pronged approach. First, use
with the system. The Terminal is a far more powerful environment the desktop to make regular backups of the folders you're working
than the desktop, which has several safeguards in place in case you in when in the Terminal. This way, should anything go wrong, there's
accidentally delete all your work, such as Rubbish Bin to recover a quickand handy backup waiting foryou.
deleted files.
However, the Terminal doesn't offer that luxury. If Second, research before blindly entering a
you were to access a folder with files within via the command you've seen on the Internet. If you see the
Terminal and then enter the command: rm * . *, all the files in that command: sudo dd if=/dev/random of=/dev/sdaand use
folder would be instantly deleted. They won't appear in the Rubbish it in a script, you’ll soon come to regret the action as the command
Bin either, they're gone for good. will wipe the entire hard drive and fill it with random data. Take a
moment to Google the command and see what it does.
udev - What does dd if=/dev/zero of=/dev/sda' do - Unix & Linux Stack ...
https //unix slackexchange convquestions/ /what-does-dd-rf-dev-zero-of-dev-sda-do »
8 Apr 2016 - dd if=/dev/zero ol=/deWsda bs=4096 count=4096 Q why 4096 is particularly used for
counter? This will zero out the first 16 MiB of the drive
Can "dd if=/dev/zero of=/dev/sda" physically damage your hard disk ...
https://wwwcenlos.org > Board index > C en tos General Purpose > C en tos Social *
GET SCRIPTING
A Bash script is simply a series of commands that Mint will run through to complete a certain task. They can be simple or
remarkably complex, it all depends on the situation.
You'll be working within the Terminal and with a To begin with, and before you start to write any
text editor throughout the coming pages. There scripts, you need to create a folder where you can
are alternatives to the text editor, which we’ll look at in a moment put all our scripts into. Start with mkdir scripts, and enter the
but for the sake of ease, we'll be doing our examples in Xed. Before folder cd scripts/. This will be our working folder and from here
you begin, however, run through the customary update check: sudo you can create sub-folders if you want of each script you create.
apt-get update && sudo apt-get upgrade.
davii:
davii File Edit View Search Terminal Help
File Edit View Search Term inal Help david@david-mint — $ mkdir scripts
d a v i d @ d a v i d - m i n t - $ cd s c r i p t s /
david<adavid-mint ~ $ s u d o a p t - g e t u p d a t e & & s u d o a p t - g e t up g r
david@david-mint -/scripts S |
[sudo] p a s s w o r d for david:
H i t :1 h t t p : / / p p a . l a u n c h p a d .n e t / o p e n s h o t . d e v e l o p e r s / p p a / u b u n t u
H i t : 2 h t t p : / / p p a . l a u n c h p a d . n e t / p e t e r l e v i / p p a / u b u n t u x e n i a l In
Hit:3 http://archive.canonical.com/ubuntu xenial InRelease
Hit:4 http://ppa.launchpad.net/thomas-schiex/blender/ ubuntu x
Hit:5 http://archive.ubuntu.com/ubuntu xenial InRelease
I g n :6 h t t p : / / v / w w . m i r r o r s e r v i c e .o r g / s i t e s / p a c k a g e s . l i n u x m i n t .c
Get:7 http://archive.ubuntu.com/ubuntu xenial-updates InRelea
H i t : 8 http:// p p a . l a u n c h p a d . n e t / w i n e / w i n e - b u i l d s / u b u n t u xenial
H i t :9 h t t p : / / w w w . m i r r o r s e r v i c e .o r g / s i t e s / p a c k a g e s .l i n u x m i n t .c
H i t : 10 h t t p : / / r e p o s i t o r y . s p o t i f y . c o m s t a b l e I n R e l e a s e
.Get:11 h t t p ; / / a r c h i v e.ub.unlu , c o m / u b u n t u x e n i a l - b a c k p o r t s I n R e
There are several text editors we can use to create Windows users will be aware that in order fora
a Bash script: Xed, Vi, Nano, Vim, GNU Emacsand batch file to work, as in be executed and follow the
so on. In the end it all comes down to personal preference. Our programming within it, it needs to have a .BAT file extension. Linux
use of Xed is purely due to making it easier to read the script in the is an extension-less operating system but the convention is to give
screenshots you see below. scripts a .sh extension.
d avi
File Edit View Search Terminal Help
|david@da v i d - m i n t - / s c r i p t s $ Is
scriptl.sh script2.sh scrlpt3.sh script4.sh
david@david-mint -/scripts S |
Let's start with a sim ple script to output som ething W hen you enter is again, you can see that the
to the Terminal. Enter xed helloworld.sh. helloworld.sh script has now turned from being
This w ill launch Xed and create a file called helloworld.sh. In Xed, white to green, meaning that it's now an executable file. To run
enter the Following: # ! /bin/bash, then on a new line: echo the script, in other w ords make it do the things you've typed into it,
Hello World!. enter: . /helioworld, sh.
davi
File Edit View Search Terminal Help
# ! /bin/bash
echo H e l l o World!
The # ! /bin/bash line tells the system w hat Shell Although it’s not terribly exciting, the w ords 'Hello
you're going to be using, in this case Bash. The hash World!' should now be displayed in the Terminal.
(#) denotes a com m ent line, one that is ignored by the system, the The echo command is responsible for outputting the w ords after
exclamation mark (!) means that the com m ent is bypassed and will it in the Terminal, as we move on you can make the echo command
force the script to execute the line as a command. This is also known output to other sources.
as a Hash-Bang.
*hi;
*helloworld.s File Edit
File Edit View Search Tools Documents Help
File Edit View Search Tools Documents Help david@da
david@d;
C IO Di **** X i D B Q, 9. hellowo
david@da
£> 6 Di ^ (□ 6 9, 9,
david<ada a ^helloworld.sh x
*helloworld.5h X hellowor
# ■ /bin/bash
david@da
# ! /b i n / b a s h
Hello W
e c h o H e l l o World! This is my fi r s t s c r i p t in Li n u x Mil
david@da
e c h o He l l o World!
You can save this file, clicking File > Save, and exit Think o f echo as the old BASIC Print command. It
back to the Terminal. Entering is, w ill reveal the displays either text, numbers or any variables that
script in the folder. To make any script executable, and able to are stored in the system, such as the current system date. Try this
run, you need to modiFy its permissions. Do this with chmod +x example:echo Hello World! Today is $ (date +%A).The
helloworld.sh. You need to do this with every script you create. $(date +%A) is calling the system variable that stores the current day
o f the week.
davi
File Edit View Search Terminal Help
david@david-mint -/scripts £ xe d h e l l o w o r l d . s h
david@david-mint -/scripts s Is
h e l l o w o r l d .sh
david@david-mint -/scripts S c h m o d +x h e l l o w o r l d . s h
david@david-mint -/scripts % |
VARIABLES
Ju st as in every other programming language a Bash script can store and call certain variables From the system, either generic
or user created.
Let's start by creating a new script called hello.sh; The output now w ill be Hello David. This is because
xed hello .sh. In it enter: # ! /bin/bash, then, Bash autom atically assigns variables For the user,
echo Hello $1. Save the File and exit Xed. Back in the Terminal which are then held and passed to the script. So the variable
make the script executable with: chmod +x hello.sh. '$1' now holds ’David'. You can change the variable by entering
som ething diFFerent: ./hello.sh Mint.
As the script is now executable, run it with . / You can even rename variables. ModiFy the hello,
hello.sh. Now, as you probably expected a simple sh script with the Following: firstname=$l,
'Hello' is displayed in the Terminal. However, if you then issue the surname=$2, echo Hello $firstname ^surname. Putting
command with a variable, it begins to get interesting. For example, each statem ent on a new line. Save the script and exit back into
try . /hello.sh David. the Terminal.
W hen you run the script now you can use two Let's expand things Further. Create a new script
custom variables: . /hello .sh David Hayward. called greetings.sh. Enter the scripting as below
Naturally change the two variables with your own name; unless in the screenshot, save it and make it executable with the chmod
you're also called David Hayward. A t the m om ent we're just printing command. You can see that there are a Few new additions to the
the contents, so let's expand the two-variable use a little. script now.
d greetings, sh
Create a new script called addition, sh, using We've added a -n to the echo command here
the same Format as the hello.sh script, but which w ill leave the cursor on the same line as the
changing the variable names. Here we've added firstnumber and question, instead oF a new line. The read command stores the
secondmumber, and used the echo command to ou tpu t some users’ input as the variables Firstname and surname, to then read
simple arithm etic by placing an integer expression, echo The sum back later in the last echo line. And the clear command clears
is $ (($firstnumber+$secondnumber) ). Save the script, and the screen.
m aKe ic ex ecu ca D ie tcnmoa +x aaaition.sn).
dav
addition.sh File Edit View Search Terminal Help
File Edit View Search Tools Documents Help H e l l o D a v id H a y w a rd , how a r e you to d a y ?
d a v id t a d a v id - m in t - / s c r i p t s S
^ « y. id g Q . &
B addition.sh x
# !/b in /b ash
firstnumber=$l
secondnumber=$2
echo The sum i s $ ( ($f irstn um b er+ isecon dn u m b er))
W hen you now run the addition.sh script we can As a Final addition, let's include the date variable
enter two numbers: . /addition, sh 1 2.The we used in the last section. Am end the last line
result w ill hopeFuily be 3, w ith the Terminal displaying 'The sum oF the script to read: echo Hello $firstname $surname, how
is 3'. Try it with a Few diFFerent numbers and see what happens. are you on this fine $ (date +%A) ?. The ou tpu t should
See also iFyou can alter the script and rename it do m ultiplication, display the current day oF the week, calling it from a system variable.
and subtraction.
greetings, sh
Let's look at the If, Then and Else statem ents now, The next line, ELSE, is what happens if the variable
which when executed correctly, com pare a set of doesn’ t equal 'David'. In this case it sim ply outputs
instructions and simply w ork out that IF som ething is present, TFIEN to the screen the now familiar 'Hello...'. The last line, the FI
do something, ELSE do som ething different. Create a new script statem ent, is the command that will end the loop. If you have an If
called greeting2.sh and enter the text in the screenshot below command w ithout a Fi command, then you get an error.
into it.
david@david
*greetings.sl File Edit View Search Terminal Help
File Edit View Search Tools Documents Help H e l l o P i n k Floyd, h o w are you on t h i s fine W e d n e s d a y ?
dauidQdavid-mint -/scripts £
p 5 Qi l i i s e
S *greetings.sh X
#! / b i n / b a s h
e c h o -n Hello, w h a t is y o u r name?
read firs tn a m e
e c h o -n "Thank you, and w h a t is y o u r s u r n a m e ?
read surname
clear
if [ $ firs tn a m e == David' ]
Creeting2.sh is a copy o f greeting.sh but with a You can obviously play around w ith the script a
slight difference. Here we've added a loop starting little, changing the name variable that triggers a
at the if statem ent. This means, IF the variable entered is equal to response; or maybe even issuing a response w here the first name
David the next line, THEN, is the reaction to w hat happens, in this and surname variables match a specific variable.
case it w ill output to the screen 'Awesome name,' follow ed by the
variable (which is David).
david@davi
File Edit View Search Terminal Help
A w e s o m e name, Da v i d
david@david-mint -/scripts S
MORE LOOPING
You can loop over data using the FOR, WHILE and UNTIL statements. These can be handy iPyou're batch naming, copying or
running a script where a counter is needed.
Create a new script called count, sh, Enter the The UNTIL loop works much the same way as the
text in the screenshot below, save it and make it WHILE loop only, more oFten than not, in reverse.
executable. This creates the variable 'count' which at the beginning So our counting to a hundred, using UNTIL, would be: until
oF the script equals zero. Then start the WHILE loop, which WHILE [ $count -gt 100 ] ; do. The diFFerence being, UNTIL count is
count is less than (the LT part) 100 w ill print the current value o f greater than (the gt part) one hundred, keep on looping.
count in the echo command.
*count.sh (
count.sh (■ File Edit View Search Tools Documents Help
File Edit View Search Tools Documents Help
n e °r ^ y. ip e a
O O Di ir» y. ip e Q. &
B *count.sh x
B countsh X
#!/bin/bash
# ! /b i n / b a s h
until [
$ c o u n t -gt
ec h o $count
100 ]; do
count=0
let count=count+l
done
w h i l e [ $co u n t -It
echo $co u n t
let c o u n t = c o u n t + l
100 ;do
i
done]
Executing the count.sh script will result in the You're not limited to numbers zero to one hundred.
num bers 0 to 99 listing down the Term inal screen; You can, within the loop, have w hatever set oF
when it reaches 100 the script w ill end. M odifying the script with the commands you like and execute them as many times as you w ant
FOR statem ent, makes it w ork in much the same way. To use it in our the loop to run For. Renaming a million Files, creating Fifty Folders
script, en ter the text From the screenshot into the count.sh script. etc. For example, this script w ill create ten Folders named Folderl
through to fo ld e rl 0 using the FOR loop.
*count.sh (
#!/bin/bash
for count in {0..10© }; do
echo $count
for co u n t in {6|. .16};do
let c o u n t = c o u n t + l
mkdir Folder$count
done
let count=count+l
done
The addition we have here is: for count in Using the FOR statem ent once more, w e can
(0 . . 1 0 0 } ; do. W hich means: FOR the variable execute the counting sequence by manipulating the
’count’ IN the num bers From zero to one hundred, then start the {0..100} part. This section oF the code actually means {START..END..
oop. The rest o f the script is the same. Run this script, and the same NCREMENT}, if there's no increm ent then it's just a single digit up to
o u tpu tsh ou ld a ppe arin the Terminal. the END. For example, w e could get the loops to count up to 1000 in
W O ’ S With: lo t: c o u n t I n { 0 . . 1000 . . 2 }; do.
9 *count.sh x
*count.sh (
A very basic backup script would look som ething Once the -/backups Folder is created, we can now
along the lines oF: # ! /bin/bash, then, create a new subFolder within it based on the
tar cvrfz ~/backups/my-backup. tgz - “/Documents/, This Time Stamp variables you set up at the beginning. Add mkdir -p
will create a compressed File backup oF the -/D ocum ents Folder, $dest/"$day $month $year". It's in here that you put the
with everything in it, and put it in a Folder called /backups with the backup File relevant to that day/month/year.
name my-backup.tgz.
E9 backup 1,sh x
# ! /b in /b a s h
backupl.sh ('/scripts)
File Edit View Search Tools Documents Help c le a r
# Time stamp
d a y = s(d ate +%A)
^ x t D B m onth=$(date +%B)
ye a r= $ (date +%Y)
9 backupl .sh X
# F o ld e rs
# ! / b in /b a s h dest= ~/b ackups
sauce=~/Documents
t a r c v f z ~ /b a c k u p s/m y -b a c k u p .tg z -/Docum ents/I
i f [ -d S d e st ]; then
echo "Backup fo ld e r e x i s t s "
e ls e
echo Backup fo ld e r does not e x i s t ! I'm now c r e a tin g i t . . . " ; (m kdir -p Sd e st)
echo
fi
read -p " P r e ss any key to co ntinue . -n l -s
m kdir -p $ d e st/ $day Smonth $year
W hile perfectly Fine, we can make the sim ple script W ith everything in place, you can now enter the
a lot more interactive. Let's begin with deFining actual backup routine, based on the Tar command
some variables. Enter the text in the screenshot into a new backup, From Step 5. Com bined with the variables, you have: tar cvf z
sh script. Notice that we've m isspelt 'source' as ’sauce', this is $dest/"$day $month Syear"/DocmentsBackup.tgz
because there's already a built-in command called 'source' hence the Ssance. In the screenshot, w e added a handy "Now backing up..."
diFFerent spelling on our part. echo command.
£9 backupl .sh X
# ! / b in / b a s h
c le a r
# T im e stam p
d a y -S (d a t e
m o n th -$ (d a ta +%B)
y e a r= S (d a t e +%Y)
# Folders
d e st= ~ /b ac k u p s
s a u c e=~/Document s
i f [ -d S d e s t ] ; the n
e cho "B a ck u p f o ld e r e x i s t s "
e ls e
• c h o "B a ck u p f o ld e r d o e s n o t e x i s t ! I ‘ m now c r e a t i n g it ; (m k d ir -p s d e s t )
echo
fi
re ad -p " P r e s s a n y key to c o n t in u e . - n l -s
m k d ir -p S d e s t / Sday Smonth S y e a r
c le a r
• c h o "Now b a c k in g u p . P le a s e w a i t . . . "
t a r c v f z S d e s t / Sday Smonth S y e a r /D o c u m e n ts B a c k u p .tg z S sa u c e
The previous script entries allowed you to create Finally, you can add a Friendly message: echo
a Time Stamp, so you know when the backup was "Backup complete. All done...".T h e
taken. You also created a 'd e s f variable, which is the Folder where com pleted script isn't too over-complex and it can be easily
the backup File w ill be created (-/backups). You can now add a customised to include any Folder within your Home area, as w ell as
section oF code to First check iF the -/backups Folder exits, iF not, the entire Home area its e lf
then it creates one.
B backupl .sh X
# ! /b in /b a s h
B backupl .sh x
c le a r
# ! /b in /b a s h # Tim e stamp
d a y = S (d a te +%A)
m onth=S(date +%B)
c le a r y e a r= $(d a te +VO
# Time stamp
day = $ (d ate +%A) # F o ld e r s
m onth=$(date +%B) d e s t— /backups
sauce=~/Documents
y e a r=$ (d a te +%Y)
i f [ -d S d e s t ] ; then
# F o ld e r s echo Backup f o ld e r e x is t s "
d e st= "-/back ups echo kup f o ld e r does not e x i s t ! I ‘ n now c r e a t in g i t j (m k d ir -p s d e s t)
sa u c e=~/Docum ents echo
fi
read -p P r e s s any key to c o n tin u e . - n l -s
i f [ -d $ d e st 3; then m kd ir -p s d e s t/ sday smonth S y e a r
ache "Backup f o ld e r e x i s t s "
e ls e c le a r
■cho "Now b a c kin g up. P le a s e w a i t . .
echo Backup f o ld e r does not e x i s t ! I ’ m now c r e a t in g i t . . . " ; (m k d ir -p S d e st) t a r c v f z $ d e s t / ’Sday $month S y e a r /D o cum entsB ackup.tg z Ssauce
echo
fi
Let's start by creating a script to help display the Each oF the sections runs a diFFerent Terminal
M in t system inFormation; always a handy thing command, outputting the results under the
to have. Create a new script called sysinfo.sh and enter the appropriate heading. You can include a lo t more, such as the current
Following into Xed, or the text editor oF your choice. aliases being used in the system, the current tim e and date and so
on. Plus, you could also pipe all that inFormation into a handy HTML
File, ready to be viewed in a browser.
■-----------------------------------------------------------------------------
david@david-mint -/scripts
File Edit View 5earch Terminal Help
Idav i d @ d a v i d - m i n t - / s c r i p t s 5 ./ s y s i n f o . s h > s y s i n f o . h t m l
david@david-mint -/scripts $
look4.sh (-j1
We've included a couple oF extra commands in File Edit View Search Tools Documents Help
this script. The First is the -e extension For echo,
£ )© 0| X E> 6 Q.9.
this means it’ll enable echo interpretation oF additional instances
oFa new line, as w ell as other special characters. The proceeding Ej§ look4.sh X
'31;43m' elem ent enables colour For Foreground and background. #! /bin/bash
target*-/
read name
W hen executed the script waits for input from the The output from colours.sh can, o f course, be
user, in this case the file extension, such asjpg, mixed together, bringing different effects
mp4 and so on. It's not very friendly though. Let's make it a little depending on w h atyou w ant to the output to say. For example,
friendlier. Add an echo, with: echo -n "Please enter the white text in a red background flashing (or blinking). Sadly the
extension of the file you're looking' tor: " J u s t blinking effe ct doesn't work on all Terminals, so you may need to
before the read command. change to a d iffe re nt Terminal.
a *look4.sh x
Normal Text
#!/bin/bash
Default Default
target=~/ Default
read name
Yellow
output=$< find Starget -iname Sname 2> /dev/null ) Default
c le a r # ! /b in /b a s h
echo e "N o rm a l \ e [lm B o ld "
echo e “ N o rm a l \ e [ 2mDim" firs tn a m e = $ < z e n ity - - e n t r y - - t i t l e = ' Your Name - te x t= W h a t i s yo ur f i r s t nam e?’ )
echo e 'N o rm a l \ e [4 m U n d e r lin e d "
s u rn a m e = $ (ze n ity - - e n t r y - - t it le ® "You: Name - -text=~W hat i s yo ur f i r s t surnam e?' )
echo e 'N o rm a l \ e [ 5 m B l in k "
echo e 'N o rm a l \e [7 m in v e rte d "
z e n i t y - - in f o - - t i t l e = “ H ell< --te x t= 'W e lc o m e to L in u x M in i;. s n \n Have fu> , S fir s tn a m e Ssurname-
echo e 'N o rm a l \ e [8 m H id d e n "
echo
echo e ' \ e [ 0mNo r m a l T e x t "
echo
echo e “ D e fa u lt \e [3 9 m D e fa u lt"
echo e ' D e f a u l t \ e [ 3 0 m B la c k " W hile gaming in a Bash script isn't som ething
echo e “ D e f a u l t \ e [31mRed"
echo
echo
e 'D e f a u l t \ e [3 2 m fir e e n " that’s often touched upon, it is entirely possible,
e ‘ D e f a u l t \ e [ 3 3 m Y e llo w "
echo
echo
e 'D e f a u l t \ e [3 4 m B lu e "
e 'D e f a u l t \ e [35m M agenta“
albeit, a little basic. Movement-based games are diffiuclt, and
echo e “ D e f a u l t \ e [3 6 m C y a n "
echo e • D e f a u lt \ e [ 3 7 m L ig h t g r a y "
som etim es buggy, however a good text adventure, or Fighting
echo e “ D e f a u l t \e [9 0 m D a r k g r a y "
echo e 'D e f a u l t \ e [ 9 1 m l ig h t r e d " Fantasy type game is a perfect choice for gaming in the Terminal,
echo e 'D e f a u l t \ e [ 9 2 m L ig h t g r e e n ”
echo e " D e f a u l t \ e [ 9 3 m L ig h t y e llo w " give ita go, and let us know how you get on.
echo e 'D e f a u l t \ e [ 9 4 m L ig h t b lu e "
echo e 'D e f a u l t \ e [ 9 5 m L ig h t m a g e n ta "
echo e • D e f a u l t \ e [ 9 6 m L ig h t c y a n "
©
1
1
echo
echo e 'D e f a u l t \ e [ 4 9 m D e f a u lt '' -0 -0 -0 -0 -0 -0 -0 -0 -0 -0
echo e 'D e f a u l t \ e [4 0 m B la c k ''
echo e " D e f a u l t \ e [4 1 m R e d " /o\/o\/o\/o\/o\/o\/o\/o\/o\/o\
echo e ' D e f a u l t \ e [4 2 m G r e e n "
echo e “ D e f a u l t \ e [ 4 3 m Y e llo w "
echo e " D e f a u l t \ e [4 4 m B lu e "
/o\/o\/o\/o\/o\/o\/o\/o\/o\/o\
echo e 'D e f a u l t \e [4 5 m M a g e n ta ”
echo e " D e f a u l t \ e [4 6 m C y a n ”
echo e “ D e fa u lt
echo e 'D e f a u l t \e [1 0 O m D a rk g r a y "
echo e " D e fa u lt \ e [ 1 0 lm lig h t re d "
echo e " D e f a u l t \ e [ 1 0 2 m L ig h t g r e e n "
echo e 'D e f a u l t \ e [ 1 0 3 m L i g h t y e llo w " mu uuu mu ###
echo e 'D e f a u l t \ e [ 1 0 4 m L i g h t b lu e " it ttftU K »#### uuuuu
echo e " D e f a u l t \ e [ 1 0 5 m L i g h t m a g e n ta " U ttU U U U U ####### ####### #######
echo e 'D e f a u l t \ e [ 1 0 6 m L i g h t c y a n " ## ## u# ## ## uu
echo e " D e f a u l t \ e t l0 7 m W h it e " ** **
C om m and Line
Quick Reference
W hen you start using Linux full time, you w ill quickly realise that the graphical
interfaces o f Ubuntu, Mint, etc. are great for many tasks but not great for all tasks.
Understanding how to use the command line not only builds your understanding o f
Linux but also improves your know ledge o f coding and program m ing in general. O ur
com mand line quick reference guide is designed to help you m aster Linux quicker.
TOP 10 CO M M A N D S
These may not be the most common commands used by everyone but they will certainly Feature Frequently For many users oF
Linux and the command line.
The c d com m and is one oF the com m andsyou The m? com m and moves a File to a diFFerent
w ill use the m ost at the com m and line in Linux. It location or renames a File. For example mv file
allow s you to change your working directory. You sub renames the original File to sub. mv sub
use it to move around w ithin the hierarchy oFyour -/Desktop moves the File 'sub' to your desktop
File system. You can also use chdir. directory but does not rename it. You must speciFy
a new Filename to rename a File.
The is com m and shows you the Files in your The chown command changes the user and/
current directory. Used with certain options, it lets or group ow nership oF each given File. IF only an
you see File sizes, when Files w here created and File ow ner (a user name or numeric user ID) is given,
permissions. For example, is - shows you the Files that user is made the ow ner oFeach given file, and
that are in your home directory. the Files' group is not changed.
The cp command is used to make copies oF Files The chmod com m and changes the permissions on
and directories. For example, cp file sub makes the Files listed. Permissions are based on a Fairly
an exact copy oF the File whose name you entered sim ple model. You can set permissions For user,
and names the copy sub but the First File will still group and world and you can set w hether each can
exist with its original name. read, w rite and or execute the File.
The pwd command prints the Full pathname of The m c o m m a n d removes (deletes) Files or
the current working directory (pwd stands For directories. The removal process unlinks a Filename
"print working directory"). Note that the G N O M E in a Filesystem From data on the storage device
terminal also displays this inFormation in the title and marks that space as usable by Future writes. In
bar o f its window. other words, removing Files increases the am ount
o f available space on your disk.
The clear com m and clearsyou rscreen if this Short For "make directory", mkdir is used to
is possible. It looks in the environm ent fo r the create directories on a file system, if the speciFied
terminal type and then in the terminFo database directory does not already exist. For example,
to Figure out how to clear the screen. This is mkdir w ork creates a w ork directory. M ore than
equivalent to typing Control-L when using the one directory may be speciFied when calling mkdir.
bash shell.
C :\Commonly_Used_Commands
USEFUL HELP/INFO C O M M A N D S
The following commands are useful for when
you are trying to learn more about the system or
program you are working with in Linux. You might
not need them every day, but when you do, they
will be invaluable.
The iw aiis com m and displays the to ta l am ount The H iS l com m and opens a stream editor.
o f free and used physical and swap m em ory in A stream e dito r is used to perform text
the system. For example, gives the transform ations on an input stream: a file or input
inform ation using megabytes. from a pipeline.
W//////7A '////A
The ffH Sffi com m and allow s you to search inside a The B B lW iB H B com m and is especially useful.
num ber o f files for a particular search pattern and It displays the Introduction to User Commands,
then prin t m atching lines. An exam ple w ould be: man intro which is a welt w ritten, fairly b rief introduction to
|grep blah file| the Linux com m and line.
156 C o m m o n C o d in g M is ta k e s jJTTM T
158 P y th o n B e g in n e r 's M is ta k e s
Planning Your
Code
Knowing how to code is great, but it's not going to get you very far if you don't know
w hat it is you're supposed to be coding. Small samples o f code don't need much
planning, but bigger projects do, so here are some tips on planning your code.
You w ill find that nearly all the professional developers out there w ill
set aside some time to plan out how their code is going to fit into the
wider project on which they're working. Regardless o f w hether they're
working as part of a team on the latest game, developing a w orkflow
user interface for the company, or creating a set o f automated
tasks that can be used across a num ber o f different platforms, each
developer will set out their code in a plan.
PSEUD O CO DE
Code Example
Line 1 RECEIVE userName FROM (STRING) KEYBOARD
Line 2 RECEIVE pmNmnber FROM (STRING) KEYBOARD
Line 3 IF userName VALID OR pinNumber VALID THEN
Line 4 Allow access to network
Line 5 ELSE
Line 6 SEND “Access Denied” TO SCREEN
Line 7 END IF
N = input
One o f the more popular m ethods of planning to code is using It’s very simplistic, but from
pseudocode. It's terms used in programming circles that allows the there the developer can
developer to represent the im plem entation of code, the sequence continue to plan the remainder
of the actions, using plain English and a mixture o f code examples o f the code needed w ithout
together with a flowchart or two to help 'picture' loops within the taking up too much valuable
coding project. t im e - b u t while also having a
readable plan o f action for how
For example, a developer who is planning to write a program that w ill the code is going to be formed.
check user input for odd or even numbers w ill probably begin with a
basic statem ent o f pseudocode: The actual writing o f the code,
therefore, takes place later on
A program to allow a user to check if the number is odd or even. in the project. Once there's
Then the basic statem ent can be expanded: a plan o f action in place, the
developer can share the plan with their colleagues, lead developers,
managers, and so on. Then the plan can be further tweaked to include
other aspects that the original developer may have missed or may
have been removed due to being being classed as unnecessary.
This process w ill not only trim the Fat o ff the code before it's even
written but w ill also help plug any gaps in the project before the hard
work of entering the code begins.
GRAPH PAPER
If you're planning to include graphics in you r project, such as a
platform game, then one of the best resources you can use - and
one that has been used since the early days o f coding games - is
graph paper.
G ET PLANNING
The w hole poin t o f planning is to create som ething easy to fo llo w that
w ill help you w rite the code fo r your project. Planning isn't supposed
to be a chore; it's there to aid you when you get stuck trying to w ork
ou t which variables you've used, w here you are in the game, with w hat
you're le ft and how the game w ill eventually pan ou t and end.
W hen planning, begin with sm all steps. Coding a Hangman game, for
example, begins w ith the plan to get the player's name, then includes
the w ord bank, drawing ou t the stages o f the Hangman, asking the
righ t questions, and finishing the game in one of two s ta te s - a win or
a lose - then asking if the player w ants another go.
Once you're used to planning it'll come naturally, and y o u 'll find
you rse lf thankful fo r all those post-it notes stuck to a sheet o f A3
paper, as w e ll as the ream s o f graph paper that d e ta il your characters
and level designs.
Finding
Resources
The Python com m unity is huge and spans countless websites and forum s on the
Internet, so finding extra help here and there isn't too much o f a problem. However,
finding good Python resources can be, so here are som e ideas for you to try.
You w ill reach a point in your Python coding experience when you need to rely f reeCodeCamp(A)
on some external resources to help you through a sticky patch in your project
Welcome t o free Code Cam p .o rg
or give you a bit of inspiration. Python resources are available throughout
Learn to code.
the Internet, but not all o f them are any good. If you spend any time looking
up code fo ra particular project, then you're likely to come across copious B uild p rojects.
That's one o f the main issues with resources for Python. W ith the language Since 2814, more than 40,080 freeCodeCainp.org graduates have gotten
Jobs at tech companies including:
being twenty-nine years old, and many different versions under the bridge,
there's a significant am ount o f content out there that's simply out of date - or Apple Google Amazon M icrosoft S p otify
just wrong for the version you're using. Newer versions, even by one number Sign in and get s ta rte d ( I t ' s fre e )
out, can have d ifferent outputs for your code from a previous version - it's
C e rtification s:
not always that case, but it can happen. Therefore, you need to find yourself Responsive Web Design
some trusted Python resources that work, or at least 90% would work, with the
version you're using and the code within.
One o f the first places that's worth turning to is: freeCodeCamp.org. This website P ytho n Exa m p le s
features a wealth o f code that covers most aspects o f the learning experience, □ TUTORIALS S EXAMPLES 0 REFERENCES © ONUNE COMPILER
even for those who are experts at Python. You'll find content that w ill take your Popular Examples
Python journey to new heights; with code snippets to help you access networking
elements, military-style encryption and more, and you can even gain certification
through the site.
If you're looking for resources about using graphics in Python, then Input ! [12, 35, 9, 55, 24)
Output 3 [74, 15, 9, 56, 17J
ProgramArcadeCames.com is a good place to start. This site has plenty of code for Input ! f l , 2, 31
the Pygame module, including moving an object around the screen using a mouse Output s [3, 2, 1)
or game controller, creating fractals, moving sprites, and an example o f a classic Approach #1 r I ind the length of the list and simply swap the first element with {n-1 )th element
GitHub is always worth a look. However, the code featured here isn't always up
to date, and you may find yourself having to convert Python 2 code into Python
iv Swopping
U-p « n«wLl»L[0)
3. Nevertheless, you do come across some gems from time to time, especially if
21
newlist[W] ■ newList[si£« - l]
newList[sl e - ] = temp
you look up the Pygame examples that users have uploaded. We recommend the
excellent Solarwolf, by Pete Shinners.
m p o r t pygsme
£ T h is c l a s s re p re se n ts t h e p la y e r
£ I t d r i v e s ” ron tn e ’ S p r it e ' c la s s in Fygame
c la s s Pla> e"(pygflrte.sp,,it e . :5 p r i t e ) :
£ C o n s t r u c t o r . P a ss in t r e co lo n o f t h e b lo c k , and i t s x and y p o s itio n
def in i t ( s e lf ) :
£ C a l l t h e p a re n t c la s s ( S p r it e ) c o n s t ru c t o r
STRONG GOOGLE-FU h e ig h t = 15
For then y o u 'll need to specify the Python version you're using; £ Uodate th e p o s it io n o f th e p la y e r
include Pygame, and include w hat it is you're looking for - it may •def update ( s e l f ) :
£ Get t h e c u r r e n t mouse p o s it io n . T h is r e t j m s t h e o o s it io n
sound like w e’ re teaching you to suck eggs, but effective searching £ as a l i s t o f two numbers,
pos = p y g am e.n ouse.g et_pos()
is often overlooked.
£ Fetch t i e x and y ou t o f th e l i s t , j u s t l i c e w e'd f e t c h l e t t e r s o j t
£ o f a s t r in g .
£ fJOTE: I f you want t o ceeo th e mouse a t t h e r o t t e n th e s c r e e n , j u s t
Again, it’s also w orth looking up w orking exam ples o f a type o f £ s e t y s 5S0, and no t update i t w ith t h e mouse p o s it io n sto red in
f p o s [ l]
game if you're looking for Pygame content. If you w an t to learn X = oos[0]
how to engineer sprites moving from one side o f the screen
to the other, then look up some exam ples o f Space Invaders, £ S e t t h e a t t r ib u t e f o r t h e too l e f t co rn e r where t h i s o b je c t i s
£ lo cated
which feature such m ovem ents. The same goes if you're making s e lf .r e c t .x = x
s e if .r e c t .y = y
a platform game, exam ine som e classic games that involved
platform ing, like M ario and so on. pygame. i n i t ( )
£ T h is re p r e s e n ts th e b a l l c o n t r o lle d by t h e p la y e r
p la y e r = P la y e r Q
£ -dd tn e o a l l t o th e l i s t o f p la y e r - c o n t r o lle d o b je c t s
a l l _ s p r i t e s _ l i s t . add (p la y e r )
£ ------------- H a m P ro g ra m L w p --------------------
w h ile not done:
f o r e ven t in pygame. e v e n t , g e t ( ) :
i f e v e n t .ty p e = pygame.QUIT:
done = True
£ — Game lo g i c
a ll_ s |id t e s _ lis t .u p d a t e ( )
£ — D is p la y f Drawing coda
£ C le a r tn e screen
s c r e e n , f i l l (U tTTE)
£ L in i t _t o £0 fram es p e r second
c lo c k .t ic k ( = 0 )
j/ js iis .q jit Q
© RERLTIME Q
-
SOFTURRE 54
m lA 1
t
then proceed to colour
its e lf in w hile the loading t i m e .s l e e p (seconds)
raster bars danced s c r e e n s .c l o s e ()
around in the borders of
#Main Cod e Start
the screen.
o s .s y s t e m ( 'els' if os.name == 'nt' else
Loading screens w ere a part o f the 'clear')
package and often the buy-in for loading screen (.5)
the w hole game as an experience. Some
rint ("\nYour code begi n s here...")
loading screens featured anim ations, or a countdow n fo r tim e
rem aining as the game loads, w hile others even w ent so far as to
File Edit Form at Run Options W indow Help
include some kind o f playable game. The poin t being: a loading
|import os
screen is n ot ju st an a rtistic part o f com puting history, b u t an lnport time
introduction to the program that's about to be run.
def loading_screen(seconds):
screens=open(“screens.txt“, *r *)
W hile these days loading screens may no longer be w ith us, in for lines in screens:
term s o f m odern gaming w e can still include them in ou r own print(lines, end='')
time.sleep(seconds)
Python content. Either ju st fo r fun, or to add a little retro-them ed screens.close()
spice to the mix.
(_)_ wWWWw
>rint ("\nYour code begins h e r e . ..
@
@@@ (.)0( ) vVWV ( ) ()
m m wwwww ( )\ ( ) () m m v (: )@( )
( ) •|/ V <m ) \ i1 ( )\ The code works in much the same way as the previous, except,
/ Y VI VI/ a ) M / l
\ 1 \ 1/ 1/ \ 1/ M/ 1/ \| \|/ instead o f reading from a te xt file, it's running through a For loop
1// \\|/// \\\|//\u|//y \|/// \\\|// \\|// Y\\|//
that prints Loading... follow ed by an animation of sorts, along w ith a
yo ur code b e g in s h e r e . . . percentage counter; clearing the screen every second and displaying
C;\Users\david\Docui!ients\Python\SplashScr> the new results. It's simple, yes, but quite effective in its design.
Save the code as screens.py, drop into a Command P rom pt or COMBINING TH E TWO
Term inal and execute it. The screen w ill clear and you r ASCII art
Flow about com bining the two elem ents we've looked at? Let's
inside the text file w ill load in line-by-line, creating a loading
begin w ith a Loading... progress bar, follo w ed by the loading
screen effect.
screen. A fte r that, you can include your own code and continue
you r program. Flere's the code:
LOADING...
timel
inpniNr
Luriuii iu loading bar(seconds):|
for loading in r a n g e (0,seconds+1) :|
percent = (loading * 100) // seconds!
pr int("\n") |
print("Loading..
p r i n t ("<" + ("-" * loading) + (' * (seconds-!
A n oth e r favourite introduction screen is th a t o f a sim ple loading
loading ) ) + "> " + str(percent) +
anim ation, w here the w ord loading is displayed, follow ed by
print("\n")|
some characters, and a percentage o f the program loaded. W hile
t i m e .s l e e p (
it may not take long for your Python code to load, the e ffe c t can
o s .system('els' if os.name == 'nt' els
be interesting.
'clear'
Create a New File in Python and enter the follow ing code:
def 1oa ding screen(seconds) :|
screens=open("screens.txt"
import time for lines in screens:|
print(lines, end='')|
def loading bar(seconds):
ti m e .sleep(seconds) |
for loading in ran g e (0,seconds+1):
screens.clo s e (
percent = (loading * 100) // seconds
print("\n") #Main
p r i n t ("Loading.. 1 loading_bar(10) |
p r i n t ("<" + C * loading) +
loading)) + "> " + str(percent) + "%") |
(seconds- V o s .s y s t e m ('els' if o s .name ==
loading screen(.5)1
'nt' else Aclear'
print("\n")
print ("\nYour code begins here.
t i m e .s l e e p (1)
os.system!'els' if os.name == 'nt' els You can, o f cours^, pull those functions up w herever and w henever
'clear') you w ant in you r cade and th e y'll display, as they should, at the
beginning. Rem em ber to have the ASCII text file in the same folder
#Main Code Start
as the Python code; or, at the screens=open("screens.txt”, 'r') part
loading b a r (10)
o f the code, point to w here the te xt file is located.
If you can think back to some o f the classic text adventures you
may have played in the past, consider the am ount o f work that was
needed to get them up and running. If you're not familiar with a text
adventure, then open a browser and go to http://textadventures.
co.uk/gam es/play/5zyoqrsugeopel3ffhz_vq. This is an online version
of the classic text adventure Zork.Zork was created for the DEC PDP
10 workstations, using the M D L programming language back in the
late seventies. Despite its age, it's still considered one o f the best text
adventures to play. The second crucial elem ent is choice. W ithout that, the player may as
w ell read the story from a book. It's the choice presented to the player
that makes the game an adventure. If the player chooses something
Welcome to ZORK.
wrong, they could be punished, whereas a correct choice could gain
Release 13 / Serial number 040826 / Inform V6.14 Library 6/7
W e s t o f H o u se
them gold or some other form o f reward. However, it doesn't always
This is an open field west o f a white house, with a boarded front door. need to be a positive or negative choice; after all, m ost common real-
There is a small mailbox here.
A rubber mat saying ’Welcome to Zork!' lies by the door. life decisions we make aren't life or death, they merely result in one
>open mailbox thing happening or another.
You open the mailbox, revealing a small leaflet
>read leaflet
(first taking the small leaflet) Locations are similarly important. Text Adventures rely on good the
WELCOME TO ZORK
locations featured in the game can draw a picture in the mind o f the
ZORK is a game o f adventure, danger, and low cunning. In it you will explore some o f the most amazing
territory ever seen by mortal man. Hardened adventurers have run screaming from the terrors contained player. W hether they're on a wooden ship in the middle of the sea or
within!
trying to escape a haunted mansion, each location has to stand out.
In ZORK the intrepid explorer delves into the forgotten secrets o f a lost labyrinth deep in the bowels of the
earth, searching for vast treasures long hidden from prying eyes, treasures guarded by fearsome monsters
and diabolical traps!
Items are also a vital requirement for a good adventure game. A
Zork, o r any o th e r te xt adventure game, features several elem ents player w ill need to be able to pick up, examine, take, and use, an item
necessary to m ake the game both interestin g and playable. from its location in the game. For example, your character could find a
key in the first location, pocket it, and then use it later on in the game
to unlock a door. You'll need to factor in the list o f possible items, and ■
INGREDIENTS F O R A you'll also need to factor in the real-world physics o f each item too. If
COM PELLING ADVEN TURE you have your adventurer enter a room with an anvil, then allowing
The first ingredient is a story, a plot that w ill take the player on a ride them to pick up the anvil and put it in their pocket isn’t particularly
through their own imagination. It doesn't necessarily have to include realistic. One o f the major drawbacks o f some text adventures, and
dragons, barbarians, spaceships, or other such things, but it needs to even modern graphical games, is the unrealistic carrying capability of
be engaging. Perhaps it could follow the theme of a m urder mystery, the player.
much in the same vein as an Agatha Christie novel, or it could be
something that explores the base fears o f people.
Although not always necessary, puzzles do Form an interesting aspect Lists, tu ples and dictionaries w ill be needed to store the
o f a text adventure. These puzzles can test the player's abilities various elem ents o f the game. These can be descriptions o f
and expand the game beyond simply finding an object and using characters w hom you’ ll meet, e ith e r friend or foe. Locations, with
it. Puzzles can range from using these objects correctly to achieve descriptions, th rou gh ou t the game; item s you 'll come across that
something to finding the correct route through a maze, with some can be used, along w ith a player inventory, which w ill grow or
being vital to the plot while others are simply there to give the player lessen depending on w hat the player has used/dropped/picked up.
something interesting to do. Ideally, puzzles should be easy near the
beginning o f the game and get progressively harder as your character Variables w ill be needed to hold v ita l statistics during gameplay,
advances through the game. the player's name, am ount o f strength, endurance, skill and health,
for example. You'll also need variables to hold the current score
or num ber o f moves used so far, plus any statistics regarding the
S m a 11 building other characters you 'll m eet.
THE CO D E * ----
It's im possible to list the code you 'll need fo ry o u r adventure
game since it'll be d iffe re n t from each reader to the next, but here
are som e pointers to help you out.
if c m d = = "1": d e f getcmd(c m d l i s t ) :
r a g g e d () c m d = input(name+">")
elif c m d = = "2": if c m d in cmdlist:
g u a r d s () return cmd
elif c m d = = "help":
d e f ragged(): p r i n t ("\nEnter y o u r choices as d e t a i l e d in
print("\n" * 200) t he game.")
pri n t ( ' " Y o u w a l k u p to t h e r a g g e d l o o k i n g m a n a n d p r i n t ("or e nter 'quit' to leave t he game")
g r e e t him. r e t u r n getcmd(cmdlist)
H e s m i l e s a t o o t h l e s s g r i n and,, w i t h a strange elif c m d = = "quit":
accent, says. p r i n t ("\n ")
"Buy m e a c u p of wine, a n d I'll tell y o u of time, s leep (1)
g r e a t treasure...'") p r i n t ("Sadly y o u r e t u r n to y our h o m e l a n d w ithout
time, s l e e p (2) f a m e or fortune...")
time, s leep (5)
d e f g u a r d s (): exit()
print("\n" *200)
pri n t ( ' " Y o u w a l k u p to the d a n g e r o u s l o o k i n g g u a r d s
a n d g r e e t them. if name = =" main ":
T h e g u a r d s look u p f r o m t h e i r d r i n k s a n d startO
snarl at you.
" W h a t d o y o u want, b a r b a r i a n ? " O n e g u a r d r e aches
for t h e h i l t of h i s sword../")
time, s l e e p (2)
Adventure Time
This, asyou can see, is just the beginning oF the adventure and •Adventure py - /home/pi/Documents/Python Code/Adventure py (3.4.2)*
takes up a Fair Few Lines oFcode. When you expand it, and weave file §dit Format Bun Qptions Windows Help
the story along, you'll find thatyou can repeat certain instances print<“W * 200)
such as a chance meeting with an enemy or the like. CR=0
S tre n g th s
Health=0
Luck=0
We've created each oFthe two encounters as a deFined set
p rin t("T h e mountains o f the north make fo r a hard l i f e . " )
of Functions, along with a list oF possible choices under the p r in t ( "Press Enter to r o l l the d ic e and see how stro n g ", name, “is : " )
in p u t()
cmdlist list, and cmd variable, o f which is also a deFined Function. Strength= randam .randint(1,20)
print(nam e, "has a Strength value o f : " . Strength)
Expanding on this is quite easy, just map out each encounter and p r in t ( " \ n lt ‘ s a hard l i f e indeed, and a l l northeners are born w a rrio rs ." )
p r in t ( “Press Enter to r o l l the d ic e and see the Combat R a ting f o r " , name+
choice and create a deFined Function around it. Providing the user in p u t( )
CR=random.randint(1, 30)
doesn't enter quit into the adventure, they can keep playing. print(nam e, "has a Combat R ating o f : - , CR)
p r in t ( "XnYoUr H ealth i s the t o t a l o f your Strength and Combat R a tin g .")
p n n t ( “Press Enter to se e", name+’" s " , "Health v a lu e .")
in p u t()
There's also room in the adventure Fora set oF variables designed Health=Strength+CR
print(nam e, “has a Health value o f : " . H ealth)
p r in t ( "\nEveryone needs a c e rta in amount o f lu ck to s u r v iv e ." )
For combat, luck, health, endurance and even an inventory or p r in t ( "Press Enter to r o l l the d ic e and see how lu ck y ", name, " i s . " )
in p u t( )
am ount of gold earned. Each successFul com bat situation can Luck=random .randintf1. 15)
i f Luck > 13:
reduce the main character's health but increase their com bat skills print(nam e, " i s lu ck indeed, and has a Luck value o f : " . Luck)
e ls e :
or endurance. Plus, they could loot the body and gain gold, or earn pnnt(nam e, “has a Luck value o f : " . Luck)
tim e .sle ep (5)
gold through quests. p rin t ( " \ n " *200)
p r in t ( "H ere 's your ch a ra cter s t a ts :\ n " )
print(nam e)
p r in t ( "\nCombat R ating CR)
Finally, how about introducing the Random module. This will p n n t ( "Strength =” . Strength)
p r in t ( "Health =", H ealth)
enable you to include an elem ent oFchance in the game. For p rin t( " L u c k =“ , Luck)
p r in t ( “\n" *5)
example, in combat, when you strike an enemy you will do a p r in t ( “Press En te r to s t a r t your adventure.
in p u t( )
random am ount o f damage as will they. You could even work out p n n tC 'M i" *200)
the maths behind improving the chance oFa better hit based on
p r in t ( ‘ ' You fin d y o u rs e lf at a sm a ll in n . T h e re 's l i t t l e g old in your purse
your oryo ur opponent's com bat skills, current health, strength and but your sword i s sharp, and y o u 're ready f o r adventure.
With you are three other custom ers.
endurance. You could create a game oFdice in the inn, to see if you A ragged lo oking man. and a p a ir o f dangerous lo oking g u a rd s .1•')
win or lose gold (again, improve the chances of winning by working def s t a r t ( ) :
p r i n t ( " \ n --------------” )
p rin t( " 0 o you approach t h e . . . " )
ou ty o u r luck Factor into the equation). p rin t ( " \ n " )
p r i n t ( “ l . Ragged looking man")
p r in t ( " 2 . Dangerous lo o k in g guards")
Needless to say, your text adventure can grow exponentially
and prove to be a w ork oF wonder. Good luck, and have Fun with
your adventure.
Retro Coding
There's a school o f thought, that to m aster the Foundations oF good coding skills you
need to have som e experience oF how code was w ritten in the past. In the past is a bit
oFa loose term, but mostly, it means coding From the 80s.
5 HOME recognised that one o f the 'best', and possibly m ost utilised, form of
18 PRINT "--- U N I T C O N V E R T E R --- “ BASIC from the 80s was that of BBC BASIC.
28 I N P U T " C F 3 A H - C E L O R CC3EL-Fft
H ; II •QJ
BBC BASIC was used on the Acorn BBC M icro range o f computers,
30 INPUT "ENTER UNIT “ ;U N
48 X = C U N I T - 3 2 ) *. 5
_ ✓ 9 utilising the M OS 6502-based processor technologies. It was one of
‘
50 .............
Y = <UNI 41T * >• 5> + 32
IF C * = I p II
60
?a
S I US;
IF CS
“}
= ‘C
THEN PRINT
T H E N __ P R I N T
“C E L
1F f lH
the quickest examples of BASIC and, thanks to an inline assembler, it
was also capable o f allowing the developers o f the time to write code
for different processor types, such as the Zilog Z 8 0 - a CPU present in
THE GOLDEN ERA O F CODE the ZX Spectrum, as w ell as many arcade machines.
While it may seem a little counterproductive to learn how to code in a The BBC Micro was designed and built by Acorn C o m pu te rs-a
language that's virtually obsolete, there are some surprising benefits company that is historically responsible for the creation o f the ARM
to getting your hands dirty with a bit o f retro coding. Firstly, learning CPU - the processor that's used in virtually every Android phone and
old code w ill help you build the structure of code as, regardless of tablet, smart TV, set top box and so on, as w ell as the Raspberry P i-
whether it is a language that was developed yesterday, or forty years so essentially, the BBC Micro is the grandfather o f the Raspberry Pi.
ago, code still demands strict discipline to work correctly. Secondly,
The BBC Micro was born in a time when the UK government was
everyday coding elements, such as loops, sub routines and so on, are
looking for a countrywide com puter platform to be used throughout
a great visual aid to learn in older code, especially BASIC. Lastly, it's
education. D ifferent companies bid, but it was the BBC’s Computer
simply good fun.
Literacy Project (the BBC Micro) that was chosen, due to its
±050 REM F O R I- ruggedness, upgradability, and potential for education. A s a result,
1060 REM PRINT
1070 REM NEXT I the BBC Micro, or the Beeb as it’s affectionately known, became the
1080 REM dominant educational com puter throughout the 80s.
1080 POKE 512, O
1100 POKE 513,6
111© REM
iiZG
1130
FOR
READ
1=1536
A BEEBEM
Naturally, you could scour eBay and look fo ra working BBC Micro to
GOING BASIC play around on, and it'll be a lot o f fun. However, for the sake o f just
getting hands-on with some retro code, we'll use one o f the best BBC
The easiest retro language to play around with is, wfthout doubt,
Micro emulators available: BeebEm.
BASIC. Developed back in the mid-sixties, BASIC (Beginner's All-
Purpose Symbolic Instruction Code) is a high-level programming BeebEm was originally developed for UNIX in 1994 by Dave Gilbert and
language whose design was geared toward ease o f use. In a time later ported to Windows. It is now developed by Mike Wyatt and Jon
when computers were beginning to become more accessible, Welch, who maintain the Mac port of the emulator, and is therefore
designers John Kemeny and Thomas Kurtz needed a language that available for Windows 10, Linux and macOS, as well as other platforms.
students could get to grips with, quickly and easily. Think of BASIC as a
If you're using W indows 10, simply navigate to http://www.mkw.
distant relation to Python.
me.uk/beebem/index.html, and download the BeebEM414.exe
that's displayed in the main screen.
TH EBEEB
The problem with BASIC is that there were so many different versions
available, across m ultiple 8-bit platforms, with
each having its own unique elem ents
on top of the core BASIC
functions. The BASIC that
was packaged with the
Com modore 64 was different
to that on the ZX Spectrum,
or the Atari home computers, Once downloaded, launch the executable and follow the on-screen
due to the differing hardware of instructions to install it. MacOS users can get everything they need
each system. However, it’s widely from: http://www.g7jjf.com/. However, Raspberry Pi and Linux users
will have to do a little nifty keyboard work before they can enjoy the clears the screen; although the Pi uses Clear instead o f CLS. W e’re also
benefits o f the Beeb on their screens. Here's how to get it working able to do some maths work, and play around with variables too:
under Linux:
sudo ap t - g e t u p d a t e && u p g r a d e |
|30 i f a > 40 p r i n t " Y o u ' r e o v e r 40 y e a r s o l d
[wget h t t p :/ / b e e b e m - u n i x .b b c m i c r o .c o m / d o w n l o a d / !
|40 i f a < 40 p r i n t " Y o u ' r e u n d e r 40 y e a r s old.
b e e b e m - 0 . 0 . 1 3 . t a r .gzl
R E M A r e a of c i rcle
Now enter the following lines, hitting Enter and answering Y to accept
20 I n p u t " E n t e r t he r a dius:
any changes:
30 l e t a r e a = PI*r*r|
40 p r i n t " The a r e a o f y o u r c i r c l e is:
sudo apt- g e t install l i b g t k 2 . - d e v l i b s d l l .2-devi
./ configure
ke >LIST
1 REM AREA OF A CIRCLE
2 CLS
20 INPUT "ENTER THE RADIUS: “ R
This may take some time, but when it's all done, simply enter: 30 LET AREA = PI*R*R
40 PRINT "THE AREA OF YOUR CIRCLE IS:
to start the BBC M icro emulator. ";AREA
50 PRINT ‘11
>
BBC BASIC
Once installed and pow ered up, BeebEm w ill display the defau lt As you'll notice, variables with a dollar ($) represent strings, nothing
BBC system start-up, along w ith a couple o f beeps. Those o f you after the variable, or a hash (#) represent floating point decimals; a
old enough to have been in a UK school in the 80s w ill certainly w hole integer has a % character, and a byte has an am persand (&).
recall this setup. The single quotes a fte r the Print on line 50 indicate a blank line, one
for each tick, while REM on line 1 is a comment, and thus ignored by
In BASIC, we use line numbers to determine which lines of code run in
the BASIC compiler.
sequence. For example, to print something to screen we’d enter:
Needless to say, there's a lo t you can learn, as w ell as having fun, with
BBC Computer 32K BBC BASIC. It's a rainy day project and something that's interesting to
Acorn DFS show the kids - this is how we rolled back in the 80s, kids!
Once you've typed the above in, press
There are a num ber o f sites you can visit to learn BBC BASIC, such
Enter and then type:
>10 PRINT "HELLO" as http://archive.retro-kit.co.uk/bbc.nvg.org/docs.php3.html.
>RUN See w hat you can come up with using BBC BASIC, or o th e r BASIC
HELLO
> types fo r d iffe re n t systems, and le t us know what you've created.
print(message) |
THE FINAL COUNTDOWN p r i n t ("<
Let's begin with some example code that w ill display a large
countdown from ten, then clear the screen and display a message. Iprint ("\n\n\n") I
The code itself is quite simple, but lengthy. You w ill need to start by
importing the OS and Time modules, then start creating functions The code in its entirety can be viewed
that display the numbers (see image below) and so on to 10. It'll take from within our Code Repository:
some time, but it’s worth it in the end. O f course, you can always take https://pclpublications.com/exdusives, where
a different approach and design the numbers yourself. you're free to copy it to your own Python IDLE
and use it as you see fit. The end effect is quite
The next step o f the process is to initialise the code settings and start
good and it'll be worth adding to your own games,
the countdown:
o r presentations, in Python.
From there, you w ill need to specify the im ported code in the
Countdown section:
RO CKET LAUNCH
Building on the previous
countdown example, we can
create an animated rocket that'll
launch after the Blast OFF!!
message has been printed. The
code would look something like:
d e f R o c k e t () :
highest roller wins the round and the losers' health drops as a result.
distanceFromTop = 2 0
It's an age-old combat sequence, used mainly in the Dungeon and
while T r u e :
Dragons board games and Fighting Fantasy novels, but it works well.
o s .s y s t e m ( 'els' =
if os.name = 'nt' else 'clear')
print("\n" * distanceFromTop) | The code you'll need to animate a dice roll is:
p r i n t (" A ")
p r i n t (" 11 ") i m p o r t os[
p r i n t (" 11 ") i m p o r t time|
p r i n t (" / 11 \ ")l from random import randint|
t i m e .s l e e p (0.2)
die [' \n O \n ']
o s .s y s t e m f 'els'
d i e . a p p e n d (" 0\n \nO ") #2
distanceFromTop -
|die.append ("0 \n 0 \n O") #3
if d i s t a n c e F r o m T o p <0:
d i e .a p p e n d ("0 0\n \nO O") #4[
d i s t a n c e F r o m T o p = 20
d i e .a p p e n d ("0 0\n 0 \nO O") #5|
JttMain C o d e B e g i n s |
p r i n t ( " \ n \ n\n\n")
i n p u t ( " P r e s s E n t e r to l a u n c h r o c k e t ..."|
You may need to tweak the 0 entries, to line up the dots on the
This w ill allow your m essage to be displayed and then, when the
virtual dice. Once it's done, though, you'll be able to add this
user has hit the Enter button, the rocket w ill launch.
Function to your adventure game code and call it up w henever your
Again, the code in its e ntirety can be Found in the Code Repository character, or the situation, requires some elem ent o f luck, combat,
at: https://bdmpublications.com/ code-portal. or chance roll o f the dice.
you can ask questions and experts w ill try and help you. It doesn't Q Simple rectangle terminal animation in Python 3.x
always work out, but m ost of the time, you’ll find what you're change its lie
Q&A torwork 1
Also, if you're after a simple animation then take to Google and Q: Carriage return escape character behaves like a newline in Python 3 and O S X
J trom "Learn Python the Hard Way" while Irue lor i in | T "--.T/tt'.TJ pnnt("%s\r % i, end=") It's suppo|
spend some time searching for it. While you may not Find exactly lo look like a little rotating bar like a busy animation or I searched and couidnt find an answer to this r
trying to use V as a carnage return in a program but it behaves like a newline instead. Here's the code I'm t
w hat it is you're aFter, you're bound to come across something to use. adapted tor Python
p>0ion mecos asked Jan 15 '14 by nonet
very like the desired eFFect; all you need to do is m odify it slightly
to accomplish your own goals. Q Belousov-Zhabotinsky (BZ) reaction animation code in python
SMALL CHUNKS
It would be w onderful to be able to M ean in gfu l naming for variables is a m ust to elim inate
work like Neo from The M atrix movies. com m on coding mistakes. Having le tte rs o f the alphabet
Simply ask, your operator loads it into is fine but w hat happens when the code states there's
your m em ory and you instantly know a problem with x variable. It's not too d ifficu lt to name
everything about the subject. Sadly variables lives, money, p la y e rl and so on.
though, we can't do that. The first
major pitfall is som eone trying to learn 1 var points = 1023;
2 var lives = 3 ;
too much, too quickly. So take coding in
3 var totalTime - 45;
small pieces and take your time. 4 write("Points: "tpoints);
5 write("Lives: "+lives);
6 write("Total Time: "+totalTime+" secs");
7 write ("-------------------------- ") ;
8 var totalScore = 0;
9 write("Your total Score is: "+totalScore);
//COMMENTS
Use com m ents. It’s a simple concept b ut com m enting on
you r code saves so many problem s when you next come to
lo ok over it. Inserting com m ent lines helps you quickly sift
through the sections o f code that are causing problems;
PLAN AHEAD
also useful if you need to review an old e r piece o f code.
W hile it's great to wake up one m orning and decide to code
orig += 2 ? a classic te xt adventure, it’s n ot always practical w ith o u t a
target +■ 2;
good plan. Sm all snippets o f code can be w ritten w itho u t
— n;
too much thou ght and planning bu t longer and m ore in-
55 >
5c #endxf depth code requires a good w orking plan to stick to and
if (n == 0) help iron out the bugs.
return?
6° //
// Loop unrolling. Bare be dragonj.
62 //
c J
// (n & (-3)) la the greateat multiple of 4 r
// In the while loop ahead, orig will move ov
^ MamMenu
==D
// increments (4 elements of 2 bytes).
// end rcarJcs our barrier for not falling outa
char const * const end = orig + 2 * (n & (~3)
c J
Coding SProgramming
Common Coding Mistakes
USER ERROR
User input is often a paralysing mistake in code. For
example, when the user is supposed to enter a num ber for
their age and instead they enter it in letters. O ften a user
can enter so much into an input that it overflow s some
internal buffer, thus sending the code crashing. Watch those
BACKUPS
user inputs and clearly state what's needed from them.
Alw ays make a backup o f you r work, w ith a secondary
Enter an integer number
backup for any changes you've made. M istakes can be
aswdfdsf rectified if there's a good backup in place to revert to for
You haue entered wrong input
s
those tim es when som ething goes wrong. It's much easier
You haue entered wrong input to start w here you le ft off, rather than starting from the
!"£"!£!”
beginning again.
You haue entered wrong input
sdfsdf213213123
You haue entered wrong input
123234234234234234
You haue entered wrong input
12
the number i$: 12
RE-INVENTING WHEELS r
You can easily spend days trying to fathom ou t a section SECURE DATA
o f code to achieve a given resu lt and it's frustrating and
often tim e-wasting. W hile it's equally rewarding to solve If you’re w riting code
the problem yourself, often the same code is out there on to deal w ith usernames
the Internet som ew here. D on't try and re-invent the wheel, and passwords, or
lo ok to see if some else has done it first. other such sensitive
data, then ensure
that the data isn't in
cleartext. Learn how
to create a function
to encrypt sensitive
data, p rior to feeding
into a routine that can
transm it or store it
w here som eone may be
able to get to view it.
V_____________________________ / V
D EF B EG IN N ER(MISTAKES= 10)
Here are ten common Python programming mistakes most beginners Find themselves making. Being able to identiFy these
mistakes will save you headaches in the Future.
* sec up counting
score = 0
p y th o n t sec up font
fone = pygame.fone.Sysfonc(1califcxa', 50)
def makeplayerO :
A bout D o w n lo a d s D o c u m e n ta tio n C o m m u n ity S u c c e ss S to rie s New player = pygame.Rect(370, 635, 60, 25)
/C\TT
def makeinvaders(invaders):
Download the latest version for Windows y = 0
for i ir. invaders:
x = 0
for 3 in range(1 1 ):
invader = pygame.Rect(75+x, 75+y, 50, 20)
Wondering which version to use? Here's more about the difference i .append(invader)
x += 60
between Python 2 and 3.
TH E IN TERN ET C O M M E N T IN G
Every programmer has and does at some point go on the Internet Again w e m ention com m enting. It's a hugely im portant Factor in
and copy som e code to insert into their own routines. There's programming, even iFyou're the only one who is ever going to view
nothing wrong with using others' code, but you need to know how the code, you need to add com m ents as to what's going on. Is this
the code works and w hat it does beForeyou go blindly running it on Function w here you lose a life? W rite a com m ent and help you, or
your own computer. anyone else, see what's going on.
# set up pygame
Create/delete a ,txt file in a python program
pygame.init()
mainClock = pygame.time.Clock ()
I have created a program to grab values from a text file. A s you can see, depending on the value of the
results, I have an if/else statement printing out the results of the scenario.
# set up the window
M y problem is I want to set the code up s o that the i
fstatement creates a simple .txt file called data.txt
to the C:\Python\Scripts directory.
width = 800
height = 700
In the event the opposite is . I would like tire else statement to delete this .txt file if it exists.
0 screen = pygame.display.set_mode((width, height), 0, 32) 0 0 1
I’m a novice programmer and anything I've looked up or tried hasn't worked for me, s o any help or pygame.display.set_caption('caption')
assistance would be hugely appreciated.
0 1 1
dublin = X .readlines(125) moveUp = False 11 1
percentaBe_velue = [flo a t( re .f in d a ll( 1kd+\. \d+(?=\X)|\d+\.\d+<: i[- l] )[6 ] ) foi• i in [Ci moveDown = False
1 o 1 print(percentage_value)
)u
1 0
i t set up direction variables n
u n
u
111 i f percentage_value[0] <= percentage_value[l]; i DO W NLEFT = 1
0 1 else:
print('W ebsite i s hosted in D u blin')
0 D O W N R IG H T = 3 0 10
;
10 10 1 10 0 0 0 0 1 10 1 1
o
0 0i n 0
°
0 i
1 0 0 ) 1 1 1 1 10 o 10 1 o 1 10 1 0
goding & Programming
0 0 1 11 10 0 0 10 1 0 o0 1 0
o
0
o
0 1 1 1 0 o 00o 1 i 00 0 0 1 00 1 1 1 1 1 1 0 0 0 11 10 10 0 1
Python Beginner's Mistakes
Which w ill return 1 to 10. And so on. The colon is w hat separates the code, and creates the
indents to which the follow ing code belongs to.
L* Python 3.6.2 Shell - □ X
def hangman_over(self):
recurr se l f .hangman_won() or (len(self.missed_letters) — 6)
VOID(C++, MISTAKES)
Admittedly it's not just C++ beginners that make the kinds oF errors we outline on these pages, even hardened coders are
prone to the odd mishap here and there. Here are some common issues to try and avoid.
U N D E C L A R E D IDENTIFIERS STD N A M E S P A C E
A com m on C++ mistake, and to be honest a common mistake with Referencing the Standard Library is com m on for beginners
most programming languages, is when you try and output a variable throughout their code, but if you miss the std:: elem ent o f a
that doesn't exist. Displaying the value o f x on-screen is fine but not statem ent, your code errors out when compiling. You can com bat
if you haven't told the com piler w hat the value o f x is to begin with. this by adding:
#include <iostream> i n t a, b, c, d;
a=10;
b=20;
int maint) c=30;
{ d =40;
std::cout « x; cout « a, b, c, d;
} }
S E M IC O LO N S GCCORG++
Rem em ber that each line o f a C++ program m ust end with a If you're com piling in Linux then you w ill no doubt come across
semicolon. If it doesn't then the com piler treats the line with the gcc and g++. In short, gcc is the Gnu Com piler Collection (or Gnu
missing sem icolon as the same line with the next semicolon on. This C Com piler as it used to be called) and g++ is the Gnu ++ (the C++
creates all m ann erof problem s when trying to compile, so don't version) o f the compiler. If you're compiling C++ then you need to
forget those semicolons. use g++, as the incorrect com piler drivers w ill be used.
double d;
w h ile (c in » d ) v.push_back(d).j / / read elements in t mainU
i f ( Ic i n .e o f O ) { (/ cfiecft- i f in pu t f a ile d
c e r r << "format e r r o r W . {
/ / e r r o r return
i in t x;
cout << "read ” << v .s iz e Q •« " elementstn” ; strin g mystring = This is a string \n ;
re v e rs e (v.b e g in C ),v.e n d ()> ;
cout << "elements in reverse o rd e r;\n ” ;
cout « ‘Wh a t ’s the value of x? ;
f o r ( i n t i » 0; i c v .s i z e f ) ; -n -i) cout « v £ i] « A n ';
cin » x;
return 0 ; / / success return
} cout « x;
{
cout « \n\n ;
cout « mystring;
QUOTES
Missing quotes is a common mistake to make, for every level of user. >
Remember that quotes need to encase strings and anything that's
going to be outputted to the screen or into a file, for example. Most
compilers errors are due to missing quotes in the code.
INITIALISE VARIABLES
In C++ variables aren’t initialised to zero by default. This means if
you create a variable called x then, potentially, it is given a random
number from 0 to 18,446,744,073,709,551,616, which can be
difficult to include in an equation. When creating a variable, give it
the value of zero to begin with: x = 0 .
in t m a in O
t
i n t x;
x=0;
cou t « x;
EXTRA SEMICOLONS
While it's necessary to have a semicolon at the end of every C++ line,
there are some exceptions to the rule. Semicolons need to be at
the end of every complete statement but some lines of code aren't
complete statements. Such as:
A.OUT
#include
A common mistake when compiling in Linux is forgetting to name
if lines
your C++ code post compiling. When you compile from the Terminal,
switch lines
you enter:
If it sounds confusing don't worry, the compiler lets you know where
g++ c o d e .cpp
you went wrong.
This compiles the code in the file code.cpp and create an a.out file
// Program to print positive number entered by the user
// If user enters negative number, it is skipped that can be executed with ./a.out. However, if you already have code
#include <iostream> in a.out then it's overwritten. Use:
using namespace std;
S watch
M ANUAL
C++
vm.r ultlmaie 'o™«eHng V~rom«W, < < « & P y th o n
§5 Manual >«ev
•uictv Thooasential codjna I L ' J *I
progtammng
,C “ e *
Not only can you learn new skills and master your
tech, but you can now SAVE 25% off all of our coding
and consumer tech digital and print guidebooks!
NYHF23CN
www.pclpublications.com
Get Your Exclusive
FREE Gift Worth
£9.99 Here!
Download FREE Software! Great G am ^ i Essential
Hardware!
Your FREE
Copy of 1
■
Q 9 £ mazing
GADGETS
Tech Shopper A P P S & G A M ES IN SID E'
Magazine a
Head over to your web Do you need a
Home Security
browser and follow these Chromebook?
Rflad our expert guide
to Google’s notebook!
Inside & Out!
Discover how to keep your
home safe and secure!
simple instructions...
The Essent
Guide for tl ^ F irsr
Time Progt mmer
IciRLBONVJS
, a 170 page
Nlagaz'ne
The Complete Manual Series: device. It remains the purchaser’s sole responsibility to determine acknowledged. Relevant graphic imagery reproduced with
the suitability of this book and its content for whatever purpose. courtesy of Lenovo, Hewlett- Packard, Dell, Microsoft, Samsung,
Coding & Programming
Any app images reproduced on the front and back cover are Linux Mint, NASA, and Apple. Additional images contained within
21 | ISBN: 978-1-914404-36-8 solely for design purposes and are not representative of content. this publication are reproduced under licence from Shutterstock.
Published by: Papercut Limited We advise all potential buyers to check listing prior to purchase Prices, international availability, ratings, titles and content are
Digital distribution by: Readly, Zinio & Pocketmags for confirmation of actual content. All editorial opinion herein is subject to change.
© 2024 Papercut Limited All rights reserved. No part of this that of the reviewer - as an individual - and is not representative of All information was correct at time of publication. Some content
publication may be reproduced in any form, stored in a retrieval the publisher or any of its affiliates. Therefore the publisher holds may have been previously published in other volumes or titles.
system or integrated into any other publication, database or no responsibility in regard to editorial opinion and content.
commercial programs without the express written permission of This is an independent publication and as such does not Papercut Limited
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
necessarily reflect the views or opinions of the manufacturers or
hardware and software, applications or products contained within.
This publication is not endorsed or associated in any way with
3 Registered in England & Wales No: 04308513