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

PCL. the Complete C++ & Python Manual 15ed 2023

The document is a manual for learning Python and C++ programming, highlighting the importance of programming in modern technology. It provides step-by-step tutorials and guides for beginners, covering setup, basic concepts, and practical applications of both languages. The manual emphasizes the accessibility and versatility of Python and C++, making them ideal for newcomers to programming.

Uploaded by

cassanovaxd5688
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

PCL. the Complete C++ & Python Manual 15ed 2023

The document is a manual for learning Python and C++ programming, highlighting the importance of programming in modern technology. It provides step-by-step tutorials and guides for beginners, covering setup, basic concepts, and practical applications of both languages. The manual emphasizes the accessibility and versatility of Python and C++, making them ideal for newcomers to programming.

Uploaded by

cassanovaxd5688
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 148

LEARN PYTHON & C++ CODING

The Complete

& Python
Manual

OVER

F9C
GUIDES
&TIPS

www.pclpublications.com S Popercut 100% INDEPENDENT


The Complete
Manual Series
Available on
DESKTOP PC, LAPTOP & SURFACE ■■

y The Complete The Complete The lete

Windows 10 WhatsApp
User Manual Manual
Master Windows 10 on your PC
to mastering WhatsApp
with step-by-step tutorials and guides
-—MOStd^professiondl technic Photoshop Ughtroom and
and Improvejr^ur photogrt improve your photo editing skills

880
□o&q 900

BsexiiAo.uios.nrs STuronw^j

The Complete ‘ The Complete The Complete The Complete


Photqgrqf
Mac
User Manual
MacBook
User Manual
The essential manual to mastering
your MacBook and macOS Ventura
Outdoor
Photography
Manual
Master your Mac and macOS Ventura

W»lpMw
Master yourtdrnera 890 । Ventura rual to improvTUg out
PhotograjSSg§tdf!s

ON PHOTOGRAPHY & CAMERAS

The complete The Complete The Complete The Complete

Nikon, Python
Coding Manual
Raspberry
Coding
Camera Manual
Manual
The essential manual to improve your
Raspberry Pi coding skills

920
The essential programming manual
Master jrour Nitron a®»« to improve your Python coding skills
one Improve your photographic

The Complete The Complete e The Complete The Complete


Samsung Mac Cloud
Galaxy Linux
Coding Manual Studio Computing
Manual " Manual Manual
Master your Samsung Galaxy
^^^^smaitphone and tablet
§ 'uW Master your Apple Mac Studio & Display Master Cloud storage and services

over
for home and business

Master'Linux qnW Improve J/dur


- ” 'll । ^ur^fd^fbfhmfng Skills s ■ TT
— I I I I--T'^---------
3 Po percut

For a full list of titles available visit:


www.pclpublications.com
The Complete

C++
& Python
Manual
Unleash the power of Python and C++
Having a basic knowledge of programming can open many different
doors for the newcomer to explore. You can gain a better understanding
of how hardware and software work together, how your computer or
device functions and how incredible open-world gaming environments are
converted from ones and zeros to what's on your monitor or TV.
Technology is everywhere and it's all connected through programming.
Your TV, microwave, in-car entertainment and the Internet itself are all
reliant on good programming to make them work the way you want them
to. Within these pages are the building blocks to help you take your first
steps into the world of programming. We've taken two of the most
powerful and versatile programming languages available, Python and C++
and broken them down into bite-sized tutorials and guides to help you
learn how they work, and how to make them work for you.

3 Papercut
www.pclpublications.com
Contents

Contents
Say Hello to Python

8 Why Python?
10 Equipment You Will Need
12 Getting to Know Python
14 How to Set Up Python in Windows
16 How to Set Up Python on a Mac
18 How to Set Up Python in Linux 56 Date and Time
58 Opening Files
60 Writing to Files
Getting Started with Python 62 Exceptions
64 Python Graphics
22 Starting Python For the First Time
24 Your First Code
26 Saving and Executing Your Code
Using Modules
28 Executing Code From the Command Line
30 Numbers and Expressions 68 Calendar Module
32 Using Comments 70 OS Module
34 Working with Variables 72 Random Module
36 User Input 74 Tkinter Module
38 Creating Functions 76 Pygame Module
40 Conditions and Loops 80 Create Your Own Modules
42 Python Modules

(86)
Say Hello to C++
44)
Working with Data
84 Why C++?
46 Lists 86 Equipment Needed
48 Tuples 88 How to Set Up C++ in Windows
50 Dictionaries 90 How to Set Up C++ on a Mac
52 Splitting and Joining Strings 92 How to Set Up C++ in Linux
54 Formatting Strings 94 Other C++ IDEs to Install

4 Python & C++ Coding


r Contents

For more
great coding
titles visit us at:
WWW.
pclpublications.com

Raspberry Pi
& Linux

124) Loops and Decision Making

98 Your First C++Program 126 While Loop


100 Structure of a C++Program 128 For Loop
102 Compile and Execute 130 Do... While Loop
104 Using Comments 132 IfStatement
106 Variables 134 If... Else Statement
108 Data Types
110 Strings
112 C++Maths
136) Working with Code

138 Common Coding Mistakes


114; C++ Input/Output
140 Beginner Python Mistakes
116 User Interaction 142 Beginner C++Mistakes
118 Character Literals 144 Where Next?
120 Defining Constants
122 File Input/Output

www.pclpublications.com 5
Say Hello
to Python

Python & C++ Coding


Say Hello to Python

There are many different programming


languages available to learn and use.
Some are complex and incredibly
powerful and some are extremely basic
and used as minor utilities for operating
systems. Python sits somewhere in the
middle, combining ease of use with a
generous helping of power that allows
the user to create minor utilities, a range
of excellent games and performance­
heavy computational tasks.

However, there's more to Python than


simply being another programming
language. It has a vibrant and lively
community behind it that shares
knowledge, code and project ideas; as
well as bug fixes for future releases.
It's thanks to this community that the
language has grown and thrived and now
it's your turn to take the plunge and learn
how to program in Python.

The first half of this book helps you


get started with the latest version of
Python and from there guide you on how
to use some of the most common and
interesting functions and features of the
language. Before long, you will be able to
code your own helpful system tools, text
adventures and even control a character
as they move around the screen.

8 Why Python?
10 Equipment You Will Need
12 Getting to Know Python
14 How to Set Up Python in Windows
16 How to Set Up Python on a Mac
18 How to Set Up Python in Linux

www.pclpublications.com
Say Hello to Python

Why Python?
There are many different programming languages available for the modern computer,
and some still available for older 8 and 16-bit computers too. Some of these languages
are designed for scientific work, others for mobile platforms and such. So why choose
Python out of all the rest?

PYTHON POWER
Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee
hours, slaving over an overheating heap of circuitry to create something akin to magic.

These pioneers of programming carved their way into a new Regardless of whether you use an Android device, iOS device, PC,
frontier, forging small routines that enabled the letter 'A' to scroll Mac, Linux, Smart TV, games console, MP3 player, GPS device built-in
across the screen. It may not sound terribly exciting to a generation to a car, set-top box ora thousand other connected and 'smart'
that's used to ultra-high definition graphics and open world, multi­ appliances, behind them all is programming.
player online gaming. However, forty-something years ago it was
blindingly brilliant. All those aforementioned digital devices need instructions to tell
them what to do, and allow them to be interacted with. These
Naturally these bedroom coders helped form the foundations for instructions form the programming core of the device and that core
every piece of digital technology we use today. Some went on to can be built using a variety of programming languages.
become chief developers for top software companies, whereas
others pushed the available hardware to its limits and founded the The languages in use today differ depending on the situation, the
billion pound gaming empire that continually amazes us. platform, the device's use and how the device wilt interact with its

C++ is usually reserved for more complex


programs, operating systems, games and so on.

Python & C++ Coding


Why Python?

environment or users. Operating systems, such as Windows, macOS Python was created over twenty sixyears ago and has evolved to
and such are usually a combination of C++, C#, assembly and some become an ideal beginner's language for learning how to program a
form of visual-based language. Games generally use C++ whilst web computer. It’s perfect for the hobbyist, enthusiast, student, teacher
pages can use a plethora of available languages such as HTML, Java, and those who simply need to create their own unique interaction
Python and so on. between either themselves or a piece of external hardware and the
computer itself.
More general-purpose programming is used to create programs,
apps, software or whatever else you want to call them. They're Python is free to download, install and use and is available for Linux,
widely used across all hardware platforms and suit virtually every Windows, macOS, MS-DOS, OS/2, BeOS, IBM i-series machines, and
conceivable application. Some operate faster than others and some even RISC OS. It has been voted one of the top five programming
are easier to learn and use than others. Python is one such general- languages in the world and is continually evolving ahead of the
purpose language. hardware and Internet development curve.

