0% found this document useful (0 votes)
107 views

Coding Programming - A Guide For Beginners 10 2021-03-07

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views

Coding Programming - A Guide For Beginners 10 2021-03-07

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

techgo

Coding
Tricks and Tips
Gain
Insider
Skills

Next level Advanced Rediscover


Secrets & Fixes Guides & Tips Your Device
Discover more of
our guides...
techgo techgo techgo techgo

Photoshop
Tricks and Tips
Android Mac Black & White
Photography
Tricks and Tips Tricks and Tips Tricks and Tips
Gain
Gain Insider
Insider Skills
Skills
Gain
Insider
Skills
Gain
Insider
Skills

Next level Advanced Rediscover Next level Advanced Rediscover Next level Advanced Rediscover Next level Advanced Rediscover
Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device

techgo techgo techgo techgo

Cloud Python Coding C++ & Python


Tricks and Tips
Computing Tricks and Tips Tricks and Tips Gain
Tricks and Tips Gain
Insider Gain
Insider
Skills
Skills Insider
Gain Skills
Insider
Skills

Next level Advanced Rediscover Next level Advanced Rediscover Next level Advanced Rediscover Next level Advanced Rediscover
Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device

NEW! | Gmail | Drive | Chrome | Maps | Play BDM’s


Made Easy Series
techgo techgo techgo techgo
The Complete
Photography
Tricks and Tips
FRITZ!Box Google GoPro
Tricks and Tips Guidebook
BDM’s Made Easy Series The Complete

Tricks and Tips


Learn how to master Google’s unmissable free apps
Tricks and Tips
Gain Gain
Gain Over
Insider
27der
Gain Insider
Insider
Skills
Skills 8Insi ls
tips
hints & e
Skills
Skil
insid
Guidebook Volume 19

£9.99
Volume 19
US$19.99
Can$19.99
Aus$17.99
NZ$18.99
100% Independent

Enhance & protect Get the best Discover apps for Keep your photos
Next level Advanced Rediscover Next level Advanced Rediscover your privacy
Next level applicationsAdvanced
for free work & play Rediscover
& docs safe Next level Advanced Rediscover
Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device

techgo techgo techgo techgo

Instagram
Tricks and Tips
iPhone iPad Landscape
Photography
Tricks and Tips Tricks and Tips
Gain
Insider Gain
Tricks and Tips
Skills Insider
Skills

Gain Gain
Insider Insider
Skills Skills

Next level Advanced Rediscover Next level Advanced Rediscover Next level Advanced Rediscover Next level Advanced Rediscover
Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device
techgo

Coding
Tricks and Tips
Welcome back... Having completed our exclusive For Beginners
digital guidebook, we have taught you all you need to master the
basics of your new device, software or hobby.
Yet that’s just the start!

Advancing your skill set is the goal of all users of consumer


technology and our team of long term industry experts will help you
achieve exactly that. Over this extensive series of titles we will be
looking in greater depth at how you make the absolute most from
the latest consumer electronics, software, hobbies and trends!
We will guide you step-by-step through using all the advanced
aspects of the technology that you may have been previously
apprehensive at attempting. Let our expert guide help you build your
understanding of technology and gain the skills to take you from a
confident user to an experienced expert.

Over the page our journey continues, and we will be


with you at every stage to advise, inform and ultimately
inspire you to go further.
Contents
6 Coding with Windows 10 Batch Files 22 Coding on Linux
8 What is a Batch File? 24 Why Linux?
10 Getting Started with Batch Files 26 The Best Linux Distributions
12 Getting an Output 28 Equipment You Will Need
14 Playing with Variables 30 Creating a Linux Installer on Windows
16 Batch File Programming 32 Installing Linux on a PC
18 Loops and Repetition 34 Installing a Virtual Environment
20 Creating a Batch File Game 36 Installing Linux in a Virtual Environment
38 Getting Ready to Code in Linux
40 Creating Bash Scripts – Part 1
42 Creating Bash Scripts – Part 2
44 Creating Bash Scripts – Part 3
46 Creating Bash Scripts – Part 4
48 Creating Bash Scripts – Part 5
50 Command Line Quick Reference

52 Code Projects and Ideas


54 Planning your Code
56 Finding Resources
58 Creating a Loading Screen
60 Planning a Text Adventure
62 Text Adventure Script
64 Retro Coding
66 Text Animations
68 Common Coding Mistakes
70 Python Beginner’s Mistakes
72 C++ Beginner’s Mistakes

4 www.bdmpublications.com
Contents

Master Python
with the help of
our fantastic Code
Portal, featuring
code for games,
tools and more.

Ch
BDM eck out
’s Cod

60 FR
e Por
tal

Pyth EE
21,50 on progra
0 line m
s of c s
Visit:
http
ode
bdmp
ublica s://
t
code ions.com
-port /
al

“Within these pages, you’ll find the foundations and


fundamentals for Python and C++, two of the most
powerful languages in the world that are used by
the likes of NASA, Microsoft, Apple and throughout
the Internet. These languages are used in Big Data,
Encryption, AI, gaming, science, engineering and
advanced mathematics. From visualising black holes
millions of light-years away to using technology to
help solve the environmental crisis, Python and C++
are at the forefront of code.”

@bdmpubs BDM Publications www.bdmpublications.com

www.bdmpublications.com 5
Coding with Windows 10 Batch Files

6 www.bdmpublications.com
Coding with
Windows 10
Batch Files
Did you know that Windows has its own built-
in scripting language? Batch files have been
around since the early days of Windows, and
while they are overshadowed by the might of
Windows’ modern graphical user interface,
they are still there and still just as capable as
they were thirty years ago.

Batch file programming is a skill that system


administrators still use, so it’s worth spending
a bit of time learning how they work, and
what you can do with them. This section
introduces batch files, and covers user
interactions, variables, loops and even a batch
file quiz game to inject an element of fun.

www.bdmpublications.com 7
Coding with Windows 10 Batch Files

What is a Batch File?


The Windows batch file has been around since the early days of DOS, and was once a
critical element of actually being able to boot into a working system. There’s a lot you
can do with a batch file but let’s just take a moment to see what one is.

.BAT MAN
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, an Autoexec.bat file could be created to

When a user powered


up their DOS-based
computer, and once the
BIOS had finished checking
the system memory
and so on, DOS would
look to the Config.sys
file to load any specific
display requirements
and hardware drivers,
allocate them a slot in the
available memory, assign
any memory managers
and tell the system where
the Command.com file,
which is the command line
interpreter for DOS, was.
Once it had done that, then
the Autoexec.bat file took
over and ran through each

The Autoexec.bat file was


a PC user’s first experience
with a batch file.

8 www.bdmpublications.com
What is a Batch File?

BATCH FILE POWER


Just like any other programming interface that can directly
interrogate and manipulate the system, batch files require
a certain amount of care when programming. It’s hard to
damage your system with a batch file, as the more important
elements of the modern Windows system are protected by
the User Account Control (UAC) security; UAC works by only
allowing elevated privileges access to important system files.
Therefore if you create a batch file that somehow deletes a
system file, the UAC activates and stop the process.

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.

That said, you’re not likely to create a batch file that


intentionally wipes out your operating system. There are
system controls in place to help prevent that; but it’s worth
mentioning as there are batch files available on the Internet
that contain malicious code designed to create problems.
Much like a virus, a rogue batch file (when executed with
Administrator privileges) can cause much mayhem and system
damage. In short, don’t randomly execute any batch file
downloaded from the Internet as an Administrator, without
first reviewing what it does.
Batch files were often used as utility programs, to help users with
complex tasks. You can learn more about batch files in the coming pages, so
don’t worry too much about destroying your system with one.
All this just demonstrates how powerful the humble batch file
load the network card driver and automatically gain access to the can be.
network. Each of these unique setups would be loaded on to a
floppy disk and booted as and when required by the user.

The Autoexec.bat was the first such file many users came across in
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
translating complex processes into something far simpler.

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.

So what do you need to start batch file programming in Windows?


Well, as long as you have Windows 10, or any older version of
Windows for that matter, you can start batch file programming
immediately. All you need is to be able to open Notepad and get to
the command prompt of Windows. We show you how it all works, so You can create complex batch files or simple ones that display
read on. ASCII images on screen.

www.bdmpublications.com 9
Coding with Windows 10 Batch Files

Getting Started with


Batch Files
Before you begin to program with batch files, there are a few things you need to know.
A batch file can only be executed once it has the .bat extension and editing one with
Notepad isn’t always straightforward.

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

STEP 1 The Windows STEP 3 While at the command prompt window, enter:
command dir/w. This lists all the files and directories from
prompt may look a little where you are at the moment in the system. In this case, that’s your
daunting to the newcomer Home directory that Windows assigns every user that logs in. You
but it’s simply another can navigate by using the CD command (Change Directory). Try:
interface (or Shell) used to
cd Documents
access the filesystem. You
can go anywhere you like in Then press Return.
the command prompt, as
you would with the graphical
interface. To begin, click on
the Windows Start button and
enter CMD into the search box.

STEP 2 Click on the search result labelled Command Prompt STEP 4 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
newly created Batch Files.
cd Batch Files
You won’t need the quotes to change directories.

10 www.bdmpublications.com
Getting Started with Batch Files

STEP 5 Now that you have the directory set up, where you STEP 8 Back at the command prompt window, enter:
store your batch files, here is how you can create dir/w again to list the newly created Test.bat file.
one. Leave the command prompt window open and click 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 dir 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.

STEP 6 To create your first batch file, enter the following STEP 9 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
@echo off
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
that feature off for the whole script; with the ‘@’ (at) sign to apply
that command to itself.

STEP 7 When saving anything in Notepad the default


extension is .txt, to denote a text file. However, you
STEP 10 The echo command displays whatever is after it
want the extension to be .bat. Click on File > Save As and navigate
to the screen. Right-click the Test.bat file from
to the newly created Batch Files directory in Documents. Click the
Windows Explorer and select Edit to add more echo commands if
drop-down menu Save as Type, and select All Files from the menu. In
you like. Try this:
File Name, call the file Test.bat.
@echo off
echo Hello World!
echo This is my first batch file
echo.
echo With a blank line between!
Remember to save each new change to the batch file.

www.bdmpublications.com 11
Coding with Windows 10 Batch Files

Getting an Output
While it’s great having the command prompt window 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 some output.

INPUT, OUTPUT
Batch files are capable of taking a normal Windows command and executing it, while also adding extra options and flags in to
the equation.

STEP 1 Let’s keep things simple to begin with. Create a new STEP 3 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 YOURNAME with your Windows username, and double-
c:\users\YOURNAME\dirview.txt
click the dirview.txt file, you can see the batch file’s output.
Substitute YOURNAME with your Windows username.

STEP 2 The new line uses the dir command to list the STEP 4 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.txt 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.

12 www.bdmpublications.com
Getting an Output

OUTPUT WITH VARIABLES


Variables offer a more interesting way of outputting something to the screen and create a higher level of interaction between
the user and the batch file. Try this example below.

STEP 1 Create a new batch file and call it name.bat. Start STEP 4 This is extremely useful if you want to create a
with the @echo 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%
@echo 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.
echo Thanks for logging in. Currently the network
is operating at 100%% efficiency.
echo.
echo Your Home directory is located at: %HOMEPATH%
echo The computer name you’re logged in to is:
%COMPUTERNAME%
echo.

STEP 2 The set /p name creates a variable called name,


with the /p part indicating that an ‘=prompt string’
is to follow. The Set command displays, sets or removes system
and environmental variables. For example, while in the command
prompt window enter: STEP 5 Save and execute the batch file changes; you can
overwrite and still use name.bat if you want. The
set
batch file takes the current system variables and reports them
To view the current system variables. Note the name= variable we accordingly, depending on the user’s login name and the name of
just created. the computer. Note: the double percent symbol means the percent
sign will be displayed, and is not a variable.

