Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

C and Python Applications: Embedding

Python Code in C Programs, SQL


Methods, and Python Sockets Philip
Joyce
Visit to download the full and correct content document:
https://ebookmass.com/product/c-and-python-applications-embedding-python-code-in
-c-programs-sql-methods-and-python-sockets-philip-joyce/
Philip Joyce

C and Python Applications


Embedding Python Code in C Programs,
SQL Methods, and Python Sockets
1st ed.
Philip Joyce
Crewe, UK

ISBN 978-1-4842-7773-7 e-ISBN 978-1-4842-7774-4


https://doi.org/10.1007/978-1-4842-7774-4

© Philip Joyce 2022

Apress Standard

The use of general descriptive names, registered names, trademarks,


service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.

The publisher, the authors and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.

This Apress imprint is published by the registered company APress


Media, LLC part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
Einführung
The C and Python programming languages are important languages in
many computer applications. This book will demonstrate how to use
the C and Python languages to write applications in SQL. It will
demonstrate how to embed a Python program within a C program.
Finally, the reader will learn how to create Python socket programs
which can communicate with each other on different computers (these
are called “sockets”).
A basic familiarity with mathematics is assumed along with some
experience of the basics of computer programs. The first two chapters
review the basics of C and Python. The chapters following these are
grouped into SQL techniques, embedded Python, and sockets
applications. There are exercises in each chapter with answers and
suggested code at the end of the book.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub via the book’s
product page, located at www.apress.com/9781484277737. For more
detailed information, please visit http://www.apress.com/source-code.
Acknowledgments
Thanks to my wife, Anne, for her support, my son Michael, and my
daughter Katharine. All three have mathematics degrees. Thanks to
everyone on the Apress team who helped me with the publication of
this, my third book.
Table of Contents
Chapter 1:​Python Programming
Definition of Variables
Real (Float) Numbers
Characters
Reading in Data
Arrays
Inserting into an Array
Deleting (Removing) from an Array
Searching
Updating an Array
Appending to an Array
Strings
Lists
Reading Entries in a List
Updating a List
Deleting an Element from List
Appending to a List
Dictionaries
Creating a Dictionary
Appending to a Dictionary
Amending a Dictionary
Deleting from a Dictionary
Searching Through a Dictionary
Tuples
Creating a Tuple
Concatenating Two Tuples
Creating Nested Tuples
Creating Repeated Tuples
Converting a List or a String into a Tuple
Creating Single-Element Tuple
Reading Tuple
Searching Within a Tuple
Deleting a Tuple
Using Tuple to Create Variables
If Then Else
Loops (For and While)
For Loops
While Loops
Switches
Arithmetic Operations Using Numpy
Numpy Calculations
Mathematical Graph Functions
User-Written Functions
File Access
Regressions
Summary
Exercises
Chapter 2:​C Programming
C Program Format
Adding Two Numbers
Multiply and Divide Two Numbers
For Loops
Do While Loops
Switch Instruction
If Else
If Else If
Data Arrays
Functions
Strings
Structures
Size of Variables
Goto Command
Common Mathematical and Logical Symbols
File Access
Student Records File
Summary
Exercises
Chapter 3:​SQL in C
Review of SQL and SQLite
Creating the Database
Creating a Table
Inserting Rows
Insert a Preset Row
Inserting a User-Entered Row
Selecting Rows
Selecting a Row Preset
Selecting All Rows
Selecting Rows by Age
Amending Rows
Deleting Rows
Summary
Exercises
Chapter 4:​SQL in Python
Review of SQL
Create a Table
Mechanism for Inserting a Row
Update a Row
Delete a Row
Read a Table
Summary
Exercises
Chapter 5:​Embedded Python
Basic Mechanism
Plot a 2D Line
Plot Two 2D Lines
Plot Trigonometric Curves
Enter Data to Plot
2D Center of Mass Plot
Histograms
Importing a Picture
Summary
Exercise
Chapter 6:​Sockets
A Closer Look at Sockets
Basic Client-Server
Server-Client Pair to Send-Receive a File
Threaded Programs
Closing Down a Threaded Server
Chat Programs
Summary
Exercise
Appendix A:​Answers to Examples
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Index
About the Author
Philip Joyce
has 28 years of experience as a software engineer, working on control
of steel production, control of oil refineries, communications software
(pre-Internet), office products (server software), and computer control
of airports. He programs in Assembler, COBOL, Coral 66, C, and C++
with SQL. He served as a mentor to new graduates in the Ferranti
Company. He obtained an MSc in computational physics (including
augmented matrix techniques and Monte Carlo techniques using
Fortran) from Salford University in 1996. He is also a chartered
physicist and a member of the Institute of Physics (member of the
Higher Education Group).
About the Technical Reviewer
Swathi Sutrave
is a self-professed tech geek. She has
been a subject matter expert for several
different programming languages,
including Python, C, and SQL, for
corporations, startups, and universities.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
P. Joyce, C and Python Applications
https://doi.org/10.1007/978-1-4842-7774-4_1

1. Python Programming
Philip Joyce1
(1) Crewe, UK

This is the first of two chapters in which you’ll review both Python and C programming
languages. A basic understanding of computing and what programs are about is assumed
although no prior knowledge of either Python or C is needed.
In this chapter, we will start with the basics of Python. This will include how items used
in a program are stored in the computer, basic arithmetic formats, handling strings of
characters, reading in data that the user can enter on the command line, etc. Then we will
work up to file access on the computer, which will lead us up to industrial/commercial-level
computing by the end of the book.
If you don’t already have a Python development environment on your computer, you can
download it and the Development Kit, free of charge, from
www.python.org/downloads/. Another way you can access Python is by using Visual
Studio. Again, a version of this can be downloaded.

Definition of Variables
This section looks at the different types of store areas that are used in Python. We refer to
these store areas as “variables.” The different types can be numbers (integers or decimals),
characters, and different types of groups of these (strings, arrays, dictionaries, lists, or
tuples).
In these examples, you can go to the command line and enter “Python” which starts up
the Python environment and produces “>>>” as the prompt for you to enter Python code.
In Python, unlike C, you don’t define the variable as a specific type. The different types
are integer, floating point, character, string, etc. The type is assigned when you give the
variable a value. So try the following code:

>>> a1 = 51
>>> print(type(a1))
We get the output
<class 'int'>
>>>

Here we are defining a variable called “a1” and we are assigning the integer value 51 to
it.
We then call the function “print” with the parameter “type” and “a1” and we get the reply
“class ‘int’”. “type” means that we want to display whether the variable is an integer, floating
point, character, string, etc.
We can now exit the Python environment by typing “quit()”.
We will now perform the same function from a program.
Create a file called “typ1a.py”.
Then enter the following two lines of Python code:

a1=51
print(type(a1))

Now on the command line, enter “python typ1a.py”.


And you should get the output

<class 'int'>

which is the same as our first example.


This is just demonstrating the equivalence of the two methods.
Obviously, if you want to run a program with many lines of code and possibly run it many
times, then having the code in a file is more efficient.
We can demonstrate different data types being stored in the same variable using the
following code:

a1=51
print(type(a1))

a1=51.6
print(type(a1))

a1='51'
print(type(a1))

When we run this, we get

<class 'int'>
<class 'float'>
<class 'str'>

The 51 entered is an int. The 51.6 is a float (decimal) type, and ‘51’ is a string.
We can make the results a little clearer if we use print(“a1 is”, type(a1)).
So our program now reads

a1=51
print("a1 is",type(a1))

a1=51.6
print("a1 is",type(a1))

a1='51'
print("a1 is",type(a1))
and the output is

a1 is <class 'int'>
a1 is <class 'float'>
a1 is <class 'str'>

We can put a comment on our line of code by preceding it with the “#” character.

a1='51' #assign string containing 51 to variable a1


print("a1 is",type(a1)) # print the type assigned to a1

Some simple arithmetic operations are shown in the following.


The following code is held in the file “arith1.py”:

arith1a.py

Initialize the variables v1, v2, v3, and v4 with integer values.

v1= 2
v2 = 4
v3 = 7
v4 = 8

Add v1 to v2 and store the result in v5.

v5 = v1 + v2
print(v5)

The result is

You can combine the adding with the print as follows:

print(v1+v2)

Giving the same answer:

Now a subtraction:

v6 = v4 - v3
print(v6)
giving
1

Now a multiplication:
v7 = v4 * v3

print(v7)
giving
56
Now a division:

v8 = v4 / v1
print(v8)
giving
4.0

v10 = v3 % v2 # the % sign means show the remainder of the


division
print(v10)
gives
3

Raise by the power 2.

v11 = v2 ** 2
print(v11)
gives
16

Raise to the power held in variable v1.


Here v2 contains 4 and v1 contains 2.

v11 = v2 ** v1
print(v11)
gives
16

Show how Python obeys the rules of BODMAS (BIDMAS).


Here v2 contains 4, v1 contains 2, v3 contains 7, and v4 contains 8.

v11 = v1 + v2 * v4 - v3 # show BODMAS