Python is what's known as a High-Level Language, in that it'talks' So to answer the question: why python? Simply put, it’s free, easy to
to the hardware and operating system using a variety of arrays, learn, exceptionally powerful, universally accepted, effective and a
variables, objects, arithmetic, subroutines, loops and countless superb learning and educational tool.
more interactions. Whilst it's not as streamlined as a Low-Level
Language, which can deal directly with memory addresses, call
stacksand registers, its benefit is that it's universally accessible 4.0 LET py = 15
70 FOR w = 1 TO 10
and easy to learn. 71 CLS
75 LET by =INT (RND+28)
80 LET bx = 0
|//fi le: invoke, java 90 FOR d = 1 TO 20
import java.lang.reflect.*; 100 PRINT AT px,py;" U "
110 PRINT AT bx,by;"o"
class invoke { 120 IF INKEY$="p" THEN LET py=p
public static void main( String [] args ) { y +1
try { 130 IFINKEYJ="O" THEN LET py=p
y -1 U
Class c = Class.forName/ args[0] ); 135 FOR n=l TO 100: NEXT n
Method m = c.getMethod( argsfl], new class 14-0 IF py<2 THEN LET p y = 2
[] { } ); 150 IF py>27 THEN LET pu=27
Object ret = m.invoke( null, null ); 180 LET bx=bx+l
system.out.pri ntln( 185 PRINT AT bX-l,by;" ”
"invoked static method: " + args[1] 190 NEXT d
+ " of class: " + args[0] 200 IF (by-l)=py THEN LET S=S+1
+ " with no args\nResults: " + ret ); 210 PRINT AT 10,10;"score=";s
220 FOR V=1 TO 1000: NEXT V
catch ( ClassNotFoundException e ) { 300 NEXT W
// class.forName( ) can’t find the class
} catch ( NoSuchMethodException e2 ) { 0 OK, 0:1
// that method doesn't exist
catch C lllegalAccessException e3 ) {
// we don't nave permission to invoke that BASIC was once the starter language that early
method
8-bit home computer users learned.
} catch ( InvocationTargetException e4 ) {
// an exception ocurred while invoking that
method
system.out.pri ntln( print(HANGMAN[0])
attempts = len(HANGMAN) - 1
"Method threw an: " + e4.
getTargetException( ) );
while (attempts != 0 and in word_guessed):
print((”\nYou have {} attempts remaining").format(attempts))
joined_word = "".join(word_guessed)
print(joined_word)

Java is a powerful language try:


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

guessed_letters.append(playerguess)

for letter in range(len(chosen_word)):


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

if player_guess not in chosen_word:

Python is a more modern take on BASIC, it's easy to learn


and makes Foran ideal beginner’s programming language.

www.pclpublications.com
Say Hello to Python

EquipmentYou
Will Need
You can learn Python with very little hardware or initial financial investment. You
don't need an incredibly powerful computer and any software that's required is
freely available.

WHAT WE'RE USING


Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linux, Raspberry Pi and more. If
you have one of those systems, then you can easily start using Python.

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

AN IDE
An IDE (Integrated Developer Environment) is used to enter and execute Python
code. It enables you to inspect your program code and the values within the code, as
well as offering advanced features. There are many different IDEs available, so find
the one that works foryou and gives the best results.

PYTHON SOFTWARE
macOS and Linux already come with Python preinstalled as part of the operating
system, as does the Raspberry Pi. However, you need to ensure that you're running
the latest version of Python. Windows users need to download and install Python,
which we'll cover shortly.

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

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

TIME AND PATIENCE


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

Python & C++ Coding


Q Equipment You Will Need

THE RASPBERRY PI
Why use a Raspberry Pi? The Raspberry Pi is a tiny computer that’s very cheap to purchase but offers the user a fantastic learning
platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many Modules and extras.

RASPBERRY PI

The Raspberry Pi 3 is the latest version, incorporating a more


powerful CPU, more memory, Wi-Fi and Bluetooth support.
You can pick up a Pi for around £32 or as a part of kit for £50+,
depending on the kityou're interested in.

FUZE PROJECT

The FUZE is a learning environment built on the latest model


of the Raspberry Pi. You can purchase the workstations that
come with an electronics kit and even a robot arm for you to
build and program. You can find more information on the FUZE
atwww.fuze.co.uk.

BOOKS

We have several great coding


titles available via www.
pclpublications.com. Our Pi
RASPBIAN books cover how to buy your
first Raspberry Pi, set it up and
The Raspberry Pi's main operating system is a Debian-based use it; there are some great
Linux distribution that comes with everything you need in step-by-step project examples
a simple to use package. It’s streamlined for the Pi and is an and guides to get the most
ideal platform for hardware and software projects, Python from the Raspberry Pi too.
Jargon-frd
Tips & Adj
programming and even as a desktop computer.

Ceding &P^eCts jt Manual Se,

=52^
Coding & Programming
| ihe essentia! &
steP-by-step
manual to /’+>Ss7
Improving your
nu* programming
md Cortina

OVER /’’’GEsF
795
Raspberry
Raspberry

pi 4 400
SEP!

2°22 EDITION

www.pclpublications.com
Say Hello to Python

Getting to
Know Python
Python is the greatest computer programming language ever created. It enables
you to Fully harness the power of a computer, in a language that's clean and easy
to understand.

WHAT IS PROGRAMMING?
It helps to understand what a programming language is before you try to learn one, and Python is no different. Let’s take a
look at how Python came about and how it relates to other languages.

■ (:\UcMS\luryh\Droph<wW_Artinn\rfripeNt - Sublime lent (UNRfGIS I HttU)

PYTHON PROGRAMMING RECIPES file Edit Selection find View Goto Tools Project Preferences Help

Programs are like recipes forcomputers. A 1 |Put 100 grams of self-raising flour in a bowl.
A programming language recipe to bake a cake could go like this: 2 Add 100 grams of butter to the bowl.
is a list of instructions that 3 Add 100 millilitres of milk.
4 Bake for half an hour.
a computer follows. These Put 100 grams of self-raising flour in a bowl.
instructions can be as simple Add 100 grams of butter to the bowl.
as displaying your name Add 100 millilitres of milk.
or playing a music file, or Bake for half an hour.
as complex as building a
whole virtual world. Python
[4 C:\UwrsMucyti\OropboiAO.Artion\Mlrew<2.7.11)
is a programming language CODE He Edit Form* Run Options Window Help
class Cake(object)s
conceived in the late 1980s def init (self):
Just like a recipe, a program consists of instructions that you follow self.ingredients = []
by Guido van Rossum d - cook(self,ingredients) :
in order. A program that describes a cake might run like this: print "Baking cake ..."
at Centrum Wiskunde &
cake = CakeO
Informatica (CWI) in the | bowl = □
bowl ■ []
Netherlands as a successor to flour = 100 flour - 100
butter = 50
the ABC language. butter = 50 milk = 100
bowl.append([flour,butter,milk])
| milk = 100
ca ke.coo k(bowl)
Guido van Rossum, the | bowl. append ( [flour, butter, mi Ik]) I

father of Python. cake.cook(bowl)

PROGRAM COMMANDS
You might not understand some of the Python commands, like bowl.append and cake.cook(bowl).
The first is a list, the second an object; well look at both in this book. The main thing to know is
that it's easy to read commands in Python. Once you learn what the commands do, it's easy to
figure out how a program works.

Python 3.4 2 Shell cake py - /home/pi/Documents/cake.py (3.4.2)


Die Cdit Shell Qebug fiptions Endows Help filo Edit Ffirmat gun Options Endows Help
Python 3.4.2 (default, Oct 19 2014, 13:31:11) I Cake(objecl);
(GCC 4.9.1] on linux | def _ init_ (self):
Type "copyright", "credits” or "licenseO” for more information. self.ingredients - []
»>------------------------------------------------ RESTART------------------------------- def cook(self. ingredients):
print ("Baking cake.. ")
Baking cake...
* cake'CakeO

bowl - (]
flour - 100
butter • 50
milk - 100
bowl.append((flour, butter, milk])
cake.cook(bowl)

Python & C++ Coding


(^Getting to Know Python

HIGH-LEVEL LANGUAGES ZEN OF PYTHON


Computer languages that a re easy to read are known as "high-level". Python lets you access all the power of a computer in a language
This is because they fly high above the hardware (also referred to as that humanscan understand. Behind all this is an ethos called "The
"the metal"). Languages that "fly close to the metal," like Assembly, Zen of Python." This is a collection of 20 software principles that
are known as "low-level". Low-level languages commands read a bit influences the design of the language. Principles include "Beautiful
like this:msg db ,0xa len equ $ - msg. is better than ugly" and "Simple is better than complex." Type
import this into Python and it wilt display all the principles.

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

When you visit the Python In 2008 Python 3 arrived with several new
WORLD OF PYTHON PYTHON 3.X
Download page you'll notice that and enhanced features. These features
there are two buttons available: one for Python 3.6.2 and the other provide a more stable, effective and efficient programming
for Python 2.7.13; correct at the time of writing (remember Python is environment but sadly, most (if not all) of these new features are
frequently updated so you may see different version numbers). not compatible with Python 2 scripts, modules and tutorials. Whilst
not popular at first, Python 3 has since become the cutting edge of
Python programming.
Download the latest version for Windows
|_<i Python 3.6.1 Shell — □ >
Download Python 3.6.2 I Download Python 2.7.13
File Edit Shell Debug Options Window Help
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)]
Wondering which version to use? Here’s more about the difference on Win32
Type "copyright", "credits" or "license ()" for more information.
between Python 2 and 3.

Looking for Python with a different OS? Python for Windows,

Linux/UNIX, Mac OS X, Other

Want to help test development versions of Python? Pre releases

So why two? Well, Python 2 was originally Python 3's growing popularity has meant that
launched in 2000 and has since then it's now prudent to start learning to develop
adopted quite a large collection of modules, scripts, users, tutorials with the new features and begin to phase out the previous version.
and so on. Over the years Python 2 has fast become one of the first Many development companies, such as SpaceX and NASA use
go to programming languages for beginners and experts to code Python 3 for snippets of important code.
in, which makes it an extremely valuable resource.

I Li Python 2.7.13 Shell - □ X I

I File Edit Shell Debug Options Window Help I


Il Python 2.7.13 (v2.7.13:a06454blafal, Dec 17 2016, 20:42:59) fMSC v.1500 32 bit ( *|l
I Intel)] on Win32
l| Type "copyright", "credits" or "license!)" for more information.

www.pclpublications.com
Say Hello to Python

How to Set Up
Python in Windows
Windows users can easily install the latest version of Python via the main Python
Downloads page. Whilst most seasoned Python developers may shun Windows as the
platform of choice for building their code, it's still an ideal starting point for beginners.

INSTALLING PYTHON 3.X


Microsoft Windows doesn't come with Python preinstalled as standard, so you're going to have to install it yourself manually.
Thankfully, it's an easy process to follow.

Start by opening your web browser to www.python. Choosing the Customise option allows you to
STEP1 STEP 3
org/downloads/. Look for the button detailing the specify certain parameters, and whilst you may
download link for Python 3.x.x (in our case this is Python 3.6.2 but as stay with the defaults, it’s a good habit to adopt as sometimes (not
mentioned you may see later versions of 3). with Python, thankfully) installers can include unwanted additional
features. On the first screen available, ensure all boxes are ticked
and click the Next button.

Download the latest version for Windows Optional Features


0 Documentation
Download Python 3.6.2 II Download Python 2.7.13 Installs the Python documentation file.

0 pip
Installs pip, which can download and install other Python packages.
Wondering which version to use? Here’s more about the difference
0 td/tk and IDLE
between Python 2 and 3. Installs tkinter and the IDLE development environment.

0 Python test suite


Looking for Python with a different OS? Python for Windows,
Installs the standard library test suite.
Linux/UNIX, Mac OS X, Other 0 py launcher 0 for all users (requires elevation)
Installs the global 'py' launcher to make it easier to start Python.
Want to help test development versions of Python? Pre-releases
python
for
windows Back [ Next | | Cancel |

STEP 2 Click the download button for version 3.x, and STEP 4 The next page of options include some interesting
save the file to your Downloads folder. When the additions to Python. Ensure the Associate file with
file is downloaded, double-dick the executable and the Python Python, Create Shortcuts, Add Python to Environment Variables,
installation wizard will launch. From here you have two choices: Precompile Standard Library and Install for All Users options are
Install Nowand Customise Installation. We recommend opting for ticked. These make using Python later much easier. Click Install when
the Customise Installation link. you're ready to continue.

Install Python 3.6.2 (32-bit) Advanced Options


Select Install Now to install Python with default settings, or choose 0 Install for all users
Customize to enable or disable features. 0 Associate files with Python (requires the py launcher)

0 Create shortcuts for installed applications


Install Now
0 Add Python to environment variables
C:\Users\david\AppData\Local\Programs\Python\Python36-32
0 Precompile standard library
Includes IDLE, pip and documentation
Creates shortcuts and file associations □ Download debugging symbols

□ Download debug binaries (requires VS 2015 or later)

—> Customize installation


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

python python
for 0 Install launcher for all users (recommended) for

windows □ Add Python 3.6 to PATH Cancel windows Back | ^Install | | Cancel |

Python & C++ Coding


How to Set Up Python in Windows

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

[jjl Python 3.6.2 Shell — □ X

Setup was successful File Edit Shell Debug Options Window Help
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)]
on Win32
Special thanks to Mark Hammond, without whose years of
Type "copyright", "credits" or "license!)" for more information.
freely shared Windows expertise. Python for Windows would
still be Python for DOS.

New to Python? Start with the online tutorial and


documentation.

See what's new in this release.

Q Disable path length limit


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

python
for
windows Close

Before you close the install wizard window, STEP 9 If you now click on the Windows Start button again,
STEP 6
J however, it’s best to click on the link next to the and this time type: CMD, you'll be presented with the
shield detailed Disable Path Length Limit. This will allow Python Command Prompt link. Click it to get to the Windows command line
to bypass the Windows 260 character limitation, enabling you to environment. To enter Python within the command line, you need
execute Python programs stored in deep folders arrangements. to type: python and press Enter.
Again, click Yes to authenticate the process; then you can Close the
S3 Command Prompt - python
installation window.
Microsoft Windows [Version 10.0.15063]
(c) 2017 Microsoft Corporation. All rights reserved.

C:\Users\davidxpython
Python 3.6.2 (v3.6.2:5fd33b5, 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on Win32
Type "help", "copyright", "cr ' or "license" for more information.

® Disable path length limit


Changes your machine configuration to allow programs, including Python, to
bypass the 2&0 character "MAX.PATH" limitation.

Close

The command line version of Python works in


STEP 7 Filters STEP 10
much the same way as the Shell you opened in
Best match
Windows 10 userswill now Step 8; note the three left-facing arrows (»>). Whilst it's a perfectly
IDLE (Python 3.6 32-bit)
find the installed Python fine environment, it's not too user-friendly, so leave the command
Desktop app
3.x within the Start button line for now. Enter: exitQ to leave and close the Command
Search suggestions
Recently Added section. The Prompt window.
P idle - See web results
first link, Python 3.6 (32-bit)
B Command Prompt
will launch the command
Microsoft windows [version 10.0.15063]
line version of Python when (c) 2017 Microsoft Corporation. All rights reserved.

clicked (more on that in a C:\Users\david>python


Python 3.6.7 (v3.6.2:Sfd33hS, .lul R 2017, 04:14:34) [MSC v.1000 3? hit (Intel)] on win37
moment). To open the IDLE, Type "help", "copyright", "credits" or "license" for more information.
>» exit()
type IDLE into Windows start.
C:\Users\david>


■+-■ P idle)

www.pclpublications.com
Say Hello to Python

How to Set Up
Python on a Mac
If you're running an Apple Mac, then setting up Python is incredibly easy. In fact a
version of Python is already installed. However, you should make sure you're running
the latest version.

INSTALLING PYTHON
Apple's operating system comes with Python installed, so you don’t need to install it separately. However, Apple doesn't
update Python very often and you're probably running an older version. So it makes sense to check and update first.

STEP1 Open a new Terminal window by clicking Go > Click on the latest version of Python 3.x, in our
STEP 3
Utilities, then double-click the Terminal icon. Now case this is the download button for Python 3.6.2.
enter: python --version. You should see "Python 2.5.1" and This will automatically download the latest version of Python and
even later, if Apple has updated the OS and Python installation. depending on how you've got your Mac configured, it automatically
Either way, it's best to check for the latest version. starts the installation wizard.

Open Safari and head over to www.python.org/ STEP 4 With the Python installation wizard open, click on
STEP 2
a downloads. Just as with the Windows setup the Continue button to begin the installation. It's
procedure on the previous pages, you can see two yellow download worth taking a moment to read through the Important Information
buttons: one for Python 3.6.2, and the other for Python 2.7.13. section, in case it references something that applies to your version
Note, that version numbers may be different due to the frequent of macOS. When ready, click Continue again.
releases of Python.

Download the latest version for Mac OS X


Download Python 3.6.2 I Download Python 2.7.13

Wondering which version to use? Here's more about the difference

between Python 2 and 3.

Looking for Python with a different OS? Python for Windows,


Linux/UNIX, Mac OS X, Other

Want to help test development versions of Python? Pre releases

Python & C++ Coding


How to Set Up Python on a Mac

The next section details the Software License There's nothing much else left to do in the Python
STEP 5 STEP 8
A Agreement, and whilst not particularly interesting A installation wizard so you can click the Close button.
to most folks, it's probably worth a read. When you're ready, click on If you now drop back into a Terminal session and re-enter the
the Continue button once again. command: python3 --version, you can see the new version is
now listed. To enter the command line version of Python, you need
to enter: python3.To exit, it’s: exit().
Install Python

Finally you're be presented with the amount of You need to search in Finder for the Python IDLE;
STEP 6 STEP 9
space Python will take up on your system and an when you've found it, click it to launch and it
Install button, which you need to click to start the actual installation should look similar to that of the Windows IDLE version shown on
of Python 3.x on to your Mac. You may need to enter your password the previous page. The only difference being the Mac detected
to authenticate the installation process. hardware platform it’s running on.

• W Python 3.6.0 Shell


Python 368 G3.6 0:41df79263oll, Dec 22 2816, 17:23:133
[CCC 4.2.1 (Apple Inc. build 5666) (dot 3)3 on darwin
Type "copyright", "credits" or "licenseO" for more information.
»> WARNING: The version of Tcl/Tk (8.5.9) in use way be unstable.
Visit http://www.python.org/downlood/fflac/tcltlc/ for current infoneation.

The installation shouldn’t take too long; the older Older Mac versions may have trouble with the
STEP 7 STEP 10
________ J Mac Mini we used in this section is a little slower Anewer versions of Python, in which case you will
than more modern Mac machines and it only took around thirty need to revert to a previous Python 3.x build; as long as you're using
seconds for the Installation Successful prompt to be displayed. Python 3.x, the code in this book wilt work for you.

A O Python Shell

Python 3.1.2 (r312:7936OM, Mar 24 2010, 01:33:18)


[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "copyright", "credits" or "license!)" for mo
re information.
>» I

www.pclpublications.com
Say Hello to Python

How to Set Up
Python in Linux
Python version 2.x is already installed in most Linux distributions but as we're going
to be using Python 3.x, there's a little work we need to do first to get hold of it.
Thankfully, it's not too difficult.

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

STEP1 First you need to ascertain which version of Python Some Linux distros will automatically update
STEP 3
is currently installed in your Linux system; as we the installation of Python to the latest versions
mentioned, we're going to be using Linux Mint 18.1 for this section. whenever the system is updated. To check, first do a system update
As with macOS, drop into a Terminal by pressing Ctrl+Atl+T. and upgrade with:

sudo apt-get update && sudo apt-get upgrade


david@david*mint -
File Edit View Search Terminal Help Enter your password and let the system do any updates.
david@david-mint ~ s
david@david-mint ~
File Edit View Search Terminal Help
david@david-mint - S python --version
Python 2.7.12
david@david-mint - $ sudo apt-get update && sudo apt-get upgrade
[sudo] password for david: |

STEP 2 Next enter: python - -version into the Terminal STEP 4 Once the update and upgrade is complete, you
screen. You should have the output relating to may need to answer'Y' to authorise any upgrades,
version 2.x of Python in the display. Ours in this particular case is enter: python3 --version to see if Python 3.x is updated or even
Python 2.7.12. installed. In the case of Linux Mint, the version we have is Python
3.5.2, which is fine for our purposes.
david@david-mint -
File Edit View Search Terminal Help
david@david-mint - s python --version
Python 2.7.12
david@david-mint ~ |

Python & C++ Coding


How to Set Up Python in Linux

However, if you want the latest version, 3.6.2 as per Within the Python folder, enter:
STEP 5 STEP 8
the Python website at the time of writing, you need
A -J
./configure
to build Python from source. Start by entering these commands into
sudo make altinstall
the Terminal:
This could a little while depending on the speed of your computer.
sudo apt-get install build-essential checkinstall
Once finished, enter: python3.6 --version to check the
sudo apt-get install libreadline-gplv2-dev
installed latest version.
libncursesw5-dev libssl-dev libsqlite3-dev tk-dev
libgdbm-dev libc6-dev libbz2-dev

david@david-mint - - + x
File Edit View Search Terminal Help
ldavid@david-mint - s sudo apt-get install build-essential checkinstall
Reading package lists... Done
Building dependency tree
iReading state information... Done
build-essential is already the newest version (12.Iubuntu2).
■build-essential set to manually installed.
iThe following NEW packages will be installed
checkinstall
0 to upgrade, 1 to newly install, 0 to remove and 15 not to upgrade.
iNeed to get 121 kB of archives.
lAfter this operation, 516 kB of additional disk space will be used.
Do you want to continue? [Y/n]

Open up your Linux web browserand go to For the GUI IDLE, you need to enter the following
STEP 6 STEP 9
the Python download page: www.python.org/
A _______ J command into the Terminal:
downloads. Click on the Download Python 3.6.2 (or whichever
sudo apt-get install idle3
version it's on when you look) to download the source Python-
3.6.2.tar.xz file. The IDLE can then be started with the command: idle3. Note, that
IDLE runs a different version from the one you installed from source.

About Downloads Documentation You have chosen to open:

which is; XZ ar i live (16.1 MR)


Download the latest source rele« from: httpsvAvww.python.org

H Download Python 3.6.2 I Download Python 2.7.13


Open with Archive Manager (default]
Wondering which version to use? Here's more about the diff © Save file
Python 2 and 3.

Looking for Python with a different OS? Python for Win


OS X, Other

Want to help test development versions of Python? Pre role;

STEP 7 In the Terminal, go the Downloads folderby You also need PIP (Pip Installs Packages) which is a
STEP 10
entering: cd Downloads/. Then unzip the -J tool to help you install more modules and extras.
contents of the downloaded Python source code with: tar -xvf Enter: sudo apt-get install python3-pip
Python-3.6.2. tar. xz. Now enter the newly unzipped folder
PIP is then installed; check for the latest update with:
with cd Python-3.6.2/.
pip3 install --upgrade pip

When complete, close the Terminal and Python 3.x will be available
via the Programming section in your bistro's menu.

david@david-mint ~/Downloads/Python-3.6.2 - + X
File Edit View Search Terminal Help
ldavid@david-mint - Downloads/Python-3.6.2 S sudo apt-get install python3-pip
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
python-pip-whl
Recommended packages:
python3-dev python3-setuptools python3-wheel
The following NEW packages will be installed
python-pip-whl python3-pip
0 to upgrade, 2 to newly install, O to remove and 15 not to upgrade.
Need to get 1,219 kB of archives.
After this operation, 1,789 kB of additional disk space will be used.
Do you want to continue? [Y/n] |

www.pclpublications.com
Index
Getting Started with Python

Getting started with Python may seem a


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

In this section, we cover variables,


numbers and expressions, user input,
conditions and loops; and the types of
errors you may well come across in your
time with Python.

22 Starting Python tor the First Time


24 Your First Code
26 Saving and Executing Your Code
28 Executing Code from the Command Line
30 Numbers and Expressions
32 Using Comments
34 Working with Variables
36 User Input
38 Creating Functions
40 Conditions and Loops
42 Python Modules

www.pclpublications.com
Getting Started with Python

Starting Python tor


the First Time
We're going to be using the Raspberry Pi as our Python 3 hardware platform. The
latest version of Raspbian comes preinstalled with Python 3, version 3.4.2 to be exact,
so as long as you have a version 3 Shell, all our code will work.

STARTING PYTHON
We're not going to go into the details of getting the Raspberry Pi up and running, there's plenty of material already available
on that subject. However, once you're ready, fire up your Pi and get ready for coding.

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

STEP 2 The Shell is where you can enter code and see the STEP 4 The Python Shell acts very much like a calculator,
responses and output of code you've programmed since code is basically a series of mathematical
into Python. This is a kind of sandbox, where you're able to tryout interactions with the system. Integers, which are the infinite
some simple code and processes. sequence of whole numbers can easily be added, subtracted,
multiplied and so on.

Python 3.4.2 Shell


file Edit Shell Debug Options Windows Help

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


[GCC 4.9.1] on linux
Type "copyright", "credits" or "licensee)" for more information.
»> 2+2

»> 8+6
14
»> 23453+64545522
64568975
»> 98778642342-12343
98778629999
»> 1287437*43534
56047282358
»>l

Python & C++ Coding


Q Starting Python for the First Time

While that's very interesting, it’s not particularly The Python IDLE is a configurable environment. If
STEP 5 STEP 8
A exciting. Instead, try this: -J
you don't like the way the colours are represented,
then you can always change them via Options > Configure IDLE and
print(“Hello everyone!”)
clicking on the Highlighting tab. However, we don't recommend
Just like the code we entered in Sublime in the Installing a Text that, as you won't be seeing the same as our screenshots.
Editor section of this book.
python 3.4.2 (default, oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "copyright", "credits" or "licenseO" for note information.

Python 3.4.2 Shell _ □ x


File Edit Shell fiebug Options Windows Help
»> 23453+64545522
Python 3.4.2 (default, Oct 19 2014, 13:31:11) 64568975
»> 08778642342-12343
[GCC 4.9.1] on linux 98778629999
Type "copyright", "credits” or "licenseO” for more information. »> 1287437+43534
»> 2+2 56047282358
4 »> printf"Hello everyone!")
»> 8+6
14
»> 23453+64545522
64568975
»> 98778642342-12343
98778629999
»> 1287437*43534
56047282358
>» print("Hello everyone!”)
Hello everyone!

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

»> printC’Hello everyone!”)


Hello everyone!
»> |

STEP 7 You may have noticed the colour coding within The Python IDLE is a power interface and one
STEP 10
the Python IDLE. The colours represent different that's actually been written in Python using one
elements of Python code. They are: of the available GUI toolkits. If you want to know the many ins and
outs of the Shell, we recommend you take a few moments to view
Black - Data and Variables Blue - User Functions
www.docs.python.org/3/library/idle.html, which details many of
Green-Strings Dark Red - Comments
the IDLE's features.
Purple - Functions Light Red - Error Messages
Orange - Commands 25.5. IDLE

IDLE Colour Coding


Colour Use for Examples । rerem wtnn my MnXw reyMrs wnn adia wrorvs, ano rearm vvough rrurgre rias (greo)

Black Data & variables 23.6 area


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

www.pclpublications.com
Getting Started with Python

Your First Code


Essentially, you've already written your first piece of code with the 'print("Hello
everyone!")' function from the previous tutorial. However, let's expand that and look at
entering your code and playing around with some other Python examples.

PLAYING WITH PYTHON


With most languages, computer or human, it's all about remembering and applying the right words to the right situation.
You're not born knowing these words, so you need to learn them.

If you've closed Python 3 IDLE, reopen it in You can see that instead of the number 4, the
STEP 1 STEP 3
________ J whichever operating system version you prefer. In output is the 2+2 you asked to be printed to the
A
the Shell, enter the familiar following: screen. The quotation marks are defining what's being outputted
to the IDLE Shell; to print the total of 2+2 you need to remove
printC“HeUo”)
the quotes:

Python 3.4.2 Shell _ □ x print(2+2)


File Edit Shell Debug Options Windows Help

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


[GCC 4.9.1] on linux Python 3.4.2 Shell
Type "copyright", "credits" or "licenseO" for more information.
File Edit Shell Debug Options Windows Help
»> print("Hello")
Hello Python 3.4.2 (default, Oct 19 2014. 13:31:11) |
[GCC 4.9.1] on linux
Type "copyright", “credits" or “licenseO" for more information.
»> print("Hello")
Hello
»> print("2+2")
2+2
»> print(2+2)
4

STEP 2 Just as predicted, the word Hello appears in the STEP 4 You can continue as such, printing 2+2, 464+2343
Shell as blue text, indicating output from a string. and so on to the Shell. An easier way is to use a
It's fairly straightforward and doesn't require too much explanation. variable, which is something we will cover in more depth later. For
Now try: now, enter:

printC“2+2”) a=2
b=2

Python 3.4.2 Shell _ □ x


File Edit Shell Debug Options Windows Help

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


[GCC 4.9.1] on linux
Type "copyright", "credits" or "licenseO" for more information.
»> print( "Hello”)
Hello
»> print("2+2")
2+2
»> print(2+2)
4

2. Python & C++ Coding


(^Your First Code

What you have done here is assign the letters a Now let's add a surname:
STEP 5 STEP 8
A and b two values: 2 and 2. These are now variables, ________ J
surname=”Hayward”
which can be called upon by Python to output, add, subtract, divide
print(surname)
and so on for as tong as their numbers stay the same. Try this:
You now have two variables containing a first name and a surname
print(a)
and you can print them independently.
print(b)

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


[GCC 4.9.1] on linux
Type "copyright", “credits" or "licensed" for more information.
»> name-"David"
>» print(name)
David
»> surname="Hayward"
»> print(surname)
Hayward
>» |

The output of the last step displays the current STEP 9 If we were to apply the same routine as before,
STEP 6
A values of both a and b individually, as you've asked using the + symbol, the name wouldn't appear
them to be printed separately. If you want to add them up, you can correctly in the output in the Shell. Try it:
use the following:
print(name+surname)
print(a+b)
You need a space between the two, defining them as two separate
This code simply takes the values of a and b, adds them together values and not something you mathematically play around with.
and outputs the result.

STEP 7 You can playaround with different kinds of variables In Python 3 you can separate the two variables
STEP 10
and the Print function. For example, you could with a space using a comma:
assign variables for someone's name:
print(name, surname)
name=”David”
Alternatively, you can add the space yourself:
print(name)
print(name+” “+surname)

The use of the comma is much neater, as you can see.


Congratulations, you've just taken your first steps into the wide
world of Python.

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


[GCC 4.9.1] on linux
Type "copyright", "credits" or "licensed" for more information.
>» name-"David"
»> print (name)
David
»> surname="Hayward"
»> print(surname)
Hayward
>» print(name*surname)
DavidHayward
»> print(name, surname)
David Hayward
»> print(name*" "♦surname)
David Hayward
>» |

www.pclpublications.com
Getting Started with Python

Saving and Executing


Your Code
Whilst working in the IDLE Shell is perfectly fine for small code snippets, it's not
designed for entering longer program listings. In this section you're going to be
introduced to the IDLE Editor, where you will be working from now on.

EDITING CODE
You will eventually reach a point where you have to move on from inputting single lines of code into the Shell. Instead, the
IDLE Editor will allow you to save and execute your Python code.

First, open the Python IDLE Shell and when it's up, You can see that the same colour coding is in place
STEP 1 STEP 3
________ J click on File > New File. This will open a new window in the IDLE Editoras it is in the Shell, enabling you
with Untitled as its name. This is the Python IDLE Editor and within it to better understand what's going on with your code. However, to
you can enter the code needed to create your future programs. execute the code you need to first save it. Press F5 and you get a
Save...Check box open.

STEP 2 The IDLE Editor is, for all intents and purposes, a STEP 4 Click on the OK button in the Save box and select a
simple text editor with Python features, colour destination where you’ll save all your Python code.
coding and so on; much in the same vein as Sublime. You enter The destination can be a dedicated folder called Python or you
code as you would within the Shell, so taking an example from the can just dump it wherever you like. Remember to keep a tidy drive
previous tutorial, enter: though, to help you out in the future.

print(“Hello everyone!”)
print("Hello everyone!”)

Python & C++ Coding


Q Saving and Executing Your Code

Enter a name foryour code, ‘print hello' for Let's extend the code and enter a few examples
STEP 5 STEP 8
A example, and dick on the Save button. Once the from the previous tutorial:
Python code is saved it's executed and the output will be detailed in
a=2
the IDLE Shell. In this case, the words 'Hello everyone!'.
b=2
nonie=”Dovid”
surnome=”Hoyward”
print(name, surname)
print (a+b)

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

This is how the vast majority of your Python code STEP 9 If you click the OK button, the file will be
STEP 6
A will be conducted. Enter it into the Editor, hit F5, overwritten with the new code entries, and
save the code and look at the output in the Shell. Sometimes things executed, with the output in the Shell. It's not a problem with just
will differ, depending on whetheryou've requested a separate these few lines but if you were to edit a larger file, overwriting can
window, but essentially that's the process. It's the process we will become an issue. Instead, use File > Save As from within the Editor
use throughout this book, unless otherwise stated. to create a backup.

print hello.py - /home/pi/Documents/Python Code/print hello.py (3.4.2) - n x


File Edit Format Run Options Windows Help

tJew File Ctrl+N


Qpen... Ctrl+O
Becent Files
Open Module... Alt+M
Class Browser Alt+C
Path Browser

Save Ctrl+S
Save As... Ctrl+SMt+S
Save Copy As... Alt+Shift+S

Print Window Ctrl+P

£lose Alt+F4
Esit Ctrl+Q

STEP 7 If you open the file location of the saved Python Now create a new file. Close the Editor, and open
STEP 10
code, you can see that it ends in a .py extension. -J
a new instance (File > New Fite from the Shell).
This is the default Python file name. Any code you create will be Enter the following and save it as hello.py:
whatever.py and any code downloaded from the many Internet
o=”Python”
Python resource sites will be .py. Just ensure that the code is written
b=”is”
for Python 3.
c=”coolI”
print(o, b, c)
You will use this code in the next tutorial.

www.pclpublications.com
Getting Started with Python

Executing Code from


the Command Line
Although we're working from the GUI IDLE throughout this book, it's worth taking
a look at Python's command line handling. We already know there's a command line
version of Python but it's also used to execute code.

COMMAND THE CODE


Using the code we created in the previous tutorial, the one we named hello.py, let’s see how you can run code that was made
in the GUI at the command line level.

STEP1 Python, in Linux, comes with two possible ways of Now you're at the command line we can start
STEP 3
executing code via the command line. One of the Python. For Python 3 you need to enter the
ways is with Python 2, whilst the other uses the Python 3 libraries command python3 and press Enter. This will put you into the
and so on. First though, drop into the command line orTerminal on command line version of the Shell, with the familiar three right-
your operating system. facing arrows as the cursor (»>).

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

■ cmd|

Python & C++ Coding


Executing Code from the Command Line

Now enter: exit() to leave the command line Python The result of running Python 3 code from the
STEP 5 STEP 8
Asession and return you back to the command Python 2 command line is quite obvious. Whilst it
prompt. Enter the folder where you saved the code from the doesn't error out in any way, due to the differences between the
previous tutorial and list the available files within; hopefully you way Python 3 handles the Print command over Python 2, the result
should see the hello.py file. isn't as we expected. Using Sublime for the moment, open the
hello.py file.
pi@raspberrypi: -/Documents/Python Code _ □ x
S C:\Users\david\Documents\Python\hello.py - Sublime Text (UNREGISTERED)
File Edit Tabs Help
pieraspberrypi:- $ python3 File Edit Selection Find View Goto Toots Project Preferences Help
Python 3.4.2 (default. Oct 19 2014. 13:31:11)
[GCC 4.9.1) on linux
Type "help", "copyright", "credits" or "license" for more information.
>» a=2 1 a="Python"
»> print(a) 2 b="is”
3 c="cool!"
»> exit()
pigraspberrypi:- $ cd Documents/ 4 print(a, b, c)
pi@raspberrypi:-ZDocments $ cd PythonX Code/ 5 I
pi@raspberrypi:-/Docinents/Python Code $ Is
hello.py print hello.py
pi@raspberrypi:-/Docinents/Python Code $ |

From within the same folder as the code you're STEP 9 Since Sublime Text isn’t available for the Raspberry
STEP 6
going to run, enter the following into the Pi, you're going to temporarily leave the Pi for the
command line: moment and use Sublime as an example that you don't necessarily
need to use the Python IDLE. With the hello.py file open, alter it to
python3 hello.py
include the following:
This will execute the code we created, which to remind you is:
name=input(“What is your name? “)
a=”Python” printC'Hello,”, name)
b=”is”
c=”coolI” S C:\Users\david\Documents\Python\hello.py • - Sublime Text (UNREGISTERED)

print(a, b, c) File Edit Selection Find View Goto Tools Project Preferences Help

1 a=”Python"
2 b="is"
3 c="cool!"
4 print(a, b, c)
5 name=input("What is your name? ")
6 print=("Hello,", name)

STEP 7 Naturally, since this is Python 3 code, using the Save the hello.py file and drop back to the
STEP 10
syntax and layout that's unique to Python 3, it only command line. Now execute the newly saved
works when you use the python3 command. If you like, try the same code with:
with Python 2 by entering:
python3 hello.py
python hello.py
The result will be the original Python is cool! statement, together
with the added input command asking you for your name, and
displaying it in the command window.

pi@raspberrypr -/Documents/Python Code


File Edit Tabs Help
pi@raspberrypi:-/Docinents/Python Code $ python3 hello.py
Python is cool!
What is your name? David
Hello, David
piPraspberrypi:-/Docunients/Python Code $ |

www.pclpublications.com
Getting Started with Python

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

IT'S ALL MATHS, MAN


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

STEP1 Open up the GUI version of Python 3, as mentioned You can use all the usual mathematical operations:
STEP 3
a you can use either the Shell or the Editor. For the A divide, multiply, brackets and so on. Practise with a
time being, you're going to use the Shell just to warm our maths few, for example:
muscle, which we believe is a small gland located at the back of the
1/2
brain (or not).
6/2
2+2*3
Cl+2)+(3*4)

In the Shell enter the


STEP 2
decimal number. In Python these are called floats,
2+2
or floating point arithmetic. However, if you need an integer as
54356+34553245
opposed to a decimal answer, then you can use a double slash:
99867344*27344484221
1//2
You can see that Python can handle some quite large numbers.
6//2

And so on.

Python & C++ Coding


Numbersand Expressions

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

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

2**3 a = 6
I | tllp t-QrmAi Hun options Bind,
10**10
print(T, a == 6)
Essentially, it's 2x2x2 but we're sure you already know the basics
print(2, a == 7) „
behind maths operators. This is how you would work it out in Python.
print(3, a == 6 and b == 7) ; ”
»> 6/2 print(4, a == 7 and b == 7) KS: -MV MV’
3.0
»> 2+2*3 print(5, not a == 7 and b == 7)
8
>» (1+2)+(3*4) print(6, a == 7 or b == 7)
15
»> 1//2 print(7, a == 7 or b == 6)
0
»> 6//2 print(8, not (a == 7 and b == 6))
3
»> 10/3 print(9, not a == 7 and b == 6)
3.3333333333333335
»> 10%3
1
»> 2**3
8
»> 10**10
10000000000

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

bin(3)

»> 1/2
0.5
»> 6/2
3.0
»> 2+2*3
8
»> (1+2)+(3*4)
15
»> 1//2
0
»> 6//2
3
»> 10/3
3.3333333333333335
>» 10%3
1
>» 2**3
8
»> 10**10
10000000000
»> bin(3)
•obir
»>l

www.pclpublications.com
Getting Started with Python

Using Comments
When writing your code, the flow of it, what each variable does, how the overall
program will operate and so on is all inside your head. Another programmer could
follow the code line by line but over time, it can become difficult to read.

#COMMENTS!
Programmers use a method of keeping their code readable by commenting on certain sections. If a variable is used, the
programmer comments on what it's supposed to do, for example. It’s just good practise.

STEP1 Start by creating a new instance of the IDLE Editor Resave the code and execute it. You can see that the
STEP 3
a (File > New File) and create a simple variable and A output in the IDLE Shell is still the same as before,
print command: despite the extra lines being added. Simply put, the hash symbol (#)
denotes a line of text the programmer can insert to inform them,
0=10
and others, of what's going on without the user being aware.
print(“The value of A is,”, a)
Save the file and execute the code.

Comments.py - /home/pi/Documen.../Python Code/Comments.py (3.4.2) _ □ x


File Edit Format Run Options Windows Help

a=10
print("The value of A is,”, a)

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

# Set the start value of A to 10 a=a-l


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

Python & C++ Coding


(fusing Comments

Whilst we know that the variable A is lives, and Inline comments are comments that follow a section
STEP 5 STEP 8
A that the player has just lost one, a casual viewer or of code. Take our examples from above, instead of
someone checking the code may not know. Imagine fora moment inserting the code on a separate line, we could use:
that the code is twenty thousand lines long, instead of just our
a=10 # Set the start value of A to 10
seven. You can see how handy comments are.
print(“The value of A is,”, a) # Print the current
value of A
a=a-l # Player lost a life!
print(“You’ve just lost a life!”)
print(“You now have”, a, “lives left!”) # Inform
player, and display current value of A (lives)

Comments py - /home/pi/Documents/Python Code/Comments py (3.4.2) _ □ x


File Edit Format Run Options Windows Help
a=to ff Set the start value of A to 10
print("The value or A is, . a) 9 Print the current value or A
i a=a-1 # Player lost a life!
I printC'You've just lost a life!")
" print(“You now have", a. "lives left!") # Inform player, and display current value of A (lives

Essentially, the new code together with comments STEP 9 The comment, the hash symbol, can also be used to
STEP 6
A could look like: comment out sections of code you don't want to be
executed in your program. For instance, if you wanted to remove
# Set the start value of A to 10
the first print statement, you would use:
a=10
# Print the current value of A # print(“The value of A is,”, a)
print(“The value of A is,”, a)
# Player lost a life!
a=a-l
# Inform player, and display current value of A
(lives)
print(“You’ve just lost a life!”)
print(“You now have”, a, “lives left!”)

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

# This is the best game ever, and has been


developed by a crack squad of Python experts This is the best game ever, and has been developed
# who haven’t slept or washed in weeks. Despite by a crack squad of Python experts who haven’t
being very smelly, the code at least slept or washed in weeks. Despite being very
# works really well. smelly, the code at least works really well.

tile tdrt format Hun options windows Help

1 This is the best gome ever, and has been developed by a crack squad of Python experts
I who havenDt slept or washed in weeks. Despite being very smelly, the code at least
I works really wcll.|

www.pclpublications.com
Getting Started with Python

Working with Variables


We've seen some examples of variables in our Python code already but it's always
worth going through the way they operate and how Python creates and assigns certain
values to a variable.

VARIOUS VARIABLES
You'll be working with the Python 3 IDLE Shell in this tutorial. If you haven't already, open Python 3 or close down the previous
IDLE Shell to clear up any old code.

STEP1 In some programming languages you're required You've seen previously that variables can be
STEP 3
a to use a dollar sign to denote a string, which is a concatenated using the plus symbol between the
A
variable made up of multiple characters, such as a name of a person. variable names. In our example we can use: print (name +
In Python this isn’t necessary. For example, in the Shell enter: “ + title). The middle part between the quotations allows us to
name=”David Hayward” (oruseyourown name, unless you're add a colon and a space, as variables are connected without spaces,
also called David Hayward). so we need to add them manually.

Python 3.4.2 Shell _ □ x Python 3.4.2 Shell


File Edit Shell Debug Options Windows Help File Edit Shell £ebug Options Windows Help

Python 3.4.2 (default. Oct 19 2014, 13:31:11) Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux [GCC 4.9.1] on linux
Type "copyright", "credits" or "licensee)" for more information. Type "copyright", "credits" or "licenseO" for more information.
»> name-”David Hayward" »> name= "David Hayward"
»> print (name) > » print (name)
David Hayward David Hayward
> » type (name)
<class 'str‘>
»> title="Descended from Vikings"
»> print (name + ": " + title)
David Hayward: Descended from Vikings
»> |

STEP 2 You can check the type of variable in use by STEP 4 You can also Python 3.4 ]
issuing the type () command, placing the name of combine variables Elie Edit Shell Cebug Qptions windows Help
Python 3.4.2 (default, Oct 19 2014, 13:31:1
the variable inside the brackets. In our example, this would be: within another variable. For [GCC 4.9.1] on linux
Type "copyright", "credits" or "licenseO"
type (name). Add a new string variable: title=”Descended example, to combine both name »> name= "David Hayward"
»> print (name)
from Vikings”. and title variables into a new David Hayward
»> type (name)
variable we use: <class 'str'>
»> title""Descended from Vikings"
>» print (name + ": “ * title)
David Hayward: Descended from Vikings
character=name + “: “ + »> character=name + “: " + title
»> print (character)
title David Hayward: Descended from Vikings
>» age-44
»> type (age)
Then output the content of the <class 'int'>

new variable as:

print (character)

Numbers are stored as different


variables:

age=44
Type (age)

Which, as we know, are integers.

Python & C++ Coding


Working with Variables

However, you can't combine both strings and This presents a bit of a problem when you want to
STEP 5 STEP 8
integer type variables in the same command, asyou
A work with a number that’s been inputted by the
would a set of similar variables. You need to either turn one into the user, as age + 10 won't work due to being a string variable and an
other or vice versa. When you do try to combine both, you get an integer. Instead, you need to enter:
error message:
int(age) + 10
print (name + age)
This will TypeCast the age string into an integer that can be
Python 3.4.2 (default, Oct 19 2014, 13:31:11) worked with.
[GCC 4.9.1] on linux
Type "copyright", "credits" or "licensee)” for more information.
»> name="David Hayward"
»> print (name) Python 3.4.2 Shell______________________ - □
David Hayward
»> type (name) File Edit Shell Debug Options Windows Help
<class ’str‘>
»> title-"Descended from Vikings" Python 3.4.2 (default. Oct 19 2014. 13:31:11)
»> print (name + " + title) [GCC 4.9.1] on linux
David Hayward: Descended from Vikings Type "copyright", "credits" or “licensed" for more information.
»> character=name + “ + title »> age- input ("How old are you? ”)
»> print (character) How old are you? 44
David Hayward: Descended from Vikings »> type(age)
ill »> age-44 cclass ‘str‘>
»> type (age)
»> age + 10
cclass ’int’>
Traceback (most recent call last):
»> print (name+age)
Traceback (most recent call last): File "<pyshell#2>", line 1, in <module>
File "<pyshell#9>", line 1. in <module> age + 10
print (name+age) TypeError: Can’t convert ’int" object to str implicitly
TypeError: Can't convert ‘int’ object to str implicitly St >» int(age) + 10
>» I 54
»>l

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

or you can use: Now enter type(shirt) and you’ll see that Python has allocated
the number as a 'float', because the value contains a decimal point.
print (character, “is“, age, “years old.”)
Notice again that in the last example, you don’t need the spaces
Python 3.4.2 Shell
between the words in quotes as the commas treat each argument
file Edit Shell Debug Options Windows Help
to print separately.
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
»> print (name + age) Type "copyright”, "credits” or ”license()" for more information.
Traceback (most recent call last): >» shirt=19.99
File "spyshellfflB*", line 1, in <module> »> type(shirt)
print (name + age) cclass 'float'>
TypeError: Can’t convert int’ object to str implicitly
»> print (character + " is " + str(age) + " years old.”) »’l
David Hayward: Descended from Vikings is 44 years old.
>» print (character, "is", age, "years old.")
David Hayward: Descended from Vikings is 44 years old.
»>

Another example of Typecasting is when you ask for When combining integersand floats Python
STEP 7 STEP 10
a input from the user, such as a name, for example, -J
usually converts the integer to a float, but should
enter: the reverse ever be applied it’s worth remembering that Python
doesn't return the exact value. When converting a float to an
age= input (“How old are you? “)
integer, Python will always round down to the nearest integer,
All data stored from the Input command is stored as a string variable. called truncating; in our case instead of 19.99 it becomes 19.

Python 3.4.2 Shell Python 3.4.2 Shell


File Edit Shell Debug Options Windows Help File Edit Shell Debug Options Windows Help
Python 3.4.2 (default. Oct 19 2014. 13:31:11) Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux [GCC 4.9.1] on linux
Type "copyright", "credits" or "licenseO" for more information. Type "copyright", "credits” or "licenseO” for more information.
»> age- input ("How old are you? ")
»> shirt=19.99
How old are you? 44
»> type(age) »> type(shirt)
cclass ‘str‘> cclass 'float'>
»> int(shirt)
»> I 19
>»l

www.pclpublications.com
Getting Started with Python

User Input
We've seen some basic user interaction with the code from a few of the examples
earlier, so now would be a good time to focus solely on how you would get information
from the user then store and present it.

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

If it's not already, open the Python 3 IDLE Shell, Now that we have the user’s name stored in a
STEP 1 STEP 3
________ J and start a New File in the Editor. Let's begin with couple of variables we can call them up whenever
something really simple, enter: we want:

printC“Hello”) print(“Welcome”, firstname, surname, “. I hope


firstname=input(“What is your first name? “) you’re well today.”)
print(“Thanks.”)
surname=input(“And what is your surname? “)

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

print(“Welcome”, firstname, surname+“. I hope


you’re well today.”)

Python & C++ Coding


(^2 User Input

You don't always have to include quoted text within What you've created here is a condition, which we
STEP 5 STEP 8
A the input command. For example, you can ask the will coversoon. In short, we're using the input from
user their name, and have the input in the line below: the userand measuring it against a condition.So, if the userenters
David as their name, the guard will allow them to pass unhindered.
print(“Hello. What’s your name?”)
Else, if they enter a name other than David, the guard challenges
name=input()
them to a fight.

userinput.py - /home/pi/Documents/Python Code/usi


File Edit Format Run Options Windows Help
printC'Hello. What's your name?")
name-input()

The code from the previous step is often regarded STEP 9 Just as you learned previously, any input from a
STEP 6
A as being a little neater than having a lengthy user is automatically a string, so you need to apply a
amount of text in the input command, but it's not a rule that's set in TypeCast in order to turn it into something else. This creates some
stone, so do as you like in these situations. Expanding on the code, interesting additions to the input command. For example:
try this:
# Code to calculate rate and distance
print(“Halt! Who goes there?”) print(“Input a rate and a distance”)
name=input() rate = float(input(“Rate: “))

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

www.pclpublications.com
Getting Started with Python

Creating Functions
Now that you've mastered the use of variables and user input, the next step is to tackle
functions. You've already used a few functions, such as the print command but Python
enables you to define your own functions.

FUNKY FUNCTIONS
A function is a command that you enter into Python to do something. It’s a little piece of self-contained code that takes data,
works on it and then returns the result.

STEP1 It’s not just data that a function works on. They can You can pass variables through functions in much
STEP 3
a do all manner of useful things in Python, such as A the same manner. Let's assume you want the
sort data, change items from one format to another and check the number of letters in a person's surname, you could use the following
length or type of items. Basically, a function is a short word that's code (enter the text editor for this example):
followed by brackets. For example, len(), list() or type().
name=input (“Enter your surname: “)
count=Len(name)
print (“Your surname has", count, “letters in
it.”)

Press F5 and save the code to execute it.

A function takes data, usually a variable, works on STEP 4 Python has tens of functions built into it, far too
STEP 2
________ J it depending on what the function is programmed many to get into in the limited space available here.
to do and returns the end value. The data being worked on goes However, to view the list of built-in functions available to Python 3,
inside the brackets, so if you wanted to know how many letters navigate to www.docs.python.org/3/library/functions.html. These
are in the word antidisestablishmentarianism, then you'd enter: are the predefined functions, but since users have created many
len(“antidisestablishmentarianism”)and the number 28 more, they're not the only ones available.
would return.

Python & C++ Coding


6 Creating Functions

Additional functions can be added to Python To use a function from a module enter the name of
STEP 5 STEP 6
through modules. Python has a vast range of
A A the module followed by a full stop, then the name
modules available that can cover numerous programming duties. of the function. For instance, using the math module, since you've
They add functions and can be imported as and when required. For just imported it into Python, you can utilise the square root function.
example, to use advanced mathematics functions enter: To do so, enter:

import math math.sqrt(16)

Once entered, you have access to alt the math module functions. You can see that the code is presented as module.function(data).

FORGING FUNCTIONS
There are many different functions you can import created by other Python programmers and you will undoubtedly come
across some excellent examples in the future; you can also create your own with the def command.

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

Ifrom Hello import Hello]

Press F5 to save and run the script. You can see Hello in the Shell, Press F5 to save and execute the code.
type in Hello() and it returns the new function.

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

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

£«• £« SMf fiptlonj window U«lr


mno(n«w):

H»Uo Oavid
>>> Hello(rua»)

www.pclpublications.com I9
Getting Started with Python

Conditionsand Loops
Conditions and loops are what makes a program interesting; they can be simple or
rather complex. How you use them depends greatly on what the program is trying to
achieve; they could be the number of lives left in a game or just displaying a countdown.

TRUE CONDITIONS
Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let's start then by checking
if something is TRUE, then doing something else if it isn't.

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

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


something else.

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

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


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

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

Python & C++ Coding


(^Conditions and Loops

Press F5 and save the code to execute it. Enter Now expand the code to include another conditions.
STEP 5 STEP 6
a four-letter word in the Shell to begin with, you
A Eventually, it could become quite complex. We've
A
should have the returned message that it's the word is four letters. added a condition for three-letter words:
Now press F5 again and rerun the program but this time enter a
word=input(“Please enter a four-letter word: “)
five-letter word. The Shell will display that it's not a four-letter word.
word_length=len(word)
if word_length == 4:
print (word, “is a four-letter word. Well
done.”)
elif word_length == 3:
print (word, “is a three-letter word. Try again.”)
else:
print (word, “is not a four-letter word.”)

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

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

words=|_ Cat , Dog , Unicorn J

for word in words


print (xj
x = x + 1

*Untitled*
File Edit Format Bun Options Windows Help

■.'I 11? x<10:

The difference between if and while is when while The For loop can also be used in the countdown
STEP 2 STEP 4
gets to the end of the indented code, it goes back example by using the range function:
and checks the statement is still true. In our example x is less than
for x in range (1?
10. With each loop it prints the current value of x, then adds one to
that value. When x does eventually equal 10 it stops.
The x=x+1 part isn't needed here because the range function
creates a list between the first and last numbers used.

toopl.py-/hc

P.tlwn
(GCC 4...
T»pe “copyright-.

www.pclpublications.com
Getting Started with Python

Python Modules
We've mentioned modules previously, (the Math module) but as modules are such a
large part of getting the most from Python, it's worth dedicating a little more time to
them. In this instance we're using the Windows version of Python 3.

MASTERING MODULES
Think of modules as an extension that's imported into your Python code to enhance and extend its capabilities. There are
countless modules available and as we've seen, you can even make your own.

STEP1 Although good, the built-in functions within Python The result is an error in the IDLE Shell, as the
STEP 3
a are limited. The use of modules, however, allows us pygame module isn't recognised or installed in
A
to make more sophisticated programs. As you are aware, modules Python. To install a module we can use PIP (Pip Installs Packages).
are Python scripts that are imported, such as import math. Close down the IDLE Shell and drop into a command prompt or
Terminal session. At an elevated admin command prompt, enter:
L<p Python 3.62 Shell — □ X

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

C:\Users\david>pip install pygame

STEP 2 Some modules, especially on the Raspberry Pi, STEP 4 The PIP installation requires an elevated status
are included by default, the math module being a due it installing components at different locations.
prime example. Sadly, other modules aren't always available. A good Windows users can search for CMD via the Start button and right­
example on non-Pi platforms is the pygame module, which contains click the result then click Run as Administrator. Linux and Mac users
many functions to help create games. Try: import pygame. can use the Sudo command, with sudo pip install package.

L<Jk Python 3.6.2 Shell - □ X


Administrator: Command Prompt
File Edit Shell Debug Options Window Help
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)]
Microsoft Windows [Version 10.0.15063]
on Win32 (c) 2017 Microsoft Corporation. All rights reserved.
Type "copyright", "credits" or "license))" for more information.
»> import math
>» import pygame
C:\WINDOWS\system32>pip install pygame
Traceback (most recent call last) : Collecting pygame
File "<pyshell#l>", line 1, in <module> Using cached pygame-1.9.3-cp36-cp36m-win32.whl
import pygame
ModuleNotFoundError: No module named 'pygame*
Installing collected packages: pygame
Successfully installed pygame-1.9.3

C:\WINDOWS\system32>

Python & C++ Coding


Q Python Modules

Close the command prompt orTerminal and Multiple modules can be imported within your code.
STEP 5 STEP 8
relaunch the IDLE Shell. When you now enter:
A ________ J To extend our example, use:
import pygame, the module will be imported into the code
import random
without any problems. You'll find that most code downloaded or
import math
copied from the Internet will contain a module, mainstream of
unique, these are usually the source of errors in execution due to for I in range(5):
them being missing. printfrandom.randint(l, 25))

[jjr Python 3.6.2 Shell - □ X print(math.pi)


File Edit Shell Debug Options Window Help
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] [jsr P.nd Number.py - C:/Users/david/Documents/Python/Rnd Number.py (3.6.2) — □ X
on Win32
File Edit Format Run Options Window Help
Type "copyright", "credits" or "license()" for more information.
»> import pygame import random
import math

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

print(math.pi)

The modules contain the extra code needed to STEP 9 The result is a string of random numbers followed
STEP 6
achieve a certain result within your own code, as
A by the value of Pi as pulled from the math module
we've previously experimented with. For example: using the print(math.pi) function. You can also pull in certain
functions from a module by using the from and import commands,
import random
such as:
Brings in the code from the random number generator module. You
from random import randint
can then use this module to create something like:
for i in range(5):
for i in range(10):
print(randint(l, 25))
print(random.randint(l, 25))
Rnd Number.py- C:/Users/david/Documents/Python/Rnd Number.py (3.6.2) — □ X
L4 “Unfitted* — □ X
File Edit Format Run Options Window Help
File Edit Format Run Options Window Help from random import randint
import random
for i in range(5):
for i in range(10): print(randint(1, 25))
print(random.randint(1, 25))

STEP 7 This code, when saved and executed, will display ten This helps create a more streamlined approach to
STEP 10
random numbers from 1 to 25. You can play around programming. You can also use import module*,
with the code to display more or less, and from a great or lesser which will import everything defined within the named module.
range. For example: However, it's often regarded as a waste of resources but it works
nonetheless. Finally, modules can be imported as aliases:
import random
import math as m
for i in range(25):
print(random.randintfl, 100)) printfm.pi)
Of course, adding comments helps to tell others what's going on.

*Rnd Number.py - G/Users/david/Documents/Python/Rnd Number.py (3.6.2)* — □ X

File Edit Format Run Options Window Help


import math as m

print(m.pi)

www.pclpublications.com
Index

Working
with Data

Python & C++ Coding


Working with Data

Data is everything. With it you can


display, control, add, remove, create
and manipulate Python to your every
demand. Over these coming pages we
look at how you can create lists, tuples,
dictionaries and multi-dimensional lists;
and see how to use them to forge exciting
and useful programs.

Then, you can learn how to use date


and time functions, write to files in your
system and even create graphical user
interfaces that take your coding skills to
new levels and into new project ideas.

46 Lists
48 Tuples
50 Dictionaries
52 Splitting and Joining Strings
54 Formatting Strings
56 Date and Time
58 Opening Files
60 Writing to Files
62 Exceptions
64 Python Graphics

www.pclpublications.com
Working with Data

Lists
Lists are one of the most common types of data structures you will comes across in
Python. A list is simply a collection of items, or data if you prefer, that can be accessed
as a whole, or individually if wanted.

WORKING WITH LISTS


Lists are extremely handy in Python. A list can be strings, integers and also variables. You can even include functions in lists,
and lists within lists.

STEP1 A list is a sequence of data values called items. You You can also access, or index, the last item in a list by
STEP 3
a create the name of your list followed by an equals Ausing the minus sign before the item number [-1],
sign, then square brackets and the items separated by commas; or the second to last item with [-2] and so on. Trying to reference an
note that strings use quotes: item that isn't in the list, such as [10] will return an error:

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


mythical_creatures - [“Unicorn”, “Balrog”, mythical_creatures[-4]
“Vampire”, “Dragon”, “Minotaur”]

Python 3.4.2 Shell _ □ x


rile Edit Shell Debug Options Windows Help

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


[GCC 4.9.1] on linux
Type "copyright", "credits" or "liccnscO" for more information.
»> numbers -[1.4 , 7, 21. 98, 156]
»> mythical_creatures = ["Unicorn", "Balrog", "Vampire", "Dragon". "Minotaur"]

STEP 2 Once you've defined your list you can call each STEP 4 Slicing is similar to indexing but you can retrieve
by referencing its name, followed by a number. Lists multiple items in a list by separating item numbers
start the first item entry as 0, followed by 1,2, 3 and so on. with a colon. For example:
For example:
numbers [1:3]
numbers
Will output the 4 and 7, being item numbers 1 and 2. Note that the
To call up the entire contents of the list. returned values don't include the second index position (as you
would numbers[1:3] to return 4, 7 and 21).
numbers[3]
Type "copyright", "credits" or “licensed" for more information.
To call the third from zero item in the list (21 in this case). »> numbers - [1. 4, 7. 21. 98. 156]
»> mythical_creatures = ["Unicorn", "Balrog", "Vampire", “Dragon", "Minotaur")
»> numbers
(1, 4. 7, 21. 98. 156)
»> numbers[3]
21
> » mythical_creatures
(‘Unicorn'. 'Balrog', 'Vampire'. 'Dragon'. 'Minotaur']
> » mythical_creatures[3]
'Dragon'
> » numbers[-1]
156
> » numbersf-21
98
»> mythical_creatures[-1]
'Minotaur'
> » mythical_creatures[-4]
'Balrog'
> » numbers[1:3]
(4. 7)
> » numbers[0:4]
(1. 4. 7. 21]
»> nunbers[3:5]
(21, 98]
numbers [ 1: ]
(4, 7, 21, 98, 156]
»> |

Python & C++ Coding


Lists

You can update items within an existing list, remove You can view what can be done with lists by entering
STEP 5 STEP 8
items and even join lists together. For example, to
A dir(list) into the Shell. The output is the available
join two lists you can use: functions, for example, insert and pop are used to add and remove
items at certain positions. To insert the number 62 at item index 4:
everything = numbers + niythical_creatures
numbers.insert(4, 62)
Then view the combined list with:
To remove it:
everything
numbers.pop(4)
Python 3.4.2 Shell _ □ x type copyngnt , credits or "licensee)" tor more mrormation.
»> dir(list)
File Edit Shell Qebug Options Windows Help
['____ add_', '___ class ', ' contains ', '_delattr__ ', '__ de litem___ ', • dir__’
Python 3.4.2 (default. Oct 19 2014, 13:31:11) , '___ doc_'_______ eq ', '____ format ', ' ge_'. '__ getattribute__ '. '___ getitem__'
[GCC 4.9.1] on linux , ’___ gt_ ', '____ hash ', ' iadd ', ' imul_', '____ init__ ', ’__ iter___ ', ' le__'
Type "copyright", "credits" or "licensee)" for more information. . ’_ len__ ’. '_ It___ '. '__ mul__ '. '__ ne___', '__ new '. '___reduce___ ', '__ reduce_e
»> numbers - [1. 4, 7. 21. 98, 156] x__ ', '__ repr__ ’, '_ reversed___ ' , '__ rmul___ ', '__ setattr_ ’, ’___ setitem__ ’, '__ s
>» mythical_creatures - ("Unicorn", "Balrog", "Vampire", "Dragon", "Minotaur"] izeof__ ', '__ str__ ', '__ subclasshook__ ', 'append', 'clear', 'copy', 'count'. 'ex
»> everything = numbers ♦ mythical_creatures tend'. 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
»> everything »> numbers = [1, 4, 7, 21. 98. 156]
[1, 4, 7, 21. 98. 156, 'Unicorn', 'Balrog', 'Vampire', 'Dragon', 'Minotaur'] »> numbers
[1. 4. 7, 21. 98. 156)
»> numbers.insert(4, 62)
>» numbers
[1. 4, 7, 21, 62, 98, 156]

I
»> numbers.pop(4)
62
>» numbers
[1, 4. 7, 21. 98. 156]

Items can be added to a list by entering: You also use the list function to break a string down
STEP 6 STEP 9
A ________ J into its components. For example:
numbers=numbers+[201]
list(“David”)
Or for strings:
Breaks the name David into 'D', 'a', 'v', 'i', 'd'. This can then be passed
mythical_creatres=mythical_creatures+[“Griffin”]
to a new list:
Or by using the append function:
name=list(“David Hayward”)
mythical_creatures.append(“Nessie”) name
numbers.append(278) age=[44]
user = name + age
»> numbers = [1. 4. 7. 21. 98. 156]
»> mythical_creatures - ("Unicorn", "Balrog", "Vampire", "Dragon", "Minotaur"] user
>» numbers
[1. 4, 7, 21, 98, 156]
»> mythical_creatures
['Unicorn', Balrog', Vampire', 'Dragon', 'Minotaur']
»> numbers=numbers+[201]
»> numbers
[1. 4, 7, 21. 98. 156. 201]
»> mythical_creatures“mythical_creatures+["Griffin"]
»> mythical_creatures
['Unicorn', 'Balrog', 'Vampire', 'Dragon', 'Minotaur', 'Griffin']
»> mythical_creatures.append("Nessie")
»> mythical_creatures
('Unicorn', 'Balrog'. 'Vampire', 'Dragon', 'Minotaur', 'Griffin', 'Nessie']
>» numbers.append(278)
»> numbers
[1, 4, 7, 21, 98, 156, 201, 278]
»>l

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

del numbers[7] name=input(“What’s your name? “)


lname=li st(name)
Alternatively, by item name:
age=int(input(“How old are you: “))
mythical_creatures.remove(“Nessie”) lage=[age]
»> mythical_creatures ■ ("Unicorn", "Balrog", "Vampire". "Dragon". "Minotaur] user = Iname + lage
»> numbers
[1, 4, 7, 21, 98, 156]
>» mythical_creatures
[’Unicorn’, Balrog’, Vampire’, ’Dragon’, ’Minotaur’]
The combined name and age list is called user, which can be called
»> numbers=numbers+[201]
»> numbers
by entering user into the Shell. Experiment and see whatyou can do.
[1.4. 7, 21. 98. 156. 201]
»> mythical_creatures«mythical_creatures*["Griffin"]
»> mythical_creatures
[’Unicorn’, Balrog’, ’Vampire", 'Dragon'. 'Minotaur', 'Griffin']
»> mythical_creatures.append("Nessie")
»> mythical_creatures
['Unicorn', 'Balrog'. 'Vampire'. 'Dragon'. 'Minotaur', 'Griffin', ’Nessie']
»> numbers.append(278)
»> numbers
[1, 4, 7, 21, 98, 156, 201, 278]
»> del numbers[7]
»> numbers
[1, 4, 7, 21, 98. 156, 201]
»> mythical_creatures.remove("Uessie")
»> mythical_creatures
['Unicorn'. 'Balrog'. 'Vampire'. 'Dragon'. 'Minotaur', 'Griffin']

www.pclpublications.com
Working with Data

Tuples
Tuples are very much identical to lists. However, where lists can be updated, deleted or
changed in some way, a tuple remains a constant. This is called immutable and theyTe
perfect for storing fixed data items.

THE IMMUTABLE TUPLE


Reasons for having tuples vary depending on what the program is intended to do. Normally, a tuple is reserved for something
special but they're also used for example, in an adventure game, where non-playing character names are stored.

STEP1 A tuple is created the same way as a list but in this You can create grouped tuples into lists that contain
STEP 3
a instance you use curved brackets instead of square multiple sets of data. For instance, here is a tuple
A
brackets. For example: called NPC (Non-Playable Characters) containing the character name
and their combat rating for an adventure game:
months=(“January”, “February”, “March”, “April”,
“May”, “June”) NPC=[(“Conan”, 100), (“Belit”, 80), (“Valeria”,
months 95)]

Python 3.4.2 Shell Python 3.4.2 Shell


File Edit Shell Debug Options Windows Help File Edit Shell Debug Options Windows Help

Python 3.4.2 (default. Oct 19 2014, 13:31:11) Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux [GCC 4.9.1] on linux
Type "copyright", "credits" or "licenseO" for more information. Type "copyright”, "credits" or "licenseO" for more information.
>» months=("January". "February", “March". "April". "May", “June”) »> NPC=[("Conan".100), ("Belit", 80). ("Valeria", 95)]
»> months >» I
(•January’. ’February’. ’March’. ’April’. ’May’. ’June’)

Just as with lists, the items within a named tuple can STEP 4 Each of these da ta i terns can be accessed as a
STEP 2
________ J be indexed according to their position in the data whole by entering NPC into the Shell; or they can be
range, i.e.: indexed according to their position NPC[0]. You can also index the
individual tuples within the NPC list:
months[0]
months[5] NPC[0][1]

However, any attempt at deleting or adding to the tuple will result Will display 100.
in an error in the Shell.
Python 3.4.2 Shell _ □ x
file Edit Shell Debug Options Windows Help

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


[GCC 4.9.1] on linux
Type "copyright", "credits" or "licenseO" for more information.
>» NPC=[("Conan”. 100). ("Belit". 80). ("Valeria". 95)]
»> NPC
[(’Conan’. 100). (’Belit’. 80). (’Valeria’. 95)]
>» NPC[0]
(’Conan’. 100)
»> NPC[0][1]
100

Python & C++ Coding


It's worth noting that when referencing multiple Now unpack the tuple into two
STEP 5 STEP 8
A tuples within a list, the indexing is slightly different -J corresponding variables:
from the norm. You would expect the 95 combat rating of the
(name, combat_rating)=NPC
character Valeria to be NPC[4][5], but it's not. It's actually:
You can now check the values by entering name and combat_rating.
NPC[2][1]

This means of course that the indexing follows thus: STEP 9 Remember, as with lists, you can also index tuples
STEP 6
________ J using negative numbers which count backwards
0 1, 1
from the end of the data list. For our example, using the tuple with
0, 0 2
multiple data items, you would reference the Valeria character with:
0, 1 2, 0
1 2,1 NPC[2][-0]
1, 0
Python 3 4.2 Shell
Which as you can imagine, gets a little confusing when you've got a
File Edit Shell Debug Options Windows Help
lot of tuple data to deal with. Python 3.4.2 (default. Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "copyright", "credits" or "licensee)" for more information. Type "copyright", "credits" or "licenseO” for more information.
»> NPC=[("Conan". 100). ("Belit11. 80). ("Valeria". 95)] »> IIPC=[( "Conan", 100), ("Belit", 80). ("Valeria", 95)]
»> NPC[0] »> NPC[2][-0]
(•Conan1. 100) ■Valeria1
»> NPC[0][0] >» I
1 Conan1
»> NPC[0][1]
100
»> NPC[1]
(‘Belit’. 80)
»> NPC[1][0]
•Belit1
»> NPC [ 1 ] [ 1 ]
80
»> NPC[2]
(‘Valeria1. 95)
>» NPC[2][0]
‘Valeria1
»> NPC[2][1]
95

STEP 7 Tuples though utilise a feature called unpacking, You can use the max and min functions to find the
STEP 10
where the data items stored within a tuple are -J
highest and lowest values of a tuple composed of
assigned variables. First create the tuple with two items (name and numbers. For example:
combat rating):
numbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99)
NPC=(“Conan”, 100)
The numbers can be integersand floats.To output the highest and
lowest, use:

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

www.pclpublications.com
Working with Data

Dictionaries
Lists are extremely useful but dictionaries in Python are by far the more technical way
of dealing with data items. They can be tricky to get to grips with at first but you'll soon
be able to apply them to your own code.

KEY PAIRS
A dictionary is like a list but instead each data item comes as a pair, these are known as Key and Value. The Key part must be
unique and can either be a number or string whereas the Value can be any data item you like.

STEP1 Let's say you want to create a phonebook in Python. As with lists and tuples, you can check the contents
STEP 3
a You would create the dictionary name and enter A of a dictionary by giving the dictionary a name:
the data in curly brackets, separating the key and value by a colon phonebook, in this example. This will display the data items you've
KeyiValue. For example: entered in a similar fashion to a list, which you're no doubt familiar
with by now.
phonebook={“Emma”: 1234, “Daniel”: 3456, “Hannah”:
6789}

Just as with most lists, tuples and so on, strings STEP 4 The benefit of using a dictionary is that you
STEP 2
__________ A need be enclosed in quotes (single or double), can enter the key to index the value. Using the
whilst integerscan be left open. Remember that the value can be phonebook example from the previous steps, you can enter:
either a string or an integer, you just need to enclose the relevant
phonebook[“Emma”]
one in quotes:
phonebook[“Hannah”]
phonebook2={“David”: “0987 654 321”}

Python 3.4.2 Shell _ □ x


Elie Edit Shell Debug Options Windows Help

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


(GCC 4.9.1 J on linux
Type "copyright", "credits” or "licensed" for more information.
>» phonebook={"Emma": 1234, "Daniel”: 3456, "Hannah”: 6789}
»> phonebook2={"David": "0987 654 321"}
»> |

Python & C++ Coding


Dictionaries

Adding to a dictionary is easy too. You can include Next, you need to define the user inputs and
STEP 5 STEP 8
A a new data item entry by adding the new key and variables: one for the person's name, the other
value items like: for their phone number (let's keep it simple to avoid lengthy
Python code):
phonebook[“David”] = “0987 654 321”
phonebook name=input(“Enter name: “)
number=int(input(“Enter phone number: “))

You can also remove items from a dictionary by STEP 9 Note we've kept the number as an integer instead
STEP 6
A issuing the del command followed by the item's of a string, even though the value can be both
key; the value will be removed as well, since both work as a pair of an integer or a string. Now you need to add the user’s inputted
data items: variables to the newly created blank dictionary. Using the same
process as in Step 5, you can enter:
del phonebook[“David”]
phonebook[name] = number

STEP 7 Taking this a step further, how about creating a Now when you save and execute the code, Python
STEP 10
piece of code that will ask the user for the dictionary will ask fora name and a number. It will then insert
key and value items? Create a new Editor instance and start by those entries into the phonebook dictionary, which you can test by
coding in a new, blank dictionary: entering into the Shell:

phonebook={} phonebook
phonebook[“David”]

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


so remove the int part of the input.

www.pclpublications.com
Working with Data

Splitting and
Joining Strings
When dealing with data in Python, especially from a user's input, you will undoubtedly
come across long sets of strings. A useful skill to learn in Python programming is being
able to split those long strings for better readability.

STRING THEORIES
You've already looked at some list Functions, using .insert, .remove, and .pop but there are also Functions that can be applied
to strings.

STEP1 The main tool in the string Function arsenal is ,split(). Note that the text.split part has the brackets,
STEP 3
With it you're able to split apart a string oF data, quotes, then a space Followed by closing quotes
based on the argument within the brackets. For example, here's a and brackets. The space is the separator, indicating that each list
string with three items, each separated by a space: item entry is separated by a space. Likewise, CSV (Comma Separated
Value) content has a comma, so you'd use:
text=”Daniel Hannah Emma”
text=”January,February,March,April,May,June”
months=text.splitC",
months

STEP 2 Now let's turn the string into a list and split the You've previously seen how you can split a string
STEP 4
content accordingly: ________ J into individual letters as a list, using a name:
names=text.split(“ “) name=list(“David”)
name
Then enter the name oF the new list, names, to see the three items.
The returned value is 'D', 'a', V, 'i', ’d'. Whilst it may seem a little
useless under ordinary circumstances, it could be handy For creating
a spelling game For example.

Python & C++ Coding


Splitting and Joining Strings

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

This will display 'abode' in the Shell.


Eile Edit Shell Qebug Options Windows Help
Python 3.4.2 (default. Oct 19 2014. 13:31:11)
[GCC 4.9.1) on linux
Type "copyright", "credits" or “liccnse(>" for more information.
»> list-("Conan", "raised", "his”, "mighty", "sword", "and”, "struck", "the", “demon"]
»> text-" ".join(list)
conan raised his mighty sword and struck the demon-
»> colours-(“Red". "Green". "Olue")

■ Red.Green.Blue'

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

We've joined the string back together, and retained the list called
Python 3.4.2 Shell -ox
name, passing it through the .join function.
File Edit Shell Debug Options Windows Help

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


[GCC 4.9.1] on linux
Type "copyright", "credits" or "licensee)" for more information.
»> title-"conan the Cimmerian"
»> title.capitalize()
‘Conan the Cimmerian'
»> title.title()
'Conan The Cimmerian'

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

Python 3.4.2 Shell _ □ x


Ells Edit Sho[l Qebug Options Windows H»ip File Edit Shell Debug Options Windows Help
Python 3.4.2 (default. Oct 19 2014, 13:31:11) Python 3.4.2 (default. Oct 19 2014. 13:31:11)
[GCC 4.9.1] on linux
Type "copyright", "credits" or "licensee)" for more information. [GCC 4.9.1] on linux
>» list-["Conan“. "raised", "his", "mighty", "sword", "and", "struck", "the", "demon") Type "copyright", “credits" or "license!)" for more information.
>»> text-" ".jointlist) »> message-’Have a nice day"
»> text »> “nice" in message
conan raised his mighty sword and struck the demon-
True
»> "bad" not in message
True
»> "day" not ir message
False
»> "night" in message
False

www.pclpublications.com
Working with Data

Formatting Strings
When you work with data, creating lists, dictionaries and objects you may often want
to print out the results. Merging strings with data is easy especially with Python 3, as
earlier versions of Python tended to complicate matters.

STRING FORMATTING
Since Python 3, string formatting has become a much neater process, using the .format function combined with curly brackets.
It’s a more logical and better formed approach than previous versions.

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

Python 3.4.2 Shell _ □ x


File Edit Shell Debug Options vyindows Help

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


(GCC 4.9.1] on linux
Type "copyright", "credits" or "licenseO" for more information.
»> name="Conan”
»> print("The barbarian hero of the Hyborian Age is: {}".format(name))
The barbarian hero of the Hyborian Age is: Conan
»> |

STEP 2 Remember to close the print function with two sets STEP 4 There are many different ways to apply string
of brackets, as you've encased the variable in one, formatting, some are quite simple, as we've shown
and the print function in another. You can include multiple cases of you here; others can be significantly more complex. It all depends
string formatting in a single print function: on whatyou want from your program. A good place to reference
frequently regarding string formatting is the Python Docs webpage,
name=”Conan”
found at www.docs.python.org/3.1/Ubrary/stnng.html. Here, you
place=”Cimmeria”
will find tons of help.
print(“{} hailed from the North, in a cold land
known as {}”.format(name, place))

Python 3.4.2 Shell -ax


7.1.3. Format String Syntax
Eiie Edit Shell Debug options windows Help
python 3.4.2 (default, oct 19 2014, 13:31:11)
(GCC 4.9.1] on linux
Type "copyright”, "credits" or "licenseO” for more information.
»> name=''Conan”
>» place«"Cunmeri.a"
»> print("() hailed from the north, in a cold land known os ()”.format(na«nc. place))
Conan hailed from the North, in a cold land known as Cimmeria
>»l

Python & C++ Coding


Formatting Strings

Interestingly you can reference a list using the string You can also print out the content of a user’s input
STEP 5 STEP 8
A formatting function. You need to place an asterisk in -J in the same fashion:
front of the list name:
name=input(“What’s your name? “)
numbers=l, 3, 45, 567546, 3425346345 print(“Hello {}.”.format(name)
print(“Some numbers: {}, {}, {}, {}, {}”.
format(*numbers))

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

STEP 7 And as you probably suspect, you can mix strings You can also call upon a pair of listsand reference
STEP 10
and integers in a single list to be called in the them individually within the same print function.
.format function: Looking back the code from Step 7, you can alter it with:

characters=[“Conan”, “Belit”, “Valeria”, 19, 27, names=[“Conan”, “Belit”, “Valeria”]


20] ages=[25, 21, 22]
print (“{0} is {3} years old. Whereas {1} is {4}
Creating two lists. Now you can call each list, and individual items:
years old.”.format(*characters))
print(“{0[0]} is {1[0]} years old. Whereas {0[1]}
Python 3.4.2 Shell is {![!]} years old.”.format(names, ages))
Elie Edit Shell Qebug Options windows Help
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "copyright", "credits" or "licensee)" for more information.
»> characters=["Conan". "Belit", "Valeria". 19. 27. 20]
>» print ("{0} is {3} years old. Whereas (1) is {4} years old. ”.format(*characters))
Conan is 19 years old. Whereas Belit is 27 years old.

www.pclpublications.com
Working with Data

Date and Time


When working with data it's often handy to have access to the time. For example, you
may want to time-stamp an entry or see at what time a user logged into the system and
for how long. Luckily acquiring the date and time is easy, thanks to the Time module.

TIME LORDS
The time module contains functions that help you retrieve the current system time, reads the date from strings, formats the
time and date and much more.

STEP1 First you need to import the time module. It's one You can see the structure of how time is presented
STEP 3
a that's built-in to Python 3 so you shouldn't need to ________ J by entering:
drop into a command prompt and pip install it. Once it's imported,
time, local. timeO
you can call the current time and date with a simple command:
The output is displayed as such: ‘time. struct_time(tm_
import time
year=2017, tm_mon=9, tm_mday=7, tm_hour=9,
time.asctimeO
tm_min=6, tm_sec=13, tm_wday=3, tm_yday=250, tm_
isdst=0) obviously dependent on your current time as opposed
Python 3.4.2 Shell
to the time shown above.
Eile Edit Shell pebug Qptions Windows Help

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


[GCC 4.9.1] on linux
Type "copyright”, "credits" or "licensee)“ for more information. Python 3.4.2 Shell _ □ x
»> import time
»> time.asctimeO file Edit Shell Qebug Qptions Windows Help
■Thu Sep 7 08:44:24 2017'
Python 3.4.2 (default. Oct 19 2014. 13:31:11)
[GCC 4.9.1) on linux
Type "copyright", "credits” or "licensed" for more information.
>» impor t time
»> time.localtime()
time.struct_time(tm_year=2017. tm_mon=9, tm_mday=7, tm_hour=9, tm_min=6, tm_sec=
13, tm_wday=3, tm_yday=250, tm_isdst=0)

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

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

0 4-digit year 2016

1 Month 1 to 12

2 Day 1 to 31

3 Hour 0 to 23

4 Minute 0 to 59

5 Second 0 to 61 (60 or 61 are leap-seconds)

6 Day of Week 0 to 6 (0 is Monday)

7 Day of year 1 to 366 (Julian day)

8 Daylight savings -1, 0, 1, -1 means library determines DST

Python & C++ Coding


Date and Time

This naturally means you can incorporate various You saw at the end of the previous section, in the
STEP 5 STEP 8
A functions into your own code, such as: code to calculate Pi to however many decimal places
the users wanted, you can time a particular event in Python. Take
time.strftime(“%a”)
the code from above and alter it slightly by including:
time.strftime(“%B”)
time.strftime(“%b”) start_tinie=time. timeO
time.strftime(“%H”)
Then there's:
time.strftimeC“%H%M”)
endtime=time.time()-start_time

logintime.py - /home/pi/Documents/Python Code/logmtime.py (3.4.2) -ax


Eile Edit Ffirmat Bun Options Windows Help

import time

start_time-time.time()
name=input("Enter login name: ")
endtime-time.time()-start_time

print("Welcome", name, "\d”)

print("User, name, "logged in at", time.strftime("%H:%M"))


print ("It took", name, endtime, "to login to their account.")

Note the last two entries, with %H and %H%M, as STEP 9 The output will look similar to the screenshot below.
STEP 6
A you can see these are the hours and minutes and as The timer function needs to be either side of the
the last entry indicates, entering them as %H%M doesn't display the input statement, as that’s when the variable name is being created,
time correctly in the Shell. You can easily rectify this with: depending on how long the user took to log in. The length of time is
then displayed on the last line of the code as the endtime variable.
time.strftime(“%H:%M”)

Python 3.4.2 Shell _ □ x


File Edit Shell Debug Options Windows Help

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


[GCC 4.9.1] on linux
Type "copyright", “credits" or "licenseO" for more information.
>» —--------- ———————----- ______ RESTART ———————

Enter login name: David


Welcome David \d
user: David logged in at 09:52
It took David 5.311823129653931 to login to their account.

STEP 7 This means you're going to be able to display There's a lot that can be done with the time
STEP 10
either the current time or the time when module; some of it is quite complex too, such as
something occurred, such as a user entering their name. Try this displaying the numberof seconds since January 1st 1970. Ifyou
code in the Editor: want to drill down further into the time module, then in the Shell
enter: help(time) to display the current Python version help file
import time
for the time module.
name=input(“Enter login name: “)
print(“Welcome”, name, “\d”)
print(“User:”, name, “logged in at”, time.
strftime(“%H:%M”))

Try to extend it further to include day, month, yearand so on.

www.pclpublications.com
Working with Data

Opening Files
In Python you can read text and binary files in your programs. You can also write to file,
which is something we will look at next. Reading and writing to files enables you to
output and store data from your programs.

OPEN, READ AND WRITE


In Python you create a File object, similar to creating a variable, only pass in the File using the open() Function. Files are usually
categorised as text or binary.

STEP1 Start by entering some text into your system's text If you now enter poem into the Shell, you will get
STEP 3
a editor. The text editor is best, not a word processor, A some information regarding the text file you've just
as word processors include background Formatting and other asked to be opened. You can now use the poem variable to read the
elements. In our example, we have the poem The Cimmerian, by contents of the file:
Robert E Howard. You need to save the file as poem.txt.
poem. readO
Note than a /n entry in the text represents a new line, as you
File Edit Seaich Options Help
1 remember used previously.
the dark woods, masking slopes of s<
the grey clouds' leaden everlasting
The dusky streams that flowed withot
And the lone winds that whispered d<
21/06/17
H Addition py 52 bytes 18/08/17 |Vista on vista marching, hills on hi
Slope beyond slope, each dark with I
8 cake.py 251 bytes 25/08/17' Our gaunt land lay. So when a man cl
a rugged peak and gazed, his shaded
S Circle py 150bytes 21/08/17 Saw but the endless vista - hill on
® graphicspy 19 kB Fnday Slope beyond slope, each hooded lik<
3 Hello,py 45 bytes 18/08/17
Wimgpy 61 bytes 21/08/17 It was a gloomy land that seemed to
All winds and clouds and dreams tha'
8 imgtestpy 350 bytes 21/08/17 | With bare boughs rattling in the lor
And the dark woodlands brooding ovei
H toopi py 43 bytes 18/08/17 Not even lightened by the rare dim :
M main.py 175 bytes 15/06/17 Which made squat shadows out of men,
Cinmeria, land of Darkness and deep
M namecounlpy 101 bytes 18/08/17
HR Pi.png 42.2 kB 21/08/17 It was so long ago and far away
S Square py 155 bytes 21/08/17 I have forgot the very name nen call
The axe and flint-tipped spear are 1
Stestpy 40 bytes 18/08/17 ( And hunts and wars are shadows. I r<
Only the stillness of that sombre li
Tlw clouds that piled forever on tin
3 wordgame.py 287 bytes 18/08/17 I The dimness of the everlasting wood:

cnsrscter coding: | Current iccale (UTF-8) -j| if

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

This time, the /n entries are removed in favour of new lines and
Python 3.4.2 Shell _ □ x
readable text.
£ile Edit Shell Qebug Options Windows Help

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


[GCC 4.9.1] on linux
Type "copyright", "credits" or "licensee)" for more information.
»> poem=open("/home/pi/Documents/Poem.txt")

Python & C++ Coding


Q Opening Files

Just as with lists, tuples, dictionaries and so on, Extending this further, you can use readlinesQ to
STEP 5 STEP 8
A you're able to index individual characters of the grab all the lines of the text and store them as
text. For example: multiple lists. These can then be stored as a variable:

poem.read(5) poem=open(“/home/pi/Documents/Poem.txt”)
lines=poem. readlinesQ
Displays the first five characters, whilst again entering:
lines[0]
poem.read(5) lines[l]
lines[2]
Will display the next five. Entering (1) will display one character at
a time.

Similarly, you can display one line of text at a time by You can also use the for statement to read the lines
STEP 6 STEP 9
________ J using the readlineQ function. For example: ________ J of text back to us:
poem=open(“/home/pi/Documents/Poem.txt”) for lines in lines:
poem. readlineQ print(lines)

Will display the first line of the text with: Since this is Python, there are other ways to produce the same output:

poem.readline() poem=open(“/home/pi/Documents/Poem.txt”)
for lines in poem:
Displaying the next line of text once more.
print(lines)

STEP 7 You may have guessed that you can pass the Let's imagine that you want to print the text one
STEP 10
readlineQ function into a variable, thus allowing you -J character at a time, like an old dot matrix printer
to call it again when needed: would. You can use the time module mixed with what you've looked
at here. Try this:
poem=open(“/home/pi/Documents/Poem.txt”)
line=poem. readlineQ import time
line poem=open(“/home/pi/Documents/Poem.txt”)
lines=poem. readQ
for lines in lines:
printQines, end=””)
time.sleep(.15)

The output is fun to view, and easily incorporated into your own code.

www.pclpublications.com
Working with Data

Writing to Files
The ability to read external files within Python is certainly handy but writing to a file is
better still. Using the write() function, youTe able to output the results of a program to
a file, that you can then read() back into Python.

WRITE AND CLOSE


The write() function is slightly more complex than read(). Along with the filename you must also include an access mode which
determines whether the file in question is in read or write mode.

STEP1 Start by opening IDLE and enter the following: However, the actual text file is still blank (you can
STEP 3
a a check by opening it up). This is because you've
t=open(“/home/pi/Documents/text.
written the line of text to the file object but not committed it to the
txt”,”w”)
file itself. Part of the writeQ function is that you need to commit the
Change the destination from /home/pi/Documents to your own changes to the file; you can do this by entering:
system. This code will create a text file called text.txt in write mode
t.closeO
using the variable't'. If there's no file of that name in the location, it
will create one. If one already exits, it will overwrite it, so be careful.
Python 3.4.2 Shell _ □ x
File Edit Shell Qebug Options Windows Help

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


[GCC 4.9.1] on linux
Type "copyright", "credits" or "licensee ) ** for more information.
»> t=open("/home/pi/Documents/text.txt".”w")
»> t.write("You awake in a small, square room. A single table stands to one sid
e. there is a locked door in front of you.”)
109
>» t.closeO

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

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

Python & C++ Coding


Writing to Files

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

t=open(“/home/pi/Documents/text. txt”, ”a”) import math


t.writeC“\n”) print(“Value of Pi is: “,math.pl)
t.wrlte(“ You stand and survey your surroundings. print(“\nWriting to a file now...”)
On top of the table is some meat, and a cup of
water.\n”) *wntepitofile.py - /home/pi/Docume...ython Code/writepitofile.py (3.4.2)* -ax
file Edit Fermat Run Options Windows Help

import math
Python 3.4.2 Shell
print("Value of Pi is: ",math.pi)
File Edit Shell Debug Options Windows Help
print("\nWriting to a file now...")
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "copyright", "credits" or "licensed" for more information.
»> t=open("/home/pi/Documents/text .txt","a”)
»> t.write("\n")
1
»> t.write("You stand and survey your surroundings. On top of the table is some
meat, and a cup of water.\n")
94

You can keep extending the text line by line, Now let’s create a variable called pi and assign it the
STEP 6 STEP 9
ending each with a new line (\n). When you're
A value of Pi:
done, finish the code with t.closeQ and open the file in a text
pi=math.pi
editor to see the results:
You also need to create a new file in which to write Pi to:
t.write(“The door is made of solid oak with iron
strips. It’s bolted from the outside, locking you t=open(“/home/pi/Documents/pi.txt”,”w”)
in. You are a prisoner I An”)
Remember to change your file location to your own particular
t.close()
system setup.

*wntepitofile.py - /home/pi/Docume...ython Code/writepitofile.py (3.4.2)* -ox


Eile Edit Fermat Bun Options Windows Help

import math

print("Value of Pi is: .math.pi)

print("\nwriting to a file now...")

pi-math.pi

t-open("Zhome/pi/Docunents/pi .txt","w")

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

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

www.pclpublications.com
Working with Data

Exceptions
When coding, you'll naturally come across some issues that are out of your control.
Let's assume you ask a user to divide two numbers and they try to divide by zero. This
will create an error and break your code.

EXCEPTIONAL OBJECTS
Rather than stop the flow of your code, Python includes exception objects which handle unexpected errors in the code. You
can combat errors by creating conditions where exceptions may occur.

STEP1 You can create an exception error by simply trying You can use the functions raise exception to create
STEP 3
a to divide a number by zero. This will report back A our own error handling code within Python. Let's
with the ZeroDivisionError: Division by zero message, as seen in the assume your code has you warping around the cosmos, too much
screenshot. The ZeroDivisionError part is the exception class, of however results in a warp core breach. To stop the game from
which there are many. exiting due to the warp core going supernova, you can create a
custom exception:

raise Exception(“warp core breach”)

BaseException

STEP 2 Most exceptions 4— SystemExit


STEP 4 To trap any errors in the code you can encase the
+— Keyboardinterrupt
are raised 4— GeneratorExit potential error within a try: block. This block consists
+— Exception
automatically when Python +— Stopiteration of try, except, else, where the code is held within try:, then if there's
+— StopAsyncIteration
comes across something that's +— ArithmeticError an exception do something, else do something else.
I +— FloatingPointError
inherently wrong with the code. I +— OverflowError
I +— ZeroDivisionError
However, you can create your +— AssertionError
+— AttributeError
own exceptions that are designed +— BufferError
4— EOFError
to contain the potential error and +— ImportError
+— ModuleNotFoundError
react to it, as opposed to letting 4— LookupError
the code fail. I
I
+— IndexError
+— KeyError
4— MemoryError
4-— NameError
I 4-— UnboundLocalError
4-— OSError
I 4-— BlockinglOError
I 4-— ChildProcessError
I 4-— ConnectionError
I I 4— BrokenPipeError
I I 4— ConnectionAbortedError
I I 4-— ConnectionRefusedError
I I 4-— ConnectionResetError
I 4-— FileExistsError
I 4-— FileNotFoundError
I 4-— InterruptedError
I 4-— IsADirectoryError
I 4-— NotADirectoryError
I 4-— PermissionError
I 4-— ProcessLookupError
I 4-— TimeoutError
4— ReferenceError
4-— RuntimeError

Python & C++ Coding


Exceptions

For example, use the divide by zero error. You can Naturally, you can quickly fix the issue by changing
STEP 5 STEP 8
create an exception where the code can handle the
A the "r" read only instance with a "w" for write. This,
error without Python quitting due to the problem: as you already know, will create the file and write the content then
commit the changes to the file. The end result will report a different
try:
set of circumstances, in this case, a successful execution of the code.
a=int(input(“Enter the first number: “))
b=int(input(“Enter the second number: “))
print(a/b)
except ZeroDivisionError:
print(“You have tried to divide by zero!”)
else:
print(“You didn’t divide by zero. Well done!”)

You can use exceptions to handle a variety of useful You can also use a finally: block, which works in a
STEP 6 STEP 9
tasks. Using an example from our previous tutorials, similar fashion butyou can't use else with it. To use
let’s assume you want to open a file and write to it: our example from Step 6:

try: try:
txt = open(“/home/pi/Documents/textfile.txt”, “r”) txt = open(“/home/pi/Documents/textfile.txt”, “r”)
txt.write(“This is a test. Normal service will try:
shortly resume!”) txt.write(“This is a test. Normal service will
except lOError: shortly resume!”)
print (“Error: unable to write the file. Check finally:
permissions”) print (“Content written to file successfully.
else: Have a nice day.”)
print (“Content written to file successfully. Have txt.close()
a nice day.”) except lOError:
txt.close() print (“Error: unable to write the file. Check
permissions”)

STEP 7 Obviously this won't work due to the file textfile.txt As before an error will occur as you've used the
STEP 10
being opened as read only (the "r" part). So in this "r" read-only permission. If you change it to a "w",
case rather than Python telling you thatyou're doing something then the code will execute without the error being displayed in the
wrong, you've created an exception using the lOError class IDLE Shell. Needless to say, it can be a tricky getting the exception
informing the user that the permissions are incorrect. code right the first time. Practise though, and you will get the hang
of it.
exception2.py - /home/pi/Documen.../Python Code/exception2.py (3.4.2) -ax
File Edit Format Run Options Windows Help

txt = open("/home/pi/Docixnents/textfile.txf, "r”)


txt.write("This is a test, normal service will shortly resume!")
’ except lOError:
print (“Error: unable to write the file. Check permissions”)
I else:
print ("Content written to file successfully. Have a nice day.”)
txt. closed

www.pclpublications.com
Working with Data

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

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

One of the best graphical modules to begin learning The command turtle.circle(50) is what draws the
STEP 1 STEP 3
Python graphics is Turtle. The Turtle module is, as circle on the screen, with 50 being the size. You
the name suggests, based on the turtle robots used in many schools, can play around with the sizes if you like, going up to 100, 150 and
that can be programmed to draw something on a large piece beyond; you can draw an arc by entering: turtle. circle(50,
of paper on the floor. The Turtle module can be imported with: 180), where the size is 50, but you're telling Python to only draw
import turtle. 180° of the circle.

Let's begin by drawing a simple circle. Start a New STEP 4 The last part of the circle code tells Python to keep
STEP 2
________ J File, then enter the following code: the window where the drawing is taking place to
remain open, so the user can click to close it. Now, let's make a square:
import turtle
import turtle
turtle.ci rcle(50)
turtle. getscreenQ ._root.mainloopO print(“Drawing a square...”)

As usual press F5 to save the code and execute it. A new window will for t in range(4):
now open up and the 'Turtle' will draw a circle. turtle.forward(100)
turtle.left(90)
turtle. getscreenQ. _root. mainloopQ

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

Python & C++ Coding


You can add a new line to the square code to add Now let's get the code by importing the pygame module:
STEP 5 STEP 8
________ J some colour:
import pygame
turtle.color(“Red”) pygame. initO

Then you can even change the character to an actual turtle by entering: img = pygame.image.load(“RPi.png

turtle.shape(“turtle”) white = (255, 255, 255) imgtest py - /home/pi/Docur


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

screen.fill((white))
screen.fill((white)) screen.blit(img.(0.0))
pygame.d isplay.flip()
screen.blit(img,(0,0))
wtiile true:
pygame.display.flip() for event in pygame.event.get():
f event.type -- pygame.QIITT:
pygame.Quito
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()

You can see that the Turtle module can draw out STEP 9 In the previous step you imported pygame, initiated
STEP 6
Asome pretty good shapes and become a little the pygame engine and asked it to import our saved
more complex as you begin to master the way it works. Enter this Raspberry Pi logo image, saved as RPi.png. Next you defined the
example: background colour of the window to display the image and the
window size as per the actual image dimensions. Finally you have a
from turtle import *
loop to close the window.
color(‘red’, ‘yellow’)
begin_fill() w ■ 900
while True: h = 450
forward(200) screen = pygame.display. set_mode((w, h))
left(170) screen.f111((white))
if abs(pos()) < 1:
break screen.fill((white))
end_fill() screen.blit(img,(0,0))
Squaie.py • /honie/pi/Ducunierils/Squaiep)
done() tile Edit Format Hun options Windows Help pygame.display.flip()
colorcred', yellow’)
It's a different method, begin_fill()
■Ahlie True:
but very effective. forward(200)
leftc1/O)
if absCposO) < I:
for event in pygame.event.get( ) :
end_fill() if event.type == pygame.QUIT:
done()
pygame,quit()

STEP 7 Another way in which you can display graphics is Press F5 to save and execute the code and your
STEP 10
by using the Pygame module. There are numerous -J image will be displayed in a new window. Have a
ways in which pygame can help you output graphics to the screen playaround with the colours, sizes and so on and take time to look
but for now let's look at displaying a predefined image. Start by up the many functions within the pygame module too.
opening a browserand finding an image, then save it to the folder
where you save your Python code.

www.pclpublications.com
Index

66 Python & C++ Coding


Using Modules

A Python module is simply a Python-


created source File which contains the
necessary code For classes, Functions
and global variables. You can bind
and reFerence modules to extend
Functionality and create even more
spectacular Python programs.

Want to see how to improve these


modules to add a little something
extra to your code? Then read on and
learn how they can be used to Fashion
Fantastic code.

68 Calendar Module
70 OS Module
72 Random Module
74 Tkinter Module
76 Pygame Module
80 Create Your Own Modules

www.pclpublications.com 67
Using Modules

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

WORKING WITH DATES


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

Launch Python 3 and enter: import calendar to There are numerous functions within the calendar
STEP 1 STEP 3
________ J call up the module and its inherent functions. Once A module that may be of interest to you when
it's loaded into memory, start by entering: forming your own code. Forexample, you can display the number of
leap years between two specific years:
sep=calendar.TextCalendar(calendar.SUNDAY)
sep.prmonth(2017, 9) leaps=calendar.leapdays(1900, 2018)
print(leaps)
The result is 29, starting from 1904 onward.

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

68 Python & C++ Coding


QCalendar Module

You can also create a program that will display all You're also able to print the individual months or
STEP 5 STEP 8
________ J the days, weeks and months within a given year: J days of the week:

import calendar import calendar


year=int(input(“Enter the year to display: “) for name in calendar.month_name:
printfcalendar.prcal(year)) print(name)

We're sure you'll agree that's quite a handy bit of code to have import calendar
to hand. for name in calendar.day_name:
print(name)

Interestingly we can also list the number of days in a STEP 9 The calendar module also allows us to write the
STEP 6
________ J month by using a simple for loop: functions in HTML, so that you can display it on a
website. Let’s start by creating a new file:
import calendar
cal=calendar.TextCalendar(calendar.SUNDAY) import calendar
for i in cal.itermonthdays(2018, 6): cal=open(“/home/pi/Documents/cal.html”, “w”)
print(i) c=calendar.HTMLCalendar(calendar.SUNDAY)
cal.write(c.formatmonth(2018, 1))
cal.closef)

This code will create an HTML file called cal, open it with a browser
and it displays the calendar for January 2018.

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

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

www.pclpublications.com 69
Using Modules

OS Module
The OS module allows you to interact directly with the built-in commands Found in your
operating system. Commands vary depending on the OS youTe running, as some will
work with Windows whereas others will work with Linux and macOS.

INTO THE SYSTEM


One oF the primary Features oF the OS module is the ability to list, move, create, delete and otherwise interact with Files
stored on the system, making it the perfect module For backup code.

STEP1 You can start the OS module with some simple The Windows output is difFerent as that’s the
STEP 3
a
Functions to see how it interacts with the operating A current working directory oF Python, as determined
system environment that Python is running on. iFyou're using Linux by the system; as you might suspect, the os.getcwdQ Function is
or the Raspberry Pi, try this: asking Python to retrieve the Current Working Directory. Linux users
will see something along the same lines as the Raspberry Pi, as will
import os
macOS users.
home=os. getcwdQ
print(home)

STEP 2 The returned result From printing the variable home STEP 4 Yet another interesting element to the OS module,
is the current user's home Folder on the system. is its ability to launch programs that are installed
In our example that's /home/pi; it will be diFFerent depending on in the host system. For instance, iFyou wanted to launch the
the user name you log in as and the operating system you use. Chromium browser From within a Python program you can use
For example, Windows 10 will output: C:\Program Files (x86)\ the command:
Python36-32.
import os
L<i Python 3.6.2 Shell - □ X browser=os.system(“/usr/bin/chromium-browser”)
File Edit Shell Debug Options Window Help
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)]
on Win32
Type "copyright", "credits" or "license()" for more information.
>» import os
»> home=os.getcwd()
>» print (home)
C:\Program Files (x86)\Python36-32

70 Python & C++ Coding


Q OS Module

The os.systemQ function is what allows interaction The ability to manipulate directories, or folders if
STEP 5 STEP 8
A with external programs; you can even call up you prefer, is one of the OS module's best features.
previous Python programs using this method. You will obviously For example, to create a new directory you can use:
need to know the full path and program file name for it to work
import os
successfully. However, you can use the following:
os.mkdir(“NEW”)
import os
This creates a new directory within the Current Working Directory,
os.system(‘start chrome “https://www.youtube.com/
named according to the object in the mkdir function.
feed/music”’)

You can also rename any directories you've created


STEP 9
by entering:

import os
os. renameC“NEW”, “OLD”)

To delete them:
For Step 5's example we used Windows, to show
STEP 6
A that the OS module works roughly the same across import os
all platforms. In that case, we opened YouTube's music feed page, so os.rmdirC“OLD”)
it is therefore possible to open specific pages:

import os
os.system(‘chromium-browser “http://
bdmpublications.com/”’)

Another module that goes together with OS is


STEP 10
A shutil. You can use the shutil module together
with OS and time to create a time-stamped backup directory, and
copy files into it:

import os, shutil, time

root_src_dir = r’/home/pi/Documents’
root_dst_dir = ‘/home/pi/backup/’ + time.asctimeO
for src_dir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_src_dir, root_
STEP 7 Note in the previous step's example the use of dst_dir, 1)
single and double-quotes. The single quotes encase if not os.path.exists(dst_dir):
the entire command and launching Chromium, whereas the double os.makedirs(dst_dir)
quotes open the specified page. You can even use variables to call for file_ in files:
multiple tabs in the same browser: src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
import os
if os.path.exists(dst_file):
a=(‘chromium-browser “http://bdmpublications.
os.remove(dst_file)
com/” ’)
shutil,copy(src_file, dst_dir)
b=(‘chromium-browser “http://www.google.co.uk”’)
os.system(a + b) print(“»»»»»Backup complete<<««««”)

www.pclpublications.com 71
Using Modules

Random Module
The random module is one you will likely come across many times in your Python
programming lifetime; as the name suggests, it's designed to create random numbers
or letters. However, it's not exactly random but it will suffice for most needs.

RANDOM NUMBERS
There are numerous Functions within the random module, which when applied can create some interesting and very useFul
Python programs.

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

Python 3.4.2 Shell


File Edit Shell Debug Options Windows Help

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


[GCC 4.9.1] on linux
Type “copyright", “credits" or "licensee)" for more information.
»> import random
»> random.choice(("Conan", "Valeria", “Belit"])
’Conan’

STEP 2 In our example


the number four
was returned. However, enter
the print function a few more
times and it will display different
integer values from the set of
numbers given, zero to five. The
overall effect, although pseudo­
You can extend the previous example somewhat by
random, is adequate for the STEPS
having random.choiceQ select from a list of mixed
average programmer to utilise in
variables. For instance:
their code.
import random
lst=[“David”, 44, “BDM Publications”, 3245.23,
“Pi”, True, 3.14, “Python”]
rnd=random.choice(lst)
Fora bigger set of numbers, including floating
STEP 3 print(rnd)
A point values, you can extend the range by using the
multiplication sign:
Python 3.4.2 Shell
import random Elie Edit Shell Debug options Windows Help

print(random. randomQ *100) Python 3.4.2 (default, Oct 19 2014. 13:31:11)


[GCC 4.9.1] on linux
Type "copyright", "credits" or "licensee)” for more information.
Will display a floating point number between 0 and 100, to the tune »> import random
>» lst=["David", 44. "BDM Publications". 3245.23. "Pi", True, 3.14, "Python"]
of around fifteen decimal points. >» rnd=random.choice(lst)
»> print(rnd)
3245.23

72 Python & C++ Coding


Random Module

Interestingly, you can also use a function within the STEP 9 Let's use an example piece of code which flips a
STEP 6
random module to shuffle the items in the list, thus virtual coin ten thousand times and counts how
adding a little more randomness into the equation: many times it will land on heads or tails:

random, shuffle(lst) import random


print(lst) output={“Heads”:0, “Tails”:0}
coin=li stfoutput. keysQ)
This way, you can keep shuffling the list before displaying a random
item from it. for i in range(10000):
output [random.choice(coin)]+=l

print(“Heads:”, output[“Heads”])
printC“Tails:”, output[“Tails”])

Using shuffle, you can create an entirely random list


STEP 7
________ J of numbers. For example, within a given range:
import random
lst=[[i] for I in range(20)]
random, shuffle(lst) Here's an interesting piece of code. Using a text
STEP 10
print(lst) A file containing 466 thousand words, you can pluck
a user generated number of words from the file (text file found at:
Keep shuffling the list and you can have a different selection of
www.github.com/dwyl/english-words):
items from 0 to 20 every time.
import random

print(“»»»»»Random Word Finder<<««««”)


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

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


“))
with open(“/home/pi/Downloads/words.txt”, “rt”) as
f:
words = f. readlinesQ
words = [w.rstripO for w in words]

You can also select a random number from a given print(“------------------------------------ ”)


STEP 8
________ J range in steps, using the start, stop, step loop:
for w in random.sample(words, wds):
import random print(w)
for i in range(10):
print(“------------------------------------ ”)
print(random.randrange(0, 200, 7))

Results will vary but you get the general idea as to how it works.

www.pclpublications.com 73
Using Modules

Tkinter Module
While running your code from the command line, or even in the Shell, is perfectly fine,
Python is capable of so much more. The Tkinter module enables the programmer to set
up a Graphical User Interface to interact with the user, and it's surprisingly powerful too.

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

STEP1 Tkinter is usually built into Python 3. However, if it's The ideal approach is to add mainloopQ into the
STEP 3
a available when you enter: import tkinter, then code to control the Tkinter event loop, but well
A
you need to pip install tkinter from the command prompt. get to that soon. You've just created a Tkinter widget and there are
We can start to import modules differently than before, to save on several more we can playaround with:
typing and by importing all their contents:
btn=ButtonO
import tkinter as tk btn.packQ
from tkinter import * btn[“text”]=”Hello everyone!”
The first line focuses on the newly created window. Click back into
the Shell and continue the other lines.

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

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

tkintercode1.py-/home/pi/Docume...ython Code/tkintercodel.py (3.4.2) -ax


File Edit Format Run Options Windows Help

I
import tkinter as tk
from tkinter import *
btn=Button()
btn.pack()
btn["text"]="Hello everyone!"

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

74 Python & C++ Coding


(^Tkinter Module

Save and execute the code from Step 4 and a You can create radio buttons too. Try:
STEP 5 STEP 8
A window appears with 'Hello everyone!' inside. If you J
from tkinter import *
click the Hello everyone! button, the Shell will output the text 'You
just clicked me!'. It's simple but shows you what can be achieved root = TkQ
with a few lines of code.
v = IntVarQ
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux Label(root, root.title(“Options”), text=”””Choose
Type "copyright", "credits" or "licensed" for more information.
»> ================================ RESTART ================================ a preferred language:”””,
>» You just clicked me! justify = LEFT, padx = 20).pack()
You just clicked me!
You just clicked me! Radiobutton(root,
text=”Python”,
padx = 20,
variable=v,
value=l).pack(anchor=W)
Radiobutton(root,
text=”C++”,
padx = 20,
variable=v,
value=2).pack(anchor=W)

mainloopO
the code. Here's an example using the BDM Publishing logo:
STEP 9 You can also create check boxes, with buttons and
from tkinter import *
output to the Shell:
root = TkO
from tkinter import *
logo = PhotoImage(file=”/home/pi/Downloads/BDM_logo.
root = TkQ
gif”)
wl = Label(root, root.title(“BDM Publications”), def var_states():
image=logo).pack(side=”right”) print(“Warrior: %d,\nMage: %d” % (varl.getQ,
content = From its humble beginnings in 2004, var2.get()))
the BDM brand quickly grew from a single publication
Label(root, root.title(“Adventure Game”),
produced by a team of just two to one of the biggest
text=”»»»»»Your adventure role<««<««”).
names in global bookazine publishing, for two simple
grid(row=0, sticky=N)
reasons. Our passion and commitment to deliver the
varl = IntVarQ
very best product each and every volume. While
Checkbutton(root, text=”Warrior”, variable=varl).
the company has grown with a portfolio of over 250
grid(row=l, sticky=W)
publications delivered by our international staff,
var2 = IntVarQ
the foundation that it has been built upon remains
Checkbutton(root, text=”Mage”, variable=var2).
the same, which is why we believe BDM isn’t just
grid(row=2, sticky=W)
the first choice it’s the only choice for the smart
Button(root, text=’Quit’, command=root.destroy).
consumer.
grid(row=3, sticky=W, pady=4)
w2 = Labelfroot,
Buttonfroot, text=’Show’, command=var_states).
justify=LEFT,
grid(row=3, sticky=E, pady=4)
padx = 10,
text=content).pack(side=”left”) mainloopQ
root.mainloopO
The code from Step 9 introduced some new
STEP 10
geometry elements into Tkinter. Note the
STEP 7
sticky=N, E and W arguments. These describe the locations of the
The previous code is check boxes and buttons (North, East, South and West). The row
quite weighty, mostly argument places them on separate rows. Have a play around and
due to the content see what you get.
variable holding a part
of BDM's About page
from the company
website. You can
obviously change the
content, the root.title
and the image to suit
your needs.

www.pclpublications.com 75
Using Modules

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

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

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

import pygame import pygame


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

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

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

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


STEP 2
________ J it a title:
gamewindow=pygame.di splay.set_mode((800,600))
pygame.display.set_caption(“Adventure Game”)
You can see that after the first line is entered, you need to click back
into the IDLE Shell to continue entering code; also, you can change
the title of the window to anything you like.

76 Python & C++ Coding


Pygame Module

STEP 4 If the Pygame window still won't Adventure Game


close don't worry, it's just a
discrepancy between the IDLE (which is written pi@raspberrypi: ~/Documents/Python Code _ □ x
with Tkinter) and the Pygame module. If you File Edit Tabs Help
run your code via the command line, it closes |pi(?raspberrypi:-/Docuaents/Python Code $ python3 pygamel.py
lpieraspberrypi:~/Oocuaents/Pytbon Code $ |
perfectly well.

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


STEP 5
running the main Pygame code within a while loop; spritel.png”)
it makes it neater and easier to follow. We've downloaded a graphic
def sprite(x,y):
to use and we need to set some parameters for pygame:
gamewindow.blitfimg, (x,y))
import pygame
x=(800*0.45)
pygame. initO
y=(600*0.8)
running=True
gamewindow.fill(white)
while running: sprite(x,y)
pygame. display. updateQ
gamewindow=pygame.di splay.set_niode((800,600))
pygame.display.set_captionC“Adventure Game”) for event in pygame.event.get():
black=(0,0,0) if event.type==pygame.QUIT:
whlte=(255,255,255) running=False

pygamel py -/home/pi/Documents/Python Code/pygamel py (3.4.2) _ □ x


Adventure Game File Edit Format Run Options Windows Help
(import pygame
fiorr pygame.locals import *
pygame.init()

running=T rue

while running:

gamewindow=py game.display.set_mode((800.600))
pygame.display.set_caption("Adven ture Game")
black=(0.0.0)
wtlite=(255,255,255)
img=pygame.image.load(“/home/pi/Downloads/sprite1.png”)

def sprite(x.y):
gamewindow.blit( img, (x,y))

x-(800*0.45)
y=(600*0.8)

gamewindow.fill(white)
sprite(x.y)
pygame.display.update()

foi event in pygame.event.get():


if event.type==QUIT:
running-”jIse
pygame.quit()

Let's quickly go through the code changes. We've downloaded image called spritel.png and allocated it to the
STEP 6
defined two colours, black and white together variable img; and also defined a sprite function and the Blit function
with their respective RGB colour values. Next we've loaded the will allow us to eventually move the image.

|import pygame x-(800*0.45)


from pygame.locals import * y=(600*0.8)
pygame.init()
gamewindow.f i1l(white)
running=T rue sprite(x,y)
pygame.display.update()
while running:

gam ewindo'A-py game .disp lay. set_mode( (800,600 ))


pygame.display.set_capt ion( ’Adventure Game”)
black=(0,0,0) for event in pygame.event.get():
wtiite=(255,255,255) if event.type==QUIT;
img=pygame.image.load("/home/pi/Downloads/spritel.png”) running“ralse
pygame.quit()
def sprite(x.y):
gamewindow.blit(img, (x,y))

www.pclpublications.com 77
Using Modules

STEP 7 Now we can change the code around again, this imgspeed=0
time containing a movement option within the
while running:
while loop, and adding the variables needed to move the sprite
for event in pygame.event.get():
around the screen:
if event.type==QUIT:
import pygame running=False
from pygame.locals import *
if event.type == pygame.KEYDOWN:
pygame. initO
if event.key==pygame.K_LEFT:
running=True xchange=-5
el if event.key==pygame.K_RIGHT:
gamewindow=pygame.display.set_mode((800,600))
xchange=5
pygame.di splay.set_captionC“Adventure Game”)
if event.type==pygame.KEYUP:
black=(0,0,0)
if event.key==pygame.K_LEFT or event
white=(255,255,255)
key==pygame.K_RIGHT:
img=pygame.image.load(“/home/pi/Downloads/spritel.
xchange=0
png”)
x += xchange
def sprite(x,y):
gamewindow.blit(img, (x,y)) gamewindow.fill(white)
sprite(x,y)
x=(800*0.45)
pygame. display. updateQ
y=(600*0.8)
pygame.quit()
xchange=0

Copy the code down and using the left and right arrow keys on the keyboard you can move your sprite across the bottom of
STEP 8
________ J the screen. Now, it looks like you have the makings of a classic arcade 2D scroller in the works.
w+iile running:
import pygame
for event in pygame.event.get():
from pygame.locals import *
if event.type==QUIT:
pygame.init()
running=False
running=True
if event.type == pygame.KEYDOWN:
gamewindow=pygame.display.set_mode((800,600)) if event.key==pygame.K_LEFT:
pygame.display.set_caption("Adventure Game") xchange=-5
black=(0,0,0) elif event.key==pygatne.K_RIGHT:
white-(255,255,255) xchange=5
img=pygame.image.load("/home/pi/Downloads/sprite1.png") if event.type==pygame.KEYUP:
if event.key==pygame.K_LEFT or event.key==pygame.K_RIGHT:
def sprite(x.y): xchange=0
gamewindow.blit(img, (x,y))
x +- xchange
x-(800*0.45)
y=(600*0.8) gamewindow.fill(white)
sprite(x.y)
xchange=0 pygame.display.update()
imgspeed=0
pygame.quit()

78 Python & C++ Coding


Pygame Module

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

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

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

def reset(self):
self._gen = text_generator(self.text)
self.done = False
self .updateQ

def update(self):
if not self.done:
try: self.rendered = self.font. When you run this code it will display a long,
STEP 10
render(next(self._gen), True, (0, 128, 0)) a narrow Pygame window with the intro text
except Stopiteration: scrolling to the right. Aftera pause of ten seconds, it then launches
self.done = True the main game Python script where you can move the warrior sprite
time.sleep(10) around. Overall the effect is quite good but there's always room
subprocess.Popen(“python3 /home/pi/Documents/ for improvement.
PythonX Code/pygamel.py 1”, shell=True)

def draw(self, screen):


screen.blit(self.rendered, seif.pos)

text=(“A long time ago, a barbarian strode from the


frozen north. Sword in hand...”)

message = DynamicText(font, text, (65, 120),


autoreset=True)

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: break
if event.type == pygame.USEREVENT: message.
updateQ
else:
screen.fill(pygame.color.Color(‘black’))
message.draw(screen)

www.pclpublications.com 79
Using Modules

Create Your Own Modules


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

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

STEP1 Let's start by creating a set of basic mathematics Now you're going to take the function definitions
STEP 3
a functions. Multiply a number by two, three and out of the program and into a separate file.
square or raise a number to an exponent (power). Create a New File Highlight the function definitionsand choose Edit > Cut. Choose File
in the IDLE and enter: > New File and use Edit > Paste in the new window. You now have
two separate files, one with the function definitions, the other with
def timestwo(x):
the function calls.
return x * 2
def timesthree(x):
return x * 3

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

Under the above code, enter functions to call the STEP 4 If you now try and execute the basic_math.py code
STEP 2
________ J code: again, the error 'NameError: name 'timestwo' is
not defined' will be displayed. This is due to the code no longer
print (timestwo(2))
having access to the function definitions.
print (timesthree(3))
print (square(4)) Traceback (most recent call last):
File "/home/pi/Documents/Python Code/basic_math.py", line 3, in <module>
print (power(5,3)) print (timestwo(2))
HameError: name 'timestwo' is not defined
Save the program as basic_math.py and execute it to get the results. »> I

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

80 Python & C++ Coding


Q Create Your Own Modules

Back to the basic_math.py window: at the top of the STEP 9 Finally, you can now create a range of if statements
STEP 6
________ J code enter: to determine what to do with the number and
utilise the newly created function definitions:
from minimath import *
if choice == ‘1’:
This will import the function definitions as a module. Press F5 to
print(timestwo(numl))
save and execute the program to see it in action.
elif choice == ‘2’:
print(timesthree(numl))
elif choice == ‘3’:
print(square(numl))

elif choice == ‘4’:


num2 = int(input(“Enter second number: “))
print(power(numl, num2))
else:
print(“Invalid input”)

STEP 7 You can now use the code further to make the
program a little more advanced, utilising the newly
created module to its full. Include some user interaction. Start by
creating a basic menu the user can choose from:

print(“Select operation.\n”)
print(“l.Times by two”)
print(“2.Times by Three”)
print(“3.Square”)
print(“4.Power of”)
choice = input(“\nEnter choice (1/2/3/4):”)

Now we can add the user input to get the number


STEP 8
the code will work on:

numl = int(input(“\nEnter number: “))

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


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

www.pclpublications.com 81
Index

Python & C++ Coding


Say Hello to C++

C++ is a high level programming language


that's used in a multitude of technologies.
Everything from your favourite mobile
app, console and PC game to entire
operating systems, all are developed
using C++ and a collection of software
development kits and custom libraries.

C++ is the driving force behind most


of what you use on a daily basis, which
makes it a complex and extraordinarily
powerful language to get to grips with.
In this section, we look at how to install a
C++ IDE and compiler on your computer.

84 Why C++?
86 Equipment Needed
88 How to Set Up C++in Windows
90 How to Set Up C++on a Mac
92 How to Set Up C++in Linux
94 Other C++IDEs to Install

www.pclpublications.com
Say Hello to C++

Why C++?
C++ is one of the most popular programming languages available today. Originally
called C with Classes, the language was renamed C++ in 1983. It's an extension of the
original C language and is a general purpose object-oriented (OOP) environment.

C EVERYTHING
Due to how complex the language can be, and its power and performance, C++ is often used to develop games, programs,
device drivers and even entire operating systems.

Dating back to 1979, the start of the golden era of home computing labsand by regular people who didn't have access to the
computing, C++, or rather C with Classes, was the brainchild of mainframesand large computing data centres.
Danish computer scientist Bjarne Stroustrup while working on his
PhD thesis. Stroustrup's plan was to further the original C language, C++'s impact in the digital world is immense. Many of the programs,
which was widely used since the early seventies. applications, games and even operating systems are coded using
C++. For example, all of Adobe's major applications, such as
C++ proved to be popular among the developers of the ’80s, Photoshop, InDesign and so on, are developed in C++. You will find
since it was a much easier environment to get to grips with and that the browser you surf the Internet with is written in C++, as
more importantly, it was 99% compatible with the original C well as Windows 10, Microsoft Office and the backbone to Google's
language. This meant that it could be used beyond the mainstream search engine. Apple's macOS is written largely in C++ (with some

C++ code is much faster than that of Python.

1 #i nc1ude< i os Lream>
2 using namespace std;
3 void inain()
4 □ (char ch;
5 cout<<"Enter d charater to check it is vowel or not,";
6 cin>>ch;
7 switch(ch)
8 □ (
9 case a1: case’ A1 :
10 cout«ch<<" is a Vowel";
11 break;
12 case *e’: case'E1:
13 cout<<ch<<" is a Vowel";
14 break;
15 case ' i' : case I’:
16 cout«ch<<" is a Vowel";
17 break;
18 case ’o': case'O’:
19 cout<<ch<<" is a Vowel";
20 break;
21 case 'u': case U’:
22 cout<<ch<<" is a Vowel";

8‘ Python & C++ Coding


Installing - Visual Studio Community 2017 (15.026223.1)

Workloads Individual components Language packs

Windows (3)
Summary
00 Universal Windows Platform development .NET desktop development * Desktop development with C...
■I 0 Create applications for the Universal Windows Platform with C# Build WPF, Windows Forms and console applications using the
VB, JavaScript, or optionally C++. .NET Framework. Included

✓ Visual C++ core desktop features

i**-I
I »
Desktop development with C++
Build classic Windows-based applications using the power of the
□ Optional

Q VC++ 2017 v141 toolset (x86,x64)


Visual C++ toolset, ATI, and optional features like MFC and... 3 C++profiling tools
3 Windows 10 SDK (10.0.14393.0)
3 Visual C++ tools for CMake
□ Visual C++ ATL support
Web & Cloud (4)
□ Windows 8.1 SDK and UCRT SDK
ASP.NET and web development Azure development I_ | Windows XP support for C++
Build web applications using ASP.NET, ASP.NET Core, HTML Azure SDK, tools, and projects for developing cloud apps and ED MFC and ATL support (x86 and x64)
JavaScript, and CSS. creating resources. □ C++/CU support
I I Clang/C2 (experimental)
0 Standard Library Modules

Node.js development Data storage and processing


Build scalable network applications using Node.js, an asynchronous Connect, develop and test data solutions using SQL Server, Azure
0 By continuing, you agree to the license for the
Visual Studio edition you selected. We also offer the
event-driven JavaScript runtime. Data Lake, Hadoop or Azure ML
ability to download other software with Visual
Studio. This software is licensed separately, as set

Microsoft's Visual Studio is a great,

e free environment to learn C++ in.

other languages mixed in depending on the function) and the tikes


of NASA, SpaceX and even CERN use C++ for various applications,
programs, controlsand umpteen other computing tasks.
Windows
C++ is also extremely efficient and performs well across the board Mac
as well as being an easier addition to the core C language. This
higher level of performance over other languages, such as Python,
BASIC and such, makes it an ideal development environment for

®
modern computing, hence the aforementioned companies using it
so widely.

While Python is a great programming language to learn, C++ puts


the developer in a much wider world of coding. By mastering C++,
you can find yourself developing code for the likes of Microsoft,
debian ubuntu
Apple and so on. Generally, C++ developers enjoy a higher salary
than programmers of some other languages and due to its Indeed, the operating system
versatility, the C++ programmer can move between jobs and
companies without the need to relearn anything specific.
However, Python is an easier language to begin with. If you're
completely new to programming then we would recommend you
e you're using is written in C++.

begin with Python and spend some time getting to grips with
programming structure and the many ways and means in which you
find a solution to a problem through programming. Once you can
happily power up your computerand whip out a Python program
with one hand tied behind your back, then move on to C++. Of
course, there's nothing stopping you from jumping straight into
C++; if you feel up to the task, go for it.

Getting to use C++ is as easy as Python, all you need is the right set
of tools in which to communicate with the computer in C++ and
you can start your journey. A C++ IDE is free of charge, even the
immensely powerful Visual Studio from Microsoft is freely available
to download and use. You can get into C++ from any operating
system, be it macOS, Linux, Windows or even mobile platforms.

Just like Python, to answer the question of Why C++ is the answer
is because it's fast, efficient and developed by most of the
applications you regularly use. It's cutting edge and a fantastic
language to master.

www.pclpublications.com
Say Hello to C++

Equipment Needed
You don't need to invest a huge amount of money in order to learn C++ and you
don't need an entire computing lab at your disposal either. Providing you have a fairly
modern computer, everything else is freely available.

C++SETUPS
Most, if not all, operating systems have C++ in their code, so it stands to reason that you can learn to program in C++ no matter
what OS you're currently using.

J COMPUTER
Unless you fancy writing out your C++ code by hand on a sheet of
paper (which is something many older coders used to do), a computer
is an absolute must have component. PC users can have any recent
Linux distro or Windows OS, Mac users the latest macOS.

J AN IDE
Just as with Python, an IDE is used to enter and execute your C++
code. Many IDEs come with extensions and plugins that help make
it work better, or add an extra level of functionality. Often, an IDE
provides enhancements depending on the core OS being used, such as
being enhanced for Windows 10.

J COMPILER
A compiler is a program that converts the C++ language into binary,
so that the computer can understand. While some IDEs come with a
compiler built in, others don't. Code::Blocks is our favourite IDE that
comes with a C++ compiler as part of the package. More on this later.

J TEXT EDITOR
Some programmers much prefer to use a text editor to assemble their
C++ code before running it through a compiler. Essentially you can
use any text editor to write code, just save it with a .cpp extension.
However, Notepad++ is one of the best code text editors available.

J INTERNET ACCESS
While it's entirely possible to learn how to code on a computer that's
not attached to the Internet, it's extraordinarily difficult. You need
to install relevant software, keep it up to date, install any extras or
extensions and look for help when coding. All of these require access
to the Internet.

J TIME AND PATIENCE


Yes, as with Python, you're going to need to set aside significant time
to spend on learning how to code in C++. Sadly, unless you're a genius,
it's not going to happen overnight, or even a week. A good C++ coder
has spent many years honing their craft, so be patient, start small and
keep learning.

Python & C++ Coding


Equipment Needed

OS SPECIFIC NEEDS
C++ will work in any operating system but getting all the necessary pieces together can be confusing to a newcomer. Here are
some OS specifics for C++.

LINUX WINDOWS

Linux users are lucky in that they already have a compiler and We have mentioned previously that a good IDE is Microsoft’s
text editor built into their operating system. Any text editor Visual Studio. However, a better IDE and compiler is
allows you to type out your C++ code, when it's saved with a CodecBlocks, which is regularly kept up to date with a new
.cpp extension, use g++ to compile it. release twice a year. Otherwise Windows users can enter
their code in Notepad++, then compile it with MinGW as used
by CodecBlocks.

RASPBERRY PI MAC

The Raspberry Pi's operating Mac owners will need to


system is Raspbian, which download and install Xcode
is Linux based. Therefore, to be able to compile their
you're able to write your code C++ code natively. Other
out using a text editor, then options for the macOS
compile it with g++ as you include Netbeans, Eclipse or
would in any other Linux distro. CoderBlocks. Note: the
latest CodecBlocks isn't
available for Mac due to a lack
of Mac developers.

www.pclpublications.com
Say Hello to C++

How to Set Up
C++ in Windows
Windows users have a wealth of choice when it comes to programming in C++. There
are plenty of IDEs and compilers available, including Visual Studio from Microsoft.
However, in our opinion, the best C++ IDE to begin with is Code::Blocks.

CODE::BLOCKS
Code::Blocks is a Free C++, C and Fortran IDE that's Feature rich and easily extendible with plug-ins. It’s easy to use, comes with
a compiler and has a vibrant community behind it.

STEP1 Start by visiting the Code::Blocks download site, at When you've located the File, click on the
STEP 3
www.codeblocks.org/downloads. From there, click -J
SourceForge.net link at the end oF the line and a
on the 'Download the binary releases' link to be taken to the latest download notiFication window appears; click on Save File to start
downloadable version For Windows. the download and save the executable to your PC. Locate the
downloaded CoderBlocks installer and double-click to start. Follow
the on-screen instructions to begin the installation.

Q? Code::Blocks Installation - □ X

Welcome to CodeBlocks Setup

Setup will guide you through the installation of CodeBlocks.

It is recommended that you dose all other applications


before starting Setup. This will make it possible to update
relevant system files without having to reboot your
computer.

Click Next to continue.

STEP 2 You can see that there are several Windows versions STEP 4 Once you've agreed to the licencing terms, there is a
available. The one you want to download has choice oF installation options available. You can opt
'mingw-setup.exe' at the end oF the current version number. At Fora smaller install, missing out on some oF the components but we
the time oF writing this is: codeblocks-17.12mingw-setup.exe. The would recommend you opt For the Full option as deFault.
diFFerence is that the mingw-setup version includes a C++ compiler
Code::Blocks Installation
and debugger From TDM-GCC (a compiler suite).
Choose Components
Choose which features of CodeBlocks you want to install.

File
codeblocks 17 12 sctup.oxo 30 Dec Check the components you want to install and uncheck the components you don't want to
install. Click Next to continue.
codeblocks 1712 setup nonadmin.exe 30 Dec

codeblocks-17.12-nosetupzip 30 Dec
Select the type of install: Full: All plugins, all tools, just everything
codeblock3-17 12mingw-setup exe 30 Dec
Or, select the optional ]-0 Default install a
r.orieblnr.ks-1 / 12mmgw-nosfttup zip 30 Dec
components you wish to
E J 0 Contrib Plugins
r.urtehtoeks-1 / 12mmgw_tortr»n-SAliip exe 30 Dec install:
0C::BCBP2Make
NOTE The cudvHo<;ks-17 12-svlup.exe file includes Code .Blocks with all plugins. The codeblocks-17.12-svtUfMiwiadrnin.exe file is provided foi conwn 0C::BCCTest
NOTE Tho codoblocks-17 12mingw-sotup.exe file includes aMitionallv the GCC/G++ compiler and GDB debugger from TDM GCC (version 5.1.0, 32 bit. M C::B Share Config
(TDM-GCC) -0 C::B Launcher y
NOTE. The cudeblucks-17.12(iiiingw)-nosetup.zip files aie piovided foi convenience to useis that aie alleigic against instaNeis. Howevei, it will not allow
Description
If unsure, please use codeblocks-17.12mingw-setup.exe! Space required: 253.4 MB Position your mouse over a component to see its

Python & C++ Coding


How to Set Up C++ in Windows

Next choose an install location for the Code::Blocks Before you start using CodecBlocks it's worth
STEP 5 STEP 8
files. It's your choice, but the default will generally
A -J
explaining exactly why you need the added
suffice, unless of course you have any special requirements. When compiler. First, a compiler is a separate program that reads
you click Next, the install begins; when it’s finished a notification through your C++ code and checks it against the latest acceptable
pops up asking you if you want to start Code::Blocks now, so click Yes. programming standards; this is why you need the most recently
available compiler. This is currently C++17, with C++20 underway.
Please wait while CodeBlocks is being installed.

Create shortcut: C:VJsers\david\AppDatafoamingV*1icrosoft\Windows\Start MenuV’rograms^

& then merge

2011 2012 2013 2014 2015 2016 2017 2018 2019

TS bars start and end


where work on detailed
specification wording
starts ('adopt initial
working draff) and ends
("send to publication')
Future starts/ends are
shaded to indicate that
dates, and TS branches
are approximate and
subject to change

The first time CodecBlocks loads it runs an STEP 9 Essentially, computers work and understand only
STEP 6
auto-detect forany C++ compilers you may already
A binary, ones and zeros, or Machine Language.
have installed on you system. If you don't have any, click on the Programming in binary isn't effective for human beings. For
first detected option, GNU GCC Compiler, and click the Default example, to output the words "Hello World!" to the screen in C++
button to set it as the system's C++ compiler. Click OK when you're would appear in binary as:
ready to continue.
01100011 01101111 01110101 01110100 00100000
Compilers auto-detection □ X 00111100 00111100 00100000 00100010 01001000
01100101 01101100 01101100 01101111 00100000
Note: After auto-detection, at least one compiler's master path is still empty and therefore invalid.
Inspect the list below and change the compiler's master path later in the compiler options. 01010111 01101111 01110010 01101100 01100100
Select you favourite default compiler here:
00100001 00100010 00111011
Compiler

GNU GCC Compiler

01100011 01101111 01110101 01110100 00100000 00111100


00111100 00100000 00100010 01001000 01100101 01101100
01101100 01101111 00100000 01010111 01101111 01110010
01101100 01100100 00100001 00100010 00111011

Select

STEP 7 When the program starts another message appears, The compiler therefore takes whatyou've
STEP 10
informing you that Code::Blocks is currently not the entered as C++ code and translates that to
default application for C++ files. You a couple of options: to leave Machine Language. To execute C++ code the IDE 'builds' the code,
everything as it is or allow Code::Blocks to associate all C++ file checking for errors, then pass it through the compiler to check
types. Again, we would recommend you opt for the last choice to standardisation and convert it to ones and zeros for the computer
associate Code::Blocks with every supported file type. to act upon. It’s rather clever stuff, when you stop to think about it.

www.pclpublications.com
Say Hello to C++

How to Set Up
C++ on a Mac
To begin C++ coding on a Mac you first need to install Apple's Xcode. This is a free, full
featured IDE that's designed to create native Apple apps. However, you can also use it
to create C++ code relatively easily.

XCODE
Apple's Xcode is primarily designed For users to develop apps For macOS, iOS, tvOS and watchOS applications in SwiFt or
Objective-C but you can use it For C++ too.

STEP1 Start by opening the App Store on your Mac, Apple When you're ready, click on the Get button which
STEP 3
Menu > App Store. In the Search box enter 'Xcode' then turnsinto Install App. Enteryour Apple ID
and press Return. There are many suggestions filling the App Store and Xcode begins to download and install. It may take some time
window but it’s the first option, Xcode, that you need to click on. depending on the speed of your Internet connection.

STEP 2 Take a moment to browse through the app's STEP 4 When the installation is complete, click on the
information, including the compatibility, to ensure Open button to launch Xcode. Click Agree to the
you have the correct version of macOS. Xcode requires macOS licence terms and enteryour password to allow Xcode to make
10.12.6 or later to install and work. changes to the system. When that is done, Xcode begins to install
additional components.

Python & C++ Coding


How to Set Up C++ on a Mac

With everything now installed, including the The next step asks where to create a Git Repository
STEP 5 STEP 8
A additional components, Xcode launches, displaying -J for all your future code. Choose a location on your
the version number along with three choicesand any recent projects Mac, or a network location, and dick the Create button. When
that you've worked on; with a fresh install though, this is blank. you've done alt that, you can start to code. The left-hand pane
details the files used in the C++ program you're coding. Click on the
main.cpp file in the list.

Start by clicking on Create New Xcode Project; this STEP 9 You can see that Xcode has automatically
STEP 6
A opens a template window to choose which platform completed a basic Hello World program for you.
you're developing code for. Click the macOS tab, then click the While it may not make much sense at present, you will discover
Command Line Tool option. Click Next to continue. more as you progress, the content is just Xcode utilising what's
available on the Mac.

|L JU ■
STEP 7 Fill in the various fields but ensure that the When you want to run the code, click on Product >
STEP 10
Language option at the bottom is set to C++; simply -J
Run. You may be asked to enable Developer Mode
choose it from the drop-down list. When you've filled in the fields, on the Mac; this is to authorise Xcode to perform functions without
and made sure that C++ is the chosen language, click on the Next needing your password every session. When the program executes,
button to continue. the output is displayed at the bottom of the Xcode window.

www.pclpublications.com
Say Hello to C++

How to Set Up
C++ in Linux
Linux is a great C++ coding environment. Most Linux distros already have the essential
components preinstalled, such as a compilerand the text editors are excellent for
entering code into, including colour coding; and there's tons of extra software available
to help you out.

LINUX++
If you're not familiar with Linux, then we recommend taking a look at one of our Linux titles from the BDM Publications range.
If you have a Raspberry Pi, the commands used below work just fine and for this example we're using Linux Mint.

The first step is to ensure Linux is ready for your C++ Amazingly, that's it. Everything is already for you
STEP1 STEP 3
code, so check the system and software are up to to start coding. Here's how to get your first C++
date. Open a Terminal and enter: sudo apt-get update && sudo apt- program up and running. In Linux Mint the main text editor is Xed,
get upgrade. Then press Return and enter your password. These which you can launch by clicking on the Menu and typing Xed into
commands update the entire system and any installed software. the search bar. Click on the Text Editor button in the right-hand pane
to open it.
v david@mint-mate -
File Edit View Search Terminal Help
ldavid@mint-mate - s sudo apt-get update && sudo apt-get upgrade
[sudo] password for david: |

STEP 2 Most Linux distros come preinstalled with all STEP 4 In Xed, or any other text editor you may be using,
the necessary components to start coding in enter the lines of code that make up your C++ Hello
C++; however, it's always worth checking to see if everything World program. It’s a little different to what the Mac produced:
is present. Still within the Terminal, enter: sudo apt-get
#include <iostream>
install build-essential and press Return. If you have the right
components nothing is installed; if you're missing some then they int mainO
are installed by the command. {
//My first C++ program
std::cout « “Hello World!\n”;
}

Python & C++ Coding


Q How to Set: Up C++ in Linux

When you've entered your code, click File > Save As Before you can execute the C++ file you need to
STEP 5 STEP 8
and choose a folder in which to save your program.
A compile it. In Linux it's common to use g++, an open
Name the file as helloworld.cpp (it can be any name as long as it has source C++ compiler; as you're now in the same folder as the C++
.cpp as the extension). Click Save to continue. file, enter: g++ helloworld.cpp in the Terminal and press Return.

The first thing to notice is that Xed has STEP 9 It takes a short time while the code is compiled by
STEP 6
A automatically recognised this as a C++ file, since the g++ but providing there are no mistakes or errors in
file extension is now set to .cpp. The colour coding is present in the the code you are returned to the command prompt. The compiling
code and if you open up the file manageryou can also see that file's of the code has created a new file. If you enter: Is into the Terminal
icon has C++ stamped on it. you can see that alongside your C++ file is a.out.

STEP 7 With your code now saved, drop into the Terminal The a.out file is the compiled C++ code. To run
STEP 10
again. You need to navigate to the location of -J the code enter: ./a.out and press Return. The
the C++ file you've just saved. Our example is in the Documents words 'Hello World!' appear on the screen. However, a.out isn't
folder, so we can navigate to it by entering: cd Documents. very friendly. To name it something else post-compiling, you can
Remember, the Linux Terminal is case sensitive, so any capitals recompile with: g++ helloworld.cpp -o helloworld. This creates an
must be entered correctly. output file called helloworld which can be run with: ./helloworld.

david@mint-mate -/Document
File Edit View Search Terminal Help
davidgniint-mate - s cd Documents
david@mint-mate '/Documents S |

www.pclpublications.com
Say Hello to C++

Other C++ IDEs to Install


If you want to try a different approach to working with your C++ code, then there are
plenty of options available to you. Windows is the most prolific platform for C++ IDEs
but there are plenty for Mac and Linux users too.

DEVELOPING C++
Here are ten great C++ IDEs that are worth looking into. You can install one or all of them if you like, but find the one that
works best for you.

Eclipse is a hugely popular C++ IDE that offers CodeLite is a free and open source IDE that's
ECLIPSE CODELITE
the programmer a wealth of features. It has a regularly updated and available for Windows,
great, clean interface, is easy to use and available for Windows, Linux and macOS. It's lightweight, uncomplicated and extremely
Linux and Mac. Head over to www.eclipse.org/downloads/ to powerful. You can find out more information as well as how to
download the latest version. If you're stuck, click the Need Help link download and install it at www.codelite.org/.
for more information.

£ C/C++ - Hello Wurld C++ PiojcUAic/Hello World C++ Projeit.cpp • Edipxe


File Edit Source Refactor Navigate Search Project Run Window Help

i rj > a « a I a nt+o+a+«+:*+»+:» + 0’*’:»®«*’ HIv11


9. ’ v> ’ * O’
i. E Project Explorer £3 O
_________________ 'e | v v

kJ al
kJ Hello World C • • Project
jjjf Binaries
£j; Includes
£5 src
Lcl Hello World C++ Project.cpp
fe. Debug

«s, coi a. ra iwu, ■»/<• o bw o+»u<t oej. o+«ut

GNAT The GNAT Programming Studio (GPS) is a powerful Another popular choice is NetBeans. This
NETBEANS
and intuitive IDE that supports testing, debugging is another excellent IDE that's packed with
and code analysis. The Community Edition is free, whereas the features and a pleasure to use. NetBeans IDE includes project based
Pro version costs; however, the Community Edition is available for templates for C++ that give you the ability to build applications with
Windows, Mac, Linux and even the Raspberry Pi. You can find it at dynamic and static libraries. Find out more at www.netbeans.org/
www.adacore.com/down load. features/cpp/index.html.

Python & C++ Coding


r Other C++ IDEs to Install

Microsoft's Visual Studio is a ANJUTA The Anjuta DevStudio is a Linux-only IDE that
VISUAL STUDIO
a mammoth C++ IDE that allows you features some of the more advanced features you
to create applications for Windows, Android, iOS and the web. The would normally find in a paid software development studio. There's
Community version is free to download and install but the other a GUI designer, source editor, app wizard, interactive debugger and
versions allow a free trial period. Go to www.visualstudio.com/ to much more. Go to www.anjuta.org/ for more information.
see what it can do foryou.
[il* Edit View Protect Bmld Bun Debug Documents Help

- Messages
Build 35: Debug Ql . Build 54: Debug Build 53: Debug
Entering: /bomeztorrest/tigure/Debug
makefl] Cntenng directory ’ Aiome/forrest/figureiDebug'

This cross-platform IDE is designed to MONODEVELOP This excellent IDE allows developers
QT CREATOR
create C++ applications for desktop and a
to write C++ code for desktop and
mobile environments. It comes with a code editor a nd integrated web applications across all the major platforms. There's an advanced
tools for testing and debugging, as well as deploying to you chosen text editor, integrated debugger and a configurable workbench to
platform. It's not free but there is a trial period on offer before help you create your code. It's available for Windows, Mac and Linux
requiring purchasing: www.qt.io/qt-features-libraries-apis-tools- and is free to download and use: www.monodevelop.com/.
and-ide/.
► Debug I Maed Pb " ) Defeutt 0 MmmOwu?________________________________ Q

DEV C++ Bloodshed Dev C++, despite its colourful name, Ultimate++ is a cross-platform C++ IDE that boats a rapid
a is an older IDE that is for Windows systems only. development of code through the smart and aggressive
However, many users praise its clean interface and uncomplicated use of C++. For the novice, it’s a beast of an IDE but behind its
way of coding and compiling. Although there's not been much complexity is a beauty that would make a developer’s knees go
updating for some time, it’s certainly one to consider if you want wobbly. Find out moreatwww.ultimatepp.org/index.html.
something different: www.bloodshed.net/devcpp.html.

www.pclpublications.com
Index

C++ z
Fundamentals

& C++ Coding


Q C++ Fundamentals

Within this section you can begin to


understand the structure oF C++ code
and how to compile and execute that
code. These are the Fundamentals oF C++,
which teach you the basics such as using
comments, variables, data types, strings
and how to use C++ mathematics.

These are the building blocks oF a C++


program. With them, you can Form your
own code, produce an output to the
screen and store and retrieve data.

98 Your First C++Program


100 Structure of a C++Program
102 Compile and Execute
104 Using Comments
106 Variables
108 Data Types
110 Strings
112 C++Maths

www.pclpublications.com
C++ Fundamentals

Your First C++ Program


You may have followed the Mac and Linux examples previously but you're going to be
working exclusively in Windows and Code::Blocks from here on. Let's begin by writing
your first C++ program and taking the first small step into a larger coding world.

HELLO, WORLD!
It's traditional in programming for the first code to be entered to output the words 'Hello, World!' to the screen. Interestingly,
this dates back to 1968 using a language called BCPL.

As mentioned, we're using Windows 10 and the At the moment it doesn't look like much, and
STEP1 STEP 3
________ J latest version of CodecBlocks for the rest of the C++ A it makes even less sense, but we’ll get to that
code in this book. Begin by launching Code::Blocks. When open, click in due course. Now click on File >Save File As. Create or find a
on File > New > Empty File or press Ctrl+Shift+N on the keyboard. suitable location on your hard drive and in the File Name box, call
it helloworld.cpp. Click the Save as type box and select C/C++ files.
Click the Save button.

STEP 2 Now you ca n see a blank screen, with the tab STEP 4 You can see that Code::Blocks has now changed
labelled *Untitled1, and the number one in the top the colour coding, recognising that the file is now
left of the main CodecBlocks window. Begin by clicking in the main C++ code. This means that code can be auto-selected from the
window, so the cursor is next to the number one, and entering: Code::Blocks repository. Delete the #include <iostream> line and
re-enter it. You can see the auto-select boxes appearing.
#include <iostream>

Python & C++ Coding


Your First C++ Program

Auto-selection of commands is extremely handy and Note again the colour coding change. Press Return at
STEP 5 STEP 8
cuts out potential mistyping. Press Return to get to ________ J the end of the previous step's line, and then enter:
line 3, then enter:
std::cout « “Hello, world!\n”;
int malnO

On the next line below int main(), enter a curly bracket: STEP 9 Just as before, Code::Blocks auto-completes the
STEP 6
________ J code you're entering, including placing a closing
speech mark as soon as you enter the first. Don't forget the
This can be done by pressing Shift and the key to the right of P on an semicolon at the end of the line; this is one of the most important
English UK keyboard layout. elements to a C++ program and we'll tell you why in the next
section. For now, move the cursor down to the closing curly bracket
and press Return.

STEP 7 Notice that Code::Blocks has automatically created That's all you need to do for the moment. It may
STEP 10
a corresponding closing curly bracket a couple of -J not look terribly amazing but C++ is best absorbed
lines below, linking the pair, as well as a slight indent. This is due to in small chunks. Don't execute the code at the moment as you need
the structure of C++ and it's where the meat of the code is entered. to look at how a C++ program is structured first; then you can build
Now enter: and run the code. For now, click on Save, the single floppy disc icon.

//My first C++ program

www.pclpublications.com
C++ Fundamentals

Structure of a
C++ Program
C++ has a very defined structure and way of doing things. Miss something out, even
as small as a semicolon, and your entire program will fail to be compiled and executed.
Many a professional programmer has fallen foul of sloppy structure.

INCLUDE <C++ STRUCTURE>


Learning the basics of programming, you begin to understand the structure of a program. The commands may be different
from one language to the next, but you will start to see how the code works.

#INCLUDE
The structure of a C++ program
C++ was invented by Danish is quite precise. Every C++ code
student Bjarne Stroustrup in begins with a directive: #include
1979, as a part of his Ph.D. <>. The directive instructs the
thesis. Initially C++ was called C pre-processor to include a
with Classes, which added section of the standard C++
features to the already popular code. For example: #include
C programming language, <iostream> includes the
while making it a more iostream header to support
user-friendly environment input/output operations.
through a new structure.

Bjarne Stroustrup, inventor


of C++.
INT MAIN() Start here x j *helloworld.cpp X
int main() initiates the
declaration of a function, which
1 ^include <iostream>
is a group of code statements 2
under the name 'main'. All 3 int main()
C++ code begins at the main
function, regardless of where it
4
actually lies within the code. 5
6 I

BRACES 1 #include <iost re ano­


The open brace (curly brackets) is something 2
that you may not have come across before, 3 int main()
especially if you're used to Python. The
4 B{
open brace indicates the beginning of the
main function and contains all the code that 5
belongs to that function. 6

Python & C++ Coding


(^Structure of a C++ Program

COMMENTS «
Lines that begin with a double slash are comments. This means they The two chevrons used here are insertion operators. This means
won't be executed in the code and are ignored by the compiler. that whatever follows the chevrons is to be inserted into the
Comments are designed to help you, oranother programmer std::cout statement. In this case they're the words ’Hello, world',
looking atyour code, explain what's going on. There are two types which are to be displayed on the screen when you compile and
of comment: /* covers multiple line comments,// a single line. Lines execute the code.
that begin with a double slash are comments. This means they won't
be executed in the code and
are ignored by the compiler. std

Comments are designed public ostream cout


(variable)
to help you, or another
programmer looking at Open declaration

your code, explain what's Close Top

going on. There are two


types of comment: /* covers
multiple line comments, //a
single line.

STD OUTPUTS
While std stands forsomething quite different, in C++ it means Leading on, the "Hello, world!" part is what we want to appear on
Standard. It's part of the Standard Namespace in C++, which covers the screen when the code is executed. You can enter whatever you
a number of different statements and commands. You can leave the like, as long as it’s inside the quotation marks. The brackets aren't
std:: part out of the code but it must be declared at the start with: needed but some compilers insist on them. The\n part indicates a
using namespace std; not both. For example: new line is to be inserted.

#include <iostream>
using namespace std;

cout << "Hello, world!\n"

COUT ; AND}
In this example we're using cout, which is a part of the Standard Finally you can see that lines within a function code block (except
Namespace, hence why it's there, as you're asking C++ to use it from comments) end with a semicolon. This marks the end of the
that particular namespace. Cout means Character OUTput, which statement and all statements in C++ must have one at the end or
displays, or prints, something to the screen. If we leave std:: out we the compiler fails to build the code. The very last line has the closing
have to declare it at the start of the code, as mentioned previously. brace to indicate the end of the main function.

Start here X | *helbworki.cpp x[

www.pctpubtications.com
C++ Fundamentals

Compile and Execute


You've created your first C++ program and you now understand the basics behind the
structure of one. Let's actually get things moving and compile and execute, or run if
you prefer, the program and see how it looks.

GREETINGS FROM C++


Compiling and executing C++ code From Code::Blocks is extraordinarily easy; just a matter oF clicking an icon and seeing the
result. Here's how it's done.

STEP1 Open Code::Blocks, if you haven't already, and Start by clicking on the Build icon, the yellow cog.
STEP 3
load up the previously saved Hello World code you A At this point, your code has now been run through
created. Ensure that there are no visible errors, such as missing the Code::Blocks compiler a nd checked for any errors. You can see
semicolons at the end of the stdccout line. the results of the Build by looking to the bottom window pane. Any
messages regarding the quality of the code are displayed here.

STEP 2 If your code is looking similar to the one in our STEP 4 Now click on the Run icon, the green play button.
a screenshot, then look to the menu bar along the top A command line box appears on your screen
of the screen. Under the Fortran entry in the topmost menu you can displaying the words: Hello, world!, followed by the time it's taken
see a group of icons: a yellow cog, green play button and a cog/play to execute the code, and asking you press a key to continue. Well
button together. These are Build, Run, Build and Run functions. done, you just compiled and executed your first C++ program.

*helk>worki.cpp

Python & C++ Coding


Compile and Execute

Pressing any key in the command line box closes it, Create a deliberate error in the code. Remove the
STEP 5 STEP 8
returning you to CodecBlocks. Let's alter the code
A semicolon from the cout line, so it reads:
slightly. Under the #include line, enter:
cout « “Hello, world I\n”
using namespace std;
Start here X | *tielloworld.cpp X
Then, delete the std:: part of the Cout line; like so:
1 tinclude <iostream>
cout « “Hello, world\n”;
2 using namespace std;
3
4 int main()
5 El I
6
7 cout « "Hello, world!\n"
8
9
10
11
12

In order to apply the new changes to the code, you STEP 9 Now click the Build and Run icon again to apply the
STEP 6
need to re-compile, build, and run it again. This time,
A changes to the code. This time Code::Blocks refuses
however, you can simply click the Build/Run icon, the combined to execute the code, due to the error you put in. In the Log pane at
yellow cog and green play button. the bottom of the screen you are informed of the error, in this case:
Expected ';' before token, indicating the missing semicolon.

STEP 7 Just as we mentioned in the previous pages, you Replace the semicolon and under the cout line,
STEP 10
don't need to have stdccout if you already declare -J entera new line toyourcode:
using namespace std; at the beginning of the code. We could have
cout « “And greetings from C++!\n”;
easily clicked the Build/Run icon to begin with but it's worth going
through the available options. You can also see that by building and The\n simply adds a new line under the last line of outputted text.
running, the file has been saved. Build and Run the code, to display your handiwork.

helloworld.cpp - CodenBlocks 17.12


File Edit View Search Project Build Debug Fortran wxSmith Tools Tools* Plugins DoxyBlocks Settir

www.pclpublications.com
C++ Fundamentals

Using Comments
While comments may seem like a minor element to the many lines of code that
combine to make a game, application or even an entire operating system, in actual fact
they're probably one of the most important factors.

THE IMPORTANCE OF COMMENTING


Comments inside code are basically human readable descriptions that's going to be obvious to the reader. However, if x equalling zero
that detail what the code is doing at that particular point. They don’t is something that drastically changes the program for the user, such
sound especially important but code without comments is one of as, they've run out of lives, then it certainly needs to commented on.
the many frustrating areas of programming, regardless of whether
you're a professional or just starting out. Even if the code is your own, you should write comments as if you
were going to publicly share it with others. This way you can return
In short, all code should be commented in such a manner as to to that code and always understand what it was you did or where it
effectively describe the purpose of a line, section, or individual was you went wrong or what worked brilliantly.
elements. You should get in to the habit of commenting as much as
possible, by imagining that someone who doesn't know anything Comments are good practise and once you understand how to add a
about programming can pick up your code and understand what it’s comment where needed, you soon do it as if it’s second nature.
going to do simply by reading your comments.
DEFB 26h,30h,32h,26h,30h,32h,0, 0,32h,72h,73h,32h,72h, 73h,32h
In a professional environment, comments are vital to the success DEFB 60h,61h,32h,4Ch,4Dh,32h,4Ch,99h,32h,4Ch,4Dh,32h,4Ch,4Dh
DEFB 32h,4Ch,99h,32h,5Bh,5Ch,32h,56h,57h,32h,33h,OCDh,32h,33h
of the code and ultimately, the company. In an organisation, many DEFB 34h,32h,33h,34h,32h,33h,OCDh,32h,40h,41h,32h,66h,67h,64h
DEFB 66h,67h,32h,72h,73h,64h,4Ch,4Dh,32h,56h,57h,32h,80h,OCBh
programmers work in teams alongside engineers, other developers, DEFB 19h,80h,0,19h,80h,81h,32h,80h,OCBh,OFFh
T858C:
hardware analysts and so on. If you're a part of the team that's DEFB 80h,72h,66h,60h,56h,66h,56h,56h,51h,60h,51h,51h,56h,66h
DEFB 56h,56h,80h,72h,66h,60h,56h,66h,56h,56h,51h,60h,51h,51h
writing a bespoke piece of software for the company, then your DEFB 56h,56h,56h,56h,80h,72h,66h,60h,56h,66h,56h,56h,51h,60h
DEFB 51h,51h,56h,66h,56h,56h,80h,72h,66h,60h,56h,66h,56h,40h
comments help save a lot of time should something go wrong, and DEFB 56h,66h,80h,66h,56h,56h,56h,56h
another team member has to pick up and follow the trail to pinpoint ; Game restart point
the issue.
START: XOR A
LD (SHEET),A
LD (KEMP),A
Place yourself in the shoes of someone whose job it is to find out LD (DEMO),A
LD (B845B),A
what's wrong with a program. The program LD (B8458),A
LD A,2 ;Initial lives count
has in excess of 800,000 lines of code, LD (NOMEN),A
LD HL,T845C
spread across several different SET 0, (HL)
LD HL,SCREEN
modules. You can soon appreciate LD DE,SCREEN+1
the need fora little help from the LD
LD
BC,17FFh
(HL),0
;Clear screen image

original programmers in the form of a LDIR


LD HL,OAOOOh ;Title screen bitmap
good comment. LD DE,SCREEN
LD BC,4096
LDIR
LD HL,SCREEN + 800h + 1*32 + 29
The best comments are always concise LD DE,MANDAT+64
LD C,0
and link the code logically, detailing what CALL DRWFIX
LD HL,0FC00h ;Attributes for the last room
happens when the LD DE,ATTR ;(top third)
LD BC,256
program hits this LDIR
line or section. LD HL,09E00h ;Attributes for title screen
LD BC,512 ;(bottom two-thirds)
You don't need LDIR
LD BC,31
to comment DI
XOR A
on every line. R8621:
IN E, (C)
Something along OR E
DJNZ R8621 ;$-03
the lines of: if AND 2 Oh
JR NZ,R862F ;$+07
x==0 doesn't LD A, 1
require you to R862F:
LD (KEMP),A

comment that if x LD IY,T846E


CALL C92DC
equals zero then JP NZ,L8684
XOR A
do something; LD (EUGHGT),A

Python & C++ Coding


Using Comments

C++ COMMENTS
Commenting in C++ involves using a double Forward slash or a Forward slash and an asterisk, You've already seen some
brieF examples but this is how they work.

STEP1 Using the Hello World code as an example, you can STEP 4 Be careFul when commenting, especially with block
a easily comment on diFFerent sections oF the code comments. It's very easy to Forget to add the closing
using the double Forward slash: asterisk and Forward slash and thus negate any code that Falls inside
the comment block.
//My first C++ program
cout « “Hello, world!\n”;

i ♦include <iostream>
2 using namespace std;
3
4 int main()
5 B{
6
7 cout « "Hello, world!\n";
8
9
10
11
12

However, you can also add comments to the end Obviously iF you try and build and execute the
STEP 2 STEP 5
oF a line oF code, to describe in a better way what's code it errors out, complaining oFa missing curly
going on: bracketto Finish oFF the block oF code. IF you've made the
error a Few times, then it can be time consuming to go back and
cout « “Hello, world!\n”; //This line outputs the
rectiFy. ThankFully, the colour coding in CodecBlocks helps identiFy
words ‘Hello, world!’. The \n denotes a new line.
comments From code.
Note, you don’t have to put a semicolon at the end oFa comment.
This is because it's a line in the code that's ignored by the compiler.

Start here *helloworki.cpp x[


{include <iostream>
using namespace std;

int main()
□<

cout « "Hello, world!\n";

You can comment out several lines by using the IFyouTe using block comments, it’s good practise
STEP 3 STEP 6
forward slash and asterisk: -J
in C++ to add an asterisk to each new line oF the
comment block. This also helps you to remember to close the
/* This comment can
comment block oFF beFore continuing with the code:
cover several lines
without the need to add more slashes */ /* This comment can
* cover several lines
Just remember to finish the block comment with the opposite
* without the need to add more slashes */
asterisk and forward slash.

4 int main()
5 Br Bl
6 cout « "Hello, world!\n";
7
8
9
cout « "Hello, world!\n";
cout « "And greetings from C++";
8
9
10
I cout « "And greetings from C++\n”;

11 * cover several lines


10 /* This comment can 12
11 cover several lines 13
12 without the need to add more slashes 14
15 cout « "This line is now being ignored by the compiler!\n";
13 16
14 17
15 18

www.pcLpublications.com
C++ Fundamentals

Variables
Variables differ slightly when using C++ as opposed to Python. In Python, you can
simply state that 'a' equals 10 and a variable is assigned. However, in C++ a variable has
to be declared with its type before it can be used.

THE DECLARATION OF VARIABLES


You can declare a C++ variable by using statements within the code. There are several distinct types of variables you can
declare. Here's how it works.

Open up a new, blank C++ file and enter the usual You can build and run the code but it won’t do
STEP1 STEP 3
________ J code headers: ________ J much, other than store the values 10 and 5 to the
integers a and b. To output the contents of the variables, add:
#include <iostream>
using namespace std; cout « a;
cout « ”\n”;
int mainO
cout « b;
{
The cout« "\n"; part
}
simply places a new line
between the output of
Start here X Variables.cpp X
Wand 5.
1 ^include <iostream>
2 using namespace std;|
3
4 int main()
5
6
7
8 }
9

STEP 2 Start simple by creating two variables, a and b, with Naturally you can declare a new variable, call it
STEP 4
a one having a value of 10 and the other 5. You can ________ J result and output some simple arithmetic:
use the data type int to declare these variables. Within the curly
int result;
brackets, enter:
result = a + b;
int a;
Start here X *Variables.cpp X | cout « result;
int b;
^include <iostream> Insert the above into the code as per the screenshot.
a = 10; 2 using namespace std;
b = 5; 3
4 int
5
6
7 int a;
8
9
10 a = 10;
b = 5;
12

14

Python & C++ Coding


Variables

You can assign a value to a variable as soon as you The previous step creates the variable StartLives,
STEP 5 STEP 8
A declare it. The code you've typed in could look like which is a global variable. In a game, for example,
this, instead: a player’s lives go up or down depending on how well or how bad
they're doing. When the player restarts the game, the StartLives
int a = 10;
returns to its default state: 3. Here we've assigned 3 lives, then
int b = 5;
subtracted 1, leaving 2 lives left.
int result = a + b;

cout « result; ■ C:\Users\david\Documents\C++Waria bles.exe

2
Process returned 0 (0x0) execution time : 0.040 s
Press any key to continue.

15
Process returned 0 (0x0) execution time : 0.040 s
Press any key to continue.
STEP 9 The modern C++ compiler is far more intelligent
a than most programmers give it credit. While there
are numerous data types you can declare for variables, you can in
fact use the auto feature:

#include <iostream>
using namespace std;
auto pi = 3.141593;

Specific to C++, you can also use the following int main()
STEP 6
A to assign values to a variable as soon as you
{
declare them:
double area, radius = 1.5;
int a (10);
area = pi * radius * radius;
int b (5);
cout « area;
Then, from the C++ 2011 standard, using curly brackets:
}
int result {a+b};

Jsers\david\Documents\C++\Variables.exe

rocess returned 0 (0x0) execution time : 0.038 s


ress any key to continue.

STEP 7 You can create global variables, which are variables


that are declared outside any function and used in
A couple of new elements here: first, auto won't
any function within the entire code. What you've used so far are STEP 10
work unless you go to Settings > Compiler and
local variables: variables used inside the function. For example:
tick the box labelled 'Have C++ follow the C++11 ISO C++ Language
#include <iostream> Standard [-std=c++1 ]'. Then, the new data type, double, which
using namespace std; means double-precision floating point value. Enable C++11, then
int StartLives = 3; build and run the code. The result should be 7.06858.

int main ()

{
startLives = StartLives - 1;
cout « StartLives;
}

www.pclpublications.com
C++ Fundamentals

Data Types
Variables, as we've seen, store information that the programmer can then later call up,
and manipulate if required. Variables are simply reserved memory locations that store
the values the programmer assigns, depending on the data type used.

THE VALUE OF DATA


There are many different data types available for the programmer incredibly accurate numbers but those numbers are only accurate
in C++, such as an integer, floating point, Boolean, character and so up to the fifteenth decimal place. There's also the problem when
on. It's widely accepted that there are seven basic data types, often displaying such numbers in C++ using the cout function, in that cout
called Primitive Built-in Types; however, you can create your own by default only outputs the first five decimal places. You can combat
data types should the need ever arise within your code. that by adding a cout.precision () function and adding a value inside
the brackets, but even then you’re still limited by the accuracy of the
The seven basic data types are:
double data type. For example, try this code:

#include <iostream>
TYPE COMMAND using namespace std;
Integer double PI = 3.141592653589793238463;

int mainO
Floating Point fiBBW {
cout « Pi;
Character }

Boolean imai Start here X | DataTypes.cpp X |

1 ^include <iostream>
Double Floating Point ws>iai3 2 using namespace std;
3 | double PI 3.141592653589793238463;
Wide Character 4
5 int main()
No Value 6
PI;
8
These basic types can also be extended using the following modifiers:
9
Long, Short, Signed and Unsigned. Basically this means the modifiers
10
can expand the minimum and maximum range values for each data
type. For example, the intdata type has a default value range of
-2147483648 to 2147483647, a fair value, you would agree. ■ C:\Users\d a vid\Documents\C++\DataTypes.exe

Now, if you were to use one of the modifiers, the range alters: 3.14159
Process returned 0 (0x0) execution time : 0.054 s
Unsigned int = 0 to 4294967295 Press any key to continue.
Signed int = -2147483648 to 2147483647
Short int = -32768 to 32767
Unsigned Short int = 0 to 65,535 Build and run the code and as you can see the output is only
Signed Short int = -32768 to 32767 3.14159, representing cout’s limitations in this example.
Long int = -2147483647 to 2147483647
You can alter the code including the aforementioned cout.precision
Signed Long int = -2147483647 to 2147483647
function, for greater accuracy. Take precision all the way up to 22
Unsigned Long int = 0 to 4294967295
decimal places, with the following code:
Naturally you can getaway with using the basic type without the
#include <iostream>
modifier, as there's plenty of range provided with each data type.
using namespace std;
However, it's considered good C++ programming practise to use the
double PI = 3.141592653589793238463;
modifiers when possible.
int mainO
There are issues when using the modifiers though. Double
{
represents a double-floating point value, which you can use for

Python & C++ Coding


Data Types

cout.precision(22); This is mainly due to the conversion from binary in the compiler
cout « PI; and that the IEEE 754 double precision standard occupies 64-bits
of data, of which 52-bitsare dedicated to the significant (the
significant digits in a floating-point number) and roughly 3.5-bits
are taken holding the values 0 to 9. If you divide 53 by 3.5, then you
arrive at 15.142857 recurring, which is 15-digits of precision.

To be honest, if you're creating code that needs to be accurate to


more than fifteen decimal places, then you wouldn't be using C++,
you would use some scientific specific language with C++ as the
connective tissue between the two languages.

You can create your own data types, using an alias-like system called
typedef. For example:

Il 1 C:\ll sers\d avi d\Oocu m ents\C +■+\Datatypes. exe

3.141592653589793115998
Process returned 0 (6x6) execution time : 0.847 s
Press any key to continue.

Again, build and run the code; as you can see from the command
line window, the number represented by the variable PI is different
to the numberyou've told C++ to use in the variable. The output
reads the value of PI as 3.141592653589793115998, with the
numbers going awry from the fifteenth decimal place.

Calculator — □ X
#include <iostream>
using namespace std;
= Scientific q typedef int metres;
int mainO
{
15.142857142857142857142857142857 metres distance;
distance = 15;
cout « “distance in metres is: “ « distance;

DEG HYP F-E

S3 C:\Users\david\Documents\C++\DataTypes.exe
M+ M- MS
distance in metres is: 15
Process returned 0 (0x0) execution time : 0.041 s
xz xy sin cos tan Press any key to continue.

V 10* log Exp Mod

T CE C <3

TI 7 8 9 x This code when executed creates a new int data type called metres.
Then, in the main code block, there's a new variable called distance,
n! 4 5 6 — which is an integer; so you're basically telling the compiler that
there's another name for int. We assigned the value 15 to distance

1 2 3 -f- and displayed the output: distance in metres is 15.

It might sound a little confusing to begin with but the more you use
C++ and create your own code, the easier it becomes.
( ) 0 » =

www.pcLpublications.com
C++ Fundamentals

Strings
Strings are objects that represent and hold sequences of characters. For example, you
could have a universal greeting in your code 'Welcome' and assign that as a string to be
called up wherever you like in the program.

STRING THEORY
There are different ways in which you can create a string of characters, which historically are all carried over from the original
C language, and are still supported by C++.

To create a string you use the char function. Open a Build and run the code, and 'Welcome' appears
STEP1 STEP 3
________ J new C++ file and begin with the usual header: Aon the screen. While this is perfectly fine, it's
not a string. A string is a class, which defines objects that can be
#include <iostream>
represented as a stream of characters and doesn't need to be
using namespace std;
terminated like an array. The code can therefore be represented as:
int main O
#include <iostream>
{ using namespace std;

int main O

char greet[] = “Welcome


cout « greet « “\n”;

Files ►

It’s easy to confuse a string with an array. Here's an STEP 4 In C++ there's also a string function, which works in
STEP 2
________ J array, which can be terminated with a null character: much the same way. Using the greeting code again,
you can enter:
#include <iostream>
using namespace std; #include <iostream>
using namespace std;
int main O
int main O
{
char greet[8] = {‘W’, ‘e’, ‘I’, ‘c’, ‘o’, ‘m’, {
‘ e ’, ‘\0’} ; string greet = “Welcome”;
cout « greet « “\n”; cout « greet « “\n”;

Python & C++ Coding


There are also many different operations thatyou Just as you might expect, you can mix in an integer
STEP 5 STEP 8
can apply with the string function. For instance, to
A and store something to do with the string. In this
get the length of a string you can use: example, we created int length, which stores the result of string.
size() and outputs it to the user:
#include <iostream>
using namespace std; #include <iostream>
using namespace std;
int main ()
int main ()
{
string greet = “Welcome”; {
cout « “The length of the string is: int length;
cout « greet.sizeQ « “\n”; string greetl = “Hello”;
string greet2 = world!”;
string greets = greetl + greet2;

length = greets. sizeQ;


cout « “The length of the combined strings
is: “ « length « “\n”;

STEP 9 Using the available operations that come with the


string function, you can manipulate the contentsofa
string. For example, to remove characters from a string you could use:
You can see that we used greet.size() to output the
STEP 6 #include <iostream>
length, the number of characters there are, of the
using namespace std;
contents of the string. Naturally, if you call your string something
other than greet, then you need to change the command to reflect int main ()
this. It's always stringname.operation. Build and run the code to see
{
the results.
string strg (“Here is a long sentence in a
■ Q\Users\david\Documents\C++\Stnngs.exe
string.”);
The length of the string is: 7
cout « strg « *\n’;

Process returned 0 (0x0) execution time : 0.044 s strg.erase (10,5);


Press any key to continue. cout « strg « *\n’;

strg.erase (strg.begin()+8);
cout « strg « *\n’;
You can of course add strings together, or rather
STEP 7 strg.erase (strg.begin()+9, strg.end()-9);
________ J combine them to form longer strings:
cout « strg « *\n’;
#include <iostream>
}
using namespace std;

int main ()
It's worth spending some time playing around with
{ STEP 10
the numbers, which are the character positions
string greetl = “Hello”;
in the string. Occasionally, it can be hit and miss whether you get it
string greet2 = world!”;
right, so practice makes perfect. Take a look at the screenshot to see
string greets = greetl + greet2;
the result of the code.
cout « greets « “\n”;
|11 C:\Users\david\Documents\C++\Strings,exe

Here is a long sentence in a string.


Start here X Strings.cpp X]
Here is a sentence in a string.
♦include <iostreara>
Here is sentence in a string.
using namespace std; Here is a string.
int main ()
Process returned 0 (0x0) execution time : 0.051 s
Press any key to continue.
string greetl = "Hello";
string greet2 = ", world!";
string greets = greetl + greet2;

cout « greets « "\n";

www.pclpublications.com
C++ Fundamentals

C++ Maths
Programming is mathematical in nature and as you might expect, there's plenty of
built-in scope for some quite intense maths. C++ has a lot to offer someone who's
implementing mathematical models into their code. It can be extremely complex or
relatively simple.

C++ = MC2
The basic mathematical symbols apply in C++ as they do in most other programming languages. However, by using the C++
Math Library, you can also calculate square roots, powers, trig and more.

STEP1 C++'s mathematical operations follow the Multiplication and division can be applied as such:
STEP 3
same patterns as those taught in school, in that ________ J
#include <iostream>
multiplication and division take precedence overaddition and
using namespace std;
subtraction. You can alter that though. For now, create a new file
and enter: int main O
{
#include <iostream>
float numbers = 100;
using namespace std;
numbers = numbers * 10; // This multiplies 100
int main ()
by 10
{
float numbers = 100; cout « numbers « “\n”;

numbers = numbers + 10; // This adds 10 to the numbers = numbers / 10; // And this divides
initial 100 1000 by 10

cout « numbers « “\n”; cout « numbers « “\n”;


numbers = numbers - 10; // This subtracts 10
from the new 110
| Start here jj&J Mathsxpp X [
cout « numbers « “\n”;
♦include <iostream>
using namespace std;

int main ()
B<
float numbers = 100;

numbers = numbers * 10;

cout « numbers « "\n";

numbers = numbers / 10;

cout « numbers « "\n";

STEP 2 While simple, it does get the old maths muscle


warmed up. Note that we used a float for the
numbers variable. While you can happily use an integer, if you STEP 4 Again, execute the simple code and see the results.
suddenly started to use decimals, you would need to change to a a While not particularly interesting, it’s a start into C++
float or a double, depending on the accuracy needed. Run the code maths. We used a float here, so you can playaround with the code
and see the results. and multiply by decimal places, as well as divide, add and subtract.

Si C:\Users\david\Documents\C++\Maths.exe E C:\Users\davi d\Documents\C++\Maths.exe

110 1000
100 100

Process returned 0 (0x0) execution time : 0.043 s Process returned 0 (0x0) execution time : 0.050 s
Press any key to continue. Press any key to continue.

Python & C++ Coding


C++Maths

The interesting maths content comes when you call Calculating powers of numbers can be done with:
STEP 5 STEP 8
upon the C++ Math Library. Within this header are
A
dozens of mathematical functions along with further operations. #include <iostream>
Everything from computing cosine to arc tangent with two #include <cmath>
parameters, to the value of PI. You can call the header with: using namespace std;

#include <iostream> int main ()


#include <cmath> {
using namespace std; float number = 12;

int main () cout « number « “ to the power of 2 is “


{ pow(number, 2) « “\n”;
cout « number « “ to the power of 3 is “
}
pow(number, 3) « “\n”;
cout « number « “ to the power of .08 is
« pow(number, 0.8) « “\n”;

Start by getting the square root of a number: STEP 9 Here we created a float called number with the
STEP 6
________ J value of 12, and the powfvariable, power) is where
the calculation happens. Of course, you can calculate powersand
#include <iostream>
square roots without using variables. For example, pow (12,2)
#include <cmath>
outputs the same value as the first cout line in the code.
using namespace std;
E CAUsers\david\Documents\C++\Maths.exe
int main ()
12 to the power of 2 is 144
{ 12 to the power of 3 is 1728
float number = 134; 12 to the power of .08 is 7.30037

cout « “The square root of “ « number « Process returned 0 (0x0) execution time : 0.049 s
Press any key to continue.
is: “ « sqrt(number) « “\n”;

STEP 10 The value of Pi is also stored in the cmath header


a library. It can be called up with the M_PI function.
Enter cout« M_PI; into the code and you get 3.14159; or you can
use it to calculate:

#include <iostream>
#include <cmath>
using namespace std;

int main ()
{
double area, radius = 1.5;
area = M_PI * radius * radius;
STEP 7 Here we created a new float called number and
a used the sqrt(number) function to display the cout « area « “\n”;
square root of 134, the value of the variable, number. Build and run
the code, and your answer reads 11.5758.

Bl C:\Users\david\Documents\C++\Maths.exe

The square root of 134 is: 11.5758

Process returned 0 (0x0) execution time : 0.046 s


Press any key to continue.

www.pcLpublications.com
Index

Output

Python & C++ Coding


C++ Input/Output

There's a satisfying feeling when you


program code that asks the user for
input, then uses that input to produce
something that the user can see. Even if
it's simply asking for someone's name,
and displaying a personal welcome
message, it's a big leap forward.

User interaction, character literals,


defining constants and file input and
output are all covered in the following
pages. All of which help you to understand
how a C++ program works better.

116 User Interaction


118 Character Literals
120 Defining Constants
122 File Input/Output

www.pclpublications.com
C++ Input/Output

User Interaction
There's nothing quite as satisfying as creating a program that responds to you. This
basic user interaction is one of the most taught aspects of any language and with it
youTe able to do much more than simply greet the user by name.

HELLO, DAVE
You have already used cout, the standard output stream, throughout our code. Now you're going to be using cin, the standard
input stream, to prompt a user response.

STEP1 Anything that you want the user to input into the The cin command works in the opposite way from
STEP 3
program needs to be stored somewhere in the the cout command. With the first cout line you're
A
system memory, so it can be retrieved and used. Therefore, any outputting 'What is your age' to the screen, as indicated with the
input must first be declared as a variable, so it's ready to be used by chevrons. Cin uses opposite facing chevrons, indicating an input. The
the user. Start by creating a blank C++ file with headers. input is put into the integer age and called up in the second cout
command. Build and run the code.

• C:\Users\david\Document$\C++\usennteraction.exe

<ihat is your age: 45

fou are 45 years old.

’rocess returned 0 (0x0) execution time : 4.870 s


’ress any key to continue.

If you're asking a question, you need to store the


STEP 4
input as a string; to ask the user their name, you
would use:

#include <iostream>
STEP 2 The data type of the variable must also match the using namespace std;
a type of input you want from the user. For example,
int main O
to ask a user their age, you would use an integer like this:
{
#include <iostream> string name;
using namespace std; cout « “what is your name: “;
cin » name;
int main O
{ cout « “\nHello, “ « name « “. I hope you’re
int age; well today?\n”;
cout « “what is your age:
cin » age;

cout «”\nYou are “ « age « “ years old.\n”;

Python & C++ Coding


User Interaction

The principal works the same as the previous code. While cin works well for most input tasks, it does
STEP 5 STEP 8
The user's input, their name, is stored in a string,
A have a limitation. Cin always considers spaces as a
because it contains multiple characters, and retrieved in the second terminator, so it's designed forjust single words not multiple words.
cout line. As long as the variable 'name' doesn't change, then you However, getline takes cin as the first argument and the variable as
can recall it wherever you like in your code the second:

Ml C:\Users\david\Documents\C-n-\userinteraction.exe #include <iostream>


what is your name: David
using namespace std;

I
Mello, David. I hope you're well today?
int main ()
Process returned 0 (0x0) execution time : 2.153 s
Press any key to continue. {
string mystr;
cout « “Enter a sentence: \n”;
You can chain input requests to the user but just
STEP 6 getline(cin, mystr);
make sure you have a valid variable to store the
input to begin with. Let's assume you want the user to enter two cout « “Your sentence is: “ « mystr.sizeQ «
whole numbers: “ characters long.\n”;

#include <iostream>
using namespace std;
int main ()
{
int numl, num2;

cout « “Enter two whole numbers: “;


cin » numl » num2;

cout « “you entered “ « numl « “ and “


num2 « “\n”; STEP 9 Build and execute the code, then enter a sentence
with spaces. When you're done the code reads the
}
number of characters. If you remove the getline line and replace it
with cin » mystr and try again, the result displays the number of
characters up to the first space.

I C:\Users\david\Documents\C++\userinteraction.exe

Enter a sentence:
BDM Publications Python and C++ for Beginners
Your sentence is: 45 characters long.

Process returned 0 (0x0) execution time : 27.054 s


Press any key to continue.

STEP 7 Likewise, inputted data can be manipulated once


you have it stored in a variable. For instance, ask the Getline is usually a command that new C++
STEP 10
user for two numbersand do some maths on them: programmers forget to include. The terminating
a
white space is annoying when you can't figure out why your code
#include <iostream>
isn't working. In short, it’s best to use getline(cin, variable) in future:
using namespace std;
#include <iostream>
int main ()
using namespace std;
{
float numl, num2; int main ()
{
cout « “Enter two numbers: \n”;
cin » numl » num2; string name;
cout « “Enter your full name: \n”;
cout « numl « “ + “ « num2 « “ is: “ «
getlinefcin, name);
numl + num2 « “\n”;
cout « “\nHello, “ « name « “\n”;

www.pclpublications.com
C++ Input/Output

Character Literals
In C++ a literal is an object or variable that once defined remains the same throughout
the code. However, a character literal is defined by a backslash, such as the \n you've
been using at the end of a cout statement to signify a new line.

ESCAPE SEQUENCE
When used in something like a cout statement, character literals are also called Escape Sequence Codes. They allow you to
insert a quote, an alert, new line and much more.

Create a new C++ file and enter the relevant headers: If you wanted to insert speech quotes inside a cout
STEP1 STEP 3
J statement, you would have to use a backslash as it
#include <iostream> already uses quotes:
using namespace std;
#include <iostream>
int main O using namespace std;
{
int main O
{
Hello, user. This is how to use

You've already experienced the\n character literal There's even a character literal that can trigger an
STEP 2 STEP 4
placing a new line wherever it's called. The line: cout alarm. In Windows 10, it's the notification sound
« "Hello\n" « "I’m a C++\n” « "Program\n"; outputs three lines that chimes when you use \a. Try this code, and turn upyour sound.
of text, each starting after the last\n.
#include <iostream>
using namespace std;

int main O
{
cout « “ALARM! \a”;

Python & C++ Coding


r Character Literals

A HANDY CHART
There are numerous character literals, or escape sequence codes, to choose from. We therefore thought it would be good for
you to have a handy chart available, for those times when you need to insert a code.

ESCAPE SEQUENCE CODE CHARACTER


w Backslash

V Single Quote

\” Double Quote (Speech Marks)

V Question Mark

\a Alert/Alarm

\b Backspace

\f Form Feed

\n New Line

\r Carriage Return

\t Horizontal Tab

\v Vertical Tab

\o Null Character

\uxxxx Unicode (UTF-8)

\Uxxxxxxxx Unicode (UTF-16)

UNICODE CHARACTERS (UTF-8)


Unicode characters are symbols or characters that are standard across
all platforms. For example, the copyright symbol, that can be entered
via the keyboard by entering the Unicode code, followed byALT+X. In
the case of the copyright symbol enter: 00A9 Alt+X. In C++ code, you
would enter:

#include <iostream>
using namespace std;
int main O
{
cout « “\u00A9”;

UNICODE I I
I I I
Unicode®
character
U I table
CHARACTER TABLE
A complete list of the available Unicode
characterscan be found atwww.
unicode-table.com/en/. Hoveryour
mouse over the character to see its
unique code to enter in C++.

EEE’SEEEEEEEEESEE
®ie£O¥l5 ®‘-' ® ’

' M 1 . ' “ ’ '■* * * I


AAaAaA.£<?££££ I f I I

www.pclpublications.com
C++ Input/Output

Defining Constants
Constants are fixed values in your code. They can be any basic data type but as the
name suggests their value remains constant throughout the entire code. There are two
separate ways to define a constant in C++, the #define pre-processor and const.

#DEFINE
The pre-processors are instructions to the compiler to pre-process the information before it goes ahead and compiles the
code. Sinclude is a pre-processor as is #define.

You can use the #define pre-processor to define any Note the capitals for defined constants, it’s
STEP1 STEP 3
________ J constants you want in our code. Start by creating a considered good programming practise to define all
A
new C++ file complete with the usual headers: constants in capitals. Here, the assigned values are 50, 40 and 60, so
let’s call them up:
#include <iostrecim>
using namespace std; ^include <iostream>
using namespace std;
int main O
^define LENGTH 50
{
^define WIDTH 40
} ^define HEIGHT 60

int main O

cout « “Length is: “ « LENGTH « “\n”;


cout « “Width is: “ « WIDTH « “\n”;
cout « “Height is: “ « HEIGHT « “\n”;

Start here X DefiningConstants.cpp xl

1 ♦include <iostream>
2 using namespace std;

STEP 2 Now let's assume your code has three different 3


4 ♦define LENGTH 50
constants: length, width and height. You can define
5 ♦define WIDTH 40
them with: 6 ♦define HEIGHT 60
7
#include <iostream> 8 int main ()
using namespace std; 9
10 EH
tfdefine LENGTH 50 11 cout « "Length is: " « LENGTH « "\n";
tfdefine WIDTH 40 12 cout « "Width is: " « WIDTH « "\n";
13 cout « "Height is: " « HEIGHT « "\n";|
tfdefine HEIGHT 60
14
15
int main O
16

{
}
STEP 4 Build and run the code. Just as expected, it displays
Start here X *DefiningConstants.cpp x| the values for each of the constants created. It's
Files ►
1 ♦include <iostream> worth noting that you don't need a semicolon when you're defining
2 using namespace std; a constant with the #define keyword.
3
4 ♦define LENGTH 50
■ C:\Users\david\Documents\C++\DefiningConstants.exe
5 ♦define WIDTH 40
6 ♦define HEIGHT 60 Length is: 50
Width is: 40
7 Height is: 60
8 int main ()
9 Process returned 0 (0x0) execution time : 0.049 s
Press any key to continue.
10
11

120 Python & C++ Coding


Defining Constants

You can also define other elements as a constant. Another method of defining a constant is with the
STEP 5 STEP 8
A For example, instead of using \n fora newline in the const keyword. Use const together with a data type,
cout statement, you can define it at the start of the code: variable and value: const type variable = value. Using Pi as an example:

#include <iostream> #include <iostream>


using namespace std; using namespace std;

#define LENGTH 50 int main O


#define WIDTH 40
{
#define HEIGHT 60
const double PI = 3.14159;
#define NEWLINE ‘\n’
cout « “The value of Pi is: “ « PI « endl;
int main O }

cout « “Length is: “ « LENGTH « NEWLINE;


cout « “Width is: “ « WIDTH « NEWLINE;
cout « “Height is: “ « HEIGHT « NEWLINE;

STEP 9 Because you're using const within the main block of


code, you need to finish the line with a semicolon.
You can use either, as long as the names and values don't clash, but
it’sworth mentioning that#define requires no memory, so if you're
coding to a set amount of memory, #define is your best bet.
The code, when built and executed, does exactly the
STEP 6
same as before, using the new constant NEWLINE
to insert a newline in the cout statement. Incidentally, creating a const double PI = 3.14159;
cout « "The value of Pi is; " « PI « endl;
newline constant isn’t a good idea unless you're making it smaller
than\n or even the endl command. ■ I C:\Useis\david\Documents\C*+\DefiningConstants.exe
The value of Pi is: 3.14159

Process returned 0 (0x0) execution time : 0.046 s


Length is: 50 Press any key to continue.
Width is: 40
Height 1s: 60

■pss returned 0 (0x0)

Const works in much the same way as Sdefine.


STEP 10
You can create static integers and even newlines:
STEP 7 Defining a constant is a good way of initialising your
base values at the start of your code. You can define #include <iostream>
that your game has three lives, or even the value of PI without using namespace std;
having to call up the C++ math library:
int mainO
#include <iostream>
{
using namespace std;
const int LENGTH = 50;
#define PI 3.14159 const int WIDTH = 40;
const char NEWLINE = *\n’;
int main O
int area;
{
area = LENGTH * WIDTH;
cout « “The value of Pi is: “ « PI « endl;
cout « “Area is: “ « area « NEWLINE;

www.pclpublications.com
C++ Input/Output

File Input/Output
The standard iostream library provides C++ coders with the cin and cout input and
output functionality. However, to be able to read and write from a file you need to
utilise another C++ library, called fstream.

FSTREAMS
There are two main data types within the Fstream library that are used to open a File, read From it and write to it, oFstream and
iFstream. Here's how they work.

The first task is to create a new C++ file and along We've included comments in the screenshot of step
STEP1 STEP 3
with the usual headers you need to include the new A 2 to help you understand the process. You created
fstream header: a string called name, to store the user's inputted name. You also
created a text file called name.txt (with the ofstream newfile and
#include <iostrecim>
newfile.open lines), asked the user for their name and stored it and
#include <fstream>
then written the data to the file.
Using namespace std;

int main ()

STEP 4 To read the contents of a file, and output it to the


screen, you need to do things slightly differently.
First you need to create a string variable to store the file's contents
(tine by line), then open the file, use getline to read the file line by
line and output those lines to the screen. Finally, close the file.

STEP 2 Begin by asking a user fortheir name and writing string line;
a that information to a file. You need the usual string ifstream newfile (“name.txt”);
to store the name, and getline to accept the input from the user.
cout « “Contents of the file: “ « endl;
#include <iostream>
getline(newfile, line);
#include <fstream>
cout « line « endl;
using namespace std;
newfile.close();
int main ()

{
string name;

ofstream newbie;
newfile.open(“name.txt”);
cout « “Enter your name: “ « endl;
getline(cin, name);

newfile « name « endl;

newfile.closef);

Python & C++ Coding


The code above is great for opening a file with one Just as you might expect, you can write almost
STEP 5 STEP 8
A or two lines but what if there are multiple lines? Here ad
anything you like to a file, for reading either in
we opened a text file of the poem Cimmeria, by Robert E Howard: Notepad or via the console through the C++ code:

string line; string name;


ifstream newfile (“c:\\users\\david\\ int age;
DocumentsWCimmeria. txt”);
of stream newfile;
cout « “Cimmeria, by Robert E Howard: \n” « newfile. open(“name. txt”);
endl;
cout « “Enter your name: “ « endl;
while (getline(newfile, line)) getlinefcin, name);
cout « line « endl;
newfile « name « endl;
newfile. closeQ J
cout « “\nHow old are you: “ « endl;
cin » age;

newfile « age « endl;

newfile. closef);

You can no i. by Robert C ltoward:


STEP 6
a doubt see that I he dark woods, masking slopes of sombre hills;
dusky streams that flowed without a sound.
we've included a while loop, STEP 9 The code from step 8 differs again, but only where
which we cover in a few pages it comes to adding the age integer. Notice that
time. It means that while there but the endless vista - hill on hill we used cin » age, instead of the previous getline(cin, variable).
are lines to be read from the The reason for this is that the getline function handles strings, not
li th bare boughs rattling in the lonesome winds,
text file, C++ getlines them. integers; so when you're using a data type other than a string, use
K>t even lightened by the rare dim sun
Once all the lines are read, the standard cin.
the output is displayed on the have forgot the very name men called me.
HJ C:\Users\david\Documents\C++\fileinout.exe
screen and the file is closed.
clouds that piled forever on the hills. Enter your name:
rianeria. land of Darkness and the Night. David Hayward

To clouds and winds and ghosts that shun the sun. How old are you:
45
rel of ghosts? 1 search my heart and find
iris, land of Darkness and the Night.
Process returned 0 (0x0) execution time : 7.369 s
Press any key to continue.

You can also see that the location of the text file Here's an exercise: see if you can create code to
STEP 7 STEP 10
Cimmeria.txt isn't in the same folder as the C++ write several different elements to a text file. You
program. When we created the first name.txt file, it was written to can have a user's name, age, phone number etc. Maybe even the
the same folder where the code was located; this is done by default. value of Pi and various mathematical elements. It's all good practice.
To specify another folder, you need to use double-back slashes, as
~3| C++ Write to File - Notepad
per the character literals/escape sequence code.
File Edit Format View Help
Name: David Hayward
6 Age: 45

8 string line; Pi = 3.14159

9 ifstream newfile ("ciWusersW^yXSWDocumentsWjy.^gjJ,^.^") ;


The square root of 133 is: 11.5325
10
11 cout « by Robert E Howard: \n" « endl; What else can you come up with...?|

www.pclpublications.com
Index

124 Python & C++ Coding


Q Loops and Decision Making

Loops and repetition are one of the most


important factors of any programming
language. Good use of a loop creates a
program that does exactly what you want
it to and delivers the desired outcome
without issues or errors.

Without loops and decision making


events within the code, your program will
never be able to offer the user any choice.
It's this understanding of choice that
elevates your skills as a programmer and
makes for much better code.

126 While Loop


128 For Loop
130 Do... While Loop
132 If Statement
134 If... Else Statement

www.pclpublications.com
Loops and Decision Making

While Loop
A while loop's function is to repeat a statement, or a group of statements, while a certain
condition remains true. When the while loop starts, it initialises itself by testing the
condition of the loop and the statements within, before executing the rest of the loop.

TRUE OR FALSE?
While loops are one of the most popular Form oF C++ code looping. They repeatedly run the code contained within the loop
while the condition is true. Once it proves False, the code continues as normal.

Clear what you've done so Far and create a new C++ First you
STEP1 STEP 3
File. There's no need For any extra headers at the a need to
moment, so add the standard headers as per usual: create a condition, so use a
variable called num and give
#include <iostream>
it the value 1. Now create
using namespace std;
the while loop, stating that
int main O as long as num is less than
30, the loop is true. Within
{
the loop the value oF num
} is displayed and adds 1 until
it's more than 30.
Start here X WhileLoop.cpp X

finclude <iostream>
using namespace std;

int main ()

We're introducing a Few new elements here. The


STEP 4
________ J Firstare the opening and closing braces For the
while loop. This is because our loop is a compound statement,
............................................................................................................. meaning a group oFstatements; note also, there's no semicolon
aFter the while statement. You now also have return 0, which is a
Create a simple while loop. Enter the code below,
STEP 2 clean and preFerred way oF ending the code.
________ J build and run (we've added comments to the
screen shot):

{
int num = 1;
while (num < 30 )
{ return 0;
cout « “Number: “ « num « endl;
num = num +1;
}
iFyou didn't need to see the continually increasing
STEPS
return 0; ________ J value oF num, you could have done away with the
} compound while statement and instead just added num by itselF

126 Python & C++ Coding


While Loop

It's important to remember not to add a semicolon STEP 9 You can further expand the code to enable each
STEP 6
at the end of a while statement. Why? Well, as you word of the poem to appear every second. To do
know, the semicolon represents the end of a C++ line of code. If so, you need to pull in a new library, <windows.h>. This is a Windows
you place one at the end of a while statement, your loop will be only library and within it you can use the SleepQ function:
permanently stuck untilyou close the program.
#include <iostream>
#include <fstream>
#include <windows.h>
using namespace std;

int main ()

{
string word;
ifstream newbie (“C: WusersWdavidW
DocumentsWCimmeria. txt”);

cout « “Cimmeria, by Robert E Howard: \n” «


endl;

while (newfile » word)


In our example, if we were to execute the code {
STEP 7
the value of num would be 1, as set by the int cout « word « endl;
statement. When the code hits the while statement it reads Sleep(1000);
that while the condition of 1 being less than 30 is true, loop. The }
semicolon closes the line, so the loop repeats; but it never adds 1 to
return 0;
num, as it won't continue through the compound statement.
}

You can manipulate the while statement to display Sleep() works in milliseconds, so Sleep(1000) is
STEP 8 STEP 10
different results depending on what code lies within a one second, Sleep(10000) is ten seconds and so
the loop. For example, to read the poem, Cimmeria, word byword, on. Combining the sleep function (along with the header it needs)
you would enter: and a while loop enables you to come up with some interesting
countdown code.
#include <iostream>
#include <fstream> #include <iostream>
using namespace std; #include <windows.h>
using namespace std;
int main ()
int main ()
{
string word; {
ifstream newfile (“C: WusersWdavidW int a = 10;
DocumentsWCimmeria. txt”);
while (a != 0)
cout « “Cimmeria, by Robert E Howard: \n” « {
endl; cout « a « endl;
a = a - 1;
while (newfile » word)
Sleep(1000);
{
}
cout « word « endl;
} cout « “\nBlast Off!” « endl;
return 0; return 0;
} }

www.pclpublications.com 127
Loops and Decision Making

For Loop
In some respects, a for loop works in a very similar way to that of a while loop, although it's
structure is different. A for loop is split into three stages: an initialiser, a condition and an
incremental step. Once set up, the loop repeats itself until the condition becomes false.

LOOPY LOOPS
The initialise stage of a for loop is executed only once and this sets the point reference for the loop. The condition is evaluated
by the loop to see if it's true or false and then the increment is executed. The loop then repeats the second and third stage.

STEP1 Create a new C++ file, with the standard headers: STEP 4 After the loop, you created a compound statement
a in braces (curly brackets), that displays the current
#inciude <iostream> value of the integer num. Every time the for loop repeats itself, the
using namespace std; second and third stages of the loop, it adds 1 until the condition <30
is false. The loop then ends and the code continues, ending neatly
int main O
with return 0.

S{

for( int num = 1; num < 30; num = num +1 )


Start here X | *ForLoop.cpp x[__________________________________________________ B {
1 ♦include <iostream> cout « "Number: " « num « endl;
2 using namespace std;
}
3
4 int main ()
5 return 0;
6
7
8
l^1
9

STEP 2 Start simple and create a for loop that counts from
1 to 30, displaying the value to the screen with
each increment:
A for loop is quite a neat package in C++, all
STEP 5
{ A contained within its own brackets, while the other
//For Loop Begins elements outside of the loop are displayed below. If you want to
for( int num = 1; num < 30; num = num +1 ) create a 10-second countdown, you could use:
{
#inciude <iostream>
cout « “Number: “ « num « endl;
#inciude <windows.h>
}
using namespace std;
return 0;
int main O

{
//For Loop Begins
STEP 3 Working through the process of the for loop, begin for( int a = 10; a != 0; a = a -1 )
by creating an integer called num and assigning it a {
value of 1. Next, set the condition, in this case num being less than cout « a « endl;
30. The last stage is where you create the increments; here it's the Sieep(1000);
value of num being added by 1. }
cout « “\nBiast Off!” « endl;

return 0;
for( int num = 1; num < 30; num = num +1 ) }

Python & C++ Coding


For Loop

With the countdown code, don't forget to include STEP 9 Here's an example of a for loop displaying the
STEP 6
-J
the windows.h library, so you can use the Sleep multiplication tablesofa user inputted number.
command. Build and run the code; in the command console you can Handy for students:
see the numbers 10 to 1 countdown in one second increments, until
{
it reaches zero and Blast Off! appears.
int n;
■ C:\Users\david\Documents\C++\ForLoop.exe
cout « “Enter a number to view its times
table:
cin » n;

for (int i = 1; i <= 12; ++i) {


cout « n « “ x “ « i « “ = “ « n * i
« endl;
}
Blast Off!
return 0;
Process returned 0 (0x0) execution time : 10.049 s
Press any key to continue. }

Naturally you can include a lot more content into a


STEP 7
________ J for loop, including some user input:
int i, n, fact = 1;

cout « “Enter a whole number:


cin » n;
for (i = 1; i <= n; ++i) {
fact *= i;
}
cout« “\nFactorial of “« n «” = “« fact «
endl;

return 0;

The value of the integer i can be expanded from


STEP 10
a 12 to whatever number you want, displaying a
very large multiplication table in the process (ora small one). Of
course the data type within a for loop doesn't have to be an integer;
as long as it's valid, it works.

for ( float i = 0.00; i < 1.00; i += 0.01)


{
cout « i « endl;
}
return 0;

The code from step 7, when built and run, asks for a
STEP 8
Anumber, then displays the factorial of that number
through the for loop. The user's number is stored in the integer
n, followed by the integer I which is used to check if the condition
is true or false, adding 1 each time and comparing it to the user's
number, n.

Bi C:\Users\david\Documents\C++\ForLoop.exe

Enter a whole number: 8

Factorial of 8 = 46328

Process returned 8 (8x8) execution time : 2.898 s


Press any key to continue.

www.pcLpublications.com 129
Loops and Decision Making

Do... While Loop


Ado... while loop differs slightly from that of a for or even a while loop. Both for and
while set and examine the state of the condition at the start of the loop, or the top of
the loop if you prefer. However, ado... while loop, is similar to a while loop but instead
checks the condition at the bottom of the loop.

DO LOOPS
The good thing about a do... while loop is that it's guaranteed to run through at least once. It’s structure is: do, Followed by
statements, while condition is true. This is how it works.

Begin with a new, blank C++ file and enter the Now, here'sa look at the structure of a do... while
STEP 1 STEP 3
________ J standard headers: loop. First you create an integer called num, with
the value of 1. Now the do... while loops begins. The code inside
#include <iostream>
the body of the loop is executed at least once, then the condition is
using namespace std;
checked for either true or false.
int main O

int num = 1;

^include <iostrean>>
using namespace std;
do
int main () {
cout « "Number: " « num « endl;
□{
num = num + 1;

}
while (num < 30 );

STEP 2 Begin with a simple number count:

{
STEP 4 If the condition is true, the loop is executed. This
int num = 1;
a continues until the condition is false. When the
do condition has been expressed as false, the loop terminates and the
{ code continues. This means you can create a loop where the code
cout « “Number: “ « num « endl; continues until the user enters a certain character.
num = num + 1;

}
while (num < 30 );
return 0; 8
9
ie
} ii

lumber. 14

lumber: 16
lumber: 17
lumber: 18
lumber: 19
lumber: 20
lumber- 21
lumber 22
himiier 21
lumber 24
lumber. 25
lumber: 26
lumber: 27
lumber: 28
lumber: 29

’rocess returned 0 (0x0) execution time : 0.047 s


>ress any key to continue.

Python & C++ Coding


Do... While Loop

If you want code to add up user inputted numbers Finally, the while statement checks the condition
STEP 5 STEP 8
________ J until the user enters zero: -J of the variable number. If the user has entered
zero, then the loop is terminated, if not then it continues
{
indefinitely. When the user finally enters zero, the value of sum,
float number, sum = 0.0;
the total value of all the user's input, is displayed. The loop, and
cout « “**** Program to execute a Do...
the program, then ends.
While loop continuously ****’’ « endl;
cout « “\nEnter 0 to stop and display the
sum of all the numbers entered\n” « endl;
cout « “\n-------------------------------------------------------------
—\n” « endl;

do {
cout«”\nPlease enter a number: “;
cin»number;
sum += number;
}
whilefnumber ! = 0.0);
STEP 9 Using the countdown and Blast Off! code used
cout«”Total sum of all numbers: “«sum; previously, a do... while loop would look like:

return 0; {

cout « “XnBlast Off!” « endl;


return 0;

The code from Step 5 works as follows: two floating


STEP 6
point variables are assigned, numberand sum, both
A
with the value of 0.0. There is a brief set of instructions for the user,
then the do... while loop begins.

float number, sum = 0.0;


cout << Program to execute a Do... While loop continuously *»**" « endl;
'\nttnter u to stop ana display tne sum or all tne numbers enteredXn'

The main advantage of using a do... while loop


STEP 10
a is because it's an exit-condition loop; whereas a
The do... while loop in this instance asks the user
STEP 7 while loop is an entry-control loop. Therefore, if your code requires a
to input a number, which you assigned to the float
loop that needs to be executed at least once (for example, to check
variable, number. The calculation step uses the second floating
the number of lives in a game), then ado... while loop is perfect.
point variable, sum, which adds the value of number every time the
user enters a new value.

do {
cout « "XnPlease enter a nuiober: "
cin >> number;
sum += number;

www.pclpublications.com
Loops and Decision Making

If Statement
The decision making statement 'if' is probably one of the most used statements in any
programming language, regardless of whether it's C++, Python, BASIC or anything
else. It represents a junction in the code, where IF one condition is true, do this; or IF it's
false, do that.

IF ONLY
If uses a Boolean expression within its statement. If the Boolean expression is true, the code within the statement is executed.
If not, then the code after the statement is executed instead.

First, create a new C++ file and enter the relevant


STEP1
standard headers, as usual:

#include <iostream>
using namespace std;

int main O

If is best explained when you use a number- What’s going on here? To begin, an integer called
STEP 2 STEP 3
based condition: num was created and assigned with the value of 1.
The if statement comes next, and in this case we've instructed the
{
code that if the condition, the value, of num is less than 1, then the
int num = 1;
code within the braces should be executed.
if ( num < 30 )
int num = 1;
{
cout « “The number is less than 30.” «
cout << "The number io 1cm Chun 30.” << endl;
endl;

}
cout « “Value of number is: “ « num « endl;
STEP 4 The second cout statement displays the current
return 0; value of num and the program terminates safely. It's
easy to see how the if statement works if you were to change the
initial value of num from 1 to 31.

^include <iostreaia>
using namespace std;

int main ()

S{
int num = 31;
I
if ( num < 30 )

IT 1
Python & C++ Coding
When you change the value to anything above STEP 7 The code in Step 6 is simplistic but effective. First we
STEP 5
A 30, then build and run the code, you can see that created a floating point integer called temp, then a
the only line to be outputted to the screen is the second cout do... while loop that asks the user to enter the current temperature.
statement, displaying the current value of num. This is because the
initial if statement is false, so it ignores the code within the braces.
float temp;
^osers\uavta\uot.unieni5\vf<- \rr.exe-
do
Value of number is: 31 {
cout « "\nEnter the temperature (or -10000 to exit): " « endl;
Process returned 0 (0x0) execution time : 0.046 s cin » temp;

Press any key to continue.

The first if statement checks to see if the user's


STEP 8
inputted value is less than or equal to zero. If it is,
then the output is ‘Brrrr, it's really cold!'. Otherwise, if the input is
You can include an if statement within a do... while
STEP 6 greater than zero, the code outputs ‘At least it’s not freezing!'.
________ J loop. For example:
{
float temp; cout « "\nEnter the temperature (or -10000 to exit): " « endl;
cin » temp;
if (temp <= 0 )
do {
{ cout « "\n£&&££, it’s really cold!" « endl;
)
cout « “\nEnter the temperature (or if (temp > 0 )
-10000 to exit): “ « endl; {
cout « "\nAt least it‘s not freezing!" « endl;
cin » temp;
if (temp <= 0 )
{
cout « “\nBrrrr, it’s really cold!” STEP 9 Finally, if the user enters the value -10000, which is
« endl; a impossibly cold so is therefore a unrealistic value,
} the do... while loop is terminated and a friendly 'Good bye' is
if (temp > 0 ) displayed to the screen.
{
cout « “\nAt least it’s not float temp.-
freezing!” « endl; do
}
cout « "\nEntei the temperature (or -1OOOO to exit): " « endl;
} cin » temp;
if (temp <= 0 )
while ( temp != -10000 ); {
cout « "Xngxjxj:, it's really cold!" « endl;

cout « “\nGood bye\n” « endl; if (temp > 0 )


<
return 0; cout « "\nAt least it's not freezing!" « endl;

>
while ( temp != -10000 );

cout « "\nGood bye\n" « endl;

return 0;

Using if is quite powerful, if it's used correctly. Just


STEP 10
remember that if the condition is true then the
a
code executes what's in the braces. If not, it continues on its merry
way. See what else you can come up with using if and a combination
of loops.

www.pclpublications.com
Loops and Decision Making

If... Else Statement


There is a much better way to use an if statement in your code, with if... else. If... else
works in much the same way as a standard if statement. If the Boolean expression
is true, the code with in the braces is executed. Else, the code within the next set of
braces is used instead.

IF YES, ELSE NO
There are two sections of code that can be executed depending on the outcome in an if... else statement. It's quite easy to
visualise once you get used to its structure.

Begin with a new C++ file and the standard headers: The first line in the code creates the integer called
STEP 3
num and gives it a value of 1. The if statement
#include <iostream> 1 ^include <iostream> checks to see if the value of num is less than thirty and if it is it
2 using namespace std;
using namespace std; outputs "The number is less than 30!" to the console.
3
4 int main ()
int main O
5
if ( num < 30 )
6 B{
{ (
7 cout « "Tire number is less than 30!” « endl;
} 8 } I
q

The else companion to if checks if the number is


Let's expand the code from the If Statement on the STEP 4
STEP 2 greater than 30 and if so, then displays "The number
________ J previous page:
is greater than 30!" to the console; and finally, the
{ code is terminated satisfactorily.
int num = 1;
cout << "The number is less than 30!” << endl;

if ( num < 30 ) I
else
{ {
cout « "The number is greater than 30!" « endl;
cout « “The number is less than 30!” «
endl;
}
else
You can change the value of num in the code or
{ STEPS
you can improve the code by asking the user to
cout « “The number is greater than 30!”
enter a value:
« endl;
} {
int num;
return 0;
cout « “Enter a number: “;
}
cin » num;

if ( num < 30 )
{
cout << “The number is less than 30!” «
endl;
}
else
{
cout << “The number is greater than 30!”

return 0;

Python & C++ Coding


If... Else Statement 1C

The code works the same way, as you would expect, You can take this up a notch and create a two-player
STEP 6 STEP 8
-J but what if you wanted to display something if the ________ J number guessing game. Begin by creating the variables:
user entered the number 30? Try this:
int num, guess, tries = 0;
{
int num; cout « “***** Two-player number guessing game
****’’ « endl;
cout « “Enter a number:
cout « “\nPlayer One, enter a number for
cin » num;
Player Two to guess: “ « endl;
if ( num < 30 ) cin » num;
{ cout « string(50, ‘\n’);
cout « “The number is less than 30!” «
endl;
The cout« string(50, V) line clears the screen so
} STEP 9
________ J Player Two doesn't see the entered number. Now
else if C num > 30 )
you can create a do... while loop, together with if... else:
{
cout « “The number is greater than 30!”
« endl; {
} cout « “\nPlayer Two, enter your guess: “;
else if C num == 30 ) cin » guess;
{ tries++;
cout « “The number is exactly 30!” « if (guess > num)
endl; {
} cout « “\nToo High!\n” « endl;
}
return 0;
else if (guess < num)
} {
cout « “\nToo Low!\n” « endl;
}
else if (guess == num)
{
cout « “Well done! You got it in “ «
tries « “ guesses!” « endl;
}
} while (guess != num);

return 0;

STEP 7 The new addition to the code is what's known as a STEP 10


nested if... else statement. This allows you to check
Grab a second player, then
for multiple conditions. In this case, if the user enters a number less
build and run the code.
than 30, greater than 30 or actually 30 itself, a different outcome is
Player One enters the
presented to them.
number to be guessed,
Si CAUsers\david\Documents\C++\lfElse.exe
then Player Two can take
as many guesses as they
Enter a number: 30
need to get the right
The number is exactly 30!
number. Want to make
Process returned 0 (0x0) execution time : 4.037 s it harder? Maybe use
Press any key to continue. decimal numbers.

www.pclpublications.com
Index

136 Python & C++ Coding


(^Working with Code

By now you should have the essential


building blocks of how to program in both
Python and C++. You can create code,
store data, ask the user questions, offer
them a choice and repeat functions until
they prove true and provide the correct
output. What next then?

This final section looks at some of the


more common coding mistakes that
Python and C++ beginners make and
where you can turn to next to continue
your programming adventure.

138 Common Coding Mistakes


140 Beginner Python Mistakes
142 Beginner C++Mistakes
144 Where Next?

71

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

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

SMALL CHUNKS EASY VARIABLES


It would be wonderful to be able to Meaningful naming for variables is a must to eliminate
work like Neo from The Matrix movies. common coding mistakes. Having letters of the alphabet
Simply ask, your operator loads it into is fine but what happens when the code states there's
your memory and you instantly know a problem with x variable. It's not too difficult to name
everything about the subject. Sadly variables lives, money, playerl and so on.
though, we can't do that. The first
major pitfall is someone trying to learn 1 var points = 1023;
2 var lives = 3;
too much, too quickly. So take coding in
3 var totalTime = 45;
small pieces and take your time. 4 write("Points: "tpoints);
5 write("Lives: "+lives);
6 write("Total Time: "+totalTime+" secs");
7 write ("-------------------------- ") ;
8 var totalscore = 0;
9 write("Your total Score is: "+totalScore):
//COMMENTS
Use 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 PLAN AHEAD
through the sections of code that are causing problems;
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
ong +=2; a classic text adventure, it's not always practical without a
target +■ 2;
good plan. Small snippets of code can be written without
—n;
} too much thought and planning but longer and more in-
tendif depth code requires a good working plan to stick to and
if (n = 0) help iron out the bugs.
return;

Loop unrolling. be dragons

// (n & (~3)) is the greatest multiple of 4 r


In the while loop ahead, orig will move ov
increments (4 elements of 2 bytes).
end marks our barrier for not falling outa
char const * const end = orig + 2 * (n &

// See xf we’re aligned for wnttmg in


#if ACE_SIZEOF_LONG = 8 && \
! ((defined( amd64 ) I I defined (

138 zations.com
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 BACKUPS
internal buffer, thus sending the code crashing. Watch those
user inputs and clearly state what's needed from them.
Always make a backup of your work, with a secondary
Enter an integer number backup for any changes you've made. Mistakes can be
aswdfdsf rectified if there's a good backup in place to revert to for
You haue entered wrong input
s
those times when something goes wrong. It's much easier
You haue entered wrong input to start where you left off, rather than starting from the
beginning again.
You haue entered wrong input
sdfsdf213213123
You haue entered wrong input
123234234234234234
You haue entered wrong input
12
the number is: 12

Process returned 0 (0x0) execution time : 21.495 s


Press any key to continue.

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
.OVvOT’
data, prior to feeding
into a routine that can
transmit or store it
MR
A ' Z> 'If.
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 in the correct manner, obey any forum rules and be can have disastrous effects depending on what the code is
polite, then your question isn't silly. set to do. In short, double check your code equations.

set terminal xll


set output
915,002
max = 5
nraax = 10®

complex (x, y) = x * {1, 0} + y * {0, 1}


■andel (x, y, z, n) = (abs (z)> max || n>= 100)? n: mandel (x, y. z * z ♦ complex (x, y), n + 1)
set xrange [-0.5:0.51
set yrange [—0.5:0.51
set logscale z
set samples 200
set isosample 200
set pm3d map
set size square
a= #A#
b= #0#
splot mandel(-a/100,-b/100,complex(x,y),0) notitle

rcom 139
Working with Code

Beginner Python Mistakes


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

DEF BEGINNER(MISTAKES=10)
Here are ten common Python programming mistakes most beginners find themselves making. Being able to identify these
mistakes will save you headaches in the future.

VERSIONS INDENTS, TABS AND SPACES


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

python t sec up font


font - pygamc.fone.SyoFont(1calibri1, 50)

def uakeplayei () ;
About Downloads Documentation Community Success Stories Nevi player = pvaame.Rect(370, 635, 60, 25)

Download the latest version for Windows


Download Python 3.6.4 I Download Python 2.7.14 fox 1 in ranae(ii):
invader ■ pyaame.Kect(75+x, 7S+y, so, 20)
Wondering which version to use? Here’s more about the difference 1.append(invader)
between Python 2 and 3. x *- 60
y +- 45
I ooklng for Python with a different OS? Python for Windows,
Llnux/UNIX, Mac OS X. Other def makewalla (walls) :
Want to help test development versions of Python? Pre-releases wain = pyoanie.Recc(6O, 520, 120, 30)
walla ■ pyaame.Rect(246, 520, 120, 30)
wall3 = pygame.Rect (432 , 520, 120, 30)
wa!14 = pygame.Rect(618, 520, 120, 30)

THE INTERNET COMMENTING


Every programmer has and does at some point go on the Internet Again we mention commenting. It’s a hugely important factor in
and copy some code to insert into their own routines. There's programming, even if you're the only one who is ever going to view
nothing wrong with using others' code, butyou need to know how the code, you need to add comments as to what's going on. Is this
the code works and what it does before you go blindly running it on function where you lose a life? Write a comment and help you, or
your own computer. anyone else, see what's going on.

# set up pygame
Create/delete a txt file in a python program
pygame.init()
mainClock = pygame.time.Clock()
A I have created a program to grab values from a text hie As you can see, depending on the value of the
results, I have an if/else statement printing out the results of the scenario.
0 # set up the window
My problem is I want to set the code up so that the if statement creates a simple txt file called data txt
to the C.tPytfiontScripts directory.
width = 800
height = 700
In the event the opposite is true, I would like the else statement to delete this txt file if it exists.
screen = pygame.display.set_mode((width, height), 0, 32)
I’m a novice programmer and anything I’ve looked up or tried hasn't worked tor me, so any help or pygame.display.set_caption(1 caption•)
assistance would be hugely appreciated.

# set up movement variables


moveLeft = False
x - opM(-Wtt.txt-.T-)
California = x.readlines(11) moveRight = False
dublin ■ x.readlines(US) moveUp = False
percentage value - |tloat(re.tindall(’\d+\.\d+(f-\%)|\d+\.\d+(r-\s\*)’, i(-l))|0]) tor i in [ci moveDown = False
print(percentage value)
# set up direction variables
it percentage value]0| <■ percentage vaiuc|l|: DOWNLEFT = 1
print('Website is hosted in Dublin')
else: DOWNRIGHT = 3

140 Python & C++ Coding


Beginner Python Mistakes

COUNTING LOOPS COLONS


Remember that in Python a loop doesn't count the last numberyou It's common for beginners to forget to add a colon to the end of a
specify in a range. So if you wanted the loop to count from 1 to 10, structural statement, such as:
then you will need to use:
class Hangman:
n = list(range(l, 11)) def guessfself, letter):

Which will return 1 to 10. And so on. The colon is what separates the code, and creates the
indents to which the following code belongs to.
[Jr Python 3.6.2 Shell - □ X

File Edit Shell Debug Options Window Help class Hangman:


Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] def __ init___(self,word):
on Win32 self.word = word
Type "copyright", "credits" or "license ()" for more information. self.missed_letters = []
self.guessed_letters = []
======== RESTART: C:\Users\david\Documents\Python\Space Invaders.py ========
»> n = list (range (1, 11)) def guess(self,letter):
»> print (n) if letter in self.word and letter not in self.guessed_letters:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.guessed_letters.append(letter)
elif letter not in self.word and letter not in self.missed_letters:
self.missed_letters.append(letter)
else:
return False
return True

def hangman_over(self):
return self.hangman_won() or (len(self.missed_letters) = 6)

def hangman_won(self):
if not in self.hide_word():
return True

CASE SENSITIVE return False

def hide word(self):


rtn = ' '
Python is a case sensitive programming language, so you will need for letter in self.word:
if letter not in self.guessed_letters:
to check any variables you assign. For example, Li ves=10 is a rtn +=
different variable to lives=10, calling the wrong variable in your code else:
rtn += letter
can have unexpected results. return rtn

J Python 3.6.2 Shell


File Edit Shell Debug Options Window Help
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:3 OPERATORS
on Win32
Using the wrong operator is also a common mistake to make. When
Type "copyright", "credits" or "license()" for mor
you're performing a comparison between two values, for example,
>» Lives=10
>» lives=9 you need to use the equality operator (a double equals, ==). Using
>» print (Lives, lives) a single equal (=) is an assignment operator that places a value to a
10 9 variable (such as, lives=10).
»>
b = 5
c = io
d = 10
b == c #false because 5 is not equal to 10
c = d #true because 10 is equal to 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 cis. Whereas, for Linux you need to use
def print_game_status(self): clear. You need to solve this by capturing the errorand issuing it
print (board[len(self.missed_letters)])
with an alternative command.
print ('Word: ' + self.hide_word())
print ('Letters Missed: ',)
for letter in self.missed_letters: # Code to detect error for using a different OS
run=l
print (letter,) while (run=l) :
print ()
print ('Letters Guessed: ',) os.system('clear')
for letter in self.guessed_letters: except OSError:
os.system(1 cis')
print (letter,) print ('\n»»»»»Python 3 File Manager«««««\n')
print ()

www.pclpublications.com
Working with Code

Beginner C++ Mistakes


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

VOID(C++f MISTAKES)
Admittedly it's not just C++ beginners that make the kinds of errors we outline on these pages, even hardened coders are
prone to the odd mishap here and there. Here are some common issues to try and avoid.

UNDECLARED IDENTIFIERS STD NAMESPACE


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

using namespace std;


File Edit View Search Tools Documents Help
Under the #include part and simply using cout, cin and so on from
then on.
£) u ** X |O C 9 ^include <iostream>
using namespace std;
[cj testl.cpp x int mainO
{
#include <iostream> int a, b, c, d;
a=10;
b=28;
int mainO c=30;
d=40;
std::cout « x; cout « a, b, c, d;

} }

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

#include <iostream> david@mint-mate '■/Documents

File Edit View Search Terminal Help


david@mint-mate '-/Documents s gcc testl.cpp -o test
int mainO /tmp/ccA5zhtg.o: In function 'main':
{ testl.cpp:(.text+0x2a): undefined reference to 'std::cout'
int a, b, c, d; testl.cpp:(.text+0x2f): undefined reference to 'std::ostream::
a=10; /tmp/ccA5zhtg.o: In function '__staticinitializationand dest
)':
b=20; testl.cpp:(.text+0x5d): undefined reference to 'std::iosbase:
c=30 testl.cpp:(.text+0x6c): undefined reference to 'std::iosbase:
d=40; collect2: error: Id returned 1 exit status
david@mint-mate '■/Documents s g++ testl.cpp -o test
david@mint-mate -/Documents S
std::cout « a, b, c, d;

Python & C++ Coding


(^Beginner C++ Mistakes

COMMENTS (AGAIN) TOO MANY BRACES


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

#include <iostream>
using namespace std;

int mainf)
{
int x;
string mystring = "This is a string!\n’;
cout « "What’s the value of x?
cin » x;
cout « x;
{
cout « \n\n ;
cout « mystring;
QUOTES
Missing quotes is a common mistake to make, for every level of user. }
Remember that quotes need to encase strings and anything that's
going to be outputted to the screen or into a file, for example. Most
compilers errors are due to missing quotes in the code.
INITIALISE VARIABLES
In C++ variables aren’t initialised to zero by default. This means if
you create a variable called x then, potentially, it is given a random
number from 0 to 18,446,744,073,709,551,616, which can be
difficult to include in an equation. When creating a variable, give it
the value of zero to begin with: x=0.

#include <iostream>
using namespace std;

int main()
I
int x;
x=0;

cout « X;
EXTRA SEMICOLONS
While it's necessary to have a semicolon at the end of every C++ line, I
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
// Program lo print positive number entered by the user
// If user enters negative number, it is skipped that can be executed with ,/a.out. However, if you already have code
•include <iosrream> in a.out then it’s overwritten. Use:
using namespace std;

int main() g++ code.cpp -o nameofprogram


(
int number;
cout « "Enter an Integer: ";
rin » number; david@mint-mate -/Documents

// checks if the number is positive


File Edit View Search Terminal Help
if ( number > 0) david@mint-mate -/Documents S g++ testl.cpp
(
cout << "You entered a positive integer; " << number « endl; david@mint-mate -/Documents $ ./a.out
0
david<amint-mate -/Documents s g++ testl.cpp -o printzero
rout << "This statement is always executed."; david@mint-mate -/Documents S ./printzero
return 0;
0
david@mint-mate -/Documents S

www.pclpublications.com
Working with Code

Where Next?
Coding, like most subjects, is a continual learning experience. You may not class yourself
as a beginner any more but you still need to test your code, learn new tricks and hacks to
make it more efficient and even branch out and learn another programming language.

#INCLUDE<KEEP ON LEARNING>
What can you do to further your skills, learn new coding practises, experiment and present your code and even begin to help
others using what you've experienced so far?

TWITTER OPEN PROJECTS


Twitter isn't all trolls and antagonists, among the well-publicised Look for open source projects that you like the sound of and offer
vitriol are some genuine people who are more than willing to spread to contribute to the code to keep it alive and up to date. There are
their coding knowledge. We recommend you find a few who you can millions of projects to choose from, so contact a few and see where
relate to and follow them. Often they post great tips, hacks and fixes they need help. It may only be a minor code update but it's a noble
for common coding problems. occupation for coders to get into.

@ Horn* Monunts Q Notifications (3 M«ss*gts Q |

programming

Search filters

Related searches

Who to follow
- ProSr.mmin,
VS

KEEP CODING SHARE SKILLS


If you've mastered Python fairly well, then turn your attention to Become more active on coding and development knowledge sites,
C++ or even C#. Still keep your Python skills going but learning a new such as StackExchange. If you have the skills to start and help others
coding language keeps the old brain ticking over nicely and give you a out, not only will you feel really good for doing so but you can also
view into another community, and how they do things differently. learn a lot yourself by interacting with other members.

#pragma once
StackExchange^ M saes Top u«n MewsieHea
#define EXPAND_ME _FILE_ " : " _LINE_

constexpr auto pi = 314LLu;


thread_local decitype(pi) rage = 0bl0; 2,783,281 results

[[deprecated("abc")]] charl6_t *f() noexcept { return nullptr; }

template ctypename T> struct Foo {


static_assert(std::is_floating_point<T>::value,
"Foo<T>: T must be floating point");
Call python from module and receive output

struct A final : goo {


A() = default;
[[noreturn]] virtual void foot) override;

template <typename T> concept bool EqualityCompacable = requires(T


{ a = b } -> bool;

144 Python & C++ Coding


Q Where Next?

GOING MOBILE PORTFOLIOS


The mobile market is a great place to test your coding skills and If you've learned how to code with an eye fora developerjob in
present any games or apps you've created. If yourapp is good, then the future, then it's worth starting to build up an online portfolio
who knows, it could be the next great thing to appear on the app of code. Look at job postings and see what skills they require,
stores. It's a good learning experience nevertheless, and something then learn and code something with those skills and add it to the
worth considering. portfolio. When it comes to applying, include a link to the portfolio.

My Work
Want to see more examples?

Chronicled.org

VISIT WEBSITE

ONLINE LEARNING TEACH CODE


Online courses are good examples of where to take your coding Can you teach? If your coding skills are spot on, consider
skills next, even if you start from the beginner level again. Often, approaching a college or university to see if they have need fora
an online course follows a strict coding convention, so if you're self- programming language teacher, perhaps a part-time or evening
taught then it might be worth seeing how other developers lay out course. If not teaching, then consider creating your own YouTube
their code, and what’s considered acceptable. how to code channel.

Learn to code interactively, for free.

SHARE CODE HARDWARE PROJECTS


Get sharing, even ifyou thinkyourcode isn't very good. The Contributing to hardware projects is a great resource for proving your
criticism, advice and comments you receive back help you iron out code with others and learning from other contributors. Many of the
any issues with your code, and you add them all to your checklist. developer boards have postings for coders to apply to for hardware
Alternatively your code might be utterly amazing but you won't projects, using unique code to get the most from the hardware that's
know unless you share it. being designed.

Share Code in Real-time with Developers


An online code editor for interviews, troubleshooting, teaching & more...

www.pclpublications.com
The Complete
Manual Series
Available on ■I[ Readly

The Complete The Complete v The Complete The Complete

Android Black & White Build Your Internet


User Manual Photography Security
Manual Own PC Manual
Master professional tetfpmgues
and improve your phoKgraphy
Manual Master security and stay safe online
Learn how to build a new computer

The Complete The Complete


Chromebook
User Manual
& Python
Master your Chromebook and
Google's Chrome OS

Manual

FOR ALL COMPUTERS & MOBILES


-----------------------------------------------Wi
The Complete The Complete The Complete *

Google GoPro Home


User Manual Manual Networking
Master Google's amazing
free apps and improve
Manual
your nelwort and smmt
your productivity
840

'f.
Master your GoPro camera and '
shoot amazing-photos and videos

UPDATED FOR ALL iPAD MODELS £


-----------------------------------------------
The Complete v The Complete The Complete The Complete
Instagram
User
Windows 11
User Manual iPad iPhone
'
OVER
r
The essential step-by-step manual
to mastering Microsoft's
&iPadOS*3 & iOS®r
460
GUIDES
Windows 11 operating system
User Manual User Manual
Master your iPad and iPadOS 16 Master your iPhone and iOS 16

Essential step-by-step guides to


mastering Instagram
www.pdputlical>ons.c.m QPopercut 100% INDEPENDENT www.pdpuHkaliou.om 3 PoperCUt 100% INDEPENDENT

For a full list of titles available visit:


www.pclpublications.com
Want to master your Code?
Then don't miss our NEW Programming
magazine on Readlu now!

NEW
The Future Is Code

The Ultimate IUSER


Issue Five | March 20231100% INDErtiMUti'i. —

Python
Learn, Code, Create
and Master!
PACKED WITH

Using Python To Code


100 Things You Have Usinoas^berry Pi! Your Own Games!
To Do With Python! Ragmens---------

^biningCodingPlatforms CouldYou BeTteNext


Vnnr Fvnprt Programming
VVIUI uieav —
ChecKiisiLoiiipc«=«-

Click our handy link to read now: https://bit.ly/30cL1 zx


The Complete Manual Series: device. It remains the purchaser’s sole responsibility to determine acknowledged. Relevant graphic imagery reproduced with
the suitability of this book and its content for whatever purpose. courtesy of Lenovo, Hewlett- Packard, Dell, Microsoft, Samsung,
C++ & Python Any images reproduced on the front and back cover are solely for Linux Mint, NASA, and Apple. Additional images contained within
15 | ISBN: 978-1-914404-44-3 design purposes and are not representative of content. this publication are reproduced under licence from Shutterstock.
Published by: Papercut Limited We advise all potential buyers to check listing prior to purchase Prices, international availability, ratings, titles and content are
Digital distribution by: Readly, Zinio & Pocketmags for confirmation of actual content. All editorial opinion herein is subject to change.
© 2023 Papercut Limited All rights reserved. No part of this that of the reviewer - as an individual - and is not representative of All information was correct at time of publication. Some content
publication may be reproduced in any form, stored in a retrieval the publisher or any of its affiliates. Therefore the publisher holds may have been previously published in other volumes or titles.
system or integrated into any other publication, database or no responsibility in regard to editorial opinion and content.
commercial programs without the express written permission of This is an independent publication and as such does not Papercut Limited

a
the publisher. Under no circumstances should this publication and necessarily reflect the views or opinions of the manufacturers or Registered in England & Wales No: 04308513
its contents be resold, loaned out or used in any form by way of hardware and software, applications or products contained within.
trade without the publisher’s written permission. While we pride This publication is not endorsed or associated in any way with ADVERTISING - For our latest media packs please contact:
ourselves on the quality of the information we provide, Papercut Python, C++, The Linux Foundation, The Raspberry Pi Foundation, James Gale - email: jgale@pclpublications.com
Limited reserves the right not to be held responsible for any ARM Holding, Canonical Ltd, Debian Project, Linux Mint, Microsoft,
mistakes or inaccuracies found within the text of this publication. Lenovo, Dell, Hewlett-Packard, Apple and Samsung or any INTERNATIONAL LICENSING - Papercut Limited has many great
Due to the nature of the tech industry, the publisher cannot associate or affiliate company. All copyrights, trademarks and publications and all are available for licensing worldwide.
guarantee that all apps and software will work on every version of registered trademarks for the respective companies are For more information email: jgale@pclpublications.com
Get Your Exclusive
FREE Gift Worth
£9.99 Here!
Download —BEE Software! Great Games! Essentk
are!

Your FREE
TFCM 170 Thick!

I SHOPPER
M A G A z I N E SISFSS-”-

*fQO amazing
■ gadgets
Tech Shopper APPS & GAMES INSIDE!

Magazine a
Head over to your web ?.° y°u need a ■
W Cnromebook? Home Security
browser and follow these Read our expert guide
to Google’s notebook!
Inside & Out1
Discover how to krep,our
home safe and secure!

simple instructions...

1/ Enter the following URL: www.pclpublications.com/exclusives


2/ Sign up/in and from the listings of our exclusive customer
downloads, highlight the Tech Shopper Magazine option.
3/ Enter your unique download code (Listed below) in the "Enter
download code" bar.
4/ Click the Download Now! Button and your file will automatically
download.
5/ Your file is a high resolution PDF file, which is compatible with
the majority of customer devices/platforms.

Exclusive Download Code: pcl37 862re


NOTE: This is a limited reader offer running from 1st January 2023 to 1st September 2023.
Terms and conditions apply and can be found at www.pclpublications.com

You might also like