Coding Programming - A Guide For Beginners 10 2021-03-07
Coding Programming - A Guide For Beginners 10 2021-03-07
Coding
Tricks and Tips
Gain
Insider
Skills
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
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
£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
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!
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
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.
www.bdmpublications.com 7
Coding with Windows 10 Batch Files
.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
8 www.bdmpublications.com
What is a Batch File?
Batch files are plain text and often created using Notepad. However, if you’re working in the command prompt with
elevated privileges to begin with, as the Administrator, then
the UAC won’t question the batch file and continue regardless
of what files are being deleted.
The Autoexec.bat was the first such file many users came across in
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.
www.bdmpublications.com 9
Coding with Windows 10 Batch Files
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.
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
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 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
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 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
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
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
: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
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.
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.
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-
24 www.bdmpublications.com
Why Linux?
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.
www.bdmpublications.com 25
Coding on Linux
Linux Mint has three main desktop versions available with each
new version of the core OS it releases. This may sound confusing
at first, but it’s quite simple. Currently, Linux Mint uses the
Cinnamon Desktop Environment as its flagship model, although
MATE and Xfce models are also available.
UBUNTU – UBUNTU.COM
The second most popular distro available is Ubuntu: an ancient
African word meaning ‘humanity to others’. Ubuntu’s popularity
has fluctuated over its fourteen-year life. At one time, it was
easily the most used, Linux-based operating system in the
world, sadly, some wrong choices along the way with regards
to its presentation, along with some unfavourable and
controversial elements involving privacy, saw it topple from the
number one spot. and it’s a little heavy on system resources (especially if you plan
to install it on an older computer).
That said; Ubuntu has since made amends and is slowing crawling
its way back up the Linux leader board. The latest versions of Ubuntu, for all its faults, is a good Linux distro to start
the OS use the GNOME 3 desktop environment, it’s impressive experimenting with. It’s a clean interface, easy to use and install
although it can be a little confusing for former Windows users and offers the user the complete Linux experience.
26 www.bdmpublications.com
The Best Linux Distributions
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
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
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
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
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
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
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
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
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.
46 www.bdmpublications.com
Creating Bash Scripts – Part 4
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
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.
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.
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
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 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 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.
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.
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.
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.
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.
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.
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
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
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
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.
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.
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.
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
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
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.
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
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
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
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.
//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
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.
70 www.bdmpublications.com
Python Beginner’s Mistakes
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
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.
72 www.bdmpublications.com
C++ Beginner’s Mistakes
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.
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
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
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
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
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