print(v11)
gives
27

Show how Python obeys the normal algebra rules.

v11 = (v1 + v2) * (v4 - v3)


print(v11)
gives
6

Real (Float) Numbers


This type of number contains a decimal point. So, for the following assignments

V1 = 2
V2 = 3.5
V3 = 5.1
V4 = 6.75

we get

print(type(V1))
<class 'int'>
print(type(V2))
<class 'float'>
print(type(V3))
<class 'float'>
print(type(V4))
<class 'float'>

Characters
In Python, you can also assign characters to locations, for example:

c1 = 'a'
print(type(c1))
produces
<class 'str'>

which means that c1 is classed as a string.


Now that we know what different types of variables we can have, we will look at how we
use them.

Reading in Data
Now that we can display a message to the person running our program, we can ask them to
type in a character, then read the character, and print it to the screen. This section looks at
how the user can enter data to be read by the program.
If we type in the command

vara = input()

the computer waits for the user to type in data.


So if you now enter r5, the computer stores r5 in the variable vara.
You can check this by printing the contents of vara by typing

print(vara)

which prints

r5
We can make this more explicit by using

print("data typed in is:-", vara)


giving
data typed in is:-r5

You can also make the entry command clearer to the user by entering

varb=input(“enter some data to be stored in varb”)

Then, again we can explicitly print out the contents

print("data typed in is:-", varb)


giving
data typed in is:-r5

You have to use int(input) to enter an integer.


Otherwise, it is a string (one or more characters), for example:

n = int(input('Enter a number: '))


you enter 4
>>> print(type(n))
<class 'int'>

# Program to check input


# type in Python

num = input ("Enter number :")


print(num)
#You could enter 5 here and it would store 5 as a string and not
as a number
>>> print(num)
5
>>> print ("type of number", type(num))
type of number <class 'str'>
>>>

#entering a float number (type 'float' before the 'input'


command)
n = float(input('Enter a number: '))
Enter a number: 3.8
>>> print(type(n))
<class 'float'>
>>> print(n )
3.8

Now that we can enter data manually into the program, we will look at groups of data.
Arrays
An array is an area of store which contains a number of items. So from our previous section
on integers, we can have a number of integers defined together with the same label. Python
does not have a default type of array, although we have different types of array.
So we can have an array of integers called “firstintarr” with the numbers 2, 3, 5, 7, 11,
and 13 in it. Each of the entries is called an “element,” and the individual elements of the
array can be referenced using its position in the array. The position is called the “index.” The
elements in the array have to be of the same type. The type is shown at the beginning of the
array.
The array mechanism has to be imported into your program, as shown as follows:

from array import *


firstintarr = array('i', [2,3,5,7,11])

The ‘i’ in the definition of firstintarr means that the elements are integers.
And we can reference elements of the array using the index, for example:

v1 = firstintarr[3]
print(v1)

This outputs

We can also define floating point variables in an array by replacing the “i” by “f” in the
definition of the array.
So we can define

firstfloatarr = array( 'f', [0.2,4.3,21.9,7.7])

And we can now write

varfloat1 = firstfloatarr[1]
print(varfloat1)

This will store 4.3 into varfloat1.


The array mechanism has to be imported into your program.
So at the start of each program, you need to include the code

from array import *

Once we have our array, we can insert, delete, search, or update elements into the array.
Array is a container which can hold a fix number of items, and these items should be of
the same type. Most of the data structures make use of arrays to implement their
algorithms. The following are the important terms to understand the concept of array:
Insert
Delete (remove)
Search
Update
Append
Let’s review them now.

Inserting into an Array


The following code is in the file array3.py:

from array import *

myarr = array('i', [2,3,5,7,11])

myarr.insert(1,13) # this inserts 13 into position 1 of the array


(counting from 0)

for x in myarr:
print(x)

This outputs

2
13
3
5
7
11

Deleting (Removing) from an Array


The following code is in the source code file array4.py:
array4.py

from array import *

myarr = array('i', [2,3,5,7,11])

myarr.remove(2) # this removes the element containing 2 from the


array

for x in myarr:
print(x)

This outputs

3
5
7
11
Searching
The following code is in the file array5.py:

from array import *

myarr = array('i', [2,3,5,7,11])

print (myarr.index(3))#this finds the index of the array which


contains 3

This outputs

Updating an Array
The following code is in the file array6.py:
array6.py

from array import *

myarr = array('i', [2,3,5,7,11])

myarr[2] = 17) #this updates element 2 with 17

for x in myarr:
print(x)

This outputs

2
3
17
7
11

Appending to an Array
The following code is in the file array9a.py:
array9a.py

from array import *

myarr = array('i', [2,3,5,7,11])

for x in myarr:
print(x)

new = int(input("Enter an integer: "))


myarr.append(new)
print(myarr)
This outputs

2
3
5
7
11

Enter an integer: 19

array('i', [2, 3, 5, 7, 11, 19])

This section has shown the “array” use in Python.

Strings
Strings are similar to the character arrays we discussed in the previous section. They are
defined within quotation marks. These can be either single or double quotes. We can specify
parts of our defined string using the slice operator ([ ] and [:]). As with character arrays, we
can specify individual elements in the string using its position in the string (index) where
indexes start at 0.
We can concatenate two strings using “+” and repeat the string using “*”.
We cannot update elements of a string – they are immutable. This means that once they
are created, they cannot be amended.
The following code:

firststring = 'begin'
print(firststring)
gives
begin

The following code:

one = 1
two = 2
three = one + two
print(three)
#gives
3

The following code:

first = " first "


second= "second"
concat = first + " " + second
print(concat)
#gives
first second
print("concat: %s" % concat)
gives
concat: first second
The following code is in the file tst13a.py
secondstring = "second string"
print(secondstring.index("o")) #gives
3
print(secondstring.count("s")) # count the number of s characters
in string gives
2

print(secondstring[2:9]) # prints slice of string from 2 to 9


giving

cond st
print(secondstring[2:9:1]) # The general form is
[start:stop:step] giving

cond st
print(secondstring[::-1]) # Reverses the string giving

gnirts dnoces

splitup = secondstring.split(" ")


print(splitup) #gives
['second', 'string']
Strings are immutable, so if we tried

second= "second"
second[0]="q"

we get
Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'str' object does not support item assignment


indicating that we tried to update something (a string in this case) which is immutable.

Lists
Lists are similar to arrays and strings, in that you define a number of elements, which can be
specified individually using the index. With lists, however, the elements can be of different
types, for example, a character, an integer, and a float.
The following code is in the file alist7.py:

firstlist = ['k', 97 ,56.42, 64.08, 'bernard']


We specify the elements within square brackets.
We can then access individual elements in the list using the index (starting from 0), for
example:

print(firstlist[0])
gives
k
print(firstlist[1:3])
gives
[97, 56.42]

We can amend an element in a list.

firstlist[3] = 'plj'
print(firstlist)
giving
['k', 97, 56.42, 'plj', 'bernard']

We can delete an element from a list.

del firstlist[3]
print(firstlist)
giving
['k', 97, 56.42, 'bernard']

We can append an element to the list.

firstlist.append(453.769)
print(firstlist)
giving
['k', 97, 56.42, 'bernard', 453.769]

Reading Entries in a List


The following code is held in the file alist1a.py:
alist1a.py

list1 = ['first', 'second', 'third']


list2 = [1, 2, 3, 4, 5 ]

print ("list1: ", list1)


print ("list1[0]: ", list1[0])
print ("list2: ", list2)
print ("list2[3]: ", list2[3])
print ("list2[:3]: ", list2[:3])
print ("list2[2:]: ", list2[2:])
print ("list2[1:3]: ", list2[1:3])

This outputs
list1: ['first', 'second', 'third']
list1[0]: first
list2: [1, 2, 3, 4, 5]
list2[3]: 4
list2[:3]: [1, 2, 3]
list2[2:]: [3, 4, 5]
list2[1:3]: [2, 3]

Updating a List
The following code is held in the file alist2a.py:

alist2a.py

list1 = [1, 2, 3, 4, 5 ]

print ("list1: ", list1)

list1[1] = 26 #update the second item (counting from zero)

print ("updated list1: ", list1)

This outputs

list1: [1, 2, 3, 4, 5]
updated list1: [1, 26, 3, 4, 5]

Deleting an Element from List


The following code is held in the file alist3a.py:

alist3a.py
list1 = [1,2,3,4,5,6]
print (list1)
del list1[4]
print ("Updated list1 : ", list1)

This outputs

[1, 2, 3, 4, 5, 6]
Updated list1 : [1, 2, 3, 4, 6]

Appending to a List
The following code is held in the file alist4aa.py:

alist4aa.py
list2 = [10,11,12,13,14,15]
print (list2)
new = int(input("Enter an integer: "))
list2.append(new)
print(list2)
This outputs (if you enter 489)

[10, 11, 12, 13, 14, 15]

Enter an integer: 489

[10, 11, 12, 13, 14, 15, 489]