STEP 6 Alternatively, you can run the batch file and display
it on the user’s desktop as a text file:
@echo off
echo Hello, %USERNAME%. > c:%HOMEPATH%\user.txt
STEP 3 Variables stored with Set can be called with the
echo. >> c:%HOMEPATH%\user.txt
%VARIABLENAME% syntax. In the batch file, we
echo Thanks for logging in. Currently the network
used the newly created %name% syntax to call upon the contents of
is operating at 100%% efficiency. >> c:%HOMEPATH%\
the variable called name. Your username, for example, is stored as a
user.txt
variable. Try this in a batch file:
echo. >> c:%HOMEPATH%\user.txt
echo Hello, %USERNAME%. What are you doing? echo Your Home directory is located at: %HOMEPATH%
>> c:%HOMEPATH%\user.txt
echo The computer name you’re logged in to is:
%COMPUTERNAME% >> c:%HOMEPATH%\user.txt
echo. >> c:%HOMEPATH%\user.txt
notepad c:%HOMEPATH%\user.txt
The > outputs to a new file called user.txt, while the >> adds the
lines within the file.

www.bdmpublications.com 13
Coding with Windows 10 Batch Files

Playing with Variables


There’s a lot you can accomplish with both the system and environmental variables,
alongside your own. Mixing the two can make for a powerful and extremely useful
batch file and when combined with other commands, the effect is really impressive.

USING MORE VARIABLES


Here’s a good example of mixing system and environmental variables with some of your own creation, along with a number of
external Windows commands.

STEP 1 Create a new batch file called list.bat and start it off STEP 3 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%.
cls 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

STEP 2 Save and execute the batch file. Within the STEP 4 What’s happening here is the batch file asks the user
command prompt you 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.

14 www.bdmpublications.com
Playing with Variables

STEP 5 It’s always a good idea, when creating text files STEP 8 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.
cls
del /Q view.txt
del /Q list.txt
echo All files deleted. System clean.

STEP 6 The additions to the batch file simply clear the


command prompt window (using the cls command)
and delete both the view.txt and list.txt files that were created by
the batch file. The /Q flag in the del command means it deletes
the files without any user input or notification. The final message
STEP 9 This action triggers the UAC warning message,
informs the user that the files are removed.
asking you if you’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
of action: the UAC is there to protect your system. In this case,
however, click Yes.

STEP 7 Depending
on how
your system is configured,
you may not get any
directory information
at all or a message
stating Access Denied.
This is because the UAC STEP 10 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 folder and 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.

www.bdmpublications.com 15
Coding with Windows 10 Batch Files

Batch File Programming


It’s the little additions we can make to a batch file that help it stand out and ultimately
become more useful. While the Windows graphical interface is still king, the command
line can do just as much, and this is where batch files come into their own.

SEARCHING FOR FILES


Here’s an interesting little batch file that you can easily extend for your own use. It asks the user for a file type to search for
and displays the results.

STEP 1 We are introducing a couple of new commands STEP 3 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: @echo off
cls
@echo off
color 2
cls
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
notepad.exe found.txt
cls
color
del /Q found.txt

STEP 2 The new command in this instance is color STEP 4 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.

16 www.bdmpublications.com
Batch File Programming

CHOICE MENUS
Creating a menu of choices is a classic batch file use and a good example to help expand your batch file programming skills.
Here’s some code to help you understand how it all works.

STEP 1 Rather than using a variable to process a user’s STEP 4 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:
@echo off
@echo off cls
cls echo.
choice /M “Do you want to continue? Y/N” echo ---------------------------------------------
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.
echo Press 2 for c:\Documents
echo.
echo Press 3 for c:\Pictures
echo.
echo Press 4 for c:\Videos
echo.
echo ---------------------------------------------
STEP 2 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 No. Goodbye. STEP 5 Now add the Goto sections:
goto End
:Y :Videos
echo. cls
echo You chose Yes. Hello CD %HOMEPATH%\Videos
echo You are now in the Videos directory.
:End
goto End
:Pictures
cls
CD %HOMEPATH%\Pictures
echo You are now in the Pictures directory.
goto End
:Documents
cls
CD %HOMEPATH%\Documents
echo You are now in the Documents directory.
STEP 3 The output from your choice is different depending on
goto End
whether you pick Y or N. 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 cls
important to remember to follow your Goto commands. CD %HOMEPATH%\Music
echo you are now in the Music directory.
goto End
:End

STEP 6 When executed, the batch file displays a menu and with
each choice the code changes directory to the one the
user entered. The %HOMEPATH% system variable will enter the currently
logged in user’s Music, Pictures and so directories, and not anyone else’s.

www.bdmpublications.com 17
Coding with Windows 10 Batch Files

Loops and Repetition


Looping and repeating commands are the staple diet of every programming language,
including batch file programming. For example, you can create a simple countdown or
even make numbered files or directories in the system.

COUNTERS
Creating code that counts in increasing or decreasing number sets is great for demonstrating loops. With that in mind, let’s look
at the If statement a little more, alongside more variables, and introduce the Else, Timeout and eof (End of File) commands.

STEP 1 Start by creating a new batch file called count.bat. STEP 3 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
cls @echo off
set /a counter=0 for /L %%n in (1,1,99) do echo %%n
:numbers
set /a counter=%counter%+1
if %counter% ==100 (goto :eof) else (echo
%counter%)
timeout /T 1 /nobreak > nul
goto :numbers

STEP 4 Breaking it
down, there’s
For, then the /L switch, which
handles a range of numbers.
Then the parameter labelled as
STEP 2 The count.
%%n to denote a number. Then
bat code
the in (1,1,99) part, which tells
starts at number one and
the statement how to count,
counts, scrolling down the
as in 1 (start number), 1 (steps
screen, until it reaches 100.
to take), 99 (the end number).
The Timeout command
The next part is do, meaning DO
leaves a one second gap
whatever command is after.
between numbers and the
Else statement continues
until the counter variable
equals 100 before going to
the eof (End Of File), thus
closing the loop.

18 www.bdmpublications.com
Loops and Repetition

STEP 5 You can include the pause between the numbers STEP 8 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:
@echo off @echo off
for /L %%n in (1,1,99) do (echo %%n & timeout /T 1 FOR %%F IN (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,
/nobreak > nul) s,t,u,v,w,x,y,z) DO (md C:\test\%%F)

STEP 6 One of the great time saving uses of batch files is to STEP 9 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 not sound 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

STEP 7 If you open Windows Explorer, and navigate to the STEP 10 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 user1.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:
@echo off For /? > forhelp.txt
for /L %%n in (1,1,25) do copy nul User%%n.txt

www.bdmpublications.com 19
Coding with Windows 10 Batch Files

Creating a Batch File Game


@echo off
Based on what you’ve looked at Cls
so far with batch files, you can :start
set /a score=0
probably come up with your own set /a question=0
cls
simple text adventure or multiple- set /p name= What is your name?
choice game. Here’s one that we
:menu
created, with which you’re free to cls
echo.
edit and make your own. echo ****************************************************
**
echo.
echo Welcome %name% to the super-cool trivia game.
Make up your own questions but how about also echo.
including an introductory or loading screen? Make your echo Press 1 to get started
loading screen in a separate batch file and save it as echo.
screens.bat (for example). Then, from the main game echo Press 2 for instructions
batch file, you can load it at the beginning of the file echo.
with the ‘call’ command followed by colour to reset echo Press Q to quit
echo.
the game’s colours:
echo ****************************************************
**
@echo off
choice /C 12Q
Cls
if errorlevel 3 goto :eof
Call screens.bat
if errorlevel 2 goto Instructions
color
if errorlevel 1 goto Game
:start
set /a score=0
:Instructions
set /a question=0
cls
cls
echo.
set /p name= What is your name?
echo **************************************
echo.
echo The instructions are simple. Answer the
questions correctly.
echo.
echo **************************************
pause
cls
goto menu

:Game
set /a question=%question%+1
cls
if %question% ==5 (goto end) else (echo you are on
question %question%)
echo.
echo get ready for the question...
echo.
timeout /T 5 /nobreak > nul
if %question% ==5 (goto end) else (goto %question%)

:1
cls
echo.
echo ******************************
echo.

20 www.bdmpublications.com
Creating a Batch File Game

echo Your current score is %score% if errorlevel 3 goto wrong


echo. if errorlevel 2 goto wrong
echo ****************************** if errorlevel 1 goto correct
echo.
echo. :4
echo Question %question%. cls
echo. echo.
echo Which of the following version of Windows is the echo ******************************
best? echo.
echo. echo Your current score is %score%
echo A. Windows 10 echo.
echo. echo ******************************
echo B. Windows ME echo.
echo. echo.
echo C. Windows Vista echo Question %question%.
echo. echo.
choice /C abc echo Which of the following Windows uses DirectX 12?
if errorlevel 3 goto wrong echo.
if errorlevel 2 goto wrong echo A. Windows 10
if errorlevel 1 goto correct echo.
echo B. Windows 3.11
:2 echo.
cls echo C. Windows XP
echo. echo.
echo ****************************** choice /C abc
echo. if errorlevel 3 goto wrong
echo Your current score is %score% if errorlevel 2 goto wrong
echo. if errorlevel 1 goto correct
echo ******************************
echo. :Wrong
echo. cls
echo Question %question%. echo ******************
echo. echo.
echo Which of the following version of Windows is the echo WRONG!!!!
most stable? echo.
echo. echo ******************
echo A. Windows 10 set /a score=%score%-1
echo. pause
echo B. Windows 95 goto :game
echo.
echo C. Windows ME :correct
echo. cls
choice /C abc echo ******************
if errorlevel 3 goto wrong echo.
if errorlevel 2 goto wrong echo CORRECT. YIPEE!!!
if errorlevel 1 goto correct echo.
echo ******************
:3 set /a score=%score%+1
cls pause
echo. goto :game
echo ******************************
echo. :end
echo Your current score is %score% cls
echo. echo ******************************
echo ****************************** echo.
echo. echo Well done, %name%, you have answered all the
echo. questions
echo Question %question%. echo.
echo. echo And your final score is....
echo Which of the following Windows version is the echo.
latest? echo %score%
echo. echo.
echo A. Windows 10 echo ********************************
echo. choice /M “play again? Y/N”
echo B. Windows 98 if errorlevel 2 goto :eof
echo. if errorlevel 1 goto start
echo C. Windows 7
echo.
choice /C abc

www.bdmpublications.com 21
Coding on Linux

22 www.bdmpublications.com
Coding
on Linux
Linux is such a versatile operating system that’s
both malleable and powerful, while offering
the programmer a perfect foundation on
which to build their skills. While all the popular
and mainstream programming languages are
available on Linux, as they are on Windows
and macOS, Linux also utilises its own coding
language, called scripting.

Bash scripting on Linux can be used to create


a wealth of useful, real-world programs that
interact with the user, or simply work in the
background based on a pre-defined schedule.
Scripting is a powerful interface to the Linux
system, so we’ve crafted this section to help you
get to grips with how everything fits together,
and how to make some amazing Linux scripts.

www.bdmpublications.com 23
Coding on Linux

Why Linux?
For many of its users, Linux means freedom. Freedom from the walled-gardened
approach of other operating systems, freedom to change and use the OS as you please
and freedom from any form of licensing or payment. There’s a lot more to Linux than
you may think.

FREE AND OPEN


Linux is a fantastic fit for those who want something different; the efficiency of the system, the availability of applications and
its stability, are just a few reasons why.

The first thing we need to address is that there is no basic operating Linux works very differently to Windows or macOS. For a 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 of an 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, or distros, 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, or someone 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 offer a different looking desktop environment, different in a matter of minutes.
pre-loaded applications, different ways in which to update the system
and get more apps 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. However, 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-

Linux is a great operating system in


which to start coding.

