0% found this document useful (0 votes)
37 views84 pages

(Ebook) A Course in Python: The Core of The Language by Roozbeh Hazrat ISBN 9783031497797, 3031497791 Download

The document provides information about various ebooks available for download, including titles related to Python programming and other subjects. It highlights a specific book, 'A Course in Python: The Core of the Language' by Roozbeh Hazrat, which is designed for teaching Python through concise explanations and practical exercises. The document also mentions the Springer Undergraduate Mathematics Series and the author's background in mathematics and data science.

Uploaded by

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

(Ebook) A Course in Python: The Core of The Language by Roozbeh Hazrat ISBN 9783031497797, 3031497791 Download

The document provides information about various ebooks available for download, including titles related to Python programming and other subjects. It highlights a specific book, 'A Course in Python: The Core of the Language' by Roozbeh Hazrat, which is designed for teaching Python through concise explanations and practical exercises. The document also mentions the Springer Undergraduate Mathematics Series and the author's background in mathematics and data science.

Uploaded by

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

(Ebook) A Course in Python: The Core of the

Language by Roozbeh Hazrat ISBN 9783031497797,


3031497791 download

https://ebooknice.com/product/a-course-in-python-the-core-of-the-
language-54773868

Download more ebook instantly today at https://ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Graded Rings and Graded Grothendieck Groups by Roozbeh Hazrat ISBN
9781316619582, 1316619583

https://ebooknice.com/product/graded-rings-and-graded-grothendieck-
groups-6811088

ebooknice.com

(Ebook) Programming in Python 3: A Complete Introduction to the Python Language by


Summerfield, Mark ISBN 9780321680563, 0321680561

https://ebooknice.com/product/programming-in-python-3-a-complete-introduction-
to-the-python-language-36002018

ebooknice.com

(Ebook) Python Algorithms: Mastering Basic Algorithms In The Python Language by


Hetland, Magnus Lie ISBN 9781484200568, 148420056X

https://ebooknice.com/product/python-algorithms-mastering-basic-algorithms-in-
the-python-language-38431100

ebooknice.com

(Ebook) The Soul's Journey by Hazrat Inayat Khan ISBN 9780930872533, 0930872533

https://ebooknice.com/product/the-soul-s-journey-44643430

ebooknice.com
(Ebook) A Course in Natural Language Processing by Haralambous, Yannis ISBN
9783031272257, 3031272250

https://ebooknice.com/product/a-course-in-natural-language-processing-55256482

ebooknice.com

(Ebook) Spoken Kashmiri: A Language Course (Indian Institute of Language Studies) by


Omkar N. Koul ISBN 9788186323199, 8186323198

https://ebooknice.com/product/spoken-kashmiri-a-language-course-indian-
institute-of-language-studies-2359238

ebooknice.com

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason; Viles, James ISBN
9781459699816, 9781743365571, 9781925268492, 1459699815, 1743365578, 1925268497

https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) Common Core Curriculum Maps in English Language Arts: Grades 6-8 by Common
Core ISBN 9781118108215, 1118108213

https://ebooknice.com/product/common-core-curriculum-maps-in-english-language-
arts-grades-6-8-4682914

ebooknice.com

(Ebook) Understanding Language - A Basic Course In Linguistics by Elizabeth Grace


Winkler ISBN 9781441160799, 1441160795

https://ebooknice.com/product/understanding-language-a-basic-course-in-
linguistics-42605034

ebooknice.com
Springer Undergraduate Mathematics Series

Editor-in-Chief
Endre Süli, Oxford, UK

Series Editors
Mark A. J. Chaplain, St. Andrews, UK
Angus Macintyre, Edinburgh, UK
Shahn Majid, London, UK
Nicole Snashall, Leicester, UK
Michael R. Tehranchi, Cambridge, UK
The Springer Undergraduate Mathematics Series (SUMS) is a series designed for
undergraduates in mathematics and the sciences worldwide. From core foundational
material to final year topics, SUMS books take a fresh and modern approach.
Textual explanations are supported by a wealth of examples, problems and fully-
worked solutions, with particular attention paid to universal areas of difficulty.
These practical and concise texts are designed for a one- or two-semester course
but the self-study approach makes them ideal for independent use.
Roozbeh Hazrat

A Course in Python
The Core of the Language
Roozbeh Hazrat
Centre for Research in Mathematics and Data Science
Western Sydney University
Penrith, NSW, Australia

ISSN 1615-2085 ISSN 2197-4144 (electronic)


Springer Undergraduate Mathematics Series
ISBN 978-3-031-49779-7 ISBN 978-3-031-49780-3 (eBook)
https://doi.org/10.1007/978-3-031-49780-3

Mathematics Subject Classification (2020): 00-01

© The Editor(s) (if applicable) and The Author(s), under exclusive license to Springer Nature Switzerland
AG 2023
This work is subject to copyright. All rights are solely and exclusively licensed by the Publisher,
whether the whole or part of the material is concerned, specifically the rights of translation, reprinting,
reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software, or by
similar or dissimilar methodology now known or hereafter developed.
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 Springer imprint is published by the registered company Springer Nature Switzerland AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland

Paper in this product is recyclable.


Preface

Python has become, for good reason, a very popular programming language, with a
substantial number of followers around the globe. In addition to its intuitive program-
ming language, Python now offers numerous libraries which provide powerful tools
and methods to do, among many other things, mathematics, physics, text processing,
and musical composition. Once one grasps the core of the language, then help, hints,
and a wealth of sample codes are just a google away.
Besides many books on Python, there is an uncountable number of documents on
the internet. However, I wanted to have one source that I can follow to systematically
teach (or learn) the core of the language before diving into more advanced fronts. I
also wanted to have a source that is short, to the point and which provides interesting
programming examples; examples that I enjoy coding, modifying and experimenting
with.
This book grew out of a course I gave at Western Sydney University. It allows the
reader to learn Python by going through interesting exercises step by step, with short
and concise explanations. I have tried to let the reader learn from the codes and
avoid long and exhausting explanations, as the codes will speak for themselves. Also
I have tried to inspire the reader’s imagination by showing that in Python (as in the
real world) there are many ways to approach a problem and solve it.
Thus, this book could be considered for a course in Python, or for self-study. It mainly
concentrates on the core of Python programming. I have mostly chosen problems
having something to do with natural numbers as they do not need any particular
background. The codes have been written in Jupyter using Python version 3.
Acknowledgement. My thanks go to Thomas Fischbacher from Google Research
for going through the book and providing insightful comments; to the students at
Western Sydney University for their contributions to the classes, which made them
lively and enjoyable, and to the anonymous referees for their support and feedback.
My thanks also go to Dr. Remi Lodh at Springer for his generous support throughout
the preparation of the book.

v
vi Preface

How to use the book. This book can be used as a one semester course in programming
in Python (13 weeks, 3 hours each week) at the undergraduate level or a compact crash
course (4 days, 6 hours each day) for more advanced students. Each chapter starts
with a description of new tools and topics and provides examples. The examples
are chosen so that the reader can learn from the codes by typing and running
them and then modifying them and experimenting with them. Long and exhausting
explanations are avoided. The lecturer can code the examples in the class along with
students. The students are then encouraged to take the lead role and compose codes
themselves for some of the exercises. The problems at the end of each chapter can
be given to students as homework so that they present the codes in the class the
next week. The book concludes with projects which demonstrate how to use Python
to explore mathematics. Some of these projects can be given as assignments to the
students.
Please start with the codes in the book, change them, tear them apart and turn them
upside down, and create your own better programs.

Sydney, Australia, October 2023 Roozbeh Hazrat


[email protected]
Contents

1 Basics of Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Basic Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Integers, Reals and Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Objects and their Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.4 Importing Libraries in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.5 Variables in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.6 Equalities and Boolean Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.7 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.8 Strings as Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.9 Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

2 Lists and Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23


2.1 Data: Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.1.1 Accessing entries of a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.2 Lists as Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.3 A First Glimpse of Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.4 A First Glimpse of Importing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.5 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
2.6 More Examples of Working with Data . . . . . . . . . . . . . . . . . . . . . . . . . 42
2.6.1 Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

3 Decisions and Repetitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49


3.1 Decision Making: The Fork on the Road . . . . . . . . . . . . . . . . . . . . . . . 49
3.2 Decision Making: The Forks on the Road . . . . . . . . . . . . . . . . . . . . . . 52
3.3 Loops and Repetitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.3.1 For-loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.3.2 Nested For-loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
3.3.3 While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

vii
viii Contents

4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4.1 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4.1.1 The scope of functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
4.1.2 Functions, default values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
4.1.3 Functions, specific types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
4.2 Functional Programming: Anonymous (lambda) Functions . . . . . . . . 103
4.2.1 Selecting from a collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
4.2.2 Functional programming, reduce . . . . . . . . . . . . . . . . . . . . . . . 113

5 List Comprehension and Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123


5.1 List Comprehension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
5.1.1 Putting conditions on parameters . . . . . . . . . . . . . . . . . . . . . . . 125
5.2 Sets and Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
5.2.1 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
5.2.2 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
5.3 Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
5.3.1 Generator functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

6 The sympy Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153


6.1 sympy, Symbolic Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
6.2 Graphics in sympy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
6.3 Three-Dimensional Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
6.4 Calculus with sympy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
6.4.1 Solving equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
6.4.2 Limits, derivation and integration . . . . . . . . . . . . . . . . . . . . . . . 173

7 The numpy Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183


7.1 numpy, Numerical Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
7.1.1 Calculus on arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
7.1.2 Generating arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
7.1.3 Accessing entries of an array . . . . . . . . . . . . . . . . . . . . . . . . . . 187
7.1.4 Vector calculus with arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
7.2 Universal Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207

8 The matplotlib Library and Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211


8.1 matplotlib, Plotting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
8.2 Plots as Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
8.3 Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
8.4 Case Study, Persian Carpets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
8.5 Case Study, Predictive Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
8.6 Case Study, the Thue–Morse Sequence . . . . . . . . . . . . . . . . . . . . . . . . 242

Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Chapter 1
Basics of Python

1.1 Basic Arithmetic

This first chapter gives an introduction to using Python “out of the box”, demonstrat-
ing how to use ready-made commands, performing basic arithmetic and building up
computations. One of the reasons why Python has become the language of choice
for many is its external libraries, which provide powerful tools that one can use to
investigate and analyse problems in a multitude of areas. We will showcase some of
them in this first chapter, such as working with symbols and the first instances of
symbolic computations.
Python handles all sort of numerical calculations, both exact computations and
4
approximations. If we would like to calculate 3 × 4 × 5 × 6 + 1 or 23 we only need
to enter them correctly into Python.

[1]: 3 * 4 * 5 * 6 + 1

