(Ebook) A Course in Python: The Core of The Language by Roozbeh Hazrat ISBN 9783031497797, 3031497791 Download
(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
(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
https://ebooknice.com/product/programming-in-python-3-a-complete-introduction-
to-the-python-language-36002018
ebooknice.com
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
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
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
© 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
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.
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
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
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Chapter 1
Basics of Python
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)
[4]: 2417851639229258349412352
[5]: 180630077292169281088848499041
[6]: 20615673**4
[6]: 180630077292169281088848499041
[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
[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:
[10]: (-1+0j)
As an example, we calculate ( 11 + 1
2 + 13 ) × 3 and (3 − 6𝑖) 2 .
[11]: 5.5
[12]: (3 - 6j)**2
1.2 Integers, Reals and Complex Numbers 5
[12]: (-27-36j)
[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 “.”.
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]: 1.0
Of course, one could choose any other angle, run the code, and obtain 1 again.
Solution
The only challenge here is to translate the mathematical expression correctly into
Python.
[17]: 2.998863793038475
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
[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.
[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
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]: 1.0
[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]: 1
Solution
We first use the library math to calculate the first expression.
[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]: 55.000000000000014
Employing sympy capabilities, we can actually show that equality holds for this
identity.
[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.30000000000000004
[43]: -5.551115123125783e-17
[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)
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
[46]: type(3)
[46]: int
[47]: type(math.sqrt(2))
[47]: float
[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
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.
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
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]: (4.420954861117013-1.5093064853236153j)
[58]: 4.420954861117013
[59]: -1.5093064853236153
1.4 Importing Libraries in Python 13
[60]: (4.420954861117013+0j)
Comparing the results we see the statement of the exercise is valid for this particular
𝑎 and 𝑏.
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.
[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.
[64]: x = symbols('x')
y = symbols('what?')
[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
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.
[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.
[73]: xY
[73]: -1.4
[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]: 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
[81]: print(a,'and', b)
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]: True
[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]: False
[87]: 0.30000000000000004
[88]: 2 > 3
[88]: False
[89]: True
1.6 Equalities and Boolean Statements 17
[90]: True
[91]: 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]: True
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.
p = math.pi
sh = (math.exp(p) - math.exp(-p))/2
math.sinh(p) == sh
18 1 Basics of Python
[93]: False
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.
[96]: str
One can perform certain ‘arithmetic’ operations with strings, as the following exam-
ples show.
[98]: message * 3
[99]: message
[101]: message
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
[103]: message.capitalize()
[104]: message.lower()
[105]: message.upper()
[106]: message
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 {}.
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'
[112]: x = 2
y = math.sqrt(x)
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.
Here is a standard way to change the data to numbers, in case one requires the input
to be integers, or reals etc.
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.
[117]: 25.4
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}')
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')
We finish the chapter with an amusing example, showcasing several of the methods
available for working with strings.
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 .
1 + sin(𝑥) − cos(𝑥)
= tan(𝑥/2).
1 + sin(𝑥) + cos(𝑥)
Chapter 2
Lists and Tuples
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:
[2]: type(L)
[2]: list
[3]: L
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]: False
[5]: False
[6]: 2 in [1, 2, 3]
[6]: True
[7]: False
Similar to strings, we can do certain arithmetic operations with lists. Recall the list
L above.
[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.
[11]: L
[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
[17]: L[1 : 5]
[19]: L[1 : 5 : 2]
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
[21]: L[ : 5]
[22]: L[ : -1]
[23]: L[4 : ]
[24]: L[ : 100]
[26]: L[ : : -1]
[27]: L == L[ : 4] + L[4 : ]
[27]: True
Solution
We first define our given lists.
[28]: campus = ['Parramatta ', ' Campbelltown ', ' Kingswood ']
[31]: total
[33]: CA
[33]: ['Parramatta ', ' Campbelltown ', ' Kingswood ', 30, 10, 7]
Yet another way to put these together (in the absence of loops):
[35]: CA = []
CA
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
[39]: L
[41]: L
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 }, · · · , {𝑥 𝑛 , 𝑦 𝑛 } .
{𝑥1 + 𝑦 1 , 𝑥2 + 𝑦 2 , · · · , 𝑥 𝑛 + 𝑦 𝑛 }.
{𝑥1 , 𝑥1 + 𝑥2 , · · · , 𝑥1 + 𝑥2 + · · · + 𝑥 𝑛 }.
2.2 Lists as Objects 29
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.
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.
[44]: L
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.
[46]: total
[48]: total
[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]: 3
[52]: L.reverse()
L
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
[54]: L
[55]: L[0]
[55]: [1, 2, 3]
[56]: L[0][0]
[56]: 1
2.2 Lists as Objects 31
[58]: L
Solution
Here is a clever way to do this, benefiting from the arithmetic on lists.
[59]: S = [[0] * 3] * 4
S
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]: [[0, 'upset', 0], [0, 'upset', 0], [0, 'upset', 0],
[0, 'upset', 0]]
[62]: [[0, 'upset', 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
[63]: S = [[0] * 3] * 3
S
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.
[66]: L.append(L)
[67]: print(L)
[68]: L[-1]
[69]: L[-1][0]
[69]: 3
[70]: L[-1][-1]
[71]: L[-1][-1][-1]
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
[76]: y
[78]: x
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:
[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
(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.
[89]: L
[91]: L
[93]: L
and finally there is yet another elegant way using the sequences:
[94]: [f, *r , l] = L
[95]: [l, *r , f]
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
«𝑔 ℎ 𝑘 ¬
Illustrator: C. S. Corson
Language: English
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 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.
ebooknice.com