Introduction To Python With Applications In Optimization Image And Video Processing And Machine Learning David Bezlpez David Alfredo Bez Villegas instant download
Introduction To Python With Applications In Optimization Image And Video Processing And Machine Learning David Bezlpez David Alfredo Bez Villegas instant download
https://ebookbell.com/product/an-introduction-to-statistics-with-
python-with-applications-in-the-life-sciences-2nd-2nd-edition-thomas-
haslwanter-47278200
https://ebookbell.com/product/an-introduction-to-statistics-with-
python-with-applications-in-the-life-sciences-thomas-
haslwanter-49052704
https://ebookbell.com/product/an-introduction-to-statistical-learning-
with-applications-in-python-1st-gareth-james-50703060
https://ebookbell.com/product/the-statistics-and-calculus-with-python-
workshop-a-comprehensive-introduction-to-mathematics-in-python-for-
artificial-intelligence-applications-peter-farrell-23900110
Introduction To Python Programming And Developing Gui Applications
With Pyqt Bm Harwani
https://ebookbell.com/product/introduction-to-python-programming-and-
developing-gui-applications-with-pyqt-bm-harwani-33747390
https://ebookbell.com/product/introduction-to-tornado-modern-web-
applications-with-python-michael-dory-adam-parrish-brendan-
berg-43273008
https://ebookbell.com/product/introduction-to-computation-and-
programming-using-python-with-application-to-understanding-data-mit-
press-john-v-guttag-35701908
https://ebookbell.com/product/introduction-to-computation-and-
programming-using-python-with-application-to-understanding-data-mit-
press-john-v-john-v-guttag-36029556
https://ebookbell.com/product/introduction-to-computation-and-
programming-using-python-with-application-to-understanding-data-mit-
press-john-v-guttag-37332568
Introduction to Python
Introduction to Python: with Applications in Optimization, Image and Video Pro-
cessing, and Machine Learning is intended primarily for advanced undergraduate and
graduate students in quantitative sciences such as mathematics, computer science, and
engineering. In addition to this, the book is written in such a way that it can also serve as a
self-contained handbook for professionals working in quantitative fields including finance,
IT, and many other industries where programming is a useful or essential tool.
The book is written to be accessible and useful to those with no prior experience of Py-
thon, but those who are somewhat more adept will also benefit from the more advanced
material that comes later in the book.
Features
• Covers introductory and advanced material. Advanced material includes lists, diction-
aries, tuples, arrays, plotting using Matplotlib, object-oriented programming
• Suitable as a textbook for advanced undergraduates or postgraduates, or as a reference
for researchers and professionals
• Solutions manual, code, and additional examples are available for download.
Chapman & Hall/CRC
The Python Series
About the Series
Python has been ranked as the most popular programming language, and it is widely used
in education and industry. This book series will offer a wide range of books on Python
for students and professionals. Titles in the series will help users learn the language at an
introductory and advanced level, and explore its many applications in data science, AI, and
machine learning. Series titles can also be supplemented with Jupyter notebooks.
Python Packages
Tomas Beuzen and Tiffany-Anne Timbers
David Báez-López
David Alfredo Báez Villegas
Designed cover image: ShutterStock Images
Reasonable efforts have been made to publish reliable data and information, but the author and publisher
cannot assume responsibility for the validity of all materials or the consequences of their use. The authors
and publishers have attempted to trace the copyright holders of all material reproduced in this publica-
tion and apologize to copyright holders if permission to publish in this form has not been obtained. If
any copyright material has not been acknowledged please write and let us know so we may rectify in any
future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, trans-
mitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter
invented, including photocopying, microfilming, and recording, or in any information storage or retrieval
system, without written permission from the publishers.
For permission to photocopy or use material electronically from this work, access www.copyright.com
or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-
750-8400. For works that are not available on CCC please contact [email protected]
Trademark notice: Product or corporate names may be trademarks or registered trademarks and are used
only for identification and explanation without intent to infringe.
DOI: 10.1201/9781003222118
Publisher’s note: This book has been prepared from camera-ready copy provided by the authors.
Dedicated to Laura and Gary, my children, and to
Alina, my granddaughter.
The future is yours.
Preface xiii
Author Biographies xv
1 Introduction to Python 1
1.1 What is the Python Programming Language . . . . . . . . 1
1.2 The Python Programming Language . . . . . . . . . . . . . 1
1.2.1 Downloading Python . . . . . . . . . . . . . . . . . 2
1.2.2 The Python’s Integrated Development and Learning
Environment . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Book Organization . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5.1 Types of Variables . . . . . . . . . . . . . . . . . . . 5
1.5.2 Variable Assignment . . . . . . . . . . . . . . . . . . 6
1.5.3 Basic Operations . . . . . . . . . . . . . . . . . . . . 7
1.6 Input and Output in Python . . . . . . . . . . . . . . . . . 7
1.6.1 Escape Sequences . . . . . . . . . . . . . . . . . . . 9
1.7 Programs in Python . . . . . . . . . . . . . . . . . . . . . . 10
1.8 Comments in a Program . . . . . . . . . . . . . . . . . . . . 11
1.8.1 Operations with Integer and Floating-point Numbers 13
1.9 Functions in Python . . . . . . . . . . . . . . . . . . . . . . 13
1.10 Modules and Libraries . . . . . . . . . . . . . . . . . . . . . 14
1.11 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.11.1 Arithmetic Operators . . . . . . . . . . . . . . . . . 16
1.11.2 Relational Operators . . . . . . . . . . . . . . . . . 16
1.11.3 Logical Operators . . . . . . . . . . . . . . . . . . . 17
1.11.4 Assignment Operators . . . . . . . . . . . . . . . . . 18
1.12 Alphanumeric Variables . . . . . . . . . . . . . . . . . . . . 19
1.13 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.14 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.15 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.16 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.17 Python Instructions for Chapter 1 . . . . . . . . . . . . . . 26
1.18 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.19 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
vii
viii Contents
4 Arrays 88
4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
4.2 Introduction to Arrays . . . . . . . . . . . . . . . . . . . . . 88
4.3 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
4.3.1 Access to Vectors . . . . . . . . . . . . . . . . . . . 93
4.3.2 Vectors by Comprehension . . . . . . . . . . . . . . 93
4.3.3 The Instruction append . . . . . . . . . . . . . . . . 94
4.4 Examples with Vectors in Python . . . . . . . . . . . . . . . 94
4.4.1 Vector Sorting . . . . . . . . . . . . . . . . . . . . . 102
4.5 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
4.6 Arrays in Python . . . . . . . . . . . . . . . . . . . . . . . . 105
4.6.1 Array Generation by Indexing . . . . . . . . . . . . 106
4.6.2 Array Generation by Comprehension . . . . . . . . 108
4.7 Matrix Operations using Linear Algebra with numpy . . . . 110
4.7.1 Sum, Difference, and Multiplication of Matrices . . 110
4.7.2 Sum of Matrices . . . . . . . . . . . . . . . . . . . . 110
4.7.3 Product of a Matrix by a Matrix . . . . . . . . . . . 111
4.7.4 Product of Matrices in Python . . . . . . . . . . . . 113
4.7.4.1 Matrix Multiplication Using np.dot . . . . 113
4.7.4.2 Matrix Multiplication Using np.matrix . . 113
4.8 Special Matrices . . . . . . . . . . . . . . . . . . . . . . . . 116
4.8.1 The Identity Matrix . . . . . . . . . . . . . . . . . . 116
4.8.2 The Transpose Matrix . . . . . . . . . . . . . . . . . 116
4.8.3 Transpose by Comprehension . . . . . . . . . . . . . 118
4.9 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
4.10 Arrays in Pandas . . . . . . . . . . . . . . . . . . . . . . . . 125
4.10.1 Data Frames . . . . . . . . . . . . . . . . . . . . . . 129
4.10.2 Generation of Data Frames . . . . . . . . . . . . . . 132
4.10.3 Functions for Series and Data Frames . . . . . . . . 133
4.11 Python Instructions for Chapter 4 . . . . . . . . . . . . . . 136
4.12 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
4.13 Selected Bibliography . . . . . . . . . . . . . . . . . . . . . 137
4.14 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
5 Functions 142
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
5.2 Subprograms . . . . . . . . . . . . . . . . . . . . . . . . . . 142
5.3 Functions in Python . . . . . . . . . . . . . . . . . . . . . . 143
5.4 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
5.5 Anonymous Functions or lambda Functions . . . . . . . . . 149
5.6 Pass by Reference . . . . . . . . . . . . . . . . . . . . . . . 150
5.7 Local and Global Variables . . . . . . . . . . . . . . . . . . 151
5.8 Keyword and Default Arguments . . . . . . . . . . . . . . . 152
5.9 Variable-length Arguments . . . . . . . . . . . . . . . . . . 154
5.10 Additional Examples . . . . . . . . . . . . . . . . . . . . . . 155
x Contents
9 Optimization 258
9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
9.2 Optimization Concepts . . . . . . . . . . . . . . . . . . . . . 258
9.2.1 Parameters, Variables, and Functions . . . . . . . . 259
9.3 General Format of the Optimization Process . . . . . . . . 260
9.4 Optimization with Python . . . . . . . . . . . . . . . . . . . 261
9.5 The minimize Function . . . . . . . . . . . . . . . . . . . . 262
9.6 Linear Programming . . . . . . . . . . . . . . . . . . . . . . 271
9.7 Quadratic Programming . . . . . . . . . . . . . . . . . . . . 280
9.8 Python Instructions for Chapter 9 . . . . . . . . . . . . . . 283
9.9 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
9.10 Selected Bibliography . . . . . . . . . . . . . . . . . . . . . 284
Index 431
Preface
xiii
xiv Preface
David Báez-López
David Alfredo Báez Villegas
xv
Chapter 1
Introduction to Python
DOI: 10.1201/9781003222118-1 1
2 Python with Optimization, ...
1.4 Algorithms
An algorithm is a way to solve a problem. Examples of algorithms in everyday
life can be found in cooking recipes, instructions to drive to a place, how
to assemble pre-built furniture, fixing a computer by a technician, etc. In
all of these examples, there is a sequence of steps to successfully complete
the required assignment. The last step in the design of the algorithm is the
4 Python with Optimization, ...
testing step to insure that the algorithm behaves as expected. A more accurate
definition of an algorithm is:
1.5 Variables
Variables are data that can take on different values depending upon the algo-
rithm. Variables must have a name to identify them. The name is a string of
alphanumeric characters which must start with a letter. The name may have
numbers and underscores, either capital or lower-case letters. Also, the name
is unique; that is, no other variable can have the same name. In Python, a cap-
ital letter is different from a lower-case one; thus, the variable A1 is different
from a1.
In every programming language, there are reserved words called keywords
and cannot be used as variable names. Python 3 has 33 keywords. To display
them in the IDLE type:
Names of variables must start with a letter and can only have
letters, numbers, and underscores.
12345.987
A variable is an integer one if it does not have a fractional part; that is,
it only has an integer part. For example, a = 6, speed = 45, depth = -3 are
integer variables.
An alphanumeric variable or text variable is a string of alphanumeric
characters which may include letters, numbers, and any other character. These
variables are called strings and are enclosed in single or double quotes such
as “elephant”, ‘silver_coin’, ‘year 2025’. The last string includes a blank
space which is counted as a character.
A boolean variable is a variable that can only take the values True or
False. They are used whenever a decision is taken. Boolean variables are
named after George Boole, a British mathematician who invented what is
now called Boole’s algebra.
The type of the variable is assigned when the variable is defined. Thus,
the expression a = 3 defines an integer variable, b = -3.24 defines a floating-
point variable, c = True defines a boolean variable, and d = “animal” defines
a string.
Python is a dynamic-type language. This means that a variable of a cer-
tain type can be redefined in a program with another type. For example,
the variable d = “animal” can be redefined in the program as d = -0.32, a
floating-point variable, and later on redefined as d = True, a boolean variable.
To find out what is the type of a variable the type instruction is used. For
example, if variables a, b, c, and d are given by:
>>> a = 2
>>> b = 5.6
>>> c = True
>>> d = ‘ENIAC’
6 Python with Optimization, ...
>>> type(a)
<class ‘int’>
>>> type(b)
<class ‘float’>
>>> type(c)
<class ‘bool’>
>>> type(d)
<class ‘str’>
>>> float(a)
1.0
>>> bool(a)
True
>>> str(a)
‘1’
a1 = 4
a2 = 8
In this way, a1 has the value 4 and a2 has the value 8. It is said that the value
4 is assigned to a1 and the value 8 is assigned to a2. This process is called an
assignment. If now the following is done:
a1 = a2
Now a1 is assigned the value of a2; thus, the new value of a1 is 8. The old
value of 4 is lost. The value of a2 has been assigned to a1.
Introduction to Python 7
>>> a = 3
>>> b = 5
>>> a + b
gives a result:
If a new variable is defined, the result is not automatically displayed. The user
must write the variable name at the Python prompt, as:
>>> c = a + b
>>> c
x = input( )
x = float(x)
These two instructions can be combined in a single row by assigning the type
to the string read with the input instructions. For example:
x = float(input( ))
The argument of the input instruction can have a text between double or
single quotation marks to indicate users what data is being read, as in:
8 Python with Optimization, ...
TABLE 1.1: Format options
Symbol Output type Example
d,i Signed integer -123
u Unsigned integer 123
f Floating-point 123.45
e Scientific notation 1.2345 e+002
g Shortest representation between f and e 123.45
c Character ‘a’
s String “program”
This indicates that the variable g is a floating-point one and its value is g =
9.8.
For the output of data, the instruction print can be used. To display the
value of g above, it can be done with:
print(g)
A format can be added inside the instruction print. The format options
are shown in Table 1.1. A formatting instruction can be added inside a print
instruction as in this example for the gravity as:
that displays:
The use of a print instruction provides a line feed. If there are two con-
secutive print instructions, the second print instruction is displayed in the
next line. For example,
produces:
Introduction to Python 9
a = 4
b = -7
print(f‘The value of a is: {a}. The value of b is: {b}’)
1 2 3
1
2
3
ax + b = c
that can be solved as
c−b
x=
a
This solution can be programmed1 as:
x = (c - b)/a
print(“The solution of the first-degree equation is x = ”, x)
To create this script, in the menu bar in the Python IDLE select
as shown in Figure 1.2. This opens a new window where the program can be
written. Before executing the script, it must be saved to a convenient location
with the name: Solution_first_degree_equation.py. To run this program,
in the menu bar of the program window, select Run → Run Module as shown
in Figure 1.3. The result is:
the code starting with a hash character. Finally, there are multiple lines of
code. These lines of code start with three single or double quotation marks to
open the lines of code. Triple single or double quotation marks must close the
comment block. For the solution of the first-degree equation, comments may
be implemented as:
>>> a = 3.4
>>> b = 2
>>> x = a + b
>>> print(x)
5.4
import math
a = 3
b = math.sqrt(a)
Introduction to Python 15
In this case each and everyone of the functions available in the module
are imported. This makes the program larger.
2. Instead of importing the whole module, import only the square root
function. This is done with:
import numpy as np
b = np.sqrt(a)
The option to display 92 lines is printed in the IDLE. Clicking on the option
displays all the functions available in the library numpy.
16 Python with Optimization, ...
TABLE 1.4: Arithmetic operators
Operation Operator Example Precedence
Addition + a + b 3
Subtraction - a - b 3
Multiplication * a*b 2
Division / a/b 2
Integer division // a//b 2
Power ax pow pow(a, x) 1
1.11 Operators
Operators indicate the type of operations that can be performed on the vari-
ables. There exist four types of operators:
1. Arithmetic.
2. Relational.
3. Logic.
4. Assignment.
a < b → True
a > b → False
a == b → False
a != b → True
It can readily be seen that the these statements can only have a Boolean
result, namely, either True or False.
>>> a and b
True
>>> a and c
False
>>> a or c
True
>>> a|c
True
18 Python with Optimization, ...
TABLE 1.7: Assignment operators
Python Operator
a = b =
a = a + 1 a += 1
a = a − 1 a −= 1
a = a + b a += b
a = a − b a −= b
a = a ∗ b a ∗= b
a = a / b a /= b
a = a % b a %= b
>>> a ∧ b
False
>>> a ∧ c
True
a & b | c
has the result True because a&b = False and False|c is True, but
a&(b|c)
is False because first (b|c) is computed and the result is True, but a&True is
False. Thus, using parenthesis alters the order and evaluation and the result.
a += 1 → a = 6
a -= 1 → a = 4
a += b → a = 8
Introduction to Python 19
a -= b → a = 2
a ∗= b → a = 15
a /= b → a = 1.66667
a %= b → a = 2
The result is 11 because the blank space is also counted. Strings can be con-
catenated, or added, with the symbol +. For example, given the strings a =
‘cats’, b = ‘dogs’, c = ‘ ’, d = ‘and’, they can be added as:
>>> a + c + d + c + b
cats and dogs
>>> len(a + c + d + c + b)
13
The blank string is used for separation of the strings. The length of the string
is 13 because the two blank spaces are also counted.
Each character in a string has a position. The numbering of the position
may start from the left and in that case, the left-most character is in the
position 0, the next element to the right is in position 1, and so on. The last
element in a string with length n is in position n-1. If the position numbering
starts from the right, then the right-most element is in position -1, the next
element to the left is in position -2, and so on. The left-most element is in
position -n. The numbering of a string is depicted in Figure 1.4.
20 Python with Optimization, ...
1.13 Lists
Sometimes it is necessary to work with a set of data. In Python, a list is such
a set. A list of elements is enclosed in brackets and the elements of the list
can be of several types, for example, some elements can be integer ones, but
other elements can be floating-point elements, strings, or even lists. Elements
in a list must be separated by a comma. A list must have a finite number of
elements. As an example, a list of the first ten natural numbers is:
Another example is a list of friends with their age; thus, the list elements can
be strings and integer numbers:
>>> friends = [‘Pete’, 16, ‘Rose’, 15, ‘John’, 21, “Louis”, 19]
The number of elements of a list can be found with the function len() as was
the case for strings. Further, lists can be concatenated and multiplied by an
integer. For example,
>>> name*3
[‘Tony’, 17, ‘Tony’, 17, ‘Tony’, 17]
Introduction to Python 21
The instruction len is used to find out the number of the list name as:
>>> len(name)
2
because there are only two elements in the list name. But if it is desired to
find the number of elements in the first element of the list name, the result is:
>>> len(name[0])
4
1.14 Dictionaries
Dictionaries are lists whose elements are pairs of variables. Each pair is com-
posed of a key and a value. The key and its value are separated by a colon.
The pairs are separated by commas. For example,
To print the value of a pair only the key is needed. To print the value of key
a in dictionary1 use:
The length of a dictionary is obtained with the instruction len. For exam-
ple, consider the following dictionary whose length is going to be found:
The answer is 2 because in the dictionary mat there are 2 pairs. Note that in
the dictionary mat the values are lists.
The list friends from the previous section can be better written as a
dictionary. This can be done with:
friends = {‘Pete’: 16, ‘Rose’: 15, ‘John’: 21, ‘Louis’: 19, ‘Tony’:
17}
1.15 Tuples
A tuple is an ordered collection of elements. Tuples may or may not be enclosed
in parentheses. The elements of a tuple can be strings, integers, floating-point,
lists, dictionaries, or any combination of elements. The length of a tuple can be
found with the function len( ). For example, the tuple animals = (“cats”,
“dogs”, “birds”), the length can be found with:
1.16 Examples
This section presents three examples of small programs or scripts in Python.
The first example uses tuples to swap variables, the second example computes
simple and compound interest and the last example implements temperature
conversion. The scripts have to be written in a new file and run as described
in Section 1.7.
>>> temp = x
>>> x = y
Finally, store the temporary variable which has the value of x into y:
>>> y = temp
The final result is that the values of the variables x and y have been swapped.
There is another way to do the swapping using tuples and the whole swapping
is done with:
For example, given the tuple (-7, 23), the values are swapped with:
“ ‘Temperature conversion
This script converts between different temperature scales ”’
# START
# END
To compute the power the function pow is used and it is available at the library
math that must be imported. The script is:
Introduction to Python 25
“ ‘Interest calculation.
This is Example 1.8. This program obtains the simple
and compound interest. ”’
# Simple interest:
simple_interest = principal*n*interest_rate
compound_interest = principal*pow(1 + interest_rate, n) - 1
# Display results:
print(“Simple interest: %0.2f” % simple_interest)
1.18 Conclusions
In this chapter the basic Python concepts such as variables, scripts, modules
or libraries, among many others, have been presented. Some examples show
how easy is to have a running program in Python. The Python IDLE has been
used but everything can be used in other platforms such as Jupyter or Spyder.
Introduction to Python 27
1.19 Exercises
1.1 What is displayed for the script presented below? Try to find the result
without running the script in the IDLE.
n = 4; k = 2
print(n)
print(-n)
print(n–)
print(n + k)
print(k)
print(n, k)
print(“ ”)
print(“n %3.2g” % n)
print(“n * n = %3.2g” % n*n)
print(n*n)
print(‘n’)
1.2 Indicate the output in the following segments of code:
a) x = 3
x = x + 2
print(x)
b) y = - 5.3
y = y*7.0
print(y)
c) x = 8; y = 3)
x = x%y
print(x)
1.3 Find the results for the following segments of code:
a) x = 3
x = x + 2
print(x)
b) y = - 5.3
y = y*7.0
print(y)
c) x = 8; y = 3
x = x % y;
print(x)
28 Python with Optimization, ...
1.4 The function getsizeof( ) from the library sys is used to obtain the
size of a variable. Using getsizeof( ) obtain the size of the variable “a” for
a) a = 2.0
b) a = 2
c) a = 20000
d) a = ‘2’
e) a = True
x = 42.0
y = 42.3 e-14
a = 42.3 e-14
b = −57.8
m = +87
n = +249
print(m*n)
print(x)
print(y)
print(a)
print(b)
a) x = 90.34
print(x)
b) z = 2
y = 7;
x = y + 2*z
print(“The result is: %5.2g” % x)
x = 8; y = 5
a = 1; b = 2
c) x = 1 & (a <= 2 | y = x)
Introduction to Python 29
a = 2; b = 3
x = 8.3; y = -4.6; z = 2.3
print (“a*b = %5.2f” % a*b )
print(“a/b = % 5.2f” % a/b )
print(“x/y = % 5.2f” % x/y )
print(“a*z = %5.2f” % a*z )
c = ‘8’
r = 3
print(c*r)
x = 7; y = 3
a. x % y
b. x = x + y
c. x += y
d. x =+ y
e. x *= y
f. x =* y
g. x %= y
1.11 Write a script to read the data: 7.0, 2.0, 8.3, 3.0, 5.6, 4.0 and
compute:
a. The maximum value.
b. The minimum value.
c. The addition.
d. The mean.
Chapter 2
Conditionals and Loops
2.1 Introduction
In real life, very often it is necessary to take a decision about what is the
next step in a given situation. The decision usually is taken depending upon
certain conditions in the situation. In the Python programming language, this
decision-making process also takes place, and the condition or conditions in
the process have to be evaluated. The decision-making instructions are known
as conditionals and they are studied in the first part of the chapter. The
second part of the chapter studies the instructions to repeat a process. These
instructions are called loops and they appear in iterative processes such as
those in numerical analysis, physics and finance, to name a few areas.
The chapter starts with the definition of a conditional in Python. Then, the
extension to nested conditionals is presented. Several examples show the use
of conditionals. Loops are introduced next. The two types of loops, for loops
and while loops are defined. Finally, examples using loops and conditionals
are presented.
2.2 Conditionals
Conditionals arise when an operation execution depends upon the true value
of a logic expression. For example, to take the square root of a number can only
be done if the number is positive. Thus, a conditional has to be implemented
to check that the number is positive.
The conditions in Python use the key word if in the following format:
if (logic expression):
Instructions
Next instructions
DOI: 10.1201/9781003222118-2 30
Conditionals and Loops 31
they must have the same indentation. The indented instructions are part of
the if statement and they are executed if the logic expression is True. Oth-
erwise, if the logic expression is False, the Next instructions are executed.
The logic expression can be inside parenthesis but this is not compulsory and
they may be omitted.
check = False
if (b != 0):
check = True
if (check):
c = a/b
print(“Result:”, c)
When the variable check is True, then it executes c = a/b and prints the
result. Otherwise, when a check is False it does not do anything.
The complete script is:
check = False
if (b != 0):
check = True
# End of conditional.
# Starts conditional.
if (check):
c = a/b
print(“Result:”, c)
The logic expression may use any of the relational operators shown in
Table 2.1. It can be seen that the equality comparison uses a double-equal
sign. Thus, a == b is comparing if a is equal to b. If the equality holds then
the logic expression is True. Otherwise, it is False. It is worth mentioning
that a = b is an assignment meaning that the value of b is assigned to a; thus,
it is not a comparison.
For example, consider the following example of correct and incorrect logic
expressions:
Composite logic expressions may also use the logic connectives from Table 2.2.
Some examples are:
a = 1; b = 2; c = 3
if( a < b ): True logic expression
if( a < b or c > 0): True logic expression
if( b > 1 and c == 4): False logic expression
• Read in a and b
• Check if a = 0
• Solve for x = b/a
• Display x
FOOTNOTE:
[1] It is an open question whether light corporal punishment should
not occasionally be permitted in the case of very young children who
have not yet arrived at the age of reason. In this case, at all events,
there is no danger that the permission will be abused. No one would
think of seriously hurting a very young child.
III
In order that a parent shall properly influence a child's character, it is
necessary for him to know what that character is, and what the
nature is of each fault with which he is dealing. I feel almost like
asking pardon for saying anything so self-evident. It seems like
saying that a physician who is called to a sick-bed, before beginning
to prescribe, should know the nature of the disease for which he is
prescribing, should not prescribe for one disease when he is dealing
with another.
I do not know enough about physicians to say whether such
mistakes ever happen among them; but that such egregious
mistakes do occur among parents all the time, I am sure. There are
many parents who never stop to ask before they punish—that is,
before they prescribe their moral remedies—what the nature of the
disease is with which their child is afflicted. They never take the
trouble to make a diagnosis of the case in order to treat it correctly.
There is perhaps not one parent in a thousand who has a clear idea
of the character of his child, or to whom it even so much as occurs
that he ought to have a clear conception of that character, a map of
it, a chart of it, laid out, as it were, in his mind. The trouble is that
attention is not usually called to this important matter, and I purpose
to make it the special subject of this address.
1. Obstinacy
I am prepared at the outset for the objection that the case against
parents has been overstated. There are parents who freely
acknowledge, "My child is obstinate; I know it has an obstinate
character." Others say, "My child, alas! is untruthful." Others again
declare, "My child is indolent."
But these symptoms are far too indeterminate to base upon them a
correct reformatory treatment. Such symptoms may be due to a
variety of causes, and not until we have discovered the underlying
cause in any given case can we be sure that we are following the
right method.
Take the case, for instance, of obstinacy; a child is told to do a
certain thing and it refuses. Now, here is a dilemma. How shall we
act? There are those who say: In such cases a child must be
chastised until it does what it is told. A gentleman who was present
here last Sunday had the kindness to send me during the week an
edition of John Wesley's sermons, and in this volume, in the sermon
on "Obedience to Parents," I read the following words: "Break the
will if you would not damn the child. I conjure you not to neglect,
not to delay this! Therefore (1) Let a child from a year old be taught
to fear the rod and to cry softly. In order to do this (2) Let him have
nothing he cries for, absolutely nothing, great or small, else you
undo your own work. At all events, from that age make him do as he
is bid, if you whip him ten times running to effect it. Let none
persuade you it is cruelty to do this: it is cruelty not to do it. Break
his will now, and his soul will live, and he will probably bless you to
all eternity."
But by following this line of treatment we may obtain a result the
very opposite of that which we intended. Obstinacy in many cases is
due to sensitiveness. There are some children as sensitive to
impressions as is that well-known flower which closes its quivering
leaves at the slightest touch. These sensitive children retreat into
themselves at the first sign of unfriendliness or aggression from
without. The reason why such a child does not obey its father's
command is not, perhaps, because it is unwilling to do as it is told,
but because of the stern face, the impatient gesture, the raised
voice with which the parent accompanies the command, and which
jars upon the child's feelings.
If such a parent, incensed at the child's disobedience, becomes still
more severe, raises his voice still more, he will only make matters
worse. The child will shrink from him still more and continue its
passive resistance. In this manner obstinacy, which was at first only
a passing spell, may become a fixed trait in the child's character.
To be sure, we should not, on the other hand, treat these sensitive
children only with caresses. In this way we encourage their
sensitiveness, whereas we should regard it as a weakness that
requires to be gradually but steadily overcome.
The middle way seems the best. Let the parent exact obedience
from the child by gentle firmness, by a firmness in which there shall
be no trace of passion, no heightened feeling, and with a gentleness
which, gentle as it may be, shall be at the same time unyielding. But
while obstinacy is sometimes due to softness of nature, it is at other
times due to the opposite—to hardness of nature, and according to
the case we should vary our treatment.
There are persons who, having once made up their minds to do a
thing, cannot be moved from their resolution by any amount of
persuasion. These hard natures, these concentrated wills, are bound
to have their way, no matter whom they injure, no matter what
stands in the way. Such persons—and we notice the beginnings of
this trait in children—need to be taught to respect the rights of
others. Their wills should occasionally be allowed to collide with the
wills of others, in order that they may discover that there are other
wills limiting theirs, and may learn the necessary lesson of
submission.
In yet other cases obstinacy is due to stupidity. Persons of weak
intelligence are apt to be suspicious. Not understanding the motives
of others, they distrust them; unwilling to follow the guidance of
others, they cling with a sort of desperation to their own purpose.
These cases may be treated by removing the cause of suspicion, by
patiently explaining one's motives where it is possible to do so, by
awakening confidence.
2. Untruthfulness
Again, let us take the fault of untruthfulness. One cannot sufficiently
commend the watchfulness of those parents who take alarm at the
slightest sign of falsehood in a child. A lie should always put us on
our guard. The arch fiend is justly called "the father of lies." The
habit of falsehood, when it has become settled, is the sure inlet to
worse vices.
At the same time not all falsehoods are equally culpable or equally
indicative of evil tendency, and we should have a care to
discriminate between the different causes of falsehood in the young
child, in order that we may pursue the proper treatment. Sometimes
falsehood is due to redundant imagination, especially in young
children who have not yet learned to distinguish between fact and
fancy. In such cases we may restrain the child's imagination by
directing its attention to the world of fact, by trying to interest it in
natural history and the like.
We should especially set the example of strict accuracy ourselves in
all our statements, no matter how unimportant they may be. For
instance, if we narrate certain occurrences in the presence of the
child, we should be careful to observe the exact order in which the
events occurred, and if we have made a mistake we should take
pains to correct ourselves, though the order of occurrence is really
immaterial. Precisely because it is immaterial we show by this means
how much we value accuracy even in little things.
Then, again, falsehood is often due to the desire for gain. Or it may
be due to fear. The child is afraid of the severity of the parent's
discipline. In that case we are to blame; we must relax our
discipline. We have no business to tempt the child into falsehood.
Again, untruthfulness is often due to mistaken sympathy, as we see
in the case of pupils in school, who will tell a falsehood to shield a
fellow pupil. In the worst cases falsehood is inspired by malice.
It may be said that the proper positive treatment for this fault is to
set the example of the strictest truthfulness ourselves, to avoid the
little falsehoods which we sometimes allow ourselves without
compunction, to show our disgust at a lie, to fill the child with a
sense of the baseness of lying, and above all to find out the direct
cause which has tempted the child in any given case. As a rule,
falsehood is only a means to an end; children do not tell untruths
because they like to tell them, but because they have some ulterior
end in view. Find out what that ulterior end is, and instead of
directing your attention only to the lie, penetrate to the motive that
has led the child into falsehood, and try to divert it from the bad
end. Thus you may extract the cause of its wrongdoing.
3. Laziness
Thirdly, let us consider the fault of laziness. Laziness is sometimes
due to physical causes. Nothing may be necessary but a change of
diet, exercise in the fresh air, etc., to cure the evil. Sometimes it is
the sign of a certain slow growth of the mind. There are fruits in the
garden of the gods that ripen slowly, and these fruits are often not
the least precious or the least beautiful when they finally have
matured. Sir Isaac Newton's mind was one of these slowly ripening
fruits. In school he was regarded as a dullard and his teachers had
small hopes of him.
Laziness, like other faults of character, sometimes disappears in the
process of growth. Just as at a certain period in the life of a youth or
maiden new faculties seem to develop, new passions arise, a new
life begins to stir in the heart, so at a certain period qualities with
which we had long been familiar, disappear of themselves.
We have very little light upon this subject, but the fact that a great
transformation of character sometimes does take place in children
without any perceptible cause is quite certain, and it may be offered
as a comforting reflection to those parents who are over-anxious on
account of the faults they detect in their children. But again, on the
other hand, laziness or untruthfulness or obstinacy may be a black
streak, coming to the surface out of the nethermost strata of moral
depravity, and, taken in connection with other traits, may justify the
most serious apprehension, and should then be a signal for
immediate measures of the most stringent sort.
4. Discovering Causes
I am thus led to the second branch of my subject. I have tried to
meet the objection of the parent who says, "I know the character of
my child; I know my child is obstinate," by replying, "If you only
know that your child is obstinate you know very little; you need to
know what are the causes of his obstinacy, and vary your treatment
accordingly." Or if any one says, "My child is untruthful," I reply,
"You need to find out what the cause is of this untruthfulness and
vary your treatment accordingly." Or again, in the case which we
have just considered, I have pointed out that laziness in a child may
have no serious meaning whatever or may give just cause for the
most serious alarm, according to the group of characteristic traits of
which it is one. On this point I wish to lay stress. If you desire to
obtain a correct impression of a human face, you do not look at the
eye by itself, then at the nose, then fix your attention on the cheeks
and the chin and the brow, but you regard all these features
together and view them in their relations to one another. Or let us
recur to the simile of the physician. What would you think of the
doctor who should judge the nature of a disease by some one
symptom which happened to obtrude itself, or should treat each
symptom as it appears separately, without endeavoring to reach the
occult cause which has given rise to the symptoms, of which they
are all but the outward manifestation?
And yet that is precisely the incredible mistake which every one of
us, I venture to say, is apt to make in the treatment of children's
characters. We judge of them by some one trait, as obstinacy, which
happens to obtrude itself on our attention, and we prescribe for
each symptom as it arises; we treat obstinacy by itself, and
untruthfulness and indolence separately, without endeavoring to get
at the underlying cause of all these symptoms. The point I desire to
make is that in the education of our children it is necessary not only
to study individual traits, but each trait in connection with the group
to which it belongs.
Take for an illustration the case last mentioned—that of laziness.
There is a well-known type group or group of characteristic traits, of
which laziness is one. The chief components of this group are the
following: The sense of shame is wanting, that is one trait. The will
is under the control of random impulses, good impulses mingle
helter-skelter with bad. There is an indisposition on the part of such
a child to prolonged exertion in any direction, even in the direction
of pleasure. That is perhaps the most dangerous trait of all.
If you try to deal, as people actually do, with each of these traits
separately, you will fail. If you try to influence the sense of shame,
you will meet with no response; if you disgrace such a child, you will
make it worse; if you whip it, you will harden it. If you attempt to
overcome indolence by the promise of rewards, that will be useless.
The child forgets promised rewards just as quickly as it forgets
threatened punishment.
This forgetfulness, this lack of coherency in its ideas, is particularly
characteristic. The ideas of such a child are imperfectly connected.
The ties between causes and their effects are feeble. The contents
of the child's mind are in a state of unstable equilibrium. There is no
point of fixity in its mental realm. And the cure for such a condition
is to establish fixity in the thoughts, to induce habits of industry and
application by steady, unrelaxing discipline, and especially by means
of manual training.
The immense value of mechanical labor as a means of moral
improvement has been appreciated until now only to a very
imperfect extent. Mechanical labor wisely directed secures mental
fixity because it concentrates the child's attention for days and often
for weeks upon a single task. Mechanical labor stimulates moral
pride by enabling the pupil to produce articles of value and giving
him in this way the sense of achievement. Mechanical labor also
overcomes indolence by compelling settled habits of industry,
whereby the random impulses of the will are brought under control.
The type group which we have just considered is one of the most
clearly marked and easily recognized. It is a type which we often
meet with among the so-called criminal classes, where its
characteristic features can be seen in exaggerated proportions.
Without attempting to analyze any additional types (a task of great
delicacy and difficulty), the truth that the underlying fault of
character is often unlike the symptoms which appear most
conspicuously on the surface may be further illustrated by the
following example. I have known of a person who made himself
obnoxious to his friends by his overbearing manners and apparent
arrogance. Casual observers condemned him on account of what
they believed to be his overweening self-confidence, and expressed
the opinion that his self-conceit ought to be broken down. But the
real trouble with him was not that he was too self-confident, but that
he had not self-confidence enough. His self-confidence needed to be
built up. He was overbearing in society because he did not trust
himself, because he was always afraid of not being able to hold his
own, and hence he exaggerated on the other side. Those who take
such a person to be in reality what he seems to be will never be able
to influence him. If we find such a trait in a child, and simply treat it
as if it were arrogant, we shall miss the mark entirely. We must find
the underlying principle of the character the occult cause of which
the surface symptoms are the effects.
Our knowledge of the great type groups is as yet extremely meager.
Psychology has yet to do its work in this direction, and books on
education give us but little help. But there are certain means by
which the task of investigation may possibly be assisted. One means
is the study of the plays of Shakespeare. That master mind has
created certain types of character which repay the closest analysis.
The study of the best biographies is a second means. The study of
the moral characteristics of the primitive races—a study which has
been begun by Herbert Spencer in his work on Descriptive Sociology,
and by Waitz in his Anthropologie der Naturvölker—is perhaps
another means; and honest introspection, when it shall have become
the rule among intelligent persons, instead of being the exception,
will probably be the best means.
I am afraid that some of my hearers, from having been over-
confident as educators in the beginning, may now have become
over-timid; from having said to themselves, "Why, of course we
know the characteristics of our children," may now, since the
difficulties of studying character have been explained, be disposed to
exclaim in a kind of despair, "Who can ever understand the character
of a single human being?" A perfect understanding of any human
being is indeed impossible. We do not perfectly know even those
who are nearest and dearest to us. But there are means of reaching
at least approximate results, so far as children are concerned, and a
few of these permit me to briefly summarize.
Try to win the confidence of the child so that it may disclose its inner
life to you. Children accept the benefactions of their parents as
unthinkingly as they breathe the air around them. Show them that
your care and untiring devotion must be deserved, not taken as a
matter of course. In this way you will deepen their attachment and
lead them to willingly open their hearts to you. At the same time
enter into the lesser concerns of their life. Be their comrades, their
counselors; stoop to them, let them cling to you.
Observe your children when they are at play, for it is then that they
throw off their reserve and show themselves as they are. Some
children, for instance, will not join a game unless they can be
leaders; is not that a sign of character? Some children will take an
unfair advantage at play, and justify themselves by saying, "It is only
in play." Some are persistent in a game while others tire of any
game after a little while. Others are sticklers for a strict observance
of the rules. Observe how your sons or daughters are regarded by
their companions; children are often wonderfully quick to detect one
another's faults.
Try to find out what the favorite pursuits and studies of your child
are, by what it is repelled, by what attracted, and to what it is
indifferent. Above all, keep a record of your child's development. Do
not shun the labor involved in this. You know very well that nothing
worth having can be obtained without labor, yet most parents are
unwilling to give sufficient time and attention to the education of
their children. Keep a record of the most significant words and acts
of the child. Thus after a while you may have a picture of the child's
inward condition before you, an assemblage of characteristic traits,
and by comparing one trait with another, you may find the clue to a
deeper understanding of its nature.
What I have said about children applies equally to ourselves. I
started out by saying that not one parent in a thousand knows his
child's character. I conclude by saying that not one man or woman in
a thousand knows his or her own character. We go through life
cherishing an unreal conception of ourselves which is often inspired
by vanity.
I am well aware that it is difficult to know oneself, but there are
helps in this direction also. We can look over our own past record,
we can honestly examine how we have acted in the leading crises of
our lives, we can summon our own characteristic traits before our
minds—the things that we like to dwell upon, and the things which
we would gladly blot out of our memories if we could—and by
comparing this trait with that, we may discover the springs by which
we have been moved. It is difficult to attain self-knowledge, but it is
imperative that we should try to attain it. The aim of our existence is
to improve our characters, and clearly we cannot improve them
unless we know them.
I have undertaken to grapple with a most difficult subject, but I shall
have accomplished the purpose which I had in mind if I have
awakened in you a deeper desire to ask yourselves, first, "What is
the character of my child?" and, second, "What is my own
character?" The most serious business of our lives is to try to find
the answers to these two questions.
THE AMERICAN HOME SERIES
NORMAN B. RICHARDSON, Editor
Updated editions will replace the previous one—the old editions will
be renamed.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
ebookbell.com