[1]: 361

[2]: 2**3**4

[2]: 2417851639229258349412352

Python is a powerful calculator with the basic arithmetic operations; +, − for addition
and subtraction and ∗, ∗∗ for multiplication and for raising to powers. One uses round
brackets () to group the expressions together.

[3]: (2**3)**4

[3]: 4096

[4]: 2**(3**4)

© The Author(s), under exclusive license to Springer Nature Switzerland AG 2023 1


R. Hazrat, A Course in Python, Springer Undergraduate Mathematics Series,
https://doi.org/10.1007/978-3-031-49780-3_1
2 1 Basics of Python

[4]: 2417851639229258349412352

Here is a calculation to disprove a 200-year-old conjecture of the famous mathe-


matician Euler. He conjectured that three fourth powers can never sum to a fourth
power.

[5]: 2682440**4 + 15365639**4 + 18796760**4

[5]: 180630077292169281088848499041

[6]: 20615673**4

[6]: 180630077292169281088848499041

The last two calculations show that

26824404 + 153656394 + 187967604 = 206156734 ,

which was found by Noam Elkies at Harvard in 1988, giving a counterexample to


Euler’s conjecture.
Python is even more powerful; it can handle large exact computations, as the follow-
ing shows.

[7]: 2**9941 - 1

[7]: 346088282490851215242960395767413316722628668900238547790489283
445006220809834114464364375544153707533664486747635050186414707
093323739706083766904042292657896479937097603584695523190454849
100503041498098185402835071596835622329419680597622813345447397
208492609048551927706260549117935903890607959811638387214329942
787636330953774381948448664711249676857988881722120330008214696
844649561469971941269212843362064633138595375772004624420290646
813260875582574884704893842439892702368849786430630930044229396
033700105465953863020090730439444822025590974067005973305707995
078329631309387398850801984162586351945229130425629366798595874
957210311737477964188950607019417175060019371524300323636319342
657985162360474512090898647074307803622983070381934454864937566
479918042587755749738339033157350828910293923593527586171850199
425548346718610745487724398807296062449119400666801128238240958
164582617618617466040348020564668231437182554927847793809917495
802552633233265364577438941508489539699028185300578708762293298
033382857354192282590221696026655322108347896020516865460114667
379813060562474800550717182503337375022673073441785129507385943
306843408026982289639865627325971753720872956490728302897497713
583308679515087108592167432185229188116706374484964985490944305
1.1 Basic Arithmetic 3

412774440794079895398574694527721321665808857543604774088429133
272929486968974961416149197398454328358943244736013876096437505
146992150326837445270717186840918321709483693962800611845937461
435890688111902531018735953191561073191960711505984880700270887
058427496052030631941911669221061761576093672419481606259890321
279847480810753243826320939137964446657006013912783603230022674
342951943256072806612601193787194051514975551875492521342643946
459638539649133096977765333294018221580031828892780723686021289
827103066181151189641318936578454002968600124203913769646701839
835949541124845655973124607377987770920717067108245037074572201
550158995917662449577680068024829766739203929954101642247764456
712221498036579277084129255555428170455724308463899881299605192
273139872912009020608820607337620758922994736664058974270358117
868798756943150786544200556034696253093996539559323104664300391
464658054529650140400194238975526755347682486246319514314931881
709059725887801118502811905590736777711874328140886786742863021
082751492584771012964518336519797173751709005056736459646963553
313698192960002673895832892991267383457269803259989559975011766
642010428885460856994464428341952329487874884105957501974387863
531192042108558046924605825338329677719469114599019213249849688
100211899682849413315731640563047254808689218234425381995903838
524127868408334796114199701017929783556536507553291382986542462
253468272075036067407459569581273837487178259185274731649705820
951813129055192427102805730231455547936284990105092960558497123
779789849218399970374158976741548307086291454847245367245726224
501314799926816843104644494390222505048592508347618947888895525
278984009881962000148685756402331365091456281271913548582750839
07891469979019426224883789463551

If a number of the form 2𝑛 − 1 happens to be prime, it is called a Mersenne prime.


Recall that a prime number is a number greater than 1 which is divisible only by 1
and itself. It is easy to see that 22 − 1, 23 − 1 and 25 − 1 are Mersenne primes. The
list continues. In 1963, Gillies found that the above number, 29941 − 1, is a Mersenne
prime. With my laptop it takes less than 1 second for Python to check that this is
indeed a prime number. The largest Mersenne prime found so far is 282,589,933 − 1,
having 24,862,048 digits, which was discovered in January 2018.
Within integer arithmetic, there are division and remainder operations that Python
can handle with // and %. It is a fact that for two non-zero integers 𝑛 and 𝑚 one can
write 𝑛 = 𝑚𝑞 + 𝑟, where 𝑞 and 𝑟 are unique integers with 0 ≤ 𝑟 < 𝑞. In Python we
get n//m=q and n % m =r. We check this with 𝑛 = 13 and 𝑚 = 4 below. Note the
use of the function print in the example below.
4 1 Basics of Python