This has shown the use of lists.

Dictionaries
Dictionaries contain a list of items where one item acts as a key to the next. The list is
unordered and can be amended. The key-value relationships are unique. Dictionaries are
mutable.

Creating a Dictionary
In the first example, we create an empty dictionary. In the second, we have entries.

firstdict = {}

oder

firstdict ={'1':'first','two':'second','my3':'3rd'}

Appending to a Dictionary
The following code is held in the file adict1a.py:

adict1a.py
#create the dictionary
adict1 = {'1':'first','two':'second','my3':'3rd'}

print (adict1)

print (adict1['two']) # in the dictionary 'two' is the key to


'second'

adict1[4] = 'four' # we want to add another value called 'four'


whose key is 4

print (adict1)

print (len(adict1)) #this will print the number of key-value


pairs

This outputs
{'1': 'first', 'two': 'second', 'my3': '3rd'}
second
{'1': 'first', 'two': 'second', 'my3': '3rd', 4: 'four'}
4
If we want to add value whose key is dinsdale, then we specify it as ‘dinsdale’.
So

adict1['dinsdale'] = 'doug'
print (adict1)

outputs

{'1': 'first', 'two': 'second', 'my3': '3rd', 4: 'four',


'dinsdale': 'doug'}

Amending a Dictionary
The following code is held in the file adict2a.py.
This amends the value whose key is ‘two’ to be '2nd'.

adict2a.py
adict1 = {'1':'first','two':'second','my3':'3rd'}

adict1['two'] = '2nd'

print(adict1)

This outputs

{'1': 'first', 'two': '2nd', 'my3': '3rd'}

Deleting from a Dictionary


The following code is held in the file adict3a.py:

adict3a.py
adict1 = {'1':'first','two':'second','my3':'3rd'}
print(adict1)
del adict1['two'] #this deletes the key-value pair whose key is
'two'
print(adict1)

This outputs

{'1': 'first', 'two': 'second', 'my3': '3rd'}


{'1': 'first', 'my3': '3rd'}

Searching Through a Dictionary


We want to search a dictionary to see if a specific key is contained in it. In this case, we want
to see if ‘a’ and ‘c’ are keys in the dictionary.
In Python

>>> my_dict = {'a' : 'one', 'b' : 'two'}

>>> 'a' in my_dict


TRUE
>>> 'c' in my_dict
FALSE

The following code is held in the file adict5aa.py:

adict5aa.py
print("Enter key to be tested: ")
testkey = input()
my_dict = {'a' : 'one', 'b' : 'two'}
print (my_dict.get(testkey, "none"))

This outputs (if you enter “a” when asked for a key)
Enter key to be tested:
a
one
or outputs (if you enter “x” when asked for a key)
Enter key to be tested:
x
none
We have seen what dictionaries can do. We now look at tuples.

Tuples
A tuple contains items which are immutable. The elements of a tuple can be separated by
commas within brackets or individual quoted elements separated by commas. They are
accessed in a similar way to arrays, whereby the elements are numbered from 0. In this
section, we will look at creating, concatenating, reading, deleting, and searching through
tuples.
For example, define two tuples called firsttup and secondttup:

firsttup = ('a', 'b', 'c', 1, 2, 3)


secondtup = “a”, “b”, 10, 25

The following code refers to the third element of firsttup:

firsttup[2]
gives
c

The following code refers to the third element of firsttup:

firsttup[3]
gives
1
secondtup = "a", "b", 10, 25
The following code refers to the second element of secondtup:

secondtup[1]
gives
b

The following code refers to the third element of secondtup:

secondtup[2]
gives
10

We can also use negative indices to select from the end and work backward, for example,

secondtup[-1]

which gives

25
secondtup[-2]

which gives

10

Tuples cannot be amended.


So if we had

firsttup = ('a', 'b' 'c', 1, 2, 3)


firsttup[3] = 9

we would get

File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment

Creating a Tuple
# An empty tuple
empty_tuple = ()
print (empty_tuple)
()

# Creating non-empty tuples


# One way of creation
tup = 'first', 'second'
print(tup)
('first', 'second')

# Another for doing the same


tup = ('first', 'second')
print(tup)
('first', 'second')

Concatenating Two Tuples


# Code for concatenating 2 tuples

tuple1 = (0, 1, 2, 3)
tuple2 = ('first', 'second')

# Concatenating above two


print(tuple1 + tuple2)
(0, 1, 2, 3, 'first', 'second')

Creating Nested Tuples


# Code for creating nested tuples

tuple1 = (0, 1, 2, 3)
tuple2 = ('first', 'second')
tuple3 = (tuple1, tuple2)
print(tuple3)
gives
((0, 1, 2, 3), ('first', 'second'))

Creating Repeated Tuples


# Code to create a tuple with repetition

tuple3 = ('first',)*3
print(tuple3)
gives
('first', 'first', 'first')

Converting a List or a String into a Tuple


# Code for converting a list and a string into a tuple

list1 = [0, 1, 2]
print(tuple(list1))
(0, 1, 2)
print(tuple('first')) # string 'first'
('f', 'i', 'r', 's', 't')

Creating Single-Element Tuple


# Creating tuple with single element (note that we still require
the comma)
t=(1,)
print(t)
gives
(1,)

Reading Tuple
# Reading from start (index starts at zero)
tup1=(2,3,4,5,6,7)
tup[3]
gives
5

# Reading from end (index starts at -1)


tup1[-1]
gives
7

Searching Within a Tuple


# Search
tup1=(2,3,4,5,6,7)
print (6 in tup1) # this tests if 6 is contained in tup1
gives
True
print (9 in tup1)
gives
False

Deleting a Tuple
# Deleting a complete Tuple
del tup1
print(tup1)
gives

NameError: name 'tup1' is not defined

Using Tuple to Create Variables


# define our tuple as
aTuple = (10, 20, 30, 40)
# Now we can assign each of its elements to separate variables
a, b, c, d = aTuple
print(a)
gives
10
print(b)
gives
20
print(c)
gives
30
print(d)
gives
40

We have covered definitions and uses of different types of variables in this section. We
will now look at the use of “if” statements.

If Then Else
When a decision has to be made in your program to either do one operation or the other, we
use if statements.
These are fairly straightforward. Basically, we say

if (something is true)
Perform a task

This is the basic form of if.


We can extend this to say

if (a condition is true)
Perform a task
else if it does not satisfy the above condition
Perform a different task

Here is some Python code to demonstrate this:

number = 5
if number > 3:
print('greater than 3')

number = 5
if number > 3:
print('greater than 3')
else:
print('not greater than 3')
Type in this code into a program and run it. It should come as no surprise that the output
is

greater than 3

You could modify the program so that you input the number to be tested, but don’t forget
that for this code you need number = int(input (“Enter number :”)) to enter a number.
This section has shown the importance of “if” statements in programming. Now we will
look at loops.

Loops (For and While)


When we were doing many calculations in a program, it could be a bit of a chore to do a
similar thing with, say, ten numbers. We could have done it by repeating similar code ten
times. We can make this a bit simpler by writing one piece of code but then looping round
the same piece of code ten times. This is called a “for loop.” We will also look at “while”
loops.

For Loops
Here is an example of how a for loop can help us.
The statement is

'for x in variable
Carry out some code'

So if we have a variable as the following


forloopvar1 = [20, 13, 56, 9]
we can say

for x in forloopvar1: # go through forloop1 and place each


element in x
print(x) #this is the only instruction within the loop

outputs

20
13
56
9

The “range” instruction in Python has the general format


range(start, stop, step)
where
“start” is the start value of the index. Default is 0.
“stop” is 1 less than the last index to be used.
“step” is by how much the index is incremented. Default is 1.
Here is an example using the “range” instruction.
The program goes round the for loop starting with variables number and total set to 1.
Within the loop, it multiplies the current value of the number by the running total. Then
it adds 1 to the number. So it is working out 1*2*3*4*5*6*7*8*9*10 or “10 factorial” (10!).

number = 1
total = 1
for x in range(10): ): #so here start is 0 (default), stop is 10-
1, and step is 1
total = total * number
number = number + 1
print(total)

This outputs

3628800

which you can check with your scientific calculator is 10 factorial.

for x in range(3, 6): # starts with 3 and ends with 6-1


print(x)

This outputs

3
4
5

We can also have a list of values instead of a range, as shown in the next program.
This goes through the values and finds the index position of the value 46. We can see that
46 is in position 9 (counting from 0) .

forloopvar1 = [20, 13, 56, 9, 32, 19, 87, 51, 70, 46, 56]
count = 0
for x in forloopvar1:
if x == 46:
break
count = count + 1
print(count)

This outputs

While Loops
The logic of “while” loops is similar to our for loops .
Here, we say

'while x is true
Carry out some code'
So we could have the following code which keeps adding 1 to count until count is no
longer less than 10. Within the loop, the user is asked to enter integers. These are added to a
total which is printed out at the end of the loop.

total = 0;
number = 0
# while loop goes round 10 times
while number < 10 :

