PCL. the Complete C++ & Python Manual 15ed 2023
PCL. the Complete C++ & Python Manual 15ed 2023
The Complete
& Python
Manual
OVER
F9C
GUIDES
&TIPS
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
W»lpMw
Master yourtdrnera 890 । Ventura rual to improvTUg out
PhotograjSSg§tdf!s
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
over
for home and business
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
For more
great coding
titles visit us at:
WWW.
pclpublications.com
Raspberry Pi
& Linux
www.pclpublications.com 5
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
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
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)
guessed_letters.append(playerguess)
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.
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.
THE RASPBERRY PI
Why use a Raspberry Pi? The Raspberry Pi is a tiny computer that’s very cheap to purchase but offers the user a fantastic learning
platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many Modules and extras.
RASPBERRY PI
FUZE PROJECT
BOOKS
=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.
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
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.
bowl - (]
flour - 100
butter • 50
milk - 100
bowl.append((flour, butter, milk])
cake.cook(bowl)
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.
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.
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.
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.
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.
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.
python python
for 0 Install launcher for all users (recommended) for
windows □ Add Python 3.6 to PATH Cancel windows Back | ^Install | | Cancel |
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.
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.
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.
Close
■
■+-■ 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.
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.
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
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:
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 ~ |
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.
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
www.pclpublications.com
Getting Started with Python
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.
»> 8+6
14
»> 23453+64545522
64568975
»> 98778642342-12343
98778629999
»> 1287437*43534
56047282358
»>l
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.
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.
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
www.pclpublications.com
Getting Started with Python
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:
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
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)
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)
www.pclpublications.com
Getting Started with Python
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!”)
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.
Save Ctrl+S
Save As... Ctrl+SMt+S
Save Copy As... Alt+Shift+S
£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
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|
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.
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.
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)
And so on.
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.
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:
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)
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:
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
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 (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'>
print (character)
age=44
Type (age)
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.
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:
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:
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.
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.”)
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.
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:
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:
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.
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.”)
‘Untitled* _ □ x
File Edit Format Run Options Windows Help
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.”)
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:
*Untitled*
File Edit Format Bun Options Windows Help
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
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.
C:\WINDOWS\system32>
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))
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.
print(m.pi)
www.pclpublications.com
Index
Working
with Data
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.
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:
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]
»> |
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:
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.
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 (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
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”}
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”]
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.
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
■ 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
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
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))
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))
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:
www.pclpublications.com
Working with Data
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
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:
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
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
import time
start_time-time.time()
name=input("Enter login name: ")
endtime-time.time()-start_time
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”)
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”))
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.
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:
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
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.
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
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.”)
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:
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.
import math
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:
BaseException
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
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.
Then you can even change the character to an actual turtle by entering: img = pygame.image.load(“RPi.png
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
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.
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)
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:
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.
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
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”’)
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/”’)
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.
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:
print(“Heads:”, output[“Heads”])
printC“Tails:”, output[“Tails”])
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
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
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:
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()
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()
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.
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()
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)
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
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.
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))
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):”)
www.pclpublications.com 81
Index
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
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";
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
i**-I
I »
Desktop development with C++
Build classic Windows-based applications using the power of the
□ Optional
®
modern computing, hence the aforementioned companies using it
so widely.
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.
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
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
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
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.
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
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.
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”;
}
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++
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.
kJ al
kJ Hello World C • • Project
jjjf Binaries
£j; Includes
£5 src
Lcl Hello World C++ Project.cpp
fe. Debug
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.
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
www.pclpublications.com
C++ Fundamentals
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>
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.
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
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.
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
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 ; 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.
www.pctpubtications.com
C++ Fundamentals
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
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.
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.
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.
int main()
□<
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”;
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.
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
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;
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
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.
#include <iostream>
TYPE COMMAND using namespace std;
Integer double PI = 3.141592653589793238463;
int mainO
Floating Point fiBBW {
cout « Pi;
Character }
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
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.
You can create your own data types, using an alias-like system called
typedef. For example:
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;
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.
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
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
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”;
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
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
int main ()
B<
float numbers = 100;
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.
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;
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”;
#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
www.pcLpublications.com
Index
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
#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;
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:
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;
I C:\Users\david\Documents\C++\userinteraction.exe
Enter a sentence:
BDM Publications Python and C++ for Beginners
Your sentence is: 45 characters long.
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”;
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.
V Single Quote
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
#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 ®‘-' ® ’
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
1 ♦include <iostream>
2 using namespace std;
{
}
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
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:
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 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.closef);
newfile. closef);
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
www.pclpublications.com
Index
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 ()
{
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
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”);
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{
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 ) }
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;
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
Factorial of 8 = 46328
www.pcLpublications.com 129
Loops and Decision Making
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 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
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; {
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.
#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;
>
while ( temp != -10000 );
return 0;
www.pclpublications.com
Loops and Decision Making
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
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;
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;
www.pclpublications.com
Index
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.
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
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.
rcom 139
Working with Code
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.
def uakeplayei () ;
About Downloads Documentation Community Success Stories Nevi player = pvaame.Rect(370, 635, 60, 25)
# 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.
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
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
www.pclpublications.com
Working with Code
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.
} }
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>
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;
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?
programming
Search filters
Related searches
Who to follow
- ProSr.mmin,
VS
#pragma once
StackExchange^ M saes Top u«n MewsieHea
#define EXPAND_ME _FILE_ " : " _LINE_
My Work
Want to see more examples?
Chronicled.org
VISIT WEBSITE
www.pclpublications.com
The Complete
Manual Series
Available on ■I[ Readly
—
The Complete The Complete v The Complete The Complete
Manual
'f.
Master your GoPro camera and '
shoot amazing-photos and videos
NEW
The Future Is Code
Python
Learn, Code, Create
and Master!
PACKED WITH
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...