[8]: print(13, '=', 13 // 3, 'x', 3 ,'+', 13 % 3)

[8]: 13 = 4 x 3 + 1

We will explore the function print more at the end of this chapter.

Exercise 1.1 Show that the number 142857 is cyclic, meaning if we multiply it by
any of the numbers 1 to 6, the result will be a permutation of the digits of the original
number 142857.

Solution
Later in Chapter 3 we will write a program to find cyclic numbers. Checking a
number is cyclic, however, is quite easy:

[9]: print(142857*2, 142857*3, 142857*4,142857*5, 142857*6)

[9]: 285714 428571 571428 714285 857142

1.2 Integers, Reals and Complex Numbers

Python distinguishes between different classes of numbers. The integers, denoted by


Z = {· · · , −2, −1, 0, 1, 2 · · · } in mathematics, are those numbers with no decimal
points, such as all the numbers we have worked with so far, whereas real numbers or
floats, denoted
√ by R, are those with decimal points, which are used for approximation,
such as 1.2, 2 or 𝜋.
Python can also handle complex numbers using the format a+bj, where 𝑎 is the
real part and 𝑏 is the imaginary part. Here 1 𝑗 is what in the literature is commonly
denoted by 𝑖, so that 1 𝑗 2 = −1. But note how Python presents the complex numbers.
In the example below we also add comments into the code. This is done by using #
and writing the comment after it.

[10]: (1j)**2 # 1j represents the imaginary number i

[10]: (-1+0j)

As an example, we calculate ( 11 + 1
2 + 13 ) × 3 and (3 − 6𝑖) 2 .

[11]: (1/1 + 1/2 + 1/3) * 3

[11]: 5.5

[12]: (3 - 6j)**2
1.2 Integers, Reals and Complex Numbers 5

[12]: (-27-36j)

Since 𝑖 2 = −1, it is easy to see (𝑎 + 𝑏𝑖)(𝑎 − 𝑏𝑖) = 𝑎 2 + 𝑏 2 . We check this with an


example.

[13]: (2 - 3j)*(2 + 3j)

[13]: (13+0j)

One of the reasons why Python has become so popular is that it has a large number
of libraries which contain ready to use tools and functions. Various mathematical

functions such as sin, cos or and log are available in different libraries of Python.
The first library we will use is math, which makes many of these functions available to
us. Note how we import this library into Python and how the functions (or methods)
are used from this library. Once we have imported the library, we can access its
built-in functions via dot “.”.

[14]: import math

math.pi

[14]: 3.141592653589793

[15]: math.sin(math.pi/2)

[15]: 1.0

Exercise 1.2 Show that for any chosen angle 𝑥, Python gives sin2 (𝑥) + cos2 (𝑥) = 1.

Solution
As an instance, choosing 𝜋/5 for the angle and translating the expression correctly
into Python, we have

[16]: math.sin(math.pi/5)**2 + math.cos(math.pi/5)**2

[16]: 1.0

Of course, one could choose any other angle, run the code, and obtain 1 again.

Exercise 1.3 Calculate the expression


v
u
t !
3 23
e𝜋 + log  .
sin 𝜋6
6 1 Basics of Python

Solution
The only challenge here is to translate the mathematical expression correctly into
Python.

[17]: (math.exp(math.pi) + math.log(23 / math.sin(math.pi/6)))**(1/


↩→3)

[17]: 2.998863793038475

Notice here that math.exp(math.pi) gives e 𝜋 .

Exercise 1.4 Compute


1
6+ 1
.
5+ 4+ 11
3+
2

Solution
One can immediately see a repeating pattern within this expression, and we will
later write elegant codes to capture and compute such expressions. For the moment
we can write the following. Note that the notation refers to the previous output in
Jupyter. The symbol has other uses, as we will see throughout the book.

[18]: 3 + 1/2

[18]: 3.5

[19]: 4 + 1/_

[19]: 4.285714285714286

[20]: 5 + 1/_

[20]: 5.233333333333333

[21]: 6 + 1/_

[21]: 6.191082802547771

Or in one line as:

[22]: 6 + 1/(5 + 1/(4 + 1/(3 + 1/2)))

[22]: 6.191082802547771

Besides the math library, which provides many valuable mathematical functions,
there are two other libraries in Python that are heavily used: numpy and sympy. The
1.2 Integers, Reals and Complex Numbers 7

library numpy is designed for numerical computations whereas sympy is for symbolic
computations and calculus. We look at these libraries in detail in Chapters 6 and
7. Here we just give an indication of how these libraries behave. All these libraries
provide the basic mathematical functions, such as trigonometric functions sin, cos,
tan, etc., however their methods of computation differ.

[23]: import math


import numpy
import sympy

We will calculate sin(𝜋/5) using each of these libraries.

[24]: math.sin(math.pi/5)

[24]: 0.5877852522924731

[25]: numpy.sin(numpy.pi/5)

[25]: 0.5877852522924731

[26]: sympy.sin(sympy.pi/5)


√︄
[26]: 5 5

8 8
√︃ √
The sympy library gives 58 − 85 as the value of sin(𝜋/5), which is the exact value.
This shows that sympy is not approaching the expressions numerically.
Next we will check the identity

sin2 (𝜋/5) + cos2 (𝜋/5) = 1

with the sympy functions.

[27]: sympy.sin(sympy.pi/5)**2 + sympy.cos(sympy.pi/5)**2


√ √ !2
[27]: 5 5 1 5
− + + +
8 8 4 4

We were expecting the output 1. In order to further simplify the output, we can use
the function simplify in the sympy library.

[28]: sympy.simplify(_)

[28]: 1
We will check the same identity within the numpy and math libraries.
8 1 Basics of Python

[29]: numpy.sin(numpy.pi/5)**2 + numpy.cos(numpy.pi/5)**2

[29]: 1.0

[30]: math.sin(math.pi/5)**2 + math.cos(math.pi/5)**2

[30]: 1.0

We will dive into symbolic computations and sympy later on in this book. Here we
just give a snippet of how to work with symbols. Using the library sympy we can
introduce 𝑥 as a symbol called x. Python can then carry out arithmetic symbolically
with 𝑥, without enquiring what the value of 𝑥 is.

[31]: x = sympy.symbols('x')

[32]: x + 1

[32]: 𝑥 + 1

[33]: (2 * x + 3)**2

[33]: (2𝑥 + 3) 2

[34]: x = sympy.symbols('SometimesUPandsometimesDOWN')

[35]: x

[35]: 𝑆𝑜𝑚𝑒𝑡𝑖𝑚𝑒𝑠𝑈𝑃𝑎𝑛𝑑𝑠𝑜𝑚𝑒𝑡𝑖𝑚𝑒𝑠𝐷𝑂𝑊 𝑁

[36]: x /(1 + x)

[36]: 𝑆𝑜𝑚𝑒𝑡𝑖𝑚𝑒𝑠𝑈𝑃𝑎𝑛𝑑𝑠𝑜𝑚𝑒𝑡𝑖𝑚𝑒𝑠𝐷𝑂𝑊 𝑁
𝑆𝑜𝑚𝑒𝑡𝑖𝑚𝑒𝑠𝑈𝑃𝑎𝑛𝑑𝑠𝑜𝑚𝑒𝑡𝑖𝑚𝑒𝑠𝐷𝑂𝑊 𝑁 + 1
We calculate the expression sin2 (𝑥) + cos2 (𝑥) within sympy. Python then returns the
correct identity of 1 for this expression.

[37]: sympy.simplify(sympy.sin(x)**2 + sympy.cos(x)**2)

[37]: 1

Exercise 1.5 Investigate the following identities:


√ √
(1 + 5) 10 − (1 − 5) 10
√ = 55.
1024 5
1.2 Integers, Reals and Complex Numbers 9

Solution
We first use the library math to calculate the first expression.

[38]: ((1 + math.sqrt(5))**10 - (1 - math.sqrt(5))**10)/(1024*math.


↩→sqrt(5))

[38]: 55.000000000000014

Note that we have got a floating point number which is almost 55. This is to be
expected as the functions in the math library approach calculations “numerically”
and these methods will not give exact results. However the results are generally
extremely good with high precision.
Approaching the computations with numpy built-in functions would give the same
approximation.

[39]: ((1 + numpy.sqrt(5))**10 - (1-numpy.sqrt(5))**10)/


↩→(1024*numpy.sqrt(5))

[39]: 55.000000000000014

Employing sympy capabilities, we can actually show that equality holds for this
identity.

[40]: ((1 + sympy.sqrt(5))**10 - (1 - sympy.sqrt(5))**10)/


↩→(1024*sympy.sqrt(5))

[40]: √5 − 1 − √5 10 + 1 + √5 10
     

5120

[41]: sympy.simplify(_)

[41]: 55
We emphasise that floats (real numbers) are all about approximations.

[42]: 0.1 + 0.2

[42]: 0.30000000000000004

[43]: 0.3 - (0.1 + 0.2)

[43]: -5.551115123125783e-17

Although we were expecting 0, we got a non-zero number which is almost zero.


Using the built-in function round we can comfortably see what we got is indeed
extremely close to zero.
10 1 Basics of Python

[44]: round(0.3 - (0.1 + 0.2))

[44]: 0

Because Python is so widely used, help, hints and good samples are always a google
away. But one can also get a summary of the functions by using the command help.

[45]: help(round)

[45]: Help on built-in function round in module builtins:

round(number, ndigits=None)
Round a number to a given precision in decimal digits.

The return value is an integer if ndigits is omitted or


None. Otherwise the return value has the same type as the
number. ndigits may be negative.

1.3 Objects and their Types

Everything in Python is an object. One can think of an object as an ecosystem with


its own data and its own tools and functions that can be used to modify the data. Even
the numbers 3, 3.5 and 3.2 − 2𝑖 in Python are all objects. The objects have different
types. The function type determines the type of the objects we are working with:

[46]: type(3)

[46]: int

[47]: type(math.sqrt(2))

[47]: float

[48]: type(3.2 - 2j)

[48]: complex

Once we have an object, we can access their methods and functions via dot “.”. As
an example, the float object has a method called is integer, which determines
if a real number is indeed an integer.
1.3 Objects and their Types 11

[49]: x = math.sqrt(16)

[50]: x.is_integer()

[50]: True

Here the parameter x is assigned to math.sqrt(16). So x is an object of type


float. We can then use the methods and functions that come with this object, one
being is integer.

Exercise 1.6 Let 𝑚 be a natural number and


(𝑚 + 3) 3 + 1
𝐴= .
3𝑚

Find all the integers 𝑚 less than 10 such that 𝐴 is an integer. Show that 𝐴 is always
odd.

Solution
Although we don’t currently have many tools at our disposal, we can translate the
formula for 𝐴 in Python, replace 𝑚 by 1, 2, . . . and each time check if the computation
returns an integer with the method is integer(). Later on, when we know how to
create loops, we will revisit this exercise in Chapter 5 (Exercise 5.7) and find all the
numbers up to 500.

[51]: m = 2
x = ((m + 3)**3 + 1)/(3 * m)
x.is_integer()

[51]: True

[52]: x

[52]: 21.0

When working with a complex number 𝑎 + 𝑏𝑖, we would always like to have access to
the real part, 𝑎, and the imaginary part, 𝑏. The complex object comes with methods
to obtain this information.

[53]: x = 3.4 - 5.0j

[54]: print(x.real, ' ', x.imag)

[54]: 3.4 -5.0


12 1 Basics of Python

With x.imag we can access the imaginary part of the complex number 𝑥. This
imaginary part is a float object which comes with its own methods, which we now
use.

[55]: x.imag.is_integer()

[55]: True

[56]: x.real.is_integer()

[56]: False

Although the library math provides basic functions, such as sin and cos, these
functions are designed to handle real (float) numbers. If we are working with complex
numbers, we need to import the library cmath and its functions, which allow us to
handle complex arithmetic.

Exercise 1.7 If 𝑎 and 𝑏 are real numbers, show that the real part of
2
cos(𝑎 + 𝑏𝑖) + sin(𝑎 + 𝑏𝑖)

is equal to
1 + sin(2𝑎) cosh(𝑏) 2 + sinh(𝑏) 2


and find a similar expression for its imaginary part.

Solution
Although this identity should be valid for any 𝑎 and 𝑏, we are going to choose some
values for 𝑎 and 𝑏 and test the claim. Later when we define functions in Python
we shall be able to check this for any value of 𝑎 and 𝑏. Since we are working with
complex numbers, we import the library cmath.

[57]: import cmath

(cmath.cos(1 + 1j) + cmath.sin(1 + 1j))**2

[57]: (4.420954861117013-1.5093064853236153j)

[58]: ((cmath.cos(1 + 1j) + cmath.sin(1 + 1j))**2).real

[58]: 4.420954861117013

[59]: ((cmath.cos(1 + 1j) + cmath.sin(1 + 1j))**2).imag

[59]: -1.5093064853236153
1.4 Importing Libraries in Python 13

[60]: 1 + cmath.sin(2)*(cmath.cosh(1)**2 + cmath.sinh(1)**2)

[60]: (4.420954861117013+0j)

Comparing the results we see the statement of the exercise is valid for this particular
𝑎 and 𝑏.

1.4 Importing Libraries in Python

We have seen that import math makes the library math available for use. If the
name of a library is long, one can introduce an alias.

[61]: import numpy as np

[62]: np.sin(np.pi / 2)

[62]: 1.0

Although one could use import numpy as MyDarling or any other alias, the
name np has become quite widespread in the community.
If one uses certain methods of a library quite often, one can import them directly.

[63]: from sympy import sin, cos, pi, simplify, symbols

[64]: x = symbols('x')
y = symbols('what?')

[65]: (x + 1/y) * (1/x + y)


  
[65]: 𝑤ℎ𝑎𝑡? + 1 𝑥 + 1
𝑥 𝑤ℎ𝑎𝑡?

[66]: simplify(sin(x)**2 + cos(x)**2)

[66]: 1
We should warn the reader that confusion might arise as to where these methods
belong. If one imports methods from different libraries then the later methods will
overwrite the earlier ones.
14 1 Basics of Python

1.5 Variables in Python

In order to feed data into a computer program one needs to define variables to be
able to assign data to them. Python’s methodology in assigning data to variables is
slightly different than in other languages. We start with the simplest assignment of a
number to a variable.

[67]: x = 2

[68]: x

[68]: 2

As long as you use common sense, any names you choose for variables are valid
(provided they are not used as Python keywords). Names like x, y, x3, myfunc,
xQuaternion as well as x 3, my func, x Quaternion are all fine. Also note that
Python is case-sensitive, thus xy and xY are considered as two different variables.
We assign values to these variable using ; to write the code in one line.

[69]: xy = 12 ; xY = -1.4; x_y = 2-3j

[70]: xy

[70]: 12

[71]: xY

[71]: -1.4

We could also assign the values in line as a tuples. We will see these concepts in
Chapter 2.

[72]: xy, xY, x_y = 12, -1.4, 2-3j

[73]: xY

[73]: -1.4

[74]: xy**2 - xY**2 + x_y**2

[74]: (137.04-12j)

One crucial difference in Python that we need to understand at this early stage is
that the variables are pointers. In other languages the command x = 2 creates a cell
or (an object) labelled x and 2 is stored in that cell, whereas in Python there is an
integer object 2 and x is a pointer, pointing to that object. There is no immediate
1.6 Equalities and Boolean Statements 15

harm if we just think of x as a variable that 2 is assigned to, but in the background
we have to be aware of the Python philosophy.

[75]: x = y = z = 10

The way we should understand this line is that we have created three pointers all
pointing to the integer object 10. We could change one of the pointers, pointing to a
different object without changing the direction of the other two pointers.

[76]: z = 12

We print the values of these variables. Note that the command \n in print breaks
the line as the result shows.

[77]: print('x is pointing to', x, '\ny is pointing to', y, '\nz is


↩→pointing to', z)

[77]: x is pointing to 10
y is pointing to 10
z is pointing to 12

This becomes more clear when we work with objects that can be changed (mutable),
for example lists.
On some occasions the existence of a variable is needed more so than the variable
itself. Sometimes we require that a dummy variable runs through a loop, or a list. In
this case we can simply use instead of coming up with a name.

[78]: _ = 5

[79]: _

[79]: 5

[80]: a, _ , _, b = 10, 13, 12, 100

[81]: print(a,'and', b)

[81]: 10 and 100

1.6 Equalities and Boolean Statements

Primarily there are two equalities in Python = and ==. The first one creates a pointer,
whereas == is used for comparison. The result of the comparison is a boolean value
of True or False
16 1 Basics of Python

[82]: 1 + 2 == 3

[82]: True

[83]: 3**2 + 4**2 == 5**2

[83]: True

[84]: 9**10 == 10**9

[84]: False

Recall the Euclidean division 𝑛 = 𝑚𝑞 + 𝑟. We can check its validity here with an
example.

[85]: 23 == (23 // 4) * 4 + 23 % 4

[85]: True

However we should be careful when working with floats, as the computations have
been done up to a certain precision.

[86]: 0.1 + 0.2 == 0.3

[86]: False

[87]: 0.1 + 0.2

[87]: 0.30000000000000004

In mathematical logic, statements can have a value of True, False or undefined.


These are called Boolean expressions. This helps us to “make a decision” and
write programs based on the value of a statement. We will see later how to use
if-else statements to control the flow of the program based on the value of boolean
expressions.
One can combine logical statements with the usual boolean operations and, or, not
or the equivalent &, |, !, as the following examples show:

[88]: 2 > 3

[88]: False

[89]: not(2 > 3)

[89]: True
1.6 Equalities and Boolean Statements 17

[90]: 2 > 3 or 3 > 2

[90]: True

[91]: 3**2 + 4**2 >= 5**2

[91]: True

Exercise 1.8 Is the following statement correct!?


(1 < 2 < 3) == (1 < 2) and (2 < 3)
True

Solution
In fact the way this statement is written is misleading! Indeed 1 < 2 < 3 means
exactly 1 < 2 and 2 < 3. However in the statement above, Python evaluates the
left-hand side (which is True) and then evaluates the right-hand side (again True)
and then compare the two. Therefore the statement below also gives True, which is
not mathematically equivalent.

[92]: (1 < 2 < 3) == (1 < 2) and (2 < 10)

[92]: True

Exercise 1.9 The hyperbolic functions are combinations of exponential functions.


As an example
e 𝑥 − e− 𝑥 e 𝑥 + e− 𝑥
sinh(𝑥) = , and cosh(𝑥) =
2 2

using the math library check that these equalities hold for any 𝑥.

Solution
The hyperbolic function sinh is available in the math library. We will check if this
−𝑥
function returns the same value as e −e
𝑥
2 , here for 𝜋. Later in Chapter 4, we define
−𝑥
functions within Python. Once this is done, we can define the function 𝑓 (𝑥) = e −e
𝑥
2
and systematically compare these two functions.

[93]: import math

p = math.pi
sh = (math.exp(p) - math.exp(-p))/2
math.sinh(p) == sh
18 1 Basics of Python

[93]: False

[94]: print(math.sinh(p), sh)

[94]: 11.548739357257746 11.548739357257748

Again, we can see that, although the results are not precisely the same, they are very
very close!

1.7 Strings

We have seen several types of objects: integers, floats, complex as well as booleans.
We finish this chapter with the type string.

[95]: 'this is a string'

[95]: 'this is a string'

[96]: message = 'Western Sydney '


type(message)

[96]: str

One can perform certain ‘arithmetic’ operations with strings, as the following exam-
ples show.

[97]: message + 'University'

[97]: 'Western Sydney University'

[98]: message * 3

[98]: 'Western Sydney Western Sydney Western Sydney '

[99]: message

[99]: 'Western Sydney '

[100]: message = message + 'University'

[101]: message

[101]: 'Western Sydney University'


1.8 Strings as Objects 19

1.8 Strings as Objects

We have already mentioned that everything in Python is an object. Once the object
is defined, the functions and methods are all at our disposal to use. Here we will
use several methods available for str objects. The examples below show how these
methods are used.

[102]: message

[102]: 'Western Sydney University'

[103]: message.capitalize()

[103]: 'Western sydney university'

[104]: message.lower()

[104]: 'western sydney university'

[105]: message.upper()

[105]: 'WESTERN SYDNEY UNIVERSITY'

[106]: message

[106]: 'Western Sydney University'

All the methods used above, upper, lower, capitalize are provided within the
object of string. As is clear from the example, they operate on the object message
but do not change the object itself.
One very useful method when working with strings is to use format strings, which
allows us to pass data inside a string where the location is determined by {}.

[107]: 'University of {}'.format('Sydney')

[107]: 'University of Sydney'

[108]: 'University of {}'.format(123)

[108]: 'University of 123'

[109]: name = 'First name: {}, Last name: {}'

[110]: name.format('Lustig', 'Sabzian')


20 1 Basics of Python

[110]: 'First name: Lustig, Last name: Sabzian'

There is a simpler way to use format strings, as the following shows. They can be
used very nicely with the command print, as we will see later on.

[111]: fn = 'Lustig'
ln = 'Sabzian'

f'First name: {fn}, last name: {ln}'

[111]: 'First name: Lustig, last name: Sabzian'

[112]: x = 2
y = math.sqrt(x)

f'the square root of {x} is {y}'

[112]: 'the square root of 2 is 1.4142135623730951'

1.9 Input and Output

We close this chapter with two useful commands. The command input asks for data
to be given to the program by the user. The data entered is captured as a string.

[113]: s = input('enter a text: ')


print(s + ' checked')

enter a text: Python


[113]: Python checked

Here is a standard way to change the data to numbers, in case one requires the input
to be integers, or reals etc.

[114]: s = int(input('enter a number: '))


s

enter a number: 666


[114]: 666

[115]: s = input('Name ')


t = input('age ')
s + ' is ' + t + ' years old.'
1.9 Input and Output 21

Name Dad
age 92
[115]: 'Dad is 92 years old.'

The command print will create an output. The following examples show the various
ways one can use print.

[116]: print('printing a string')

[116]: printing a string

[117]: print(2 * 3 * 4 + 1.4)

[117]: 25.4

[118]: print(12, 'is smaller than', 15)

[118]: 12 is smaller than 15

As mentioned, the format strings fit very nicely with the print command.

[119]: x = 2
y = math.sqrt(x)
print(f'the square root of {x} is {y}')

[119]: the square root of 2 is 1.4142135623730951

Finally there are certain special characters that can be used with strings. Among
them are \n and \t, which give a new line and a new tab, respectively.

[120]: print('Hello\tworld\nfinal\tgreetings')

[120]: Hello world


final greetings

We finish the chapter with an amusing example, showcasing several of the methods
available for working with strings.

[121]: secret = 'xzwoy thx uilxzcx'


x = 'zxawu'
y = 'neojs'
table = secret.maketrans(x, y)
print(secret.translate(table))

[121]: enjoy the silence


22 1 Basics of Python

Problems

1) Compute
√︂ √︂ √︂
1 1 1 1 1 1
1+ 2 + 2 + 1+ 2 + 2 + 1+ 2
+ 2
1 2 2 3 3 4
2) Compute
1
1 1 1   5 5 5 5   11 11 11 11 
+ ++ + + + + + + + +
2 3 5 7 2 3 5 7 2 3 5 7
3) Show that for any two positive numbers 𝑎 and 𝑏, if 𝑎 + 𝑏 = 1, then
 1 2  1  2 25