24 www.bdmpublications.com
Why Linux?

looking desktop, a gaming specific spin, or something directed toward


students. This extensibility makes Linux a more desirable platform to
use, as you can quickly mould the system into a development base,
including many different kinds of IDEs for use with Python, web
development, C++, Java and so on, or even a base for online anonymity,
perhaps as a Minecraft server, media centre and much more.

Another remarkable advantage for those looking to learn how to code


is that Linux comes with most of the popular coding environments
built-in. Both Python and C++ are pre-installed in a high percentage of
Linux distros, which means you can start to program almost as soon as
you install the system and boot it up for the first time.

Generally speaking, Linux doesn’t take up as many system resources


as Windows or macOS, (by system resources, we mean memory,
Each distro offers something unique to the
hard drive space and CPU load), as the Linux code has been
user but all have Linux at the core.
streamlined and is free from third-party ‘bloatware’, which hogs
those systems resources. A more efficient system, means more
available resources for the coding and testing environment and the So rather than throwing away an old computer, it can be reused with
programs you will eventually create. Less resource use also means a Linux distro.
you can use Linux on older hardware that would normally struggle,
or even refuse to run, the latest versions of Windows or macOS. However, it’s not all about C++, Python, or any of the other more
popular programming languages. Using the command line of Linux
(also called the Terminal), you’re able to create Shell scripts, which are
programs made up of scripting languages and designed to run from
the command line. They are used mainly to automate tasks, or offer the
user some form of input and output for a certain operation.

There are many more advantages we could list, for example, there
are thousands and thousands of free programs and apps available
that cover practically every aspect of computing. Known as packages,
there are (at the time of writing) over 8,700 specific programming
applications on Linux Mint alone and an incredible 62,000+ overall
packages, catering from Amateur Radio to WWW tools.

In conclusion, Linux is a great resource and environment in which


to program. It’s perfectly suited for developers, while continually
improving and evolving. If you’re serious about getting into coding, or
There are thousands of free packages
you just want to explore something new, then give Linux a try and see
available for programmers under Linux.
how it works for you.

A Linux programming environment can be


as simple or as complex as you need it to be.

www.bdmpublications.com 25
Coding on Linux

The Best Linux


Distributions
There are numerous versions of Linux available, known as “Distributions”. Each has a
different ethos and approach. Here are five great distributions to try and where you
can get them.

LINUX MINT – 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.

Cinnamon is a graphically rich desktop environment, while MATE


uses less fancy graphics but is more stable on a wider variety of
desktop systems and finally Xfce is an extremely streamlined
desktop environment that is built for speed and ultimate stability.

Throughout this title, we’ll be using the Cinnamon version,


however, you can try out any of the other desktop environments.

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.

26 www.bdmpublications.com
The Best Linux Distributions

ARCH – ARCHLINUX.ORG OPENSUSE – OPENSUSE.ORG


Arch is one of the longest running Linux distributions and Most Linux distributions fall into two camps: those with the
forms the basis of many other versions of Linux. So why latest features and technology like Ubuntu and Mint and those
install Mint, or Ubuntu when you can install Arch? Many users with fewer new features, but rock-solid reliability, like Debian.
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
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 occasional crash.
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 for you, by you.

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 educational resources.
this remarkable, tiny computer has
taken the technology world by storm Originally, Raspbian was exclusive to
since it was introduced six years ago. the Pi hardware, as the Raspberry Pi
uses an ARM processor to power it.
There are several aspects to the However, the Raspberry Pi Foundation
Raspberry Pi that make it such a has since released a PC version of
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
a fully working computer. It’s small, Desktop comes with the all the coding,
measuring not much bigger than a credit card. You can employ educational and other apps you will ever need. It’s quick, stable
it to build electronics, using a fully programmable interface and and works superbly. If you’re interested in stretching your
it comes with Raspbian, its own custom-made, Debian-based Linux experience, then this is definitely one of the top distros
operating system that includes an office suite alongside many to consider.

www.bdmpublications.com 27
Coding on Linux

Equipment You
Will Need
The system requirements for successfully installing Linux Mint 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 Mint are as follows:

CPU 700MHz

RAM 512MB

Hard Drive Space 9GB (20GB recommended)

Monitor 1024 x 768 resolution

Obviously the better the system you have, the better and 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
familiar with 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.

28 www.bdmpublications.com
Equipment You Will Need

DVD INSTALLATION INTERNET CONNECTION


DVD installation of Linux Mint simply requires a blank DVD-R It goes without saying, that an Internet connection is vital for
disc. Of course, you’ll also need an optical drive (a DVD Writer making sure that Linux Mint is resourced with the latest
drive) before you’re able to transfer, or burn, the ISO image to updates and patches, as well as the installation of further
the disc. software. Although you don’t need an Internet connection to
use Linux Mint, you’ll miss out on a world of free software
available for the distro.

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 www.virtualbox.org.

www.bdmpublications.com 29
Coding on Linux

Creating a Linux Installer


on Windows
You need to transfer the downloaded Linux ISO to either a DVD or a USB key before
you can install it to a computer. This will be a live environment, which will allow you to
test the OS prior to installation, but first you need to create the bootable media.

DVD BOOTABLE MEDIA


We’re using a Windows 10 PC here to transfer the ISO to a DVD. As long as you’re using a version of Windows from 7 onward,
the process is extremely easy.

STEP 1 First locate the ISO image of Linux you’ve already STEP 3 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
Disc Image Burner should launch.

STEP 2 Next, insert a recordable DVD disc into your STEP 4 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 for you.

30 www.bdmpublications.com
Creating a Linux Installer on Windows

USB BOOTABLE MEDIA


USB media is faster than a DVD and it’s often more convenient as most modern PCs don’t have an optical drive installed. The
process of transferring the image is easy, but you’ll need a third-party app first and a USB flash drive of 4GB or more.

STEP 1 STEP 4 When you’re ready, click on the Start button at


the bottom of the Rufus app. This may open up
First, open up a web another dialogue box asking you to download and use a new version
browser and go to of SysLinux. SysLinux is a selection of boot loaders used to allow a
https://rufus.akeo. modern PC to access and boot from a USB flash drive. It is necessary,
ie/. Scroll down the so if asked, click on ‘Yes’ to continue.
page a little and you’ll
come to a Download
heading, under which
you’ll see the latest
version of Rufus.
Left-click on the link to
start the download.

STEP 2 STEP 5 The next step asks in which image mode do you
want the Linux ISO to be written to the USB flash
Double-click the drive. Both methods work for different situations, but generally, the
downloaded Rufus recommended ISO Image Mode is the more popular. Make sure this
executable; you can mode is pre-selected and click ‘OK’ to continue, followed by ‘OK’
click ‘Yes’ to the again to confirm the action.
Windows security
question and ‘Yes’
to checking for
updates. With Rufus
launched, it should
have already identified
your inserted USB
flash drive (if not, just
remove and reinsert).

STEP 3 At first glance the Rufus interface can look a little STEP 6
confusing, don’t worry though, it’s really quite
simple. To begin with, click on the SELECT button next to the ‘Disk The Linux ISO is now
or ISO Image (Please select)’ pull-down menu. This will launch a being transferred to
Windows Explorer window from where you can locate and select the USB flash drive. The
the Linux ISO. process shouldn’t take
too long, depending on
the speed of the USB
device and the PC. During
the process, you may find
Rufus will auto-open the
USB drive in Windows
Explorer, don’t worry you
can minimise or close it
if you want. Click on the
Close button once the
process is complete.

www.bdmpublications.com 31
Coding on Linux

Installing Linux on a PC
Most Linux distros come as a Live Environment. This means you can boot into an actual,
fully working distro straight from the DVD or USB you’ve just created. Let’s see how
that works 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.

STEP 1 Insert your DVD or USB flash drive into your PC and, STEP 3 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, HDD or similar, to: USB Storage Device for the USB media option; or
Del or even F12. DVD Drive, for the DVD media option.

STEP 2 There are different versions of a UEFI BIOS, so STEP 4 Alternatively use the Boot Option Menu. With this
covering them all would be impossible. What you’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. Here 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.

32 www.bdmpublications.com
Installing Linux on a PC

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.