# ask the user to enter the integer number


n = int(input('Enter a number: '))

total = total + n
number = number + 1
print('Total Sum is = ', total)

So if the user enters the number shown in the following, we get the total:

Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
Enter a number: 6
Enter a number: 7
Enter a number: 8
Enter a number: 9
Enter a number: 10
Total Sum is = 55

We have seen the importance of loops in this section. Our next section looks at switches.

Switches
In C programming, there is an instruction used widely called “switch.” However, because
there is no switch statement in Python, this section will demonstrate some code that can be
included into your programs to perform the same function.
A switch jumps to a piece of code depending on the value of the variable it receives. For
instance, if you had to perform different code for people in their 30s to that for people in
their 40s and different to people in their 50s, we could have the following code. Here we
have the value in “option” which determines which code we jump to.
The code for this function is in the file aswitch3.py:

aswitch3.py
def switch(option):
if option == 30:
print("Code for people in their 30s")
elif option == 40:
print("Code for people in their 40s")

elif option == 50:

print("Code for people in their 50s")

else:
print("Incorrect option")
#main code in the program where you enter 30,40 or 50 and the
function 'switch' is called which uses the appropriate number as
shown.
optionentered = int(input("enter your option (30, 40 or 50 : )
"))
switch(optionentered)
running this program and entering '50' gives
enter your option : 50
Code for people in their 50s
This section has shown how to perform a switch in Python. We now move onto an
important library of functions in Python. This is called “numpy.”

Arithmetic Operations Using Numpy


Numpy is a library of mathematical functions that can be included into your Python
program. It is useful in manipulating arrays, reading text files, and working with
mathematical formulas. Numpy can be installed in various ways. One way is using “pip” from
the command line as shown as follows:

pip install numpy

It is particularly useful in manipulating matrices (or arrays with extra dimensions). The
arrays we have looked at so far are one-dimensional arrays. In this section, we will look at
arrays with more dimensions. A one-dimensional array can also be called a “rank 1 array.”

onedarray = array('i', [10,20,30,40,50])

We import numpy into our program using “import numpy”, and we assign a link for our
program. Here we define the link as “np” so the full line of code is

import numpy as np

The numpy function “shape” returns the dimensions of the array. So if your array was
defined as

b = np.array([[1,2,3],[4,5,6]])

then the array would be a 2x3 matrix (two rows and three columns) as shown as follows:

[[1 2 3]
[4 5 6]]
So if you now type

print(b.shape)

you would get

(2, 3)

as the shape.
The code for this function is in the file numpy1.py:

import numpy as np

a = np.array([1, 2, 3]) # Create a rank 1 array


print(type(a)) # Prints "<class 'numpy.ndarray'>"
print(a.shape) # Prints "(3,)"
print(a[0], a[1], a[2]) # Prints "1 2 3"
a[0] = 5 # Change an element of the array
print(a) # Prints "[5, 2, 3]"

b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array

#1 2 3
#4 5 6
# reference elements counting from 0
# so b[1, 2] is row 1 (2nd row) column 2 (3rd column)
#so if you print b[1, 2] you get 6
print("b[1, 2] follows")
print(b[1, 2])

print(b.shape) # Prints "(2, 3)" 2 rows 3


columns
print(b[0, 0], b[0, 1], b[0, 2]) # Prints "1 2 3"
print(b[1, 0], b[1, 1], b[1, 2]) # Prints "4 5 6"
print(b[0, 0], b[0, 1], b[1, 0]) # Prints "1 2 4"

The normal mathematical representation of a matrix is as shown as follows:

This is what we have defined in the preceding code using the following line of code:

b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array

Matrix arithmetic can be understood by looking at real-life examples. The following are
tables of three people working for a computer company. The first table shows how many
laptops and how many printers each person sells in a month.
In Store Sale

Person Laptops Printers


Joe 4 5
Mary 6 7
Jen 7 9

The next table shows how many laptops and printers each person has sold online.
Online Sale

Person Laptops Printers


Joe 6 22
Mary 21 24
Jen 41 17

These tables can be represented by matrices as shown in the following. We add each
term in the first matrix to the corresponding term in the second matrix to give the totals
shown in the third matrix.

The next table shows the total of laptops and printers sold by each person:
Total/Overall Sale

Person Laptops Printers


Joe 10 27
Mary 27 31
Jen 48 26

If each person doubles their total sales the following month, we can just multiply their
current sales total by 2 as shown as follows:

We now look at their totals for the first month and have another table containing the cost of
a laptop and the cost of a printer.
Total Sales
Person Laptops Printers Cost/Item list with
cost
Joe 10 27 Laptop 200
Mary 27 31 Printer 25
Jen 48 26
We can work out how much money each person makes for the company my multiplying
their total number of sales of a laptop by its cost. Then we multiply their total number of
sales of printers by its cost and then add these two together. The table and the
corresponding matrix representations of this are shown as follows:

Sales Cost
Joe 10x200 + 27x25 = 2975
Mary 27x200 + 31x25 = 3875
Jen 48x200 + 26x25 = 4775

There is a rule when multiplying matrices. The number of columns in the first matrix has
to be equal to the number of rows of the second matrix.
So if we say that a matrix is 2x3 (two rows and three columns), then it can multiply a 3x2
or a 3x3 or a 3.4, etc. matrix. It cannot multiply a 2x3 or 2x4 or 4x2 or 4x3, etc.

In the multiplication in the preceding diagram, we see it is (3x2) x (2x1) producing a (3x1)
matrix.

Numpy Calculations
Listings 1-1 through 1-5 are some programs to show basic numpy calculations with
matrices.
Add two 2x2 matrices.

import numpy as np

a = np.array(([3,1],[6,4]))

b = np.array(([1,8],[4,2]))

c = a + b
print('matrix a is')
print(a)
print('matrix b is')
print(b)
print('matrix c is')
print(c)
Listing 1-1 numpmat.py
This outputs

matrix a is
[[3 1]
[6 4]]
matrix b is
[[1 8]
[4 2]]
matrix c is
[[ 4 9]
[10 6]]

Add a 2x3 matrix to another 2x3 matrix.

import numpy as np

a = np.array(([1,2,3],[4,5,6]))

b = np.array(([3,2,1],[6,5,4]))

d = a + b

c = 2*a

print('matrix a is')
print(a)
print('matrix b is')
print(b)
print('matrix d is')
print(d)
print('matrix c is')
print(c)
Listing 1-2 numpmat2.py

This outputs

matrix a is
[[1 2 3]
[4 5 6]]
matrix b is
[[3 2 1]
[6 5 4]]
matrix d is
[[ 4 4 4]
[10 10 10]]
matrix c is
[[ 2 4 6]
[ 8 10 12]]
Add a 2x2 matrix to a 2x2 matrix both floating point.

import numpy as np

a = np.array(([3.1,1.2],[6.3,4.5]))

b = np.array(([1.3,8.6],[4.9,2.8]))

c = a + b

print('matrix a is')
print(a)
print('matrix b is')
print(b)
print('matrix c is')
print(c)
Listing 1-3 numpmat3.py

This outputs

matrix a is
[[3.1 1.2]
[6.3 4.5]]
matrix b is
[[1.3 8.6]
[4.9 2.8]]
matrix c is
[[ 4.4 9.8]
[11.2 7.3]]

Multiply a 3x2 matrix by a 2x1 matrix.

import numpy as np

a = np.array(([1,2],[4,5],[6,8]))

b = np.array(([3],[6]))

c = np.matmul(a,b) #matmul is the numpy function for multiplying


matrices

print('matrix a is')
print(a)
print('matrix b is')
print(b)
print('matrix c is')
print(c)
Listing 1-4 numpmat4.py
This outputs

matrix a is
[[1 2]
[4 5]
[6 8]]
matrix b is
[[3]
[6]]
matrix c is
[[15]
[42]
[66]]

Multiply a 3x2 matrix by a 2x3 matrix.


If you did this manually with pen and paper, this is how you would do it:

Note the way you do the multiplication by hand, 1st row x 1st column, 1st row x 2nd
column, 1st row x 3rd column, then 2nd row, and then 3rd row. Of course, if you use
numpy’s matmul function, it is all done for you.

import numpy as np

a = np.array(([1,2],[3,4],[5,6]))

b = np.array(([7,8,9],[10,11,12]))

c = np.matmul(a,b)

print('matrix a is')
print(a)
print('matrix b is')
print(b)
print('matrix c is')
print(c)
Listing 1-5 numpmat5.py
This outputs

matrix a is
[[1 2]
[3 4]
[5 6]]
matrix b is
[[ 7 8 9]
[10 11 12]]
matrix c is
[[ 27 30 33]
[ 61 68 75]
[ 95 106 117]]

This section has explored the important numpy mathematical functions in Python.

Mathematical Graph Functions


In a similar way that we included the numpy library into our programs, we can include
graph plotting libraries called “matplotlib.pyplot” so we can access the graph functions
library with the code

import matplotlib.pyplot as plt

In our program, this makes plt our pointer to matplotlib.pyplot.


You can install matplotlib using the “pip” instruction

pip install matplotlib

The program here is going to plot a graph of the marks that people got in an
examination.
The code for this function is in the file mp1a.py:

mp1a.py
import matplotlib.pyplot as plt
# x values:
marks = list(range(0, 100, 10)) #marks (x values) divided into
equal values up to 100
print(marks) # write the values calculated by the previous
instruction

This produces
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
# y values:
people = [4, 7, 9, 17, 22, 25, 28, 18, 6, 2]
# label the axes
plt.xlabel('marks')
plt.ylabel('people')
plt.plot(marks, people)
plt.show()
and outputs

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

These plot the graph shown in Figure 1-1.

Figure 1-1 Example of plotting (x,y) points

We see from the graph that most people got marks between about 30 and 70, which is
what you would expect. A few got low marks and only a few got high marks.
The next program, mp2aa.py, plots two graphs on the same axes. Here we plot
examination marks gained by females and those gained by males. We plot females as one
color and males as another.
The code for this function is in the file mp2aa.py:
Another random document with
no related content on Scribd:
THE ASCENT OF CLOUDY
MOUNTAIN, NEW GUINEA.
BY CAPTAIN CYPRIAN BRIDGE, R.N.
The Rev. James Chalmers—known all along the southern coast of
New Guinea, throughout the original British protectorate in fact, as
‘Ta-ma-té’—will always be held responsible for the first ascent of
Cloudy Mountain. Taking advantage of the presence of Commodore
Erskine’s squadron at South Cape, he instilled into the minds of
some of the officers a desire to get to the summit. With the
persuasive eloquence of which his many friends know him to be a
master, he expatiated on the honourable nature of the enterprise,
dwelling on the fact that no white man had as yet attempted it. It is
not wonderful that he excited considerable enthusiasm; nor is it,
perhaps, wonderful that, as the climate is a moist one and as the
warm tropical season was well advanced, some of the enthusiasm
had greatly decreased when the day for starting arrived. It was
interesting to observe how many pressing engagements happened
to prevent some of the more eager aspirants for alpine honours from
attempting Cloudy Mountain, when the expedition was definitely
determined on. One had arrears of correspondence to make up;
another had promised to join a friend in a shooting excursion; whilst
a third wisely took into consideration the fact of his being no longer
young. It would have been well for at least one of the party that
afterwards made the ascent if he also had remembered that the
middle age is not the best time of life at which to try climbing almost
precipitous elevations through trackless forests in the atmosphere of
a hothouse.
On Friday, the 21st of November, the union-jack had been hoisted,
and the British protectorate over the southern coast of New Guinea
had been proclaimed with imposing ceremonies on Stacey Island,
South Cape. Time, which is usually deficient when naval officers visit
places from which interesting excursions can be made, did not allow
of the start for the summit of the mountain being deferred till the
following day. It was compulsory to get away as soon as possible
after the ceremony. Mr Chalmers, whom no exertion can tire, made
arrangements for collecting a body of native carriers. He advised
each excursionist to take a change of clothes, a blanket, and enough
food for twenty-four hours. By about eleven a.m. there were
assembled at the village of Hanod, at the head of Bertha Lagoon, the
following: Captain C. Bridge; Lieutenants R. N. Ommanney and M.
Thomson; R. Millist, captain’s steward, of H.M.S. Espiègle;
Commander W. H. Henderson; Lieutenant T. C. Fenton; Mr
Glaysher, engineer; Mr T. W. Stirling, midshipman; four blue-jackets,
and one R.M. artilleryman of H.M.S. Nelson; Lieutenant John L.
Marx, commanding H.M.S. Swinger; Sub-lieutenant A. Pearson, of
H.M.S. Dart; and Mr Stuart of Sydney, New South Wales.
The tribes inhabiting the country about South Cape are of the dark
race, and were cannibals, until their recent renunciation of the
practice, under the influence of the missionaries. They are a much
merrier and more talkative people than the non-cannibal light-
coloured race, which dwells farther to the westward. The work of
selecting carriers proceeded with much vociferation; the carriers
themselves, their friends, and all the ladies of the village—in this part
of New Guinea the influence of woman is great—considering it
necessary to address lengthy speeches in a loud tone to the white
strangers. That not one of these understood a sentence of what was
being said to them, by no means discouraged the eloquence of the
villagers. ‘Ta-ma-té’s’ extraordinary faculty of influencing the natives
in a cheery way soon introduced order into what looked very much
like hopeless confusion. With the aid of the teacher Biga, who could
speak both the Motu and the South Cape languages, he chose a
sufficient number of carriers, appointed as guide an elderly native
who professed to have been to the top of the mountain, and set
about distributing the loads to be carried. The wages agreed upon
were a small ‘trade’ knife and three sticks of tobacco, value in all
about eightpence per man. Some biscuit and a little extra tobacco
were given afterwards, to keep up the spirits of the party during the
journey.
Though not much troubled with clothes, our new friends were, at all
events relatively to the western tribes, decently clad. The women
wear a becoming petticoat of leaves and fibre, coming down to the
knee. They often put on several of these garments one above the
other, the effect being much the same as that of a capacious
crinoline. In New Guinea, the women are tattooed from forehead to
ankles, occasionally in very elaborate patterns. The name Papua
given to New Guinea is said to mean ‘woolly-headed,’ and the
appellation has been well bestowed. The men of both races ‘tease’
their hair out into a prodigious mop. So do the girls. Married women
cut theirs short. The bushy wig which many of the natives of this
region seem to be wearing decidedly improves their appearance.
When their hair is cut short, the similarity of their features to those of
African negroes becomes more obvious. They are not tall; but they
have well-shaped limbs, and many of them are sturdy fellows. The
usual weight for a native carrier is twenty-five pounds. But, as the
number of travellers likely to ascend Cloudy Mountain had greatly
fallen off, we found ourselves with more carriers than we could
supply loads for. The result was that some at all events had very light
burdens. One man, for instance, carried an empty tin case for
specimens of plants; another, a few sheets of blotting-paper between
two thin pieces of board provided for the same purpose.
When officers land in the South Sea Islands, nicety of dress is not
much attended to. A helmet or straw-hat, a shirt, a pair of flannel
trousers, and boots or shoes more remarkable for utility than
elegance, are found quite sufficient. In a moist hot climate, the less
clothing the better; and in countries in which there are no roads, not
many paths, and where, as a rule, progress is only possible through
thick forest and over muddy ground, the fewer garments worn, the
fewer there are to be cleaned at the end of an excursion.
For the first half-hour after leaving the village on Bertha Lagoon, the
way ran across a mangrove swamp of soft mud, interspersed with
pools of black-looking water, and studded with the peculiar and
aggravating knobs that the roots of the mangrove bush delight to
form. It was worth while to note the care with which most of the
excursionists began to pick their way; some even evinced a desire
not to wet their boots. To keep the nether garments clean was clearly
in general considered an object worth trying for. But after a few rapid
and involuntary descents from slippery logs, seductively resembling
bridges, placed across the most forbidding sloughs, a determination
to push on straight and discontinue efforts to circumvent puddles,
became universally apparent. When the swamp had been left behind
some distance, our carriers, who belonged to a humorous race,
kindly informed us, through the interpreters—their faces beaming
with delight as the information was imparted—that they could have
taken us by a route which would have avoided it altogether. This
statement was proved to be true on our return, as some of the party
escaped traversing the swamp a second time by taking a path which
led to the westward of it, and others descended in canoes the lower
part of a river that discharges itself into the lagoon. When asked why
they had not let us know of the existence of a more agreeable road,
our native friends made the unanswerable reply, that none of our
party had suggested to them any wish to avoid the mangroves.
For an hour we had now to move along through a well-timbered
country, occasionally passing small cultivated patches, where yams,
bananas, and taro were grown. The path in most places was not
difficult; but it lost itself from time to time in a stream of clear water,
whose frequent rapids showed that we had begun to ascend.
Repeated wadings had at all events the advantage of removing all
traces of our passage across the swamp. The scenery was highly
picturesque, especially at some of the reaches of the little river. The
pebbly banks were crowned with a rich vegetation; the number and
variety of the trees and shrubs—amongst which the wild plantain,
palms of various kinds, and the pandanus were conspicuous—were
at least as great as in most tropical lands. Glimpses of lofty wooded
heights were frequently obtained. A few tuneful birds were heard,
and we saw some azure-hued kingfishers. But, as a rule, particularly
as the lower country was left, the music of the woods was
monopolised by screeching white cockatoos. The scene was greatly
enlivened by the number and beauty of the butterflies which flitted
amongst the bushes. One of our party had provided himself with a
net; and, though occasional bad shots at some peculiarly nimble
lepidoptera were made, his ‘bag’ turned out a very good one. On a
broad stretch of gravel and pebbles by the side of the water, towards
one o’clock, a halt was made for luncheon. The spot was fairly
shady, and the heat, considering our position, was not excessive. A
biscuit or two was handed to the carriers, and—what delighted them
still more—a few small fragments of tobacco. The New Guinea
fashion of smoking is peculiar. The pipe is a bamboo tube about two
feet long and two inches in diameter, with one end closed. Near this
end, a small hole like the mouth-hole of a flute is made, and in it a
piece of leaf, twisted into a pointed cup or ‘horn’ containing a little
tobacco, is inserted. Applying a light to the tobacco, the smoker
sucks vigorously at the open end of the tube; when this is filled with
smoke, he puts his lips to the small hole and takes several ‘draws,’
after which the tobacco has to be replenished and the pipe relighted.
Politeness flourishes throughout the south-western Pacific Isles;
even the naked cannibals of New Britain exhibit to friends that true
courtesy which consists in doing as one would be done by. The New
Guinean who lights the pipe, when he has filled it with smoke,
usually hands it to some one else to have the first whiff. On the
present occasion, the pipe was offered first to the white man, to
whom, so long as he behaves to them becomingly, Pacific Island
natives are almost invariably polite.
The lateness of our start rendered any but a short halt impossible, so
the repast was a hasty one. The increasing steepness showed that
we had begun the ascent in earnest. A path there certainly was, but,
as a rule, it was not easily discerned amid the thick growth of tropical
shrubs. As far as the density of the forest would allow us to examine
the country to any distance, we appeared to be mounting the ridge of
a spur of the main mountain mass. A deep valley lay on either hand,
at the bottom of which we could hear the rumbling of a stream. The
number of cockatoos increased as we got higher, and some were
shot for culinary purposes subsequently. We saw some handsome
pigeons, and at least one small flight of the large beaked bird called
toucan, though probably it differs from the South American bird to
which that name rightly belongs. Ignorance of ornithology made
some of us doubt if it were the hornbill or buceros, one of which we
heard afterwards overhead puffing like a locomotive, on our way
down. The profusion of ferns, palms, orchids, and flowering shrubs
was striking. The ascent was really a climb, as the hands had to be
used nearly as much as the feet. At one or two points, the face of a
steep water-worn rock had to be scaled. Frequent short halts
became absolutely necessary; and the head of our long and
straggling line of white men and carriers usually resumed the work of
ascending as the rear reached the point at which the former had
rested. When the afternoon had well advanced—the only watch in
the company having been broken at a specially stiff bit of climbing,
the exact time could not be told—we had reached a comparatively
open space, which our guide declared to be the summit. The
impossibility of this being so was demonstrated by the appearance of
the true summit, of which a temporary break in the clouds usually
hiding it, now permitted a glimpse. Our guide thereupon asserted
that it was the only summit which he knew; that no native of the
country had ever attempted to mount higher; and that, anyhow, no
path was to be found farther on. These assertions were probably
true. The correctness at least of the last was soon established
beyond the chance of doubt; subsequent progress disclosed the fact
that the path, which for the last hour had been scarcely visible by the
naked eye, ceased altogether.
When the rear of the line came up, these questions were being
debated: Should arrangements be made for camping for the night on
the spot then occupied? or should a further attempt to reach the
summit be made? Lieutenant Fenton and Mr Stirling settled the
matter as far as they were concerned by pushing on with the
determination of crowning the mountain by themselves, if no one
else cared to follow them. ‘Ta-ma-té’ reviewed the situation in a short
and fitting address, which closed with a reminder that not even a
native, it was now proved, had ever got to the top. This was enough
to prevent any flagging of the enthusiasm necessary to carry the
travellers higher. Even the oldest member of the party, who had
already begun to doubt the wisdom of joining in such an enterprise
by one who had years ago qualified as a member of the ‘senior’
United Service Club, unhesitatingly gave his vote for a continuance
of the ascent and for the conquest of the virgin height.
It had been held that the previous part of the journey had afforded
instances of some rather pretty climbing. It was child’s play to what
followed. Path there was none; the vegetation became if possible
denser; and the only practicable line of advance ran along the edge
of a ridge nearly as ‘sharp and perilous’ as the bridge leading to the
Mohammedan Paradise. This ridge was so steep that, thickly clothed
as it was with trees, shrubs, and creepers, it was frequently
impossible to advance without pulling one’s self up by one’s hands.
In selecting something to lay hold of to effect this, great care had to
be exercised. The ‘lawyer’ palm, which sends out trailing shoots
admirably adapted to the purpose of tripping up the unwary, is
studded with thorns in the very part where it is most natural for a
climber requiring its aid to seize it. In the most difficult places, there
flourished an especially exasperating variety of pandanus. This tree
has many uses, and in this instance it seemed to have been
purposely placed just where it might best help the ascending
traveller. The pyramid of stalks or aërial roots, which unite several
feet above the surface of the soil to form the trunk, always looked so
inviting to those in want of a ‘lift,’ that no experience was sufficient to
prevent repeated recourse to its assistance. Unhappily, each stalk of
a diameter convenient for grasping by the hand was studded with
sharp prickles, almost invariably hidden by a coating of deliciously
soft moss. It was not until the weight of the body was thrown on the
hand encircling one of these deceptive stalks, that the situation was
fully realised. In the absence of a path, it was of some advantage to
keep amongst the rearward members of the party. A few persons in
front quickly made a trail, which was not very often lost, particularly
when the leaders had had the forethought to break branches off
adjacent shrubs, so that the fractures served as guideposts to those
following. The great steepness of the sides of the spur on the ridge
of which was the line of advance, rendered it most desirable not to
stray from the path, as serious injury, if not complete destruction,
would in such case have been inevitable. Sometimes a climber
dislodged a stone that went crashing amongst the thick growth with
which the precipitous sides were covered, downwards for hundreds
of feet, till the noise of its fall died away in the distance.
Clouds were collecting about the mountain, and the sun was about
to set, when at length the whole party stood upon the summit. There
was a comparatively level space, perhaps thirty feet square, thickly
overgrown with trees and shrubs. The moist heat on the way up had
been great enough to render every one’s clothes dripping wet, even
had not occasional thick mists drenched our scanty garments. It was
so late, that no time was to be lost in making arrangements for
spending the night on the top of the mountain. Tomahawks were
brought into requisition, and several trees were felled and laid one
on another along two sides of a small square, thus forming a low
wall, under shelter of which a bivouac might be formed. Many
showers had fallen on the higher parts of the mountain during the
day, and so general was the humidity that it was difficult to light a
fire. When this was at length accomplished, a meal was prepared,
and soon despatched. The kindling of a fire incited the native carriers
to do the same on every available spot, amongst others at a point
dead to windward of the bivouac, to the grievous annoyance of the
travellers’ eyes, till a more suitable place was substituted.
With leaves and twigs plentifully strewed under the lee of the felled
logs, the white men had managed to get themselves ‘littered down’
for the night. The small rain which had been falling nearly ever since
the summit had been reached, turned into sharp showers, and
showed symptoms of continuing. The supply of water was found to
be very short, as, trusting to the statements of the natives before it
was ascertained that their knowledge of the country did not extend
beyond the termination of the path, it was thought unnecessary to
carry a large supply to the end of the journey, where, it was
anticipated, it would be found in abundance. The prospect for the
night was not cheering. Those who had brought a change of clothing
now put it on in place of the dripping garments hitherto worn, and
rolling themselves in their blankets, lay down to sleep, or to try to
sleep. Many things conspired to prevent slumber. It was soon
discovered that some of the party had no blanket. Mr Chalmers at
once set himself to rectify this, and did so in characteristic fashion.
He borrowed a knife, and, cutting his own blanket in two, insisted
upon its being accepted by a companion who had none. It is related
of one of the several Saints Martin—on board men-of-war, we cannot
be expected to be very familiar with the hagiology, so it will be well
not to attempt to specify which of them it was—that seeing a beggar
in want of a cloak, he gave him his own. Now, seriously, without in
the least desiring to disparage the charity of the saint, it may be
pointed out that beggars are usually met with in the streets of towns,
and that to give away a cloak therein is at the best not more
meritorious than giving to a companion half of your only blanket at
the beginning of a rainy night on the summit of a distant mountain.
But this was not all. It was decided that the best protection against
rain would be the erection of some sort of tent. ‘Ta-ma-té’ was soon
employed in helping to construct this shelter, and in spite of all
opposition, persisted in contributing the remaining portion of his
blanket to form the roof.
Contenting himself with as much of a companion’s blanket as could
be spared to him, he made himself, as he protested, extremely
comfortable; and that all might be as merry as possible, started a
musical entertainment by favouring the company with Auld
Langsyne. His jollity was contagious. There was a succession of
songs. When these had been concluded with a ‘fore-bitter’ of
formidable length on the death of Lord Nelson by a seaman of
H.M.S. Nelson gifted with a fine voice, the natives were invited to
take up the singing. They complied without much hesitation. They
sang in a low and rather plaintive tone, with a curious deep tremolo
uttered from time to time in unison. At length, as some began to
grow sleepy, Mr Chalmers asked for silence, so that the teacher Biga
might be able to conduct the evening devotions. This he did in an
extempore prayer, attentively followed by the natives, and, if not
understood, at all events reverently listened to, by the white men. To
one at least of the latter, sleep was impossible. Fatigue must be
indeed overwhelming which will enable one to slumber when, in the
midst of the only available sleeping-place, a point of rock is so
situated that it almost forces a passage between the ribs. Luckily,
there were no mosquitoes or other voracious insects. But there was
an unpleasant many-legged black slug four or five inches long which
evinced an unconquerable predilection for crawling over the naked
human body. It was far from pleasant to find this animal just effecting
a passage between the neckband of the shirt and the skin, or trying
to coil itself round the ear of the side which happened to be
uppermost. A careful member of our party, before lying down, had
stretched a line between two trees, and on it had hung his wet
clothes. Looking about him in the night, he discovered that the
clothes had disappeared, and his announcement of this discovery
elicited from a companion the intelligence that the natives were
wearing them. This statement, so to speak, brought down the house.
The natives heartily joined in the hilarious applause with which it was
received. The same reception was extended to occasional
ejaculations from other companions of the bivouac, such as, ‘By
Jove! there’s a native with my shirt on!’ Subsequent reflections
convinced the owners that it was fortunate that the temporary
borrowing of their clothes by their native friends had been looked
upon as part of the fun of the excursion. Had any one been so ill-
conditioned as to maltreat or scold the merry, intelligent carriers, they
would, almost to a certainty, have stolen away in the night, and have
left the white men to get themselves and their things home as best
they could. One native gentleman displayed so much ingenuity in the
mode of wearing one of the more unmentionable garments, which he
somehow or other succeeded in converting into a kind of sleeved
waistcoat, that the appreciative owner made him a present of it. The
new possessor had a proper pride in this acquisition, and wore it in
his village after the descent; indeed, he had the honour of being
introduced to the commodore whilst clad in it.
‘Ta-ma-té,’ who, with universal assent, had established a genial
despotism over the bivouac, issued a decree that every one should
make a joke, and that the joke adjudged the best should be sent to a
newspaper for publication. Either this was trying the loyalty of his
contented subjects too severely, or the labour of incubating jokes
was too great for wearied mountaineers, for, after one or two feeble
endeavours to comply with his edict, a general silence fell upon the
company.
In the morning, after a not absolutely perfect night’s rest, deficiency
of water rendered abstaining from even an attempt at breakfast
compulsory. There was little, therefore, to delay the ceremony of
hoisting the union-jack—providently brought for the purpose by
Lieutenant Fenton—upon the newly crowned summit. A suitable tree
was cut down and lopped; the flag was secured to it; and a hole
having been dug in which to insert it, the flagstaff was reared amidst
a very good imitation of three cheers from the natives, and the real
thing from the white men. The descent then began; and much of it
was effected by a different route from that of the ascent. Orchids,
ferns, and other plants were collected on the way. Sore hands,
barked shins, added to want of sleep and to a long fast, made the
descent seem to some even more fatiguing than the climb of the day
before. The interval before water was reached appeared excessive,
and before a halt could be made for breakfast, interminable. By two
p.m. the travellers were back on board their ships, proud of the
distinction of being the first to ascend a mountain summit in Eastern
New Guinea.
TREASURE TROVE.
A STORY IN FOUR CHAPTERS.—CHAP. IV.
Upon Jasper Rodley’s entrance into the house, Bertha had retired to
her own room, pleading that she was suffering from the excitement,
the fatigue, and the exposure she had undergone; but she could
hear a conversation kept up in the dining-room until a late hour, and
instinctively felt that Rodley had not come again without a reason. To
her surprise, the next morning she found that both her father and his
visitor were already downstairs, Jasper Rodley looking out of the
window and whistling to himself, the captain with evident agitation
marked on his movements and face.
‘Bertha,’ he said, without even giving her the usual morning greeting,
‘Mr Rodley has come here especially to say that from information he
has received, it will be necessary for you at once to decide what
course you intend to adopt. There is a chance, he says, that the
great evil hanging over our heads may be averted, but it depends
upon your answer.’
‘Mr Rodley must give me until this evening to think over the matter. I
am going into Saint Quinians, if possible to see Harry—that is, Mr
Symonds, for even Mr Rodley will admit that plighted troths are not
to be broken in this abrupt manner. I shall be home before dark.’
‘Then I will see you on your road,’ said Rodley, ‘as I am going into
the town.’
‘You need not trouble,’ said Bertha. ‘The road is quite familiar to me,
and I have no fear of being molested.’ Then, without waiting to hear
whether Jasper Rodley objected or not to the arrangement, she left
the house.
In exactly an hour’s time, she walked into the town. At the old gate
she was confronted by rather a pretty girl, who laid a hand gently on
her arm, and said: ‘You are Miss West, I believe?’
Bertha replied in the affirmative.
‘You are in an unhappy and terrible position, and you have very little
time to spare, I think?’ added the girl.
Bertha looked at her wonderingly, for she could not recall ever
having seen her before.
‘I mean,’ explained the girl, who observed that Bertha was surprised
at this acquaintance on the part of a stranger with her affairs—‘I
mean with regard to that man, Jasper Rodley.—Yes, I know all about
it; and I want, not only to be your friend, but to see that evil-doing
meets with its just reward.’
The girl was poorly dressed; but her accent and mode of expression
were those of an educated woman, and, moreover, she had such a
thin, sorrow-lined face, that Bertha felt she could trust her.
‘Let me be with you to-day,’ continued the girl, ‘and you may thank
me for it some day. I have long wanted to see you, and have waited
here for you often. Never mind who I am—that you shall find out
later.’
‘Very well,’ said Bertha, who naturally clung to the friendship of one
of her own sex. ‘I am going to see Mr Symonds—my betrothed.’
‘The gentleman who was obliged to leave Faraday’s Bank, four
years ago; yes, I remember,’ said the girl.
They crossed the market-place together, and were soon at Harry
Symonds’ lodgings. The servant, in reply to Bertha’s inquiries, said
that the young man was so far recovered as to be able to sit up, but
that the doctor had ordered him to keep perfectly quiet and to be free
from all excitement. So Bertha wrote him a note describing all that
had taken place, and begging for an immediate answer. In the
course of twenty minutes, the servant handed her a piece of paper,
on which was scrawled as follows:
My dearest Love—This is written with my left hand, as
my right is yet in a sling. I wish I could say all that I want
to; but as every moment is of value to you, I will simply
keep to business. Take a postchaise home; get the money
out of the cavern, and send it here. John Sargent the
fisherman is to be trusted; let him come back with it in the
postchaise. I will return it to the bank, making up out of my
savings whatever difference there is from the original
amount stolen. Lose no time, my darling, and God bless
you!—Ever your affectionate
Harry.
Bertha and the girl hurried away; and just as they entered the
Dolphin Inn to order the chaise, they espied Jasper Rodley entering
the town watchhouse, the local headquarters of the civil force which
in those days performed, or rather was supposed to perform, the
duties of our modern constabulary.
‘Miss West,’ said the girl, ‘I had better remain in the town for the
present. At what hour to-day is Jasper Rodley coming to your
house?’
‘I said I would be home by dark. He will be there before then, to
receive my final answer.’
‘Very well, then; I will be there about that time,’ continued the girl.
‘Will you not even tell me your name?’ asked Bertha.
‘Yes. My name is Patience Crowell. Till to-night, good-bye. Keep up
your spirits; all will end well.’
In a few minutes the postchaise was ready, and in order to escape
the notice of Jasper Rodley, was driven round to the town gate,
where Bertha jumped in. She stopped at John Sargent’s cottage,
and mentioned her errand.
‘Why,’ said the old fisherman, ‘I’m too glad to do anythin’ for Master
Symonds. He saved my life once at Saint Quinians’ jetty, and I’ve
never had no chance of doin’ suthin’ for him in return like.—Come
along, miss; if it’s to the end of the world, come along!’
As Jasper Rodley might pass by at any moment, Bertha thought it
best to keep the chaise out of sight, whilst she and the fisherman,
provided with a large net-basket, proceeded to the cliffs. In half an
hour’s time the bags of coin were safely stowed away in the
postchaise; John Sargent jumped in, the chaise rattled off; and
Bertha, with a light heart and a heightened colour, returned home.
The captain was stumping up and down the little gravelled space in
his garden, which from the presence there of half-a-dozen old
cannon and a flagstaff, he delighted to call the Battery. When he
beheld Bertha, he welcomed her with a sad smile, and putting her
arm in his, said: ‘Bertha, lass, I’ve been thinking over this business
ever since you went away this morning, and the more I’ve thought
about it, the more I’ve called myself a mean, cowardly, selfish old
fool.’
‘Why, father?’
‘Because, look here. I’ve been telling you to make yourself miserable
for life by marrying a man you despise and dislike, just so that I may
get off the punishment that’s due to me. I’m an old man, and in the
ordinary course of things, I can’t have many years before me. You’re
a girl with all your life before you, and yet I’m wicked enough to tell
you to give up all your long life so that my few years shouldn’t be
disturbed.’
‘But father’—— began Bertha.
‘Let me speak!’ interposed the old man. ‘I’ve been doing a wicked
thing all these four years; but I know what’s right. When this man
asks you to be his wife to-night, you say “No;” mind, you say “No.” If
you don’t, I will; and you won’t marry without my permission.’
‘Dear father, you leave it to me. I do not promise anything except that
by no act of mine shall one hair of your head be touched.—Let us
talk of other things, for Jasper Rodley will be here soon.’
So they walked up and down until the sun began to sink behind the
hills inland and the air grew chilly. They had scarcely got into the
house, when Jasper Rodley appeared. He bowed formally to Bertha,
and offered his hand to the captain, which was declined. ‘Miss West,’
he said, ‘I think I have given you fair time for decision. I have not
been so exacting as circumstances justified.’
Bertha said nothing in reply, but sat in a chair by the window, and
looked out on the sea as if nothing unusual was taking place.
So Jasper Rodley continued: ‘I will speak then at once, and to the
point. Miss West, will you accept me for your husband?’
‘No, I will not,’ replied Bertha, in a low, firm voice.
Mr Rodley was evidently unprepared for this, and looked at her with
open mouth. ‘That is your final answer?’ he asked, after a pause.
‘You are prepared to see your father, whom you love so dearly, taken
from here in custody to be brought up as a common felon?’
‘Yes. That is, Mr Rodley, if you can prove anything against him. Of
what do you accuse him?’
‘I accuse him of having lived during the past four years upon money
which was not his, but which was stolen from Faraday’s Bank in
Saint Quinians, which was taken off in a vessel called the Fancy
Lass, the said vessel being wrecked off this coast.’
‘Very well,’ continued Bertha. ‘What is your proof that he knows
anything about this money?’
‘One moment before I answer that. You refuse to marry me if I can
bring no proof. You will marry me if I do?’
‘Show me the proof first,’ answered Bertha.
‘You must follow me, then.’
‘Not alone.—Father, you must come with me.’
So the trio proceeded out into the dusk, and, conducted by Jasper
Rodley, followed the path leading to the cliffs. Bertha observed that
they were followed at a little distance by a man closely enveloped in
a long coat, and as they ascended the ledge of rock communicating
with the shore, noticed two other figures—those of a man and a
woman—watching them.
‘It’s a very nice little hiding-place,’ remarked Rodley, when they
arrived at the bushes—‘a very nice little hiding-place, and it seems
almost a pity to make it public property; but a proof is demanded,
and sentimental feelings must give way.’ He smiled as he said this,
and kicked the bush aside with his feet, thus uncovering the cavern
entrance. They entered the hole, which was now quite dark; but
Rodley had come prepared, and struck a light. He then rolled away
the stone, and without looking himself, gave Bertha the light and
bade her satisfy her doubts.
‘There is nothing here,’ she said.
‘Nothing!’ exclaimed Rodley, taking the light from her hand and
examining the cavity. ‘Why!—Gracious powers! no more there is!
There has been robbery! Some one has been here and has sacked
the bank!’ His face was positively ghastly in the weird light as he said
this, and under his breath he continued a fire of horrible execrations.
‘Well, Mr Rodley,’ said Bertha, smiling, ‘and the proof?’
Rodley did not answer, but moved as if to leave the cavern, when a
woman’s figure confronted him at the entrance, and a ringing voice
said: ‘Proof! No! He has no proof!’
Rodley staggered back with a cry of rage and surprise. ‘Patience!
Why—how have you got here? I left you at Yarmouth!—Ha! I see it
all now!’
‘Yes,’ cried the girl, ‘of course you do. I gave you fair warning, when I
found out that you were beginning to forsake me for another; but not
until after I had begged and entreated you, with tears in my eyes, to
remember the solemn protestations of love you had made me, and
the solemn troth which we had plighted together.’
‘Let me go!’ roared Rodley; ‘you’re mad!’
‘No, no—not so fast!’ cried the girl. She made a signal to some one
without, and a man entered.
‘Jasper Rodley,’ continued Patience, ‘this constable has a warrant for
your apprehension on the charge of having been concerned in the
bank robbery four years ago.—Yes, you may look fiercely at me. I
swore that the secret in my keeping should never be divulged. I
loved you so much, that I was ready even to marry a thief. But as
you have broken your faith with me, I consider myself free of all
obligations.—Captain West, it was this man who planned the
robbery, who had the coin conveyed to his boat, the Fancy Lass, and
who alone was saved from the wreck.’
Rodley made a desperate rush for the cave entrance; but the
constable held him fast, and took him off.
‘There, Miss West!’ cried the girl; ‘I have done my duty, and I have
satisfied my revenge. My mission is accomplished. Good-bye, and
all happiness be with you.’ And before Bertha could stop her, she
had disappeared.
Jasper Rodley was convicted on the charge of robbery, and received
a heavy sentence, which he did not live to fulfil. Harry Symonds paid
in to the bank the entire sum stolen, the authorities of which offered
him immediately the position of manager, which he declined. He and
Bertha were married shortly afterwards; but they could not induce
the old captain to move to the house they had taken, for he could not
get over the shame of the exposure, and declared that he was only
fit for the hermit life he had chosen; but no one outside the little circle
ever knew that he had been indirectly concerned in the robbery; and
neither Harry nor Bertha alluded to it after.
Of Patience Crowell, who had so opportunely appeared on the
scene, nothing was ever known.
THE MONTH:
SCIENCE AND ARTS.

Dr Gustav Jaeger, whose sanitary clothing reform made some little


stir a year or two back, seeks to apply the principle involved in his
theory to furniture. This theory teaches that cotton, linen, and other
stuffs of vegetable origin retain a power of absorbing those noxious
animal exhalations which as plants they digest. Dead fibre, or wood,
will, he maintains, act in the same manner, and will throw off the
deleterious matter, to the prejudice of living beings, whenever there
is a change of temperature. This, he holds, is the reason why a room
which has been shut up for some days has an unpleasant odour
attaching to it, and which is very apparent in German government
offices, which are fitted with innumerable shelves and pigeon-holes
made of plain unpainted wood. For sanitary reasons, therefore, the
back and unseen parts of furniture should be varnished, painted, or
treated with some kind of composition, to fill the pores of the wood;
hence it is that so-called sanitary furniture has in Germany become
an article of commerce, and is likely to find its way to this and other
countries.
Such large quantities of ice are now made by various artificial
processes, that ice is no longer a luxury which can only be procured
by the rich, but is an article of commerce which can be purchased at
a very low price in all large towns in the kingdom. It is not generally
known that the artificial product is far purer than natural ice, but
such, according to M. Bischoff of Berlin, who has made a scientific
analysis of specimens, is the case.
All honest persons rejoice greatly when a notorious evil-doer is run
to earth, and much the same satisfaction is experienced when
science points with unerring finger to the source of disease, for then
the first step has been taken in its eradication. Many, therefore, will
rejoice when they read the recently issued Report of Mr W. H.
Power, the Inspector of the Local Government Board, concerning an
epidemic of scarlatina which occurred in London last year. The story
is most interesting, but too long to quote in full. Suffice it to say that
the disease in question has, after the most painstaking inquiries,
been traced to the milk given by certain cows which were affected
with a skin disease showing itself in the region of the teats and
udders. We know to our cost that certain diseases can be transferred
from the lower animals to man. ‘Woolsorters’ disease’ is traced to the
same germ which produces splenic fever in cattle and sheep, a
malady which has been so ably dealt with by M. Pasteur. The terrible
glanders in horses is transferable to man. Jenner was led to the
splendid discovery of vaccination from observing the effects of
cowpox on milkmaids; and now we have scarlatina traced directly to
the cowhouse. Dr Klein, the famous pathologist, has been engaged
to report upon this new revelation concerning milk, and we may
reasonably hope that his researches will bear fruitful results.
A new method of etching on glass has been devised. The ink is of a
waxy composition, and requires to be heated to render it fluid. It is
applied to the glass with a special form of pen, which can be kept in
a hot condition by a gas or electrical attachment. When the drawing
is complete, the plate is etched by fluoric acid, which of course only
attacks and dissolves those portions not covered by the protective
ink. The result is a drawing in raised lines, which can be made to
furnish an electrotype, or can, if required, be used direct as a block
to print from.
Springs in mid-ocean are not unknown, and, if we remember rightly,
there is more than one of the kind at which ships have endeavoured
to renew their stores of fresh water. But an ocean oil-well is certainly
a rarity. The captain of a British schooner reports that in March last,
while bound for New Orleans, his vessel passed over a submarine
spring of petroleum, which bubbled up all round the ship, and
extended over the surface of the sea for some hundred yards. It
seems to be a moot-point whether this phenomenon is a mere freak
of nature, or whether it is caused by the sunken cargo of some ill-
fated oil-ship. In the latter case, the gradual leakage of casks would
account for the strange appearance.

You might also like