𝑎+ + 𝑏+ ≥ .
𝑎 𝑏 2
4) Use Python to show that
3𝜋 2𝜋 √
tan + 4 sin = 11.
11 11
Note, one needs to use the math library or numpy to have access to the square
root, sine and tangent functions.
5) Show that √︃√
3 
64 22 + (1/2) 2 − 1 = 4.
6) Show that
√︂  √︂ 
2𝜋 4𝜋 10𝜋 1 √  1 √ 
sin( ) + sin( ) + · · · + sin( )= 5− 5 + 5+ 5
10 10 10 2 2
7) Show that
   1        
1 𝜋 3𝜋 1 9𝜋 1 27 𝜋 1
2 + cos 20 2 + cos 20 2 + cos 20 2 + cos 20 = 16 .

8) By looking at various examples, observe that the product of four consecutive


numbers plus one is always a square number.
9) Using Python, demonstrate that

1 + sin(𝑥) − cos(𝑥)
= tan(𝑥/2).
1 + sin(𝑥) + cos(𝑥)
Chapter 2
Lists and Tuples

2.1 Data: Lists

In Python, lists provide the first basic building blocks for working with and handling
data.
One can think of a computer program as a function which accepts some (crude) data
or information and gives back the data we would like to obtain. The classic Python
provides certain tools to collect and handle data, such as list, tuple, set and
dictionary. Libraries such as numpy further provide capable tools to work with a
large collection of data. In this chapter we will study list and tuple; how to collect
data and how to access and process the elements in these collections. We will study
set and dictionary in Chapter 5.
Data Science starts with handling data, such as data cleansing, aggregation, trans-
formation, and data visualisation, and lists are the first stop in this process. Once we
grasp the concept of the lists and how to work with them, we can comfortably work
with other objects which are designed for handling data.
We start with an example of a list:

[1]: L = [3, 6.4, 3, 'stuff', 'xˆ2+x+1', 64/3]

[2]: type(L)

[2]: list

[3]: L

[3]: [3, 6.4, 3, 'stuff', 'xˆ2+x+1', 21.333333333333332]

© The Author(s), under exclusive license to Springer Nature Switzerland AG 2023 23


R. Hazrat, A Course in Python, Springer Undergraduate Mathematics Series,
https://doi.org/10.1007/978-3-031-49780-3_2
24 2 Lists and Tuples

list is one of the ways to collect data in Python. As this example shows, the data
(of any type and format) are arranged between square brackets, [ and ]. Lists respect
order and repetition of the data:

[4]: [1, 2] == [2, 1]

[4]: False

[5]: [1, 1, 2] == [1, 2]

[5]: False

We can check if an element belongs to a list

[6]: 2 in [1, 2, 3]

[6]: True

[7]: 'mode' in ['fast', 'fashion']

[7]: False

Similar to strings, we can do certain arithmetic operations with lists. Recall the list
L above.

[8]: L + ['more', 'less', [4, 4, 4]]

[8]: [3, 6.4, 3, 'stuff', 'xˆ2+x+1', 21.333333333333332, 'more',


'less', [4, 4, 4]]

[9]: ['Western', 'Sydney'] * 2

[9]: ['Western', 'Sydney', 'Western', 'Sydney']

[10]: [1, 2] + [3, 4]

[10]: [1, 2, 3, 4]

As the above examples show, we can add another list to the end of a given list by
adding them together or repeat the list by multiplication.

2.1.1 Accessing entries of a list

It is natural to need to access the elements of a list.


2.1 Data: Lists 25