STEP 1 Providing you’re connected to the Internet (if not, STEP 4 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. If you need to back up your files remove
the Linux disc/USB, reboot, back up and start again.

STEP 2 While the installation process is very similar across STEP 5 Eventually you will be asked to set up your Linux
most Linux distros, some offer different questions username and password. Enter your 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, but some such 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.

STEP 3 When installing a new operating system it’s STEP 6 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 disk and install Linux…’ option is selected. 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.

www.bdmpublications.com 33
Coding on Linux

Installing a Virtual
Environment
A Virtual Environment is a simulated computer system. Using a Virtual Machine, you
can mimic a standard PC and install an entire operating system on it without affecting
the one installed on your computer. It’s a great way to test and use Linux, while still
having Windows 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.

STEP 1 We’re using VirtualBox in this instance, as it’s one of STEP 3 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
Enter www.virtualbox.org and click 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.

STEP 2 Next, while still at the VirtualBox download page, STEP 4 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 ‘real’ computer. the Advanced section of the BIOS. When you’ve located it, Enable it,
save the settings, exit the BIOS and reboot the computer.

34 www.bdmpublications.com
Installing a Virtual Environment

STEP 5 With the computer back up and running, locate STEP 8 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 that any VM installed will be able to access the
Internet and your home network resources, via the computer’s,
already established, network connection. Click Yes, then, Install to
begin the installation.

STEP 6 The default installation location of VirtualBox STEP 9 You’ll probably be asked by Windows to accept a
should satisfy most users, but if you have any special security notification, click Yes for this and next
location requirements, click on the ‘Browse’ button and change the you may encounter a dialogue box asking you to trust the
install folder. Also, make sure that all the icons in the VirtualBox installation from Oracle, again, click yes and accept the installation
feature tree are selected and none of them have a red X next to of the VirtualBox application. When it’s complete, click finish to
them. Click Next to move on. start VirtualBox.

STEP 7 This section can be left to the defaults, should you STEP 10 With VirtualBox up and running, you can now
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’.

www.bdmpublications.com 35
Coding on Linux

Installing Linux in a
Virtual Environment
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 won’t affect
your currently installed operating system, which is why a VM 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.

STEP 1 With VirtualBox open, click on the New icon in the STEP 3 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
your computer, 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.

STEP 2 In the box next to Name type Linux Mint, and STEP 4 This section is where you’ll start to create the virtual
VirtualBox should automatically 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 (remember Mint using. Click Create to move on.
mainstream is based on Ubuntu). Click Next when you’re ready
to proceed.

36 www.bdmpublications.com
Installing Linux in a Virtual Environment

STEP 5 The pop-up window that appears after clicking STEP 8 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 the Settings 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.

STEP 6 The question of whether to opt for Dynamically or STEP 9 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.

STEP 7 The virtual hard disk will be a single folder, up to the STEP 10 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.50GB 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.

www.bdmpublications.com 37
Coding on Linux

Getting Ready to
Code in Linux
Coding in Linux mostly happens in the Terminal or the Command 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.

STEP 1 The Terminal is where you begin your journey STEP 3 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.

STEP 2 The Terminal will give you access to the Linux STEP 4 The flashing cursor at 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.

38 www.bdmpublications.com
Getting Ready to Code in Linux

STEP 5 All the commands you enter will work in the same STEP 6 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.

STEP 1 Having access to the Terminal means you’re STEP 3 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 quick and handy backup waiting for you.
deleted files.

STEP 2 However, the Terminal doesn’t offer that luxury. If STEP 4 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/sda and 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.

www.bdmpublications.com 39
Coding on Linux

Creating Bash Scripts


– Part 1
Eventually, as you advance with Linux Mint, you’ll want to start creating your own
automated tasks and programs. These are essentially scripts, Bash Shell scripts
to be exact, and they work in the same way as a DOS Batch file does, or any other
programming language.

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.

STEP 1 You’ll be working within the Terminal and with a STEP 3 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.

STEP 2 There are several text editors we can use to create STEP 4 Windows users will be aware that in order for a
a Bash script: Xed, Vi, Nano, Vim, GNU Emacs and 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.

40 www.bdmpublications.com
Creating Bash Scripts – Part 1

STEP 5 Let’s start with a simple script to output something STEP 8 When you enter ls again, you can see that the
to the Terminal. Enter xed helloworld.sh. helloworld.sh script has now turned from being
This will 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 words make it do the things you’ve typed into it,
Hello World!. enter: ./helloworld.sh.

STEP 6 The #!/bin/bash line tells the system what Shell STEP 9 Although it’s not terribly exciting, the words ‘Hello
you’re going to be using, in this case Bash. The hash World!’ should now be displayed in the Terminal.
(#) denotes a comment line, one that is ignored by the system, the The echo command is responsible for outputting the words after
exclamation mark (!) means that the comment 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.

STEP 7 You can save this file, clicking File > Save, and exit STEP 10 Think of echo as the old BASIC Print command. It
back to the Terminal. Entering ls, will 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
of the week.

www.bdmpublications.com 41
Coding on Linux

Creating Bash Scripts


– Part 2
Previously we looked at creating your first Bash script, Hello World, and adding a
system variable. Now you can expand these and see what you can do when you start
to play around with creating your own unique variables.

VARIABLES
Just as in every other programming language a Bash script can store and call certain variables from the system, either generic
or user created.

STEP 1 Let’s start by creating a new script called hello.sh; STEP 3 The output now will be Hello David. This is because
xed hello.sh. In it enter: #!/bin/bash, then, Bash automatically 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
something different: ./hello.sh Mint.

STEP 2 As the script is now executable, run it with ./ STEP 4 You can even rename variables. Modify the hello.
hello.sh. Now, as you probably expected a simple sh script with the following: firstname=$1,
‘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 statement on a new line. Save the script and exit back into
try ./hello.sh David. the Terminal.

42 www.bdmpublications.com
Creating Bash Scripts – Part 2

STEP 5 When you run the script now you can use two STEP 8 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. At the moment 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.

STEP 6 Create a new script called addition.sh, using STEP 9 We’ve added a –n to the echo command here
the same format as the hello.sh script, but which will 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
secondnumber, and used the echo command to output some users’ input as the variables firstname and surname, to then read
simple arithmetic 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.
make it executable (chmod +x addition.sh).

STEP 7 When you now run the addition.sh script we can STEP 10 As a final addition, let’s include the date variable
enter two numbers: ./addition.sh 1 2. The we used in the last section. Amend the last line
result will hopefully be 3, with 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 output should
See also if you can alter the script and rename it do multiplication, display the current day of the week, calling it from a system variable.
and subtraction.

www.bdmpublications.com 43
Coding on Linux

Creating Bash Scripts


– Part 3
In the previous pages we looked at some very basic Bash scripting, which involved
outputting text to the screen, getting a user’s input, storing it and outputting that to
the screen; as well as including a system variable using the Date command. Now let’s
combine what you’ve achieved so far and introduce Loops.

IF, THEN, ELSE


With most programming structures there will come a time where you need to loop through the commands you’ve entered to
create better functionality, and ultimately a better program.

STEP 1 Let’s look at the If, Then and Else statements now, STEP 3 The next line, ELSE, is what happens if the variable
which when executed correctly, compare a set of doesn’t equal ‘David’. In this case it simply outputs
instructions and simply work out that IF something is present, THEN to the screen the now familiar ‘Hello…’. The last line, the FI
do something, ELSE do something different. Create a new script statement, 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 without a Fi command, then you get an error.
into it.

STEP 2 Greeting2.sh is a copy of greeting.sh but with a STEP 4 You can obviously play around with the script a
slight difference. Here we’ve added a loop starting little, changing the name variable that triggers a
at the if statement. This means, IF the variable entered is equal to response; or maybe even issuing a response where the first name
David the next line, THEN, is the reaction to what happens, in this and surname variables match a specific variable.
case it will output to the screen ‘Awesome name,’ followed by the
variable (which is David).

44 www.bdmpublications.com
Creating Bash Scripts – Part 3

MORE LOOPING
You can loop over data using the FOR, WHILE and UNTIL statements. These can be handy if you’re batch naming, copying or
running a script where a counter is needed.

STEP 1 Create a new script called count.sh. Enter the STEP 4 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 will print the current value of greater than (the gt part) one hundred, keep on looping.
count in the echo command.

STEP 2 Executing the count.sh script will result in the STEP 5 You’re not limited to numbers zero to one hundred.
numbers 0 to 99 listing down the Terminal screen; You can, within the loop, have whatever set of
when it reaches 100 the script will end. Modifying the script with the commands you like and execute them as many times as you want
FOR statement, makes it work in much the same way. To use it in our the loop to run for. Renaming a million files, creating fifty folders
script, enter the text from the screenshot into the count.sh script. etc. For example, this script will create ten folders named folder1
through to folder10 using the FOR loop.

STEP 3 The addition we have here is: for count in STEP 6 Using the FOR statement once more, we can
{0..100}; do. Which means: FOR the variable execute the counting sequence by manipulating the
‘count’ IN the numbers from zero to one hundred, then start the {0..100} part. This section of the code actually means {START..END..
loop. The rest of the script is the same. Run this script, and the same INCREMENT}, if there’s no increment then it’s just a single digit up to
output should appear in the Terminal. the END. For example, we could get the loops to count up to 1000 in
two’s with: for count in {0..1000..2}; do.

www.bdmpublications.com 45
Coding on Linux

Creating Bash Scripts


– Part 4
You’ve encountered user interaction with your scripts, asking what the user’s name
is and so on. You’ve also looked at creating loops within the script to either count or
simply do something several times. Let’s combine and expand some more.

CHOICES AND LOOPS


Let’s bring in another command, CHOICE, along with some nested IF and ELSE statements. Start by creating a new script called
mychoice.sh.

STEP 1 STEP 3 You can, of course, increase the number of choices


but you need to make sure that you match the
The mychoice.sh script number of choices to the number of IF statements. The script can
is beginning to look a quickly become a very busy screen to look at. This lengthy script
lot more complex. What is another way of displaying a menu, this time with a fancy colour
we have here is a list scheme too.
of four choices, with
three possible options.
The options: Mint, Is,
and Awesome will be
displayed if the user
presses the correct
option key. If not, then
the menu will reappear,
the fourth choice.

STEP 2 If you follow the script through you soon get the
hang of what’s going on, based on what we’ve
already covered. WHILE, IF, and ELSE, with the FI closing loop
statement will run through the options and bring you back to the
start if you pick the wrong option.

STEP 4 You can use the


arrow keys and Enter
in the menu setup in the script. Each
choice is an external command that
feeds back various information. Play
around with the commands and
choices, and see what you can come
up with. It’s a bit beyond what we’ve
looked at but it gives a good idea of
what can be achieved.

46 www.bdmpublications.com
Creating Bash Scripts – Part 4

CREATING A BACKUP TASK SCRIPT


One of the most well used examples of Bash scripting is the creation of a backup routine, one that automates the task as well
as adding some customisations along the way.

STEP 1 A very basic backup script would look something STEP 4 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 cvfz ~/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 ~/Documents 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.

STEP 2 While perfectly fine, we can make the simple script STEP 5 With 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. Combined with the variables, you have: tar cvfz
sh script. Notice that we’ve misspelt ‘source’ as ‘sauce’, this is $dest/”$day $month $year”/DocumentsBackup.tgz
because there’s already a built-in command called ‘source’ hence the $sauce. In the screenshot, we added a handy “Now backing up...”
different spelling on our part. echo command.

STEP 3 The previous script entries allowed you to create STEP 6 Finally, you can add a friendly message: echo
a Time Stamp, so you know when the backup was “Backup complete. All done...”. The
taken. You also created a ‘dest’ variable, which is the folder where completed script isn’t too over-complex and it can be easily
the backup file will be created (~/backups). You can now add a customised to include any folder within your Home area, as well as
section of code to first check if the ~/backups folder exits, if not, the entire Home area itself.
then it creates one.

www.bdmpublications.com 47
Coding on Linux

Creating Bash Scripts


– Part 5
The backup script we looked at previously can be further amended to incorporate
choices; or in other words, user-interaction with regards to where the backup file will
be copied to and so on. Automating tasks is one of the main benefits of Bash scripting,
a simple script can help you out in many ways.

EASY AUTOMATION AND HANDY SCRIPTS


Are you entering line after line of commands to retrieve system information, find a file or rename a batch of files? A script is a
better answer.

STEP 1 Let’s start by creating a script to help display the STEP 3 Each of the sections runs a different Terminal
Mint 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 lot more, such as the current
following into Xed, or the text editor of your choice. aliases being used in the system, the current time 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.

STEP 4 Although there are simple Terminal commands to


help you look for a particular file or folder, it’s often
more fun to create a script to help you. Plus, you can use that script
for other non-technical users. Create a new script called look4.sh,
entering the content from the screenshot below.

STEP 2 We’ve included a couple of extra commands in


this script. The first is the -e extension for echo,
this means it’ll enable echo interpretation of additional instances
of a new line, as well as other special characters. The proceeding
‘31;43m’ element enables colour for foreground and background.

48 www.bdmpublications.com
Creating Bash Scripts – Part 5

STEP 5 When executed the script waits for input from the STEP 8 The output from colours.sh can, of course, be
user, in this case the file extension, such as jpg, mixed together, bringing different effects
mp4 and so on. It’s not very friendly though. Let’s make it a little depending on what you want 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 for: “, just blinking effect doesn’t work on all Terminals, so you may need to
before the read command. change to a different Terminal.

STEP 6 Here’s an interesting, fun kind of script using the


app espeak. Install espeak with sudo apt-get
install espeak, then enter the text below into a new script called
speak.sh. As you can see it’s a rehash of the first greeting script
we ran. Only this time, it uses the variables in the espeak output.

STEP 7 We briefly looked at putting some colours in the


output for our scripts. Whilst it’s too long to dig a STEP 9 Whilst we’re on making fancy scripts, how about
little deeper into the colour options, here’s a script that outputs using Zenity to output a graphical interface?
what’s available. Create a new script called colours.sh and enter Enter what you see below into a new script, mmenu.sh. Make it
the text (see below) into it. executable and then run it. You should have a couple of dialogue
boxes appear, followed by a final message.

STEP 10 While gaming in a Bash script isn’t something


that’s often touched upon, it is entirely possible,
albeit, a little basic. Movement-based games are diffiuclt, and
sometimes buggy, however a good text adventure, or Fighting
Fantasy type game is a perfect choice for gaming in the Terminal.
give it a go, and let us know how you get on.

www.bdmpublications.com 49
Coding on Linux

Command Line
Quick Reference
When you start using Linux full time, you will quickly realise that the graphical
interfaces of 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 of
Linux but also improves your knowledge of coding and programming in general. Our
command line quick reference guide is designed to help you master Linux quicker.

TOP 10 COMMANDS
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 cd command is one of the commands you The mv command moves a file to a different
will use the most at the command line in Linux. It location or renames a file. For example mv file
cd allows you to change your working directory. You mv sub renames the original file to sub. mv sub
use it to move around within the hierarchy of your ~/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 ls command shows you the files in your The chown command changes the user and/
current directory. Used with certain options, it lets or group ownership of each given file. If only an
ls you see file sizes, when files where created and file chown owner (a user name or numeric user ID) is given,
permissions. For example, ls ~ shows you the files that user is made the owner of each 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 command changes the permissions on
and directories. For example, cp file sub makes the files listed. Permissions are based on a fairly
cp an exact copy of the file whose name you entered cmod simple 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 whether each can
exist with its original name. read, write and or execute the file.

The pwd command prints the full pathname of The rm command removes (deletes) files or
the current working directory (pwd stands for directories. The removal process unlinks a filename
pwd “print working directory”). Note that the GNOME rm 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 of its window. other words, removing files increases the amount
of available space on your disk.

The clear command clears your screen if this Short for “make directory”, mkdir is used to
is possible. It looks in the environment for the create directories on a file system, if the specified
clear terminal type and then in the terminfo database mkdir directory does not already exist. For example,
to figure out how to clear the screen. This is mkdir work creates a work directory. More than
equivalent to typing Control-L when using the one directory may be specified when calling mkdir.
bash shell.

50 www.bdmpublications.com
Command Line Quick Reference

C:\Commonly_Used_Commands

USEFUL HELP/INFO COMMANDS


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 free command displays the total amount The sed command opens a stream editor.
of free and used physical and swap memory in A stream editor is used to perform text
free the system. For example, free -m gives the sed transformations on an input stream: a file or input
information using megabytes. from a pipeline.

The df command displays filesystem disk space


The adduser command adds a new user to the
usage for all partitions. The command df-h
df is probably the most useful (the -h means adduser system. Similarly, the addgroup command adds a
new group to the  system.
human-readable).

The top program provides a dynamic real-time The deluser command removes a user from
view of a running system. It can display the system. To remove the user’s files and
top system summary information, as well as a list deluser home directory, you need to add the -remove-
of processes. home option.

The uname command with the -a option prints The delgroup command removes a group from
uname-a all system information, including machine name, delgroup the system. You cannot remove a group that is the
kernel name, version and a few other details. primary group of any users.

The ps command allows you to view all the


The man man command brings up the manual
processes running on the machine. Every
ps operating system’s version of ps is slightly man man entry for the man command, which is a great place
to start when using it.
different but all do the same thing.

The grep command allows you to search inside a The man intro command is especially useful.
number of files for a particular search pattern and It displays the Introduction to User Commands,
grep then print matching lines. An example would be: man intro which is a well written, fairly brief introduction to
grep blah file. the Linux command line.

www.bdmpublications.com 51
Code Projects and Ideas

52 www.bdmpublications.com
Code Projects
and Ideas
To help you on your way to becoming a better
coder, we’ve included some great coding projects
and ideas that you can apply to your own code,
use as a demo for those who are starting to
code, or improve and send out into the coding
community. Want to learn how to craft some
retro code? How about learning how to code a
text adventure? These and more are all found in
this final section.

No matter where you go next in coding, whether


it’s on to learning more languages, creating
amazing apps and games, or helping out and
teaching new coders to avoid the pitfalls you
made, remember the basics, and have fun!

From here, it’s down to you and your imagination.


So dream it, and code it.

www.bdmpublications.com 53
Code Projects and Ideas

Planning Your
Code
Knowing how to code is great, but it’s not going to get you very far if you don’t know
what it is you’re supposed to be coding. Small samples of code don’t need much
planning, but bigger projects do, so here are some tips on planning your code.

You will find that nearly all the professional developers out there will
set aside some time to plan out how their code is going to fit into the
wider project on which they’re working. Regardless of whether they’re
working as part of a team on the latest game, developing a workflow
user interface for the company, or creating a set of automated
tasks that can be used across a number of different platforms, each
developer will set out their code in a plan.

The planning stages can be unique to the developer, unique to the


company for which they’re working, or the project on which they’re
working. Planning meetings will often sketch out a rough plan of how
the end product will function, with each developer team then working
on their element within the project. Lone developers will sometimes
go back to basics, grab paper and a pencil and start getting their ideas
down. The end result is always the same, though, a plan of action that
enables the developer to plan without worrying about the actual code
at this early stage.

PSEUDOCODE
Code Example:

If “1”
Print response
“I am result 1”

If “2”
Print response
“I am result 2”

One of the more popular methods 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 implementation of code, the sequence continue to plan the remainder
of the actions, using plain English and a mixture of code examples of the code needed without
together with a flowchart or two to help ‘picture’ loops within the taking up too much valuable
coding project. time – but while also having a
readable plan of action for how
For example, a developer who is planning to write a program that will the code is going to be formed.
check user input for odd or even numbers will probably begin with a
basic statement of pseudocode: The actual writing of 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 statement can be expanded: a plan of action in place, the

54 www.bdmpublications.com
Planning Your Code

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 will not only trim the fat off the code before it’s even
written but will 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 your 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 of coding games – is
graph paper.

Super Mario Bros., launched for the Nintendo Entertainment


System in 1985, was nearly exclusively drawn out – both characters
and levels – on graph paper before being applied to code. Entire Once the graphical planning stage is complete, it’s then down to
game maps were often created this way, especially on the you as the developer to fill in the blanks, as it were. This means
older 8-bit machines such as the Commodore 64 and Sinclair ZX creating the code that will place and animate your characters
Spectrum home computers. 8-Bit graphics were ideal for graph within the game, as well as developing interactions, collision
paper since the sprites used then were made up of eight or sixteen detection, number of lives, and so on. With the help of some
blocks; the developer could then visualise the layout of the sprite pseudocode, you could easily plan out what modules you’d use or
using the drawing on the graph paper and apply that to the code. create, the number of variables needed, and the various endgame
The end result, of course, is the character appearing on the screen. states that will arise when someone plays your game.

GET PLANNING
The whole point of planning is to create something easy to follow that
will help you write the code for your project. Planning isn’t supposed
to be a chore; it’s there to aid you when you get stuck trying to work
out which variables you’ve used, where you are in the game, with what
you’re left and how the game will eventually pan out and end.

When planning, begin with small steps. Coding a Hangman game, for
example, begins with the plan to get the player’s name, then includes
the word bank, drawing out the stages of the Hangman, asking the
right questions, and finishing the game in one of two states – a win or
a lose – then asking if the player wants another go.

Once you’re used to planning it’ll come naturally, and you’ll find
yourself thankful for all those post-it notes stuck to a sheet of A3
paper, as well as the reams of graph paper that detail your characters
and level designs.

Pseudocode flowcharts can be simple, or as complex


as necessary

Writing pseudocode will help


you visualise the actual code

www.bdmpublications.com 55
Code Projects and Ideas

Finding
Resources
The Python community is huge and spans countless websites and forums on the
Internet, so finding extra help here and there isn’t too much of a problem. However,
finding good Python resources can be, so here are some ideas for you to try.

You will reach a point in your Python coding experience when you need to rely
on some external resources to help you through a sticky patch in your project
or give you a bit of inspiration. Python resources are available throughout
the Internet, but not all of them are any good. If you spend any time looking
up code for a particular project, then you’re likely to come across copious
examples, yet not all of them seem to work.

That’s one of the main issues with resources for Python. With the language
being twenty-nine years old, and many different versions under the bridge,
there’s a significant amount of content out there that’s simply out of date – or
just wrong for the version you’re using. Newer versions, even by one number
out, can have different outputs for your code from a previous version – it’s
not always that case, but it can happen. Therefore, you need to find yourself
some trusted Python resources that work, or at least 90% would work, with the
version you’re using and the code within.

THE HITCHHIKER’S GUIDE TO PYTHON


One of the first places that’s worth turning to is: freeCodeCamp.org. This website
features a wealth of code that covers most aspects of the learning experience,
even for those who are experts at Python. You’ll find content that will take your
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.

Programiz is another useful resource that features Python code examples


covering a wide range of concepts. There’s everything in here from the original
“Hello, world!” code, through to code that will transpose a matrix or find the hash
of a file. There’s also an online compiler and in-depth looks into further reading
for aspiring data scientists.

If you’re looking for resources about using graphics in Python, then


ProgramArcadeGames.com is a good place to start. This site has plenty of code for
the Pygame module, including moving an object around the screen using a mouse
or game controller, creating fractals, moving sprites, and an example of a classic
Pong game for you to try out.

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
3. Nevertheless, you do come across some gems from time to time, especially if
you look up the Pygame examples that users have uploaded. We recommend the
excellent Solarwolf, by Pete Shinners.

56 www.bdmpublications.com
Finding Resources

STRONG GOOGLE-FU
There’s no trick to finding good Python resources online; most
of the time, it’s a case of trial and error. You’ll need to make sure
you’re searching for the right content, though, just to save you
some time. If it’s a Pygame specific set of resources you’re looking
for then you’ll need to specify the Python version you’re using;
include Pygame, and include what it is you’re looking for – it may
sound like we’re teaching you to suck eggs, but effective searching
is often overlooked.

Again, it’s also worth looking up working examples of a type of


game if you’re looking for Pygame content. If you want to learn
how to engineer sprites moving from one side of the screen
to the other, then look up some examples of Space Invaders,
which feature such movements. The same goes if you’re making
a platform game, examine some classic games that involved
platforming, like Mario and so on.

One last resource is our very own code portal. Log in to https://
bdmpublications.com/code-portal/, and you’ll find a continually
growing list of Python code and resources that you can freely
add to your own code, then chop, change, and use for whatever
projects you have in mind.

www.bdmpublications.com 57
Code Projects and Ideas

Creating a Loading Screen


If you’re looking to add a little something extra to your Python code, then consider
including a loading screen. The loading screen is a short introduction, or piece of art,
that appears before the main part of your code.

LOAD”” THE CODE


Back in the 80s, in the 8-bit Launch Python and enter the following code to a New File:
home computing era, loading
import os
screens were often used to
import time
display the cover of a game
as it loaded from tape. The def loading_screen(seconds):
image would load itself in, screens=open(“screens.txt”, ‘r’)
usually one-line-at-a-time, for lines in screens:
then proceed to colour print(lines, end=’’)
itself in while the loading time.sleep(seconds)
raster bars danced screens.close()
around in the borders of
#Main Code Start
the screen.
os.system(‘cls’ if os.name == ‘nt’ else
Loading screens were a part of the ‘clear’)
package and often the buy-in for loading_screen(.5)
the whole game as an experience. Some
print (“\nYour code begins here...”)
loading screens featured animations, or a countdown for time
remaining as the game loads, while others even went so far as to
include some kind of playable game. The point being: a loading
screen is not just an artistic part of computing history, but an
introduction to the program that’s about to be run.
While these days loading screens may no longer be with us, in
terms of modern gaming we can still include them in our own
Python content. Either just for fun, or to add a little retro-themed
spice to the mix.

SCREEN$
Creating a loading screen in Python is remarkably easy. You have
several options to hand: you can create a tkinter window and
display an image, followed by a brief pause, before starting your
main code, or you could opt for a console-based ASCII art version
that loads one-line-at-a-time. Let’s look at the latter and see how
it works.
The code is quite simple: import the OS and Time modules and
First you’ll need some ASCII art, you can look up plenty of examples
then create a Python function called loading_screen with a
online, or use an image to ASCII Art converter to transform any
(seconds) option. Within the function, open the text file with the
images you have to ASCII. When you have your ASCII art, drop it into
ASCII art as read-only and create a For loop that’ll read the text
a newly created folder inside a normal text file.
file one-line-at-a-time. Next, print the lines – incidentally, the
lines, end=’’ element will strip the newline from the text
document, without it you’ll end up with a double-line spaced
display. Include the timing in seconds and close the text file buffer.
The final part of the code, #Main Code Start, is where you’ll
clear the screen (CLS for Windows, Clear for Linux (Raspberry
Pi) and macOS) and call the function, together with the output
number of seconds to wait for each line to be written to the screen
– in this case, .5 of a second.

58 www.bdmpublications.com
Creating a Loading Screen

print (“\nYour code begins here...”)

The code works in much the same way as the previous, except,
instead of reading from a text file, it’s running through a For loop
that prints Loading… followed by an animation of sorts, along with a
percentage counter; clearing the screen every second and displaying
the new results. It’s simple, yes, but quite effective in its design.

Save the code as screens.py, drop into a Command Prompt or COMBINING THE TWO
Terminal and execute it. The screen will clear and your ASCII art
How about combining the two elements we’ve looked at? Let’s
inside the text file will load in line-by-line, creating a loading
begin with a Loading… progress bar, followed by the loading
screen effect.
screen. After that, you can include your own code and continue
LOADING… your program. Here’s the code:
import os
import time
def loading_bar(seconds):
for loading in range(0,seconds+1):
percent = (loading * 100) // seconds
print(“\n”)
print(“Loading...”)
print(“<” + (“-” * loading) + (“ “ * (seconds-
Another favourite introduction screen is that of a simple loading
loading)) + “> “ + str(percent) + “%”)
animation, where the word loading is displayed, followed by
print(“\n”)
some characters, and a percentage of the program loaded. While
time.sleep(1)
it may not take long for your Python code to load, the effect can
os.system(‘cls’ if os.name == ‘nt’ else
be interesting.
‘clear’)
Create a New File in Python and enter the following code:
def loading_screen(seconds):
import os screens=open(“screens.txt”, ‘r’)
import time for lines in screens:
print(lines, end=’’)
def loading_bar(seconds):
time.sleep(seconds)
for loading in range(0,seconds+1):
screens.close()
percent = (loading * 100) // seconds
print(“\n”) #Main Code Start
print(“Loading...”) loading_bar(10)
print(“<” + (“-” * loading) + (“ “ * (seconds- os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
loading)) + “> “ + str(percent) + “%”) loading_screen(.5)
print(“\n”)
print (“\nYour code begins here...”)
time.sleep(1)
os.system(‘cls’ if os.name == ‘nt’ else You can, of course, pull those functions up wherever and whenever
‘clear’) you want in your code and they’ll display, as they should, at the
beginning. Remember 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_bar(10)
of the code, point to where the text file is located.

ADVENTURE TIME
A good example of using loading screen, ASCII art
text images is when coding a text adventure. Once
you’ve established your story, created the characters,
events and so on, you could easily incorporate some
excellently designed ASCII art to your game.
Imagine coming across a dragon, in game, and
displaying its representation as ASCII. You can then
load up the image lines, one-by-one, and continue with
the rest of the adventure code. It’s certainly worth
having a play around with and it’ll definitely add a little
something else extra.

www.bdmpublications.com 59
Code Projects and Ideas

Planning a Text Adventure


Planning a text adventure is one of the best ways of teaching yourself some new
Python tricks and essential code. A good text adventure contains many aspects, all of
which will need to be carefully planned and structured, to get the best from the code.

If you can think back to some of the classic text adventures you
may have played in the past, consider the amount of 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/games/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 MDL programming language back in the
late seventies. Despite its age, it’s still considered one of the best text
adventures to play. The second crucial element is choice. Without that, the player may as
well 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
wrong, they could be punished, whereas a correct choice could gain
them gold or some other form of reward. However, it doesn’t always
need to be a positive or negative choice; after all, most common real-
life decisions we make aren’t life or death, they merely result in one
thing happening or another.

Locations are similarly important. Text Adventures rely on good the


locations featured in the game can draw a picture in the mind of the
player. Whether they’re on a wooden ship in the middle of the sea or
trying to escape a haunted mansion, each location has to stand out.

Items are also a vital requirement for a good adventure game. A


Zork, or any other text adventure game, features several elements player will need to be able to pick up, examine, take, and use, an item
necessary to make the game both interesting 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
INGREDIENTS FOR A to unlock a door. You’ll need to factor in the list of possible items, and
COMPELLING ADVENTURE you’ll also need to factor in the real-world physics of each item too. If
you have your adventurer enter a room with an anvil, then allowing
The first ingredient is a story, a plot that will 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 of the major drawbacks of 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 murder mystery, the player.
much in the same vein as an Agatha Christie novel, or it could be
something that explores the base fears of people.

60 www.bdmpublications.com
Planning a Text Adventure

Although not always necessary, puzzles do form an interesting aspect Lists, tuples and dictionaries will be needed to store the
of a text adventure. These puzzles can test the player’s abilities various elements of the game. These can be descriptions of
and expand the game beyond simply finding an object and using characters whom you’ll meet, either friend or foe. Locations, with
it. Puzzles can range from using these objects correctly to achieve descriptions, throughout the game; items you’ll come across that
something to finding the correct route through a maze, with some can be used, along with a player inventory, which will grow or
being vital to the plot while others are simply there to give the player lessen depending on what the player has used/dropped/picked up.
something interesting to do. Ideally, puzzles should be easy near the
beginning of the game and get progressively harder as your character Variables will be needed to hold vital statistics during gameplay,
advances through the game. the player’s name, amount of strength, endurance, skill and health,
for example. You’ll also need variables to hold the current score
or number of moves used so far, plus any statistics regarding the
other characters you’ll meet.

Randomly generated numbers are vital for those who want to


include an element of combat. Within such examples, a virtual dice
roll will determine the winner or loser, either in a fight or when
using luck to win through something.

Strings can be used to keep non-moving elements of the game,


in other words the names of the rooms you may enter. These
components are static throughout the game, each and every time you
play, so they can be called upon when the player interacts with them.

Functions are the lifeblood of a text adventure, as they will form


Hints and help along the way can make the adventure seem less the backbone of the locations, interactions, events and anything
daunting. Of course, if you’re particularly mean-spirited, then you can else that happens within the game.
opt to exclude any form of help along the way altogether. However,
most text adventures do include some form of a hint. If you’ve Loops will keep a process going, such as a fight with an orc, until an
created a great set of puzzles for the player to beat, and they’re stuck event occurs – either the death of the orc or your player. In addition,
in their progression of the game, then allowing them to enter the you’ll need to include a loop, if and else components to help out
word: help, or hint, into the system, will reveal a small clue as to what with choices made: do you take the green door or the red door?
to do next. It’s not cheating, just keeping the story moving along.

Pacing is the final aspect of the adventure game that needs to be


planned correctly. Good pacing within the story is vital to keeping
your player’s attention, as well as keeping them entertained and
engaged with what’s going on. It’s not an easy egg to crack, however.
Too much pace and the player can get lost. Too slow, and they’ll get
bored and move on to something else.

THE CODE
It’s impossible to list the code you’ll need for your adventure
game since it’ll be different from each reader to the next, but here
are some pointers to help you out.

GOOD LUCK, ADVENTURER


There’s a lot to take in and plan, so our advice is to start small and
plan out your story first. Once you’ve got the basic story, build on
the settings and locations, then puzzles and other elements. From
there, you can begin to expand the game world and add things like
combat.

It won’t be easy, but it’ll be great fun and will help you become a
better Python coder.

www.bdmpublications.com 61
Code Projects and Ideas

Text Adventure Script


Text adventures are an excellent way to build your Python coding skills and have
some fun at the same time. This example that we created will start you on the path to
making a classic text adventure; where it will end is up to you.

ADVENTURE.PY import time


The Adventure game uses just the Time module to begin
with, creating pauses between print functions. There’s a help print(“\n” * 200)
print(“>>>>>>>>>>Awesome Adventure<<<<<<<<<<\n”)
system in place to expand upon, as well as the story itself.
print(“\n” * 3)
time.sleep(3)
print(“\nA long time ago, a warrior strode forth from
the frozen north.”)
time.sleep(1)
print(“Does this warrior have a name?”)
name=input(“> “)
print(name, “the barbarian, sword in hand and looking
for adventure!”)
time.sleep(1)
print(“However, evil is lurking nearby....”)
time.sleep(1)
print(“A pair of bulbous eyes regards the hero...”)
time.sleep(1)
print(“Will”, name, “prevail, and win great fortune...”)
time.sleep(1)
print(“Or die by the hands of great evil...?”)
time.sleep(1)
print(“\n” *3)
print(“Only time will tell...”)
time.sleep(1)
print(‘...’)
time.sleep(1)
print(‘...’)
time.sleep(1)
print(‘...’)
time.sleep(1)
print(‘...’)
time.sleep(5)
print(“\n” *200)

print(‘’’ You find yourself at a small inn. There’s


little gold in your purse but your sword is sharp,
and you’re ready for adventure.
With you are three other customers.
A ragged looking man, and a pair of dangerous
looking guards.’’’)

def start():
print(“\n ----------”)
print(“Do you approach the...”)
print(“\n”)
print(“1. Ragged looking man”)
print(“2. Dangerous looking guards”)

cmdlist=[“1”, “2”]
cmd=getcmd(cmdlist)

62 www.bdmpublications.com
Text Adventure Script

if cmd == “1”: def getcmd(cmdlist):


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

Adventure Time
This, as you can see, is just the beginning of the adventure and
takes up a fair few lines of code. When you expand it, and weave
the story along, you’ll find that you can repeat certain instances
such as a chance meeting with an enemy or the like.

We’ve created each of the two encounters as a defined set


of functions, along with a list of possible choices under the
cmdlist list, and cmd variable, of which is also a defined function.
Expanding on this is quite easy, just map out each encounter and
choice and create a defined function around it. Providing the user
doesn’t enter quit into the adventure, they can keep playing.

There’s also room in the adventure for a set of variables designed


for combat, luck, health, endurance and even an inventory or
amount of gold earned. Each successful combat situation can
reduce the main character’s health but increase their combat skills
or endurance. Plus, they could loot the body and gain gold, or earn
gold through quests.

Finally, how about introducing the Random module. This will


enable you to include an element of chance in the game. For
example, in combat, when you strike an enemy you will do a
random amount of damage as will they. You could even work out
the maths behind improving the chance of a better hit based on
your or your opponent’s combat skills, current health, strength and
endurance. You could create a game of dice in the inn, to see if you
win or lose gold (again, improve the chances of winning by working
out your luck factor into the equation).

Needless to say, your text adventure can grow exponentially


and prove to be a work of wonder. Good luck, and have fun with
your adventure.

www.bdmpublications.com 63
Code Projects and Ideas

Retro Coding
There’s a school of thought, that to master the foundations of good coding skills you
need to have some experience of how code was written in the past. In the past is a bit
of a loose term, but mostly, it means coding from the 80s.

recognised that one of the ‘best’, and possibly most utilised, form of
BASIC from the 80s was that of BBC BASIC.
BBC BASIC was used on the Acorn BBC Micro range of computers,
utilising the MOS 6502-based processor technologies. It was one of
the quickest examples of BASIC and, thanks to an inline assembler, it
was also capable of allowing the developers of the time to write code
for different processor types, such as the Zilog Z80 – a CPU present in
THE GOLDEN ERA OF CODE the ZX Spectrum, as well 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 Computers – a
language that’s virtually obsolete, there are some surprising benefits company that is historically responsible for the creation of the ARM
to getting your hands dirty with a bit of retro coding. Firstly, learning CPU - the processor that’s used in virtually every Android phone and
old code will help you build the structure of code as, regardless of tablet, smart TV, set top box and so on, as well as the Raspberry Pi –
whether it is a language that was developed yesterday, or forty years so essentially, the BBC Micro is the grandfather of 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 computer platform to be used throughout
a great visual aid to learn in older code, especially BASIC. Lastly, it’s
education. Different companies bid, but it was the BBC’s Computer
simply good fun.
Literacy Project (the BBC Micro) that was chosen, due to its
ruggedness, upgradability, and potential for education. As a result,
the BBC Micro, or the Beeb as it’s affectionately known, became the
dominant educational computer throughout the 80s.

BEEBEM
Naturally, you could scour eBay and look for a working BBC Micro to
GOING BASIC play around on, and it’ll be a lot of fun. However, for the sake of just
getting hands-on with some retro code, we’ll use one of the best BBC
The easiest retro language to play around with is, without 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 of 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 Windows 10, simply navigate to http://www.mkw.
distant relation to Python.
me.uk/beebem/index.html, and download the BeebEM414.exe
THE BEEB that’s displayed in the main screen.

The problem with BASIC is that there were so many different versions
available, across multiple 8-bit platforms, with
each having its own unique elements
on top of the core BASIC
functions. The BASIC that
was packaged with the
Commodore 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

64 www.bdmpublications.com
Retro Coding

will have to do a little nifty keyboard work before they can enjoy the clears the screen; although the Pi uses Clear instead of CLS. We’re also
benefits of 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:
1 CLS
First, drop to a Terminal and enter:
10 input “how old are you? “ a
20 print
sudo apt-get update && upgrade
30 if a > 40 print “You’re over 40 years old.”
wget http://beebem-unix.bbcmicro.com/download/
40 if a < 40 print “You’re under 40 years old.”
beebem-0.0.13.tar.gz
50 print

Then, extract the compressed files with:


BBC BASIC also has some interesting built-in features, such as the
value of PI:
tar zxvf beebem-0.0.13.tar.gz, then enter the newly
created Beebem folder with: cd beebem-0.0.13/.
1 REM Area of a circle
2 CLS
Now enter the following lines, hitting Enter and answering Y to accept
20 Input “Enter the radius: “ r
any changes:
30 let area = PI*r*r
40 print “The area of your circle is: “; area
sudo apt-get install libgtk2.0-dev libsdl1.2-dev
50 print ‘’’
./configure
make
sudo make install

This may take some time, but when it’s all done, simply enter: beebem,
to start the BBC Micro emulator.

BBC BASIC
Once installed and powered up, BeebEm will display the default As you’ll notice, variables with a dollar ($) represent strings, nothing
BBC system start-up, along with a couple of beeps. Those of you after the variable, or a hash (#) represent floating point decimals; a
old enough to have been in a UK school in the 80s will certainly whole integer has a % character, and a byte has an ampersand (&).
recall this setup. The single quotes after 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 lot you can learn, as well as having fun, with
10 print “hello” BBC BASIC. It’s a rainy day project and something that’s interesting to
show the kids – this is how we rolled back in the 80s, kids!
Once you’ve typed the above in, press
There are a number of sites you can visit to learn BBC BASIC, such
Enter and then type:
as http://archive.retro-kit.co.uk/bbc.nvg.org/docs.php3.html.
See what you can come up with using BBC BASIC, or other BASIC
run
types for different systems, and let us know what you’ve created.
We can of course expand the code to
include variables, multi-line print statements, and so on:
OTHER SYSTEMS
Naturally, you don’t have
1 CLS to look to the BBC Micro
10 Input “Hello, what’s your name? “ n$ to play around with some
20 print retro code. If you grew up
30 print “Hi, “ n$ “ I hope you’re well today.” with a Commodore 64, then
you can always try VICE, the
C64 emulator. Likewise, the
ZX Spectrum has a slew of
great emulators available for
every modern system to play
around on. In fact, you can
probably find an emulator for
virtually every 8-bit or 16-bit
machine that was produced
Type RUN to execute the code, you can also type LIST to view the
over the years. Each has their
code you’ve entered.
own unique perspective and
As you can see, variables are handled in much the same way as coding nuances, so find a few
Python, a print statement on its own displays a blank line, and CLS and see what you can create.

www.bdmpublications.com 65
Code Projects and Ideas

Text Animations
There’s a remarkable amount you can do with some simple text and a little Python
know-how. Combining what you’ve already learned, we can create some interesting
animation effects from the command line.

print(message)
THE FINAL COUNTDOWN print(“< >”)
Let’s begin with some example code that will display a large print(“v^v^v^v^v^v^v^v^v^v^v^v^v^v^v”)
countdown from ten, then clear the screen and display a message. print(“\n\n\n”)
The code itself is quite simple, but lengthy. You will 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: https://
some time, but it’s worth it in the end. Of course, you can always take bdmpublications.com/code-portal, 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 of the process is to initialise the code settings and start
good and it’ll be worth adding to your own
the countdown:
games, or presentations, in Python.
#Initialise settings To extend the code, or make it easier to use,
start = 10 you can always create the number functions
message = “> BLAST OFF!! in their own Python code, call it Count.py for
<” example, then import Count at the beginning of
a new Python file called Countdown.py, along with the OS and Time
#Start the countdown
modules:
for counter in range(start, 0, -1):
if counter == 10:
import os
ten()
import time
elif counter == 9:
import count
nine()
elif counter == 8:
From there, you will need to specify the imported code in the
eight()
Countdown section:
elif counter == 7:
seven()
#Start the countdown
elif counter == 6:
for counter in range(start, 0, -1):
six()
if counter == 10:
elif counter == 5:
count.ten()
five()
elif counter == 9:
elif counter == 4:
count.nine()
four()
elif counter == 8:
elif counter == 3:
count.eight()
three()
elif counter == 7:
elif counter == 2:
count.seven()
two()
elif counter == 6:
elif counter == 1:
count.six()
one()
elif counter == 5:
time.sleep(1)
count.five()
os.system(‘cls’ if os.name ==
elif counter == 4:
‘nt’ else ‘clear’)
count.four()
elif counter == 3:
And finally, we can add a display for the message:
count.three()
elif counter == 2:
#Display the message
count.two()
print(“v^v^v^v^v^v^v^v^v^v^v^v^v^v^v”)
elif counter == 1:
print(“< >”)
count.one()

66 www.bdmpublications.com
Text Animations

ROCKET LAUNCH ROLLING DIE


Building on the previous Aside from the rocket animation, together
countdown example, we can with its countdown, another fun bit of text-
create an animated rocket that’ll based animation is that of a rolling dice.
launch after the Blast Off!!
A rolling dice can be a great animation
message has been printed. The
to include in an adventure game, where
code would look something like:
the player rolls to see what their score
is compared to that of an enemy. The
def Rocket():
highest roller wins the round and the losers’ health drops as a result.
distanceFromTop = 20
It’s an age-old combat sequence, used mainly in the Dungeon and
while True:
Dragons board games and Fighting Fantasy novels, but it works well.
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
print(“\n” * distanceFromTop) The code you’ll need to animate a dice roll is:
print(“ /\ “)
print(“ || “) import os
print(“ || “) import time
print(“ /||\ “) from random import randint
time.sleep(0.2)
die = [“ \n O \n “] #1
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
die.append(“ O\n \nO “) #2
distanceFromTop -= 1
die.append(“O \n O \n O”) #3
if distanceFromTop <0:
die.append(“O O\n \nO O”) #4
distanceFromTop = 20
die.append(“O O\n O \nO O”) #5
#Launch Rocket die.append(“O O\nO O\nO O”) #6
Rocket()
def dice():
for roll in range(0,15):
Here, we’ve created a new function called Rocket, which produces
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
the effect of an ASCII-like rocket taking off and scrolling upwards;
print(“\n”)
using the distanceFromTop variable.
number = randint(0,5)
To use this, add it to the end of the previous countdown code and, print(die[number])
at the end of the Blast Off!! message, add the following lines: time.sleep(0.2)
#Main Code Begins
print(“\n\n\n\n”)
dice()
input(“Press Enter to launch rocket...”

You may need to tweak the O entries, to line up the dots on the
This will allow your message 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 will launch.
function to your adventure game code and call it up whenever your
Again, the code in its entirety can be found in the Code Repository character, or the situation, requires some element of luck, combat,
at: https://bdmpublications.com/ code-portal. or chance roll of the dice.

DISCOVER ANIMATIONS
The great thing about Python code is that it’s so accessible. These You’ll find that many professionals will often take to the Internet
few examples will help you add some fun, or something different, to find content they’re after. True, they’re able to code it
to your programs, but they’re just the tip of the proverbial iceberg. themselves, but even experts get stuck sometimes, so don’t worry
If there’s something you want to include in your code, and you’re about hunting code snippets down; you’re in good company.
at a sticking point, then consider heading over to Stack Overflow
and search for Python 3 content.
Stack Overflow is a great online help and resource portal, where
you can ask questions and experts will try and help you. It doesn’t
always work out, but most of the time, you’ll find what you’re
looking for within this great resource.
Also, if you’re after a simple animation then take to Google and
spend some time searching for it. While you may not find exactly
what it is you’re after, you’re bound to come across something
very like the desired effect; all you need to do is modify it slightly
to accomplish your own goals.

www.bdmpublications.com 67
Code Projects and Ideas

Common Coding Mistakes


When you start something new you’re inevitably going to make mistakes, this is purely
down to inexperience and those mistakes are great teachers in themselves. However,
even experts make the occasional mishap. Thing is, to learn from them as best you can.

X=MISTAKE, PRINT Y
There are many pitfalls for the programmer to be aware of, far too many to be listed here. Being able
to recognise a mistake and fix it is when you start to move into more advanced territory.

SMALL CHUNKS EASY VARIABLES


It would be wonderful to be able to Meaningful naming for variables is a must to eliminate
work like Neo from The Matrix movies. common coding mistakes. Having letters of the alphabet
Simply ask, your operator loads it into is fine but what happens when the code states there’s
your memory and you instantly know a problem with x variable. It’s not too difficult to name
everything about the subject. Sadly variables lives, money, player1 and so on.
though, we can’t do that. The first
major pitfall is someone trying to learn
too much, too quickly. So take coding in
small pieces and take your time.

//COMMENTS
Use comments. It’s a simple concept but commenting on
your code saves so many problems when you next come to
look over it. Inserting comment lines helps you quickly sift
through the sections of code that are causing problems;
PLAN AHEAD
also useful if you need to review an older piece of code.
While it’s great to wake up one morning and decide to code
a classic text adventure, it’s not always practical without a
good plan. Small snippets of code can be written without
too much thought and planning but longer and more in-
depth code requires a good working plan to stick to and
help iron out the bugs.

68 www.bdmpublications.com
Common Coding Mistakes
USER ERROR
User input is often a paralysing mistake in code. For
example, when the user is supposed to enter a number for
their age and instead they enter it in letters. Often a user
can enter so much into an input that it overflows some
internal buffer, thus sending the code crashing. Watch those
BACKUPS
user inputs and clearly state what’s needed from them.
Always make a backup of your work, with a secondary
backup for any changes you’ve made. Mistakes can be
rectified if there’s a good backup in place to revert to for
those times when something goes wrong. It’s much easier
to start where you left off, rather than starting from the
beginning again.

RE-INVENTING WHEELS
You can easily spend days trying to fathom out a section SECURE DATA
of code to achieve a given result and it’s frustrating and
often time-wasting. While it’s equally rewarding to solve If you’re writing code
the problem yourself, often the same code is out there on to deal with usernames
the Internet somewhere. Don’t try and re-invent the wheel, and passwords, or
look 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, prior to feeding
into a routine that can
transmit or store it
where someone may be
able to get to view it.

HELP! MATHS
Asking for help is something most of us has struggled If your code makes multiple calculations then you need
with in the past. Will the people we’re asking laugh at us? to ensure that the maths behind it is sound. There are
Am I wasting everyone’s time? It’s a common mistake for thousands of instances where programs have offered
someone to suffer in silence. However, as long as you ask incorrect data based on poor mathematical coding, which
the query in the correct manner, obey any forum rules and can have disastrous effects depending on what the code is
be polite, then your question isn’t silly. set to do. In short, double check your code equations.

www.bdmpublications.com 69
Code Projects and Ideas

Python Beginner’s Mistakes


Python is a relatively easy language to get started in where there’s plenty of room for
the beginner to find their programming feet. However, as with any other programming
language, it can be easy to make common mistakes that’ll stop your code from running.

DEF BEGINNER(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.

VERSIONS INDENTS, TABS AND SPACES


To add to the confusion that most beginners already face when Python uses precise indentations when displaying its code. The
coming into programming, Python has two live versions of its indents mean that the code in that section is a part of the previous
language available to download and use. There is Python version statement, and not something linked with another part of the code.
2.7.x and Python 3.6.x. The 3.6.x version is the most recent, and Use four spaces to create an indent, not the Tab key.
the one we’d recommend starting. But, version 2.7.x code doesn’t
always work with 3.6.x code and vice versa.

THE INTERNET COMMENTING


Every programmer has and does at some point go on the Internet Again we mention commenting. It’s a hugely important factor in
and copy some code to insert into their own routines. There’s programming, even if you’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 comments as to what’s going on. Is this
the code works and what it does before you go blindly running it on function where you lose a life? Write a comment and help you, or
your own computer. anyone else, see what’s going on.

70 www.bdmpublications.com
Python Beginner’s Mistakes

COUNTING LOOPS COLONS


Remember that in Python a loop doesn’t count the last number you It’s common for beginners to forget to add a colon to the end of a
specify in a range. So if you wanted the loop to count from 1 to 10, structural statement, such as:
then you will need to use:
class Hangman:
n = list(range(1, 11)) def guess(self, letter):
Which will return 1 to 10. And so on. The colon is what separates the code, and creates the
indents to which the following code belongs to.

CASE SENSITIVE
Python is a case sensitive programming language, so you will need
to check any variables you assign. For example, Lives=10 is a
different variable to lives=10, calling the wrong variable in your code
can have unexpected results.

OPERATORS
Using the wrong operator is also a common mistake to make. When
you’re performing a comparison between two values, for example,
you need to use the equality operator (a double equals, ==). Using
a single equal (=) is an assignment operator that places a value to a
variable (such as, lives=10).

BRACKETS
Everyone forgets to include that extra bracket they should have
added to the end of the statement. Python relies on the routine OPERATING SYSTEMS
having an equal amount of closed brackets to open brackets, so any
Writing code for multiple platforms is difficult, especially when you
errors in your code could be due to you forgetting to count your
start to utilise the external commands of the operating system. For
brackets; including square brackets.
example, if your code calls for the screen to be cleared, then for
Windows you would use cls. Whereas, for Linux you need to use
clear. You need to solve this by capturing the error and issuing it
with an alternative command.

www.bdmpublications.com 71
Code Projects and Ideas

C++ Beginner’s Mistakes


There are many pitfalls the C++ developer can encounter, especially as this is a more
complex and often unforgiving language to master. Beginners need to take C++ a step
at a time and digest what they’ve learned before moving on.

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.

UNDECLARED IDENTIFIERS STD NAMESPACE


A common C++ mistake, and to be honest a common mistake with Referencing the Standard Library is common for beginners
most programming languages, is when you try and output a variable throughout their code, but if you miss the std:: element of a
that doesn’t exist. Displaying the value of x on-screen is fine but not statement, your code errors out when compiling. You can combat
if you haven’t told the compiler what the value of x is to begin with. this by adding:
using namespace std;
Under the #include part and simply using cout, cin and so on from
then on.

SEMICOLONS GCC OR G++


Remember that each line of a C++ program must end with a If you’re compiling in Linux then you will no doubt come across
semicolon. If it doesn’t then the compiler treats the line with the gcc and g++. In short, gcc is the Gnu Compiler Collection (or Gnu
missing semicolon as the same line with the next semicolon on. This C Compiler as it used to be called) and g++ is the Gnu ++ (the C++
creates all manner of problems when trying to compile, so don’t version) of the compiler. If you’re compiling C++ then you need to
forget those semicolons. use g++, as the incorrect compiler drivers will be used.

72 www.bdmpublications.com
C++ Beginner’s Mistakes

COMMENTS (AGAIN) TOO MANY BRACES


Indeed the mistake of never making any comments on code is back The braces, or curly brackets, are beginning and ending markers
once more. As we’ve previously bemoaned, the lack of readable around blocks of code. So for every { you must have a }. Often it’s
identifiers throughout the code makes it very difficult to look back at easy to include or miss out one or the other facing brace when
how it worked, for both you and someone else. Use more comments. writing code; usually when writing in a text editor, as an IDE adds
them for you.

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.

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++ code.cpp
you went wrong.
This compiles the code in the file code.cpp and create an a.out file
that can be executed with ./a.out. However, if you already have code
in a.out then it’s overwritten. Use:
g++ code.cpp -o nameofprogram

www.bdmpublications.com 73
Congratulations, we have reached the end of your latest
tech adventure. With help from our team of tech experts,
you have been able to answer all your questions, grow in
confidence and ultimately master any issues you had. You
can now proudly proclaim that you are getting the absolute
best from your latest choice from the ever changing world of
consumer technology and software.

So what’s next? Do you want to start a new hobby? Are


you looking to upgrade to a new device? Or simply looking
to learn a new skill? Whatever your plans we are here to
help you. Just check our expansive range of For Beginners
guidebooks and we are positive you will find what you
are looking for. This adventure with us may have ended,
but that’s not to say that your journey is over. Every new
hardware or software update brings its new features and
challenges, and of course you already know we are here to
help. So we will look forward to seeing you again soon.
Discover more of
our guides...
techgo techgo techgo techgo

MacBook macOS Make Your Online


Tricks and Tips Catalina Own PC Security
Tricks and Tips Tricks and Tips Tricks and Tips
Gain
Gain Insider
Insider Skills
Skills

Gain
Gain
Insider
Insider Skills
Skills
Next level Advanced Rediscover Next level Advanced Rediscover Next level Advanced Rediscover Next level Advanced Rediscover
Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device

techgo techgo techgo techgo

Outdoor Adobe Adobe Raspberry Pi


Photography Elements Lightroom Tricks and Tips
Tricks and Tips Tricks and Tips Tricks and Tips
Gain
Gain Insider
Insider Skills
Skills

Gain Gain
Insider Insider
Skills Skills

Next level Advanced Rediscover Next level Advanced Rediscover Next level Advanced Rediscover Next level Advanced Rediscover
Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device

techgo techgo techgo techgo

Samsung WhatsApp Windows 10 Canon


Galaxy Tricks and Tips Tricks and Tips
Tricks and Tips
Tricks and Tips Gain
Insider
Skills
Gain
Insider
Gain
Insider
Skills
Skills

Gain
Insider
Skills

Next level Advanced Rediscover Next level Advanced Rediscover Next level Advanced Rediscover Next level Advanced Rediscover
Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device

techgo techgo techgo techgo

Nikon Linux macOS iOS 14


Tricks and Tips Tricks and Tips Big Sur Tricks and Tips
Gain
Insider
Skills Gain
Tricks and Tips Gain
Insider
Skills
Insider
Skills

Gain
Insider
Skills

Next level Advanced Rediscover Next level Advanced Rediscover Next level Advanced Rediscover Next level Advanced Rediscover
Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device Secrets & Fixes Guides & Tips Your Device

.
Black Dog Media

From to
Beginner
Master Your Tech
Master Your Tech From Beginner Expert
to Expert
To continue learning
To continue more about
learning more Raspberry
about yourPitech
& Coding
visit usvisit
at: us at:
www.bdmpublications.com
www.bdmpublications.com
FREE
FREE Tech Guides
Guides
FREE Tech Guides

Raspberry Pi 4 Programming with Python


PC & Windows 10 Samsung & Android

Apple iPhone,
Coding Guides,iPad,
Tips & Tricks Photography,
Learn & Master C++ Coding Python,
Testing Linux Distros
Mac, MacBook & Watch Photoshop & Lightroom Raspberry Pi & Linux

EXCLUSIVE Offers
EXCLUSIVE
on Offers on
Tech Guidebooks
our Tech Guidebooks
G Print & digital editions
Print & digital
G Featuring editions
the latest updates bdmpublications.com/ultimate-photoshop
G Step-by-step Buy our Photoshop guides and download tutorial
Featuring the tutorials & guides
very latest updates
images for free! Simply sign up and get creative.
G Created by BDM
Step-by-step experts
tutorials and guides
G Created by BDM experts
When you sign up to our
PLUSout SPECIAL
Check our latest titlesDEALS
today! and Bonus Content monthly newsletter!

PLUS
Coding Tricks and Tips – 5th Edition © 2021 Papercut Limited All rights reserved. No part of this publication reviewer - as an individual - and is not representative of the publisher

SPECIAL DEALS
Raspberry Pi For Beginners © 2020 Papercut Limited All rights reserved. No part of this publication reviewer - as an individual - and is not representative of the publisher
ISBN: 978-1-912847-53-2 may be reproduced in any form, stored in a retrieval system or or any of its affiliates. Therefore the publisher holds no responsibility in
3rd Edition may be reproduced in any form, stored in a retrieval system or or any of its affiliates. Therefore the publisher holds no responsibility in
integrated into any other publication, database or commercial regard to editorial opinion and content.
Published by: Papercut Limited integrated into any other publication, database or commercial regard to editorial opinion and content.
ISBN: 978-1-912847-33-4 programs without the express written permission of the publisher. This is an independent publication and as such does not necessarily reflect

and Bonus Content


programs without the express written permission of the publisher. This is an independent publication and as such does not necessarily reflect
Digital distribution by: Under no circumstances should this publication and its contents be the views or opinions of the producers of apps or products contained
Published by: Papercut Limited Under no circumstances should this publication and its contents be the views or opinions of the producers of apps or products contained
resold, loaned out or used in any form by way of trade without the within. This publication is 100% unofficial. All copyrights, trademarks and
Readly AB, Zinio, Magzter, Cafeyn, PocketMags resold, loaned out or used in any form by way of trade without the within. This publication is 100% unofficial. All copyrights, trademarks and
Digital distribution by: publisher’s written permission. While we pride ourselves on the quality registered trademarks for the respective companies are acknowledged.
publisher’s written permission. While we pride ourselves on the quality registered trademarks for the respective companies are acknowledged.
of the information we provide, Papercut Limited reserves the right not Relevant graphic imagery reproduced with courtesy of brands and products.
Readly AB, Zinio, Magzter, Cafeyn, PocketMags of the information we provide, Papercut Limited reserves the right not Relevant graphic imagery reproduced with courtesy of brands and products.
to be held responsible for any mistakes or inaccuracies found within
to be held responsible for any mistakes or inaccuracies found within
the text of this publication. Due to the nature of the tech industry, the
Sign up to our monthly newsletter
Additional images contained within this publication are reproduced under
Additional images contained within this publication are reproduced under
licence from Shutterstock. Prices, international availability, ratings, titles and
bdmpublications.com/ultimate-photoshop the text of this publication. Due to the nature of the tech industry, the
publisher cannot guarantee that all apps and software will work on
publisher cannot guarantee that all and get the latest updates, offers
licence are
content from Shutterstock.
subject Prices, international availability, ratings, titles and
to change.
content are subject to change.
every version of device. It remains theapps and software
purchaser’s will work on
sole responsibility
Buy our Photoshop guides and download tutorial
every
to version the
determine
to determine
of device. It remains
suitability the purchaser’s
of this book and its content for whatever and news from BDM. We are here
sole responsibility All information was correct at time of publication. Some content may have
All information was correct at time of publication. Some content may have
purpose. Any the
appsuitability of this bookonand
images reproduced theitsfront
content
and for whatever
back cover been previously published in other volumes or titles.
images for free! Simply sign up and get creative.
purpose.
are
are
solely Any
solely for
app images
for design
design
purposes
purposes
reproduced
and are not
and are
on representative
not
the front and of
representative
back
of
content.to help
cover
content.
you Master Your Tech!
been previously published in other volumes or titles.
Papercut Limited
We advise all potential buyers to check listing prior to purchase for Papercut Limited
We advise allofpotential
confirmation buyersAlltoeditorial
actual content. check listing
opinionprior to ispurchase
herein for
that of the Registered in England & Wales No: 4308513
confirmation of actual content. All editorial opinion herein is that of the Registered in England & Wales No: 4308513

You might also like