[11]: L

[11]: [3, 6.4, 3, 'stuff', 'xˆ2+x+1', 21.333333333333332]

[12]: L[0]

[12]: 3

[13]: L[4]

[13]: 'xˆ2+x+1'

[14]: L[-1]

[14]: 21.333333333333332

[15]: L[-2]

[15]: 'xˆ2+x+1'

In Python indexing of elements starts from 0. Thus we start counting from 0 (which
refers to the first element of the list!) Examining the above examples reveals that
L[i] gives the 𝑖 + 1-th member of the list. Thus L[0] points to the first element
in the list. To obtain consecutive elements of a list one can use the command
L[n : m]. Here L[n : m] retrieves the elements in the list L, from the 𝑛 + 1-th up
to (at most) the 𝑚-th item. The command L[n : m : s] introduces “step” 𝑠, and
one retrieves elements 𝑛 + 1, 𝑛 + 1 + 𝑠, 𝑛 + 1 + 2𝑠, . . . up to the 𝑚-th element. The
examples below make this clear.

[16]: L

[16]: [3, 6.4, 3, 'stuff', 'xˆ2+x+1', 21.333333333333332]

[17]: L[1 : 5]

[17]: [6.4, 3, 'stuff', 'xˆ2+x+1']

Here is the meaning of retrieving up to at most the m-th item in L[n:m].

[18]: L[1 : 100]

[18]: [6.4, 3, 'stuff', 'xˆ2+x+1', 21.333333333333332]

[19]: L[1 : 5 : 2]

[19]: [6.4, 'stuff']


26 2 Lists and Tuples

Notice that in the above examples, we start with the second element in the list and
go all the way up to the sixth element and each time pick every second element.
In the command L[n : m], if we leave out n, the list starts from the beginning, and
if we leave out m, it goes all the way to the end. The examples below make this clear.

[20]: L

[20]: [3, 6.4, 3, 'stuff', 'xˆ2+x+1', 21.333333333333332]

[21]: L[ : 5]

[21]: [3, 6.4, 3, 'stuff', 'xˆ2+x+1']

[22]: L[ : -1]

[22]: [3, 6.4, 3, 'stuff', 'xˆ2+x+1']

[23]: L[4 : ]

[23]: ['xˆ2+x+1', 21.333333333333332]

[24]: L[ : 100]

[24]: [3, 6.4, 3, 'stuff', 'xˆ2+x+1', 21.333333333333332]

[25]: L[4 : 1 : -1]

[25]: ['xˆ2+x+1', 'stuff', 3]

[26]: L[ : : -1]

[26]: [21.333333333333332, 'xˆ2+x+1', 'stuff', 3, 6.4, 3]

[27]: L == L[ : 4] + L[4 : ]

[27]: True

Exercise 2.1 Define the lists


campus=['Parramatta', 'Campbelltown', 'Kingswood']
and allocation=[30,10,7]
and then create the list
total=['Parramatta', 30, 'Campbelltown', 10, 'Kingswood, 7]
2.1 Data: Lists 27

Solution
We first define our given lists.

[28]: campus = ['Parramatta ', ' Campbelltown ', ' Kingswood ']

[29]: allocation = [30, 10, 7]

This is the most naive way to put these lists together:

[30]: total = [[campus[0] , allocation[0]] ,


[campus[1] , allocation[1]] , [campus[2] ,
↩→allocation[2]]]

[31]: total

[31]: [['Parramatta ', 30], [' Campbelltown ', 10],


[' Kingswood ', 7]]

We could also use the following rather more clever approach:

[32]: CA = campus + allocation

[33]: CA

[33]: ['Parramatta ', ' Campbelltown ', ' Kingswood ', 30, 10, 7]

[34]: [CA[0 :: 3], CA[1 :: 3], CA[2 :: 3]]

[34]: [['Parramatta ', 30], [' Campbelltown ', 10],


[' Kingswood ', 7]]

Yet another way to put these together (in the absence of loops):

[35]: CA = []

[36]: CA += [[campus[0], allocation[0]]]


CA += [[campus[1], allocation[1]]]
CA += [[campus[2], allocation[2]]]

CA

[36]: [['Parramatta ', 30], [' Campbelltown ', 10],


[' Kingswood ', 7]]
28 2 Lists and Tuples

Of course, for a larger collection of lists, and with the loop facilities at our disposal
(which we will meet in Chapter 3), the above code could be modified to pair the lists
together via a loop.
Returning to our list L, we can replace an element inside the list by singling out that
element and assigning new data to it.

[37]: L

[37]: [3, 6.4, 3, 'stuff', 'xˆ2+x+1', 21.333333333333332]

[38]: L[4] = 'replacement'

[39]: L

[39]: [3, 6.4, 3, 'stuff', 'replacement', 21.333333333333332]

[40]: L[0] = L[2] = L[4] = 'XXX'

[41]: L

[41]: ['XXX', 6.4, 'XXX', 'stuff', 'XXX', 21.333333333333332]

One of the secrets of writing code comfortably is that one should be able to manipulate
lists easily. Often in applications, situations like the following arise:
• Given {𝑥1 , 𝑥2 , · · · , 𝑥 𝑛 } and {𝑦 1 , 𝑦 2 , · · · , 𝑦 𝑛 }, produce

{𝑥1 , 𝑦 1 , 𝑥2 , 𝑦 2 , · · · , 𝑥 𝑛 , 𝑦 𝑛 },

and 
{𝑥1 , 𝑦 1 }, {𝑥2 , 𝑦 2 }, · · · , {𝑥 𝑛 , 𝑦 𝑛 } .

• Given {𝑥1 , 𝑥2 , · · · , 𝑥 𝑛 } and {𝑦 1 , 𝑦 2 , · · · , 𝑦 𝑛 }, produce

{𝑥1 + 𝑦 1 , 𝑥2 + 𝑦 2 , · · · , 𝑥 𝑛 + 𝑦 𝑛 }.

• Given {𝑥1 , 𝑥2 , · · · , 𝑥 𝑛 } and {𝑦 1 , 𝑦 2 , · · · , 𝑦 𝑛 }, produce



{𝑥1 , 𝑦 1 }, {𝑥1 , 𝑦 2 }, · · · , {𝑥 1 , 𝑦 𝑛 }, {𝑥 2 , 𝑦 1 }, {𝑥2 , 𝑦 2 }, · · · , {𝑥 2 , 𝑦 𝑛 },
· · · , {𝑥 𝑛 , 𝑦 1 }, {𝑥 𝑛 , 𝑦 2 }, · · · , {𝑥 𝑛 , 𝑦 𝑛 } .

• Given {𝑥1 , 𝑥2 , · · · , 𝑥 𝑛 }, produce

{𝑥1 , 𝑥1 + 𝑥2 , · · · , 𝑥1 + 𝑥2 + · · · + 𝑥 𝑛 }.
2.2 Lists as Objects 29

• Given {𝑥1 , 𝑥2 , · · · , 𝑥 𝑛 }, produce

n   o
{𝑥1 }, {𝑥2 , . . . , 𝑥 𝑛 } , {𝑥1 , 𝑥2 }, {𝑥 3 , . . . , 𝑥 𝑛 } . . . {𝑥1 , . . . 𝑥 𝑛−1 }, {𝑥 𝑛 } .

As we progress, we will see Python and especially the library numpy provide tools
to produce such combinations from lists and other collections of data.

2.2 Lists as Objects

Recall that everything in Python is an object, which comes with its own tools (i.e.,
methods). With this view, lists are objects which we can change, the so-called mutable
objects. The objects that cannot be changed are called immutable. We have already
seen one object that, once created, cannot be modified, namely the object integers.
We will demonstrate how to use some of the list methods to modify a given list.

[42]: L = [3, 6.4, 3, 'stuff', 'xˆ2+x+1', 64/3]

[43]: L.append('extra bit')

[44]: L

[44]: [3, 6.4, 3, 'stuff', 'xˆ2+x+1', 21.333333333333332,


'extra bit']

append is one of the methods available in the object list. It adds an item to the end
of the list, as the example above demonstrates. Already the method append allows
us to solve the above exercise differently.

[45]: total = [];


total.append(campus[0])
total.append(allocation[0])

[46]: total

[46]: ['Parramatta ', 30]

[47]: total.append(campus[1]); total.append(allocation[1])

[48]: total

[48]: ['Parramatta ', 30, ' Campbelltown ', 10]


30 2 Lists and Tuples

[49]: total.append(campus[2]); total.append(allocation[2])

[50]: total

[50]: ['Parramatta ', 30, ' Campbelltown ', 10, ' Kingswood ', 7]

Besides append, list comes with several other methods, such as count, reverse,
. . . . As an example:

[51]: L = [1, 2, 1.2, 3 - 1, 'stuff', 2, 4]


L.count(2)

[51]: 3

[52]: L.reverse()
L

[52]: [4, 2, 'stuff', 2, 1.2, 2, 1]

Lists can have other lists as elements. We can envisage the notion of matrices in
mathematics via lists of list. Recall that an 𝑛 × 𝑚 matrix is mathematical objects with
𝑛-rows and 𝑚-columns. An 𝑛 × 𝑚 matrix 𝐴 then consists of 𝑛 × 𝑚 objects (usually
numbers) and an entry on the 𝑖-th row and 𝑗-column can be denoted by 𝑎 𝑖 𝑗 . We
translate the 3 × 3 matrix 𝐴 below into Python

123
𝐴 = ­4 5 6®.
© ª

«7 8 9¬

The example below can be thought of as a matrix with three rows and three columns

[53]: L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

[54]: L

[54]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

[55]: L[0]

[55]: [1, 2, 3]

[56]: L[0][0]

[56]: 1
2.2 Lists as Objects 31

[57]: L[0][0] = L[1][1] = L[2][2] = 'Diagonal'

[58]: L

[58]: [['Diagonal', 2, 3], [4, 'Diagonal', 6], [7, 8, 'Diagonal']]

Exercise 2.2 Create a 4 × 3 matrix with entries all 0


0 0 0
­0 0 0®
© ª
𝐴=­ ®.
­0 0 0®
«0 0 0¬

Solution
Here is a clever way to do this, benefiting from the arithmetic on lists.

[59]: S = [[0] * 3] * 4
S

[59]: [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

One needs to be a bit careful here: when we use list * 3, Python creates three
copies of the same object. This becomes clear when we change one of the objects,
as the example below shows:

[60]: S[0][1] = 'upset'


S

[60]: [[0, 'upset', 0], [0, 'upset', 0], [0, 'upset', 0],
[0, 'upset', 0]]

Compare the above with the following:

[61]: T = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

[62]: T[0][1] = 'upset'


T

[62]: [[0, 'upset', 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

[63]: S = [[0] * 3] * 3
S

[63]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]


32 2 Lists and Tuples

[64]: S[1] = [-1, -2]


S

[64]: [[0, 0, 0], [-1, -2], [0, 0, 0]]

Of course one needs to be mindful of what one adds to a list and how to handle it.
We give a curious example and leave it to the reader to further explore this direction.

[65]: L=[3, 6.4, 3, 'stuff', 'xˆ2+x+1', 64/3]

[66]: L.append(L)

[67]: print(L)

[3, 6.4, 3, 'stuff', 'xˆ2+x+1', 21.333333333333332, [...]]

[68]: L[-1]

[68]: [3, 6.4, 3, 'stuff', 'xˆ2+x+1', 21.333333333333332, [...]]

[69]: L[-1][0]

[69]: 3

[70]: L[-1][-1]

[70]: [3, 6.4, 3, 'stuff', 'xˆ2+x+1', 21.333333333333332, [...]]

[71]: L[-1][-1][-1]

[71]: [3, 6.4, 3, 'stuff', 'xˆ2+x+1', 21.333333333333332, [...]]

We can now explore the notion of pointers (variables) and mutable objects a bit more
using lists. Suppose we define two pointers both pointing to a list.

[72]: x = y = [1, 2, 3, 4]

[73]: x

[73]: [1, 2, 3, 4]

[74]: y

[74]: [1, 2, 3, 4]

Now if we modify the object [1, 2, 3, 4] then both pointers x and y which are
pointing to this object will show this change
2.2 Lists as Objects 33

[75]: x.append('extra bit')


x

[75]: [1, 2, 3, 4, 'extra bit']

[76]: y

[76]: [1, 2, 3, 4, 'extra bit']

However we can re-direct the pointer y to a different object.

[77]: y = ['another', 'object']


y

[77]: ['another', 'object']

[78]: x

[78]: [1, 2, 3, 4, 'extra bit']

In order to show how versatile lists are, we use the Python library PIL, which handles
images. Recall we can import libraries into Python as follows:

[79]: from PIL import Image

[80]: x = Image.open('dog.jpg')
y = Image.open('Napoleon.jpg')

The files dog.jpg and Napoleon.jpg are in the local directory. We have now
assigned x and y to these pictures, respectively.

[81]: x

[81]:
34 2 Lists and Tuples

[82]: y

[82]:

Now we can define a list which contains different types of objects, including images

[83]: pic = ['cute dog', x , x.size, 'Napoleon', y, y.size]

[84]: display(pic[0], pic[1], pic[2])

[84]: 'cute dog'

(144, 178)

The object image comes with its own methods and tools. We just sample one or two
of them here.

[85]: pic[4].rotate(180)
2.2 Lists as Objects 35

[85]:

[86]: pic[1].effect_spread(10)

[86]:

Exercise 2.3 Given a list, swap the first and the last element of the list.

Solution
First, we define a list to work with.

[87]: L=['first', 4, 8, 'stuff', 9/2, 'last']

Of course one crude approach is to do this:

[88]: L[0] = 'last'


L[-1] = 'first'
36 2 Lists and Tuples

[89]: L

[89]: ['last', 4, 8, 'stuff', 4.5, 'first']

or a slightly better approach:

[90]: temp = L[0]; L[0] = L[-1]; L[-1] = temp

[91]: L

[91]: ['first', 4, 8, 'stuff', 4.5, 'last']

However there is a more elegant way to do this:

[92]: L[0], L[-1] = L[-1], L[0]

[93]: L

[93]: ['last', 4, 8, 'stuff', 4.5, 'first']

and finally there is yet another elegant way using the sequences:

[94]: [f, *r , l] = L

[95]: [l, *r , f]

[95]: ['first', 4, 8, 'stuff', 4.5, 'last']

Here f is assigned to the first element of the list L, l is assigned to the last element
and *r assigned to the sequence between the first and last element. Thus in the next
line [l, *r, f] we simply swap the first and last element and keep the sequence
*r. Python can even recognise the assignment if we drop the brackets:

[96]: f, *r , l = L

[97]: [l, *r, f]

[97]: ['first', 4, 8, 'stuff', 4.5, 'last']

Exercise 2.4 Consider the matrix


𝑎𝑏 𝑐
𝑀 = ­𝑑 𝑒 𝑓 ®
© ª

«𝑔 ℎ 𝑘 ¬

and create its transpose.


Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of The Boy
Scouts of Woodcraft Camp
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

Title: The Boy Scouts of Woodcraft Camp

Author: Thornton W. Burgess

Illustrator: C. S. Corson

Release date: May 21, 2017 [eBook #54755]


Most recently updated: October 23, 2024

Language: English

Credits: Produced by Emmy, MFR, Sam W. and the Online


Distributed
Proofreading Team at http://www.pgdp.net (This file
was
produced from images generously made available by
The
Internet Archive). Dedicated, with much affection, to
our
friend Emmy, who "fell off the planet" far too soon.

*** START OF THE PROJECT GUTENBERG EBOOK THE BOY SCOUTS


OF WOODCRAFT CAMP ***
The Boy Scouts
of
Woodcraft Camp

By
Thornton W. Burgess
Author of
The Boy Scouts on Swift River
The Boy Scouts on Lost Trail
The Boy Scouts in a Trapper’s Camp
Illustrated by C. S. Corson

The Penn Publishing


Company Philadelphia
1922
THE CHIEF GREETED HIM PLEASANTLY
To my Wife

whose faith and encouragement


have placed me in her debt
beyond my power to pay
Introduction
The Boy Scout movement has appealed to me from the very first as
a long step in the right direction. It stands for an organized boyhood
on a world-wide plan. It has in it the essentials for a stronger and
better manhood, based on character building and physical
development. Clear and clean thinking and self-reliance are its
fundamental principles. Its weakness has been and is the difficulty in
securing leaders, men with an understanding of and sympathy with
boys, who can give the necessary time to active work in the field
with the patrols, and who are themselves sufficiently versed in the
lore of the woods and fields.
For years, before ever the Boy Scouts were organized, I had
dreamed of a woodcraft camp for boys, a camp which in its
appointments and surroundings should make constant appeal to the
imagination of red-blooded, adventure-loving boys, and which
should at the same time be a true “school of the woods” wherein
woodcraft and the ways of nature should be taught along much the
same lines as those on which the Boy Scout movement is founded.
In this and succeeding volumes, “The Boy Scouts on Swift River,”
“The Boy Scouts on Lost Trail,” “The Boy Scouts in a Trapper’s
Camp,” I have sought to portray the life of such a school camp under
Boy Scout rules. “The Boy Scouts of Woodcraft Camp” has been
written with a twofold purpose: To stimulate on the part of every
one of my boy readers a desire to master for himself the mysteries
of nature’s great out-of-doors, the secrets of field and wood and
stream, and to show by example what the Boy Scout’s oath means
in the development of character. Many of the incidents in the
succeeding pages are drawn from my own experiences. And if,
because of reading this story, one more boy is led to the Shrine of
the Hemlock, there to inhale the pungent incense from a camp-fire
and to master the art of tossing a flapjack, I shall feel that I have
not written in vain.
The Author.
Contents
I. The Tenderfoot 11
II. Woodcraft Camp 26
III. First Impressions 39
IV. The Initiation 56
V. The Recall 71
VI. The Specter in Camp 86
VII. First Lessons 100
VIII. Lonesome Pond 116
IX. A Shot in the Dusk 136
X. A Battle for Honor 161
XI. Buxby’s Buncombe 184
XII. Lost 199
XIII. The Honey Seekers 220
XIV. The Supreme Test 237
XV. Crafty Mike 254
XVI. The Poacher of Lonesome Pond 273
XVII. The Haunted Cabin 288
XVIII. On Guard 304
XIX. For the Honor of the Tribe 319
XX. The Home Trail 337
Illustrations
The Chief Greeted Him Pleasantly Frontispiece
Diagram of Woodcraft Camp 41
“Tell Him You Are to Be a Delaware” 51
He Had Built a Fire 118
Billy’s Apparatus for Making Fire 207
“Run!” He Yelled 233
The Boys Were Drilled in Wig-Wag Signaling 308
The Boy Scouts of Woodcraft Camp
CHAPTER I
THE TENDERFOOT

In the semi-darkness of daybreak a boy of fourteen jumped from a


Pullman sleeper and slipped a quarter into the hand of the dusky
porter who handed down his luggage.
“You are sure this is Upper Chain?” he inquired.
“’Spects it is, boss, but I ain’t no ways sho’. Ain’t never been up this
way afore,” replied the porter, yawning sleepily.
The boy vainly strove to pierce the night mist which shrouded
everything in ghostly gray, hoping to see the conductor or a
brakeman, but he could see barely half the length of the next
Pullman. A warning rumble at the head of the long train admonished
him that he must act at once; he must make up his mind to stay or
he must climb aboard again, and that quickly.
The long night ride had been a momentous event to him. He had
slept little, partly from the novelty of his first experience in a
sleeping car, and partly from the excitement of actually being on his
way into the big north woods, the Mecca of all his desires and
daydreams. Consequently he had kept a fairly close record of the
train’s running time, dozing off between stations but waking instantly
whenever the train came to a stop. According to his reckoning he
should now be at Upper Chain. He had given the porter strict orders
to call him twenty minutes before reaching his destination, but to his
supreme disgust he had had to perform that service for the darkey.
That worthy had then been sent forward to find the conductor and
make sure of their whereabouts. Unsuccessful, he had returned just
in time to hand down the lad’s duffle.
Now, as the preliminary jerk ran down the heavy train, the boy once
more looked at his watch, and made up his mind. If the train was on
time, and he felt sure that it was, this was Upper Chain, the junction
where he was to change for the final stage of his journey. He would
stay.
The dark, heavy sleepers slowly crept past as the train gathered
way, till suddenly he found himself staring for a moment at the red
and green tail lights. Then they grew dim and blinked out in the
enveloping fog. He shivered a bit, for the first time realizing how
cold it was at this altitude before daybreak. And, to be quite honest,
there was just a little feeling of loneliness as he made out the dim
black wall of evergreens on one side and the long string of empty
freight cars shutting him in on the other. The whistle of the laboring
locomotive shrieked out of the darkness ahead, reverberating with
an eery hollowness from mountain to mountain. Involuntarily he
shivered again. Then, with a boyish laugh at his momentary loss of
nerve, he shouldered his duffle bag and picked up his fishing-rod.
“Must be a depot here somewhere, and it’s up to me to find it,” he
said aloud. “Wonder what I tipped that stupid porter for, anyway!
Dad would say I’m easy. Guess I am, all right. Br-r-r-r, who says this
is July?”
Trudging along the ties he soon came to the end of the string of
empties and, a little way to his right, made out the dim outlines of a
building. This proved to be the depot. A moment later he was in the
bare, stuffy little waiting-room, in the middle of which a big stove
was radiating a welcome warmth.
On a bench at one side sat two roughly-dressed men, who glanced
up as the boy entered. One was in the prime of vigorous manhood.
Broad of shoulder, large of frame, he was spare with the leanness of
the professional woodsman, who lives up to the rule that takes
nothing useless on the trail and, therefore, cannot afford to carry
superfluous flesh. The gray flannel shirt, falling open at the neck,
exposed a throat which, like his face, was roughened and bronzed
by the weather.
The boy caught the quick glance of the keen blue eyes which, for all
their kindly twinkle, bored straight through him. Instinctively he felt
that here was one of the very men his imagination had so often
pictured, a man skilled in woodcraft, accustomed to meeting danger,
clear-headed, resourceful—in fact just such a man as was
Deerslayer, whose rifle had so often roused the echoes in these very
woods.
The man beside him was short, thick-set, black-haired and mare-
browed. His skin was swarthy, with just a tinge of color to hint at
Indian ancestry among his French forebears. He wore the large
check mackinaw of the French Canadian lumberman. Against the
bench beside him rested a double-bladed axe. A pair of beady black
eyes burned their way into the boy’s consciousness. They were not
good eyes; they seemed to carry a hint of hate and evil, an
unspoken threat. The man, taking in the new khaki suit of the boy
and the unsoiled case of the fishing-rod, grunted contemptuously
and spat a mouthful of tobacco juice into the box of sawdust beside
the stove. The boy flushed and turned to meet the kindly, luminous
eyes of the other man.
“If you please, is this Upper Chain?” he inquired.
“Sure, son,” was the prompt response. “Reckon we must hev come
in on th’ same train, only I was up forward. Guess you’re bound for
Woodcraft Camp. So’m I, so let’s shake. My name’s Jim Everly—‘Big
Jim’ they call me—and I’m goin’ in t’ guide fer Dr. Merriam th’ rest o’
th’ summer and try to teach you youngsters a few o’ th’ first
principles. What might yer name be an’ whar be yer from?”
“Walter Upton, but the boys mostly call me ‘Walt.’ My home is in
New York,” replied the boy.
“Never hit th’ trail t’ th’ big woods afore, did yer?” inquired the big
guide, rising to stretch.
“No,” said Walter, and then added eagerly: “But I’ve read lots and
lots of books about them, and I guess I could most find my way
along a trail even if I am a city tenderfoot. I’ve paddled a canoe
some, and I know all about the habits of wild animals and how to
build a fire and——”
“Son,” interrupted Big Jim, “stop right thar! Forget it—all this rot
you’ve been a-readin’. Woodcraft never yet was larned out o’ books,
and it never will be. I reckon you an’ me are goin’ t’ hitch up
together fine, an’ when yer go back t’ yer daddy this fall yer’ll be
able t’ take him out in th’ tall timbers an’ show him a few stunts
what ain’t down in th’ program o’ city schools, but what every
cottontail born in the north woods larns the second day he gets his
eyes open. Now yer jes’ fergit all this stuff yer’ve been a-readin’ and
stick t’ me; we’ll git along fine. I’ll make a woodsman o’ yer yer dad
will be proud o’. Let’s have a look outside t’ see how the weather is.”
As he followed the big fellow out onto the platform Walter felt his
cheeks burn at this wholesale condemnation of his treasured books,
one of which, “A Complete Guide to Woodcraft,” was at that moment
within easy reach in the top of his duffle bag. Despite his natural
admiration for this big guide, to whom the mountains, lakes and
woods were as an open book, and his unbounded delight in having
made a good impression, Walter was not yet willing to overthrow his
former idols for this new one, and he was independent enough to
stand by his opinions until convinced that he was wrong.
“Have you ever read any of them, Mr. Everly?” he inquired
courteously.
“Me? Read them books?” Big Jim’s laugh rolled out infectiously.
“What would I read ’em for, sonny? I’ve seen some o’ them book-
writers in th’ woods, and thet’s enough fer me. Lordy!” and again
Jim’s hearty laugh rolled forth.
Walter laughed a little too, but deep in his heart he resolved that he
would yet show Big Jim that there was some good in the despised
books. To change the subject he inquired about the low-browed
owner of the axe back by the fire.
“Him? Why, thet’s Red Pete, a French canuck with some Indian in
him, an’ th’ meanest man in th’ mountains,” replied Big Jim.
The mist had begun to burn off. Even as they watched they saw it
roll in great tattered masses up the side of the opposite mountain.
With the coming of the sun Walter was able to take note of his
surroundings, and his eager eyes drank in the scene so strange to
him but so familiar to his companion. It was one of those few
moments which come to all of us, when we experience sensations
which so impress themselves upon the memory that never are they
forgotten. Walter felt a thrill that made him tingle from head to foot
and, from sheer delight, clinch his hands till the nails nearly bit into
the flesh. Since he was big enough to read “Deerslayer” and “The
Pathfinder” and Captain Mayne Reid’s fascinating tales of adventure
in forest and on the plains he had lived in an imaginary world of his
own—a wonderful world, where he penetrated vast wildernesses,
voyaged on great rivers and climbed snow-capped mountains. Now
he was really in the great woods; his dreams were coming true in a
measure.
Indeed, it was a scene to stir any red-blooded boy. A gentle breeze,
moving across an unsuspected lake, rolled before it great billowing
masses of vapor. The sun, just rising above the eastern hills, drew
the mist swiftly up the mountainsides in broken, detached masses
that eddied, separated, came together and in an incredibly short
time dissipated in thin, clear air, till naught remained save in the
deepest hollows not yet penetrated by the sun’s rays. Walter drew a
long breath.
“Oh!” he gasped, and again, “Oh!”
Big Jim looked at him curiously, while a sincere liking twinkled in his
blue eyes.
“Never see a sunrise in th’ mountains afore, did yer, sonny?” he
asked. “Jes’ yer wait till yer see a sunup from th’ top of old Baldy,
and watch forty lakes throw off their night clothes all at once.”
Sordid enough was the scene now revealed close at hand in the
clear morning light, the ulcer of so-called civilization, to be seen
wherever man has pushed the outposts of commercialism into the
great forests. A dozen log houses and a few ugly frame buildings,
the latter unpainted for the most part, but with one a glaring red
and another a washed-out blue, dotted an irregular clearing on
either side of the railroad. Close by, the tail of a log jam choked a
narrow river, while the tall iron stack of a sawmill towered above the
rough board roof that afforded some protection to the engine and
saws. Off to the right glistened the end of a lake of which the river
was the outlet, its margin a mass of stark, drowned timber. The
peculiar odor of wet sawdust filled the air. A sawdust road threaded
its way among the scattered buildings, and all about were unsightly
piles of slabs, heaps of bark and mill waste.
But to Walter it was all fascinating. The sky-scrapers of his native
city seemed not half so wonderful as these moss and clay chinked
cabins. He pinched himself to make quite sure he was awake, that it
was all real. An engine and single dingy coach were backing down a
siding.
“Thar’s our train, son,” said his companion. “Better stow yer duffle
aboard. It won’t pull out for half an hour, and then it’ll be a twenty-
minute run over t’ Upper Lake. I want to see Tim Mulligan over
yonder t’ th’ store, but I’ll join yer on th’ train.”
Taking the hint, Walter put his duffle aboard the train beside the
pack basket of his friend, and then, to kill time, started out to form a
closer acquaintance with the town. From most of the houses thin
columns of smoke and the odor of frying bacon or pork proclaimed
that breakfast was being prepared. Occasionally he had glimpses of
weary-faced women in faded calico gowns. One, standing in the
doorway of her cabin, was barefooted. A frowzy-headed, dirty-faced
little urchin stared at him from the shelter of her skirts. The men he
met were for the most part rough, good-natured fellows, dressed in
the flannel shirt of the woods, their trousers thrust into high, laced,
hobnailed boots. Several nodded kindly or exchanged a “howdy”
with the bright-faced boy.
On his way back, as he neared a cabin somewhat apart from the
others, he heard voices in angry dispute. Turning a corner of the
cabin he was just in time to see a boy of about his own age, but a
good head taller, strike a vicious blow at a whimpering hunchback.
In a flash Walter confronted the astonished young ruffian, eyes
flashing and fists doubled.
“You coward!” he shouted. “You miserable coward, to strike a boy
smaller than yourself, and a cripple!”
For an instant the other stared. Then his face darkened with an ugly
scowl, and he advanced threateningly.
“Get out av here! This ain’t any av your business, ye city dude!” he
growled.
“I’ll make it my business when you hit a little fellow like that,” replied
Walter, edging between the bully and his victim.
“Want ter foight?” demanded the other.
“No, I don’t,” said Walter, “but I want you to leave that little chap
alone.”
“Huh, yez do, do yez?” responded the other, and rushing in he aimed
an ugly blow at Walter’s face. The fight was on.
And just here the young ruffian was treated to the greatest surprise
of his bullying career. Instead of crushing his slight antagonist as he
had contemptuously expected to, he lunged into empty space. The
next instant he received a stinging blow fairly on the nose. For a
moment he gasped from sheer surprise, then, with a howl of pain
and rage, he rushed again.
To all appearances it was a most unequal match. The young
backwoodsman was not only taller, but was heavy in proportion; his
muscles were hardened by work and rough outdoor life in a sawmill
village, and hard knocks had toughened him as well. In contrast, the
city boy seemed slight and hopelessly at a disadvantage. But
underneath that neat khaki jacket was a well-knit, wiry frame, and
muscles developed in the home gymnasium. Moreover, Walter’s
father believed in teaching a boy to take care of himself, and it was
not for nothing that Walter had taken lessons in boxing and
wrestling.
As before, he avoided the rush by lightly side-stepping, driving in a
vigorous left to the ear and following this with a right which raised a
lump just under his opponent’s left eye. The latter backed away.
Then he came in again, but more cautiously. He was beginning to
respect this elusive antagonist who hit so hard, yet managed to get
away untouched. It was all so new in his experience that he was
utterly at a loss to know what to expect.
Round and round they circled, each watching for an opening.
Suddenly Walter took the offensive. As he started to rush he slipped
in the wet sawdust. His opponent saw his advantage and swung
hard, but Walter caught the blow on his right forearm, and the next
instant they were locked in a clinch. This was what the bully wanted.
Now he would throw his antagonist and, once he had him down,
that would end the battle, for his ethics knew no quarter for a fallen
foe.
But again he reckoned without his host. Scientific wrestling was an
unheard-of art to the young giant, while in the home gymnasium
Walter had twice won the championship for his weight. For a few
minutes they swayed this way and that, then Walter secured the lock
he was trying for, there was an instant of straining muscles, then the
bully was pinned flat on his back.
A big hand fell on Walter’s shoulder. “Son,” said Big Jim, “I hate t’
break into yer morning exercise, but you an’ me hev an engagement
at Upper Lake, and we’ve got jes’ two minutes t’ ketch thet train.”
Walter jumped up at once, and then held out his hand to the
discomfited bully. “Will you shake?” he asked.
To the surprise of the delighted onlookers the fallen terror of the
village arose and in a manly way, though sheepishly, shook the
outstretched hand, for at heart he had the right stuff in him.
“Ye licked me fair an’ square,” he mumbled. “Oi wish ye’d show me
some av thim thricks.”
“I will if I ever have a chance. You ought to be a Boy Scout,”
shouted Walter as he and Big Jim sprinted for the train.
CHAPTER II
WOODCRAFT CAMP

The light breeze which had lifted the mist at Upper Chain had
dropped to a dead calm, and when Walter followed the guide from
the train down to the landing on Upper Lake not a ripple broke its
placid surface. As far as he could see it lay like a great magic mirror,
the heavily-wooded shores reflected so clearly that the inverted
forest appeared no less real than the original, so marvelously
counterfeited. In every direction mountain succeeded mountain, for
the most part clothed to their summits with the variegated green of
the mighty woodland growth, the somber spruce of the higher
slopes, black against the lighter green of yellow and white birch,
maple and ash, which had reclaimed to the wilderness the vast
tracts ruthlessly laid bare by reckless lumbering twenty years before.
One of the nearer mountains was crowned with bare, exposed
ledges to which clung a few unsightly blasted trunks, mute
witnesses to the devastation wrought by fire.
By a peculiar optical effect produced by the angle of light in a dead
calm at that time of the day, floating objects appeared magnified to
many times their actual size, so that a launch some two miles
distant, whose rapid put-put had drawn their attention when they
first stepped from the train, appeared to be less than half that
distance away.
Big Jim looked at it long and steadily, shading his eyes with a big
hand.
“Thet’s ‘Woodcraft Girl’ all right,” he said, “and I reckon they’re
comin’ down fer us. Yer make yerself t’ home, son, while I run back
up yonder t’ th’ hotel and rastle up some grub. We’ll be some hungry
before we reach camp if I don’t.”
Walter seated himself on the end of the pier and drank in the beauty
of the exquisite scene. Alongside a little mail boat was getting up
steam, her crew busily stowing away express packages and supplies
of all kinds for the various camps and hotels scattered along the
lake. Half a dozen passengers were already aboard. Two Adirondack
skiffs, each pulled by a brawny guide, a fisherman lolling at ease in
the stern, were just setting out for the fishing grounds. All was
hustle and activity, in strange contrast with the quiet lake and the
majestic calm of the mountains.
In a few minutes Big Jim returned with some sandwiches, which
they promptly disposed of while they waited for the approaching
launch. It was now near enough for Walter to make out the blue
pennant with the magic words “Woodcraft Camp” fluttering at the
bow, and a moment later there came a joyous hail of “Oh, you Jim!”
from the figure in the bow, followed by a wild waving of a small
megaphone.
“Oh, you Bob!” bellowed the big guide, swinging his hat.
The launch drew in rapidly and was deftly laid alongside. From it
sprang two young fellows of seventeen or eighteen, in olive khaki
trousers, flannel shirts and soft-brimmed hats, who straightway fell
upon Walter’s companion and pounded and thumped him and shook
both hands at once, and were pounded and thumped in return.
When their somewhat noisy demonstration was over the one whom
Jim had called Bob turned to Walter and held out his hand. “Guess
your name is Upton, isn’t it?” he inquired with a pleasant smile. “My
name is Seaforth, and this is Louis Woodhull, the best fellow in
Woodcraft Camp. Dr. Merriam sent us down to look for you, but I
see you were already in good company. The doctor was some
worried for fear you might have missed connections at Upper Chain,
but if he’d known that you were trailing in company with this old son
of the backwoods his mind would have been easy. Jim, you great big
stick of seasoned timber, it sure does a fellow good to look at you.
Stow this young fellow and the duffle in the launch while I get the
mail and do some errands, and we’ll be off. The whole camp’s a-
looking for you, though they don’t expect you till to-morrow. You’re
sure needed. Ed Mulligan is guiding over on Big Moose and won’t be
with us this year, but his younger brother, Tom, is taking his place,
and I guess he’ll make good.”
Bob’s errands were soon done, the supplies, duffle and mail pouch
stowed away in the launch, and her nose pointed down the lake.
Bob took the wheel, while Louis ran the engine. Walter was up
forward, “to be properly impressed,” as Bob put it. And if that was
really the object in giving him the best post of observation, its
success left nothing to be desired.
With eager eyes he drank in the wonderful panorama constantly
unfolding—as the launch sped swiftly over the lake. Here the lake
was less than half a mile wide, then abruptly it opened up great
bays which made it more than twice that width from shore to shore.
How he longed to explore those bays and coves! Two big summer
hotels on commanding bluffs were passed, showing but little life as
yet, for the season had not fairly opened. On rocky points, or half
hidden in sheltering coves, he caught glimpses of summer “camps,”
most of them built of logs, but in many cases little short of palatial,
and the boy’s lips curled with scorn at this travesty of wealth upon
the simple life. Gradually the camps became fewer and farther apart
until only an occasional lean-to or a tent now and then, clinging on
the very edge of the forest, was evidence of man’s invasion, and
Walter felt that now in truth he was entering the wilds.
From the good-natured chaff and talk of his companions he gathered
that Big Jim had been chief guide at Woodcraft Camp ever since this
famous school in the woods had been started, and that the two
young men had been among his earliest pupils. With eager ears he
drank in their talk of fish and lures, of deer, rifles and hunting lore.
Occasionally, as they skirted an island or ran around a sunken reef,
one or another would recall a famous catch of bass or a big laker
taken there.
Of the two young men, Seaforth was the more talkative. He was
dark, with sparkling black eyes and a merry, likable face, which, for
all its irrepressible good-humor, had in it a strength and purpose
which denoted a solid foundation of character. He was broad-
shouldered, deep-chested, finely-developed, a splendid type of
young American manhood.
His chum was rather slight in build, but wiry, with light hair and a
rather thin, clean, serious face which gave the impression of
tremendous nervous energy habitually under control. He took but
little part in the conversation, but his quiet smile at the sallies
between Bob and the guide was of a peculiarly winsome sweetness.
His slight reserve drew rather than repelled Walter, who instinctively
felt that the friendship of Louis Woodhull was something well worth
the winning.
They had now come some twelve miles down the lake, and presently
Bob pointed out a long pier jutting out from the eastern shore, and
beyond it, just to the left of a giant pine, a flagstaff from which Old
Glory was fluttering limply in the light breeze just beginning to ripple
the surface of the lake.
“There you are, Upton, your first glimpse of Woodcraft,” he said. “I
hope you’ll——”
But what he hoped Walter never knew. A shrill “Hy-i-i-i-i! We want
that tenderfoot!” cut him short, as a canoe manned by two
youngsters of about Walter’s own age shot out from an island the
launch was just passing. Both boys were in trunks and jerseys and
paddling like mad to intercept the launch. Suddenly the one in the
stern caught sight of the guide. For an instant he stopped paddling,
while a look of pleased surprise passed over his face, and then with
a wild yell of “Jim, oh, you Jim!” he redoubled his efforts.
Seaforth put the wheel over to port a couple of spokes. “No you
don’t, Billy!” he called with a grin. “This boat carries Uncle Sam’s
mail, and it can’t stop to pick up tows.”
“Aw, Louis, slow her down, won’t you?” begged Billy.
Louis smiled good-naturedly; but the engine slowed down not a bit.
“Ta-ta,” called Bob. “The Indian attack is foiled, Billy. I’m ashamed of
you! Your paddling is abominable. Where’s that new stroke that’s
going to win the championship? See you later.”
And then it happened. One moment two boys were frantically
digging up the water with their paddles and the next a canoe was
floating bottom up, one boy white-faced and frightened, clinging to
the bow, and the other, with a malicious grin on his freckled face,
swimming at the stern.
The instant it happened Seaforth put the wheel hard over and,
describing a short circle, headed for the canoe. Walter’s heart had
been in his mouth, but the others seemed not a bit disturbed. Louis
stopped the launch, and while the guide righted and emptied the
canoe, he and Seaforth hauled the victims aboard.
“You little beggar!” growled Bob as he grabbed Billy by the slack of
his jersey, “I’ve a mind to duck you until you howl for mercy. You did
that purposely.”
Billy grinned. “You didn’t suppose I was going to let you land Big Jim
and I not be there, did you?” he asked.
“That’s all right, Billy, but this is going to be reported,” broke in
Louis.
“Don’t, please don’t, Louis,” begged the culprit.
“Sorry, son, but it’s got to be. We love you, Billy, and because we
love you we’re going to report. You addle-pated little scamp, when
will you ever learn that whatever risks a man may run himself he has
no right to involve others in danger? How did you know that Allen
there would be able to take care of himself, plunged unexpectedly
into the water? He’s been in camp only three days, so what did you
know of his powers of resource? No, my son, we hate to tell tales,
but we’ve a duty to you to perform, so prepare to pay the penalty.”
The launch was now once more under way with the canoe in tow.
Walter was duly introduced to the penitent Billy and his victim, Harry
Allen, like himself a new recruit and therefore a tenderfoot.
Several boys had gathered on the pier to size up any newcomers the
launch might bring, and Walter felt himself the target for a battery of
eyes. The ordeal was light, however, compared with what it would
have been at nightfall or earlier in the day, for it was now nine
o’clock and the boys were largely scattered in the duties and
pursuits of camp life.
As the launch was made fast Billy whispered, “Here comes Dr.
Merriam; isn’t he a peach?”
Walter looked up with just a little feeling of awe to see the man of
whom he had heard so much—a scientist, explorer, author and
lecturer, honored by many scientific societies and institutions of
learning both at home and abroad, and now content to bury himself
in the north woods as the founder and head of the most unique
school in the world—a school with a purpose which was, as he
himself whimsically expressed it, “to make big men of little boys.”
Woodcraft Camp was the outgrowth of years of study and
observation of boy life and the needs of the tremendous army of
youth annually turned loose upon the country for three months of
idleness and mischief. It was, in effect, a vacation school, so cleverly
masked in the guise of a camp that probably not one among the
pupils, save a few of the older boys, recognized it as such. Its
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like