Python en
Python en
Table of Contents
I
Textbook
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2 Compiled and interpreted programming languages . . . . . . . . . . . . . . . . . . . . .
1.3 Basic facts about Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.4 Python programming in NCLab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5 Downloading Python programs from NCLabs database . . . . . . . . . . . . . . . .
1.6 Launching the Python module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.7 Code, output, and descriptive cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2 Using Python as a Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2 Addition and subtraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3 Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.4 Division . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.5 Modulo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6 Powers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7 Priority of operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8 Using empty characters makes your code more readable . . . . . . . . . . . . . . . .
2.9 Using mathematical functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.10 Fractions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.11 Random numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.12 Complex numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.2 Defining new functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.3 Passing arbitrary arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.4 Returning multiple values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.5 Using default arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4 Colors and Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.2 RGB colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.3 Plotting polylines and polygons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.4 Plotting functions of one variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.5 Labels, colors, and styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.6 Scaling axes and showing grid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5
5
5
5
6
6
6
7
8
8
8
9
9
11
11
12
13
13
14
15
16
17
17
18
19
19
20
23
23
24
25
27
28
30
31
32
34
35
36
39
41
43
46
46
47
48
49
50
51
52
53
53
53
53
55
55
57
60
60
61
61
63
64
65
66
67
69
69
69
69
71
72
72
74
75
75
75
76
80
82
82
82
83
83
84
85
85
86
86
87
88
89
89
90
90
91
91
92
94
100
100
100
101
102
103
104
104
105
105
108
108
108
II
108
109
109
109
Programming Exercises
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.1 Python is fun . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2 Big word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3 Military exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2 Using Python as a Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.1 Grocery shopping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2 Oil change . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3 Age average . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.4 Saving for a bike . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.5 Growing town . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6 Coffee maker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7 Gardening . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8 Setting tiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.9 Submerged soccer ball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.10 Fastest runner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.11 Triangle area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.12 Math functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.13 Random numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.14 Greatest common divisor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.15 Fractions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.1 Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.2 Square . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.3 Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.4 Sales prediction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.5 Sales tax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.6 Restaurant bill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.7 Gas consumption conversion I (EU to US) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.8 Gas consumption conversion II (US to EU) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.9 Distance per tank of gas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.10 Circuit board price . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.11 Gross pay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
113
113
113
113
113
114
114
114
114
114
114
115
115
115
115
115
116
116
116
116
116
116
117
117
117
117
117
117
118
118
118
118
118
119
119
119
119
119
119
120
120
120
120
120
120
120
121
121
121
122
122
122
122
123
123
123
123
124
124
124
124
125
125
126
126
126
126
126
127
127
128
6.10 Trapezoids . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7 Conditional Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.1 Water jar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.2 Throwing stones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.3 Missing numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.4 Trapezoids revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.5 Infinite sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.1 Spelling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.2 Inserting spaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.3 Counting chars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.4 Counting words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.5 Search and replace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9 Tuples, Lists, and Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9.1 List reverse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9.2 String to list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10 More on Counting Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.1 Analyze string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.2 Multiplication table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.3 Approximating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.4 Prime numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.5 List maximizer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.6 Fibonacci . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.7 Adding fractions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11.1 Sure plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11.2 Syntax check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12 Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.1 Bank account . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.2 Word magic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3 Number magic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4 Vector magic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13 Class Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13.1 Number master . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13.2 Vector master . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
III
128
129
129
129
130
130
130
130
131
131
131
131
131
131
131
131
132
132
132
132
132
132
133
133
133
133
134
134
134
134
135
135
136
136
136
Review Questions
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
142
146
148
154
157
160
163
165
171
172
173
175
Foreword
This course provides a gentle yet efficient introduction to Python a modern highlevel dynamic programming language that is widely used in business, science, and
engineering applications. If this is your first time learning a programming language,
then we recommend that you spend a few days with Karel the Robot before diving into
Python. Karel the Robot is available in NCLab (http://nclab.com) and it will teach you
what you will need most algorithmic thinking.
Algorithmic thinking is ability to translate your ideas into procedures, or sequences
of steps, that are compatible with the way a machine operates. It is the most essential skill in computer programming. Algorithmic thinking is not bound to any specific
programming language, and therefore it is a very good idea to acquire it using a very
simple language such as Karel the Robot. Once you have algorithmic thinking, your efficiency in learning any new programming language will improve dramatically. Moreover, Karels syntax is very similar to Python, so the transition from Karel to Python is
effortless.
In Python you will learn more applied concepts including mathematical operations
and functions, 2D and 3D plotting, local and global variables, strings, tuples, lists, dictionaries, exceptions, object-oriented programming, and more. A strong companion of
Python are its libraries. Besides the Standard Library that contains many built-in functions not present in lower-level languages such as Java, C, C++ or Fortran, Python also
has powerful scientific libraries including Scipy, Numpy, Matplotlib, Pylab, Sympy and
others. With these, you will be able to solve entry-level scientific and engineering problems. These libraries are used throughout the course.
Part I
Textbook
1
1.1
1.2
Introduction
Objectives
Learn the difference between compiled and interpreted programming languages.
Learn basic facts about Python and its powerful companion libraries.
Understand how Python programming works in the cloud setting.
Write and run your first Python program.
Compiled and interpreted programming languages
Depending on your objectives, this course may be all you will ever need. We hope
that you will like Python and want to learn more and there is much more to learn
out there. References to materials covering more advanced topics and object-oriented
programming are given in Section 15.
1.4
In NCLabs Python module, Python code is typed into one or more code cells. The code
is then sent as a text string to a remote server where it is interpreted, and the results are
sent back to your web browser. It does not matter if you are using a desktop computer,
laptop, netbook, tablet, or any other hardware platform. Your hardware is not used for
computing, only in a limited way for graphics rendering.
1.5
NCLabs public database can be accessed from the File managers File menu or from
the File menu of the Python module. In the Search box that appears, enter the keywords
that best match what you are looking for. For example, typing "textbook python" will
find exercises that belong to the Python textbook. Any project that you find you can
download into your account, modify, and use in any way you wish.
1.6
The Python module can be launched via the Programming icon on Desktop or via File
managers File menu. Initially, the module will contain a demo program Python program that can be run instantly by pressing the green arrow button. The demo program
is not necessarily the simplest possible Python program. Its purpose is to illustrate the
usage of the Python module and yield interesting graphics. The output of the present
demo program is the so-called Dragon fractal, as shown in Fig. 1.
After you do not need the demo program anymore, you can turn it off in Settings.
Next time you launch the Python module, it will not contain any code.
1.7
2.1
Objectives
Learn how to use Python for elementary as well as advanced math operations.
Learn how to work with mathematical functions, fractions, random numbers and
complex numbers.
Python can be used as an advanced scientific calculator no need to own a TI-89 ($150
value). As a matter of fact, NCLab is much more powerful a TI-89 hardly could compete with thousands of processors under NCLabs hood. In this textbook we will learn
how to use this computing power. Let us begin with the simplest math operations. The
rest of this section is fairly slow, so feel free to skip to Section 3 should it be too boring
you can always return to it later.
2.2
2.3
Multiplication
2.4
Division
sion, or floored division, and returns an integer. This is because like C, C++, and Fortran,
Python is strongly-typed. This means that python will avoid implicitly changing between types of data. In order to perform floating-point division, the type of division
that is more common in the sciences, at least one of the numbers must be represented
as a real number.
Adding a decimal point after the number will accomplish this. Now, the result is a
real number:
33. / 5
yields
6.6
An alternative way of turning an integer into a real number, which also works for
variables, is using the function float(). Then the above division could be done as
follows:
float(33) / 5
Output:
6.6
Once we understand the behavior, we can use it to our advantage. For example, we
can calculate how many times a dozen fits into a thousand:
1000 / 12
Output:
83
By calculating 1000 - 83 * 12 we obtain 4 which is the remainder of the integer
division. In fact the remainder can be calculated in a simpler way using the modulo
operator that will be introduced in the next paragraph.
10
In summary:
Keep in mind that division is a tricky operation. Failure to convert at least one
operand to a real number can be a source of mistakes that are very hard to find.
2.5
Modulo
The last of the common arithmetic operations is modulo (remainder after integer division). In Python modulo is represented via the percent symbol %:
6 % 4
Output:
2
Modulo can be applied to real numbers as well:
12.5 % 2.0
Output:
0.5
2.6
Powers
Output:
18.31786887167828
But we have to be careful with negative numbers:
(-3.2)**2.5
Output:
Traceback (most recent call last):
File "<nclab>", line 1, in <module>
ValueError: negative number cannot be raised to a fractional
power
2.7
Priority of operators
Note that no other brackets such as { } and [ ] are admissible in mathematical expressions. The reason is that they have a different function in the programming language. To illustrate the priority of operations, we evaluate the following expression:
3**4 / 27 * 5 + 3 * 5
Output:
30
If we are not sure, it never hurts to use round brackets:
12
(3**4) / 27 * 5 + 3 * 5
Output:
30
2.8
Your code will be much more readable if you use empty characters on either side of
arithmetic symbols, as well as after commas. Hence, you should never write things like
sin(x+y)+f(x,y,z)*5-2.4.
Instead, the same can be written in a much more reader-friendly form as
sin(x + y) + f(x, y, z) * 5 - 2.4.
2.9
In order to calculate square roots, exponentials, sines, cosines, tangents, and many
other math functions, the best way is to import Numpy. Numpy is a powerful Python
library for numerical computations. To import it, just include the following line in your
code:
from numpy import *
Here the symbol * stands for "everything". If you wanted to import just one or two
functions, you could do that as well by just giving their names, separated by commas.
After Numpy is imported, we can calculate, for example, e2 :
exp(2)
Output:
7.3890560989306504
13
Elementary functions (and constants) that one can import from Numpy are listed below. We also show their arguments for clarity, but the functions are imported without
them. For example, the absolute value function is imported via from numpy import
abs.
pi
abs(x)
arccos(x)
arccosh(x)
arcsin(x)
arcsinh(x)
arctan(x)
arctanh(x)
arctan2(x1 , x2 )
cos(x)
cosh(x)
exp(x)
log(x)
pow(a, b)
sin(x)
sinh(x)
sqrt(x)
tan(x)
tanh(x)
absolute value of x
inverse cosine of x
inverse hyperbolic cosine of x
inverse sine of x
inverse hyperbolic sine of x
inverse tangent of x
inverse hyperbolic tangent of x
arc tangent of x1 /x2 choosing the quadrant correctly
cosine of x
hyperbolic tangent of x
ex
natural logarithm of x
ab (same as "a**b")
sine of x
hyperbolic sine of x
square root of x
tangent of x
hyperbolic tangent of x
In summary:
Python provides many readily available mathematical functions via the Numpy
library. To use them, import them via the command from numpy import *
2.10
Fractions
Python makes operation with fractions easy via the Fraction function that is imported from the fractions library:
from fractions import Fraction
A fraction such as 4/7 can be defined simply as Fraction(4, 7). Fractions can be
used with the same operations as numbers, and the result of such an operation is a
14
2.11
Random numbers
Python provides a random number generator via the random() function that can be
imported from the random library:
from random import random
15
This function returns a random real number between 0 and 1. For example,
random()
yields
0.871979925682207
Sometimes we need to generate random integers rather than real numbers. This is easy.
For illustration, a random integer n between 1 and 3 can be generated via the code
a = random()
n = int(3*a + 1)
Here the function int() will erase the decimal part of the real number, converting it
to an integer.
2.12
Complex numbers
Complex numbers are always represented as two floating point numbers, the real and
imaginary part. Appending j or J to a real number makes it imaginary:
1j * 1J
Output:
(-1+0j)
This is one way to define complex numbers:
1 + 3j
Output:
(1+3j)
Another way is to use the command complex:
16
complex(1, 3)
Output:
(1+3j)
All arithmetic operations that are used for real numbers can be used for complex numbers as well, for example:
(1 + 2j) / (1 + 1j)
Output:
(1.5+0.5j)
To extract the real and imaginary parts of a complex number z, use z.real and
z.imag. Use abs() to get the absolute value:
a = 3 + 4j
a.real
a.imag
abs(a)
Output:
3
4
5
3
3.1
Functions
Objectives
3.2
The purpose of creating custom functions is to make selected functionality easily reusable.
In this way we can avoid code duplication, and bring more structure and transparency
into our programs.
In Karel the Robot, custom functions were similar to commands but additionally, they
could return values. For example, a function turnsouth, that turns the robot to face
South and makes him return his GPS coordinates, looks as follows:
def turnsouth
while not north
left
repeat 2
left
return [gpsx, gpsy]
In Python, the definition of a new function also begins with the keyword def, but we
moreover have to use round brackets for input arguments and the colon : at the end
of the line. For example, the following function adds two numbers and returns the result:
def add(a, b):
return a + b
The round brackets in the function definition are mandatory even if no arguments are
passed but the return statement can be omitted if not needed. The two lines of code
above are a function declaration only the function is not called. In order to call the
function, we need to write one additional line:
print "5 + 3 is", add(5, 3)
This will produce the following output:
5 + 3 is 8
In most cases, functions are defined to process some input arguments and to return
some output values. However, this does not apply always. The following function does
18
3.3
Python does not require that we specify the type of function arguments. What does
it mean? The above function add(a, b) works for real numbers, complex numbers,
vectors, strings, and any other objects where the operation + is defined. Lets try this:
def add(a, b):
return a + b
word1 = "Good "
word2 = "Evening!"
print add(word1, word2)
Output:
Good Evening!
This makes Python very intuitive and easy to use.
3.4
Python functions can return multiple values which often comes handy. For example,
the following function returns the second, third, and fourth powers of a number:
def powers(a):
return a**2, a**3, a**4
This is how the function is used:
var1 = 2
print "Powers are", powers(var1)
Output:
19
3.5
Have you ever been to Holland? It is the most bicycle friendly place in the world. Imagine that you work for the Holland Census Bureau. Your job is to ask 10000 people how
they go to work, and enter their answers into a database. The program for entering
data into the database was written by one of your colleagues, and it can be used as
20
follows:
add_database_entry("John", "Smith", "walks")
or
add_database_entry("Louis", "Armstrong", "bicycle")
or
add_database_entry("Jim", "Bridger", "horse")
etc. Since you are in Holland, it can be expected that 99% of people are using the bicycle. In principle you could call the function add_database_entry() to enter each
answer, but with 9900 bicyclists out of 10000 respondents you would have to type the
word "bicycle" MANY times.
Fortunately, Python offers a smarter way to do this. We can define a new function
def enter(first, last, transport="bicycle"):
enter_into_database(first, last, transport)
This is a simple ("thin") wrapper to the function add_database_entry() that allows
us to omit the third argument in the function call and autocomplete it with a default
argument "bicycle". In other words, now we do not have to type "bicycle" for
Louis Armstrong or any other bicyclist:
enter("Louis", "Armstrong")
Only if we meet a rare someone who uses a car, we type
enter("Niki", "Lauda", "car")
Another example: Let us return to the function add(), and let us imagine that very often (but not always) the second number that we are adding is 10. Then it makes sense
to write the function add() as follows:
def add(a, b=10):
return a + b
21
The function will work as before when called with two arguments:
A = 5
B = 1
add(A, B)
Output:
6
But it can also be called with the second argument omitted:
A = 5
add(A)
Output:
15
Few rules to remember
(1) Default arguments need to be introduced after standard (non-default) arguments.
In other words, the following code will result into an error:
def add(a=5, b):
return a + b
This is the error message:
File "<nclab>", line 1
SyntaxError: non-default argument follows default argument.
(2) If multiple default arguments are present, they have to follow the non-default ones.
If the number of arguments in the function call is less than the total number of default
and non-default arguments, then first all non-default arguments are assigned, and then
the default ones from left to right. To illustrate this, assume the function:
def add(x, a=2, b=3):
return x + a + b
22
4
4.1
4.2
RGB colors
According to the additive color model which is based on the human perception of colors,
every color can be obtained by mixing the shades of Red, Green and Blue. These are
called additive primary colors or just primary colors. The resulting color depends on the
proportions of the primary colors in the mix. It is customary to define these proportions by an integer number between 0 and 255 for each primary color. So, the resulting
color is a triplet of integers between 0 and 255. For the primary colors we have
Color
Red
Green
Blue
R G B
255 0 0
0 255 0
0 0 255
Fig. 2: Left: pure red color [255, 0, 0]. Middle: pure green color [0, 255, 0]. Right; pure
blue color [0, 0, 255].
When the proportions of all three primary colors are the same, the result is a shade of
grey. With [0, 0, 0] one obtains black, with [255, 255, 255] white. This is illustrated in
Fig. 3.
Fig. 3: Left: black color [0, 0, 0]. Middle: dark grey color [128, 128, 128]. Right; light grey
color [220, 220, 220].
24
Guessing RGB codes is not easy. If you need to find the numbers representing your
favorite color, the best way is to Google for "rgb color palette". You will find many
pages that translate colors into RGB codes. Fig. 4 shows three "simple" colors cyan,
pink and yellow along with their RGB codes.
Fig. 4: Left: cyan color [0, 255, 255]. Middle: pink color [255, 0, 255]. Right; yellow color
[255, 255, 0].
4.3
In Python, plotting is done via the Pylab library. The Pylab plot() function takes two
arrays: x-coordinates and y-coordinates of points in the xy plane. Between the points,
the curve is interpolated linearly. Let us illustrate this on a simple example with just
five points [0, 0], [1, 2], [2, 0.5], [3, 2.5] and [4, 0]:
from pylab import *
x = [0.0, 1.0, 2.0, 3.0, 4.0]
y = [0.0, 2.0, 0.5, 2.5, 0.0]
clf()
plot(x, y)
show()
The commands clf(), plot() and show() do clear the canvas, plot the graph, and
fetch the image from server, respectively. The output is shown in Fig. 5.
25
4.4
In the following we will discuss more options and show some useful techniques. Lets
say, for example, that we want to plot the function f (x) = sin(x) in the interval (0, 2).
The array of x-coordinates of equidistant points between 0 and can be created easily
using the function linspace():
from numpy import *
x = linspace(0, 2*pi, 100)
Here 100 means the number of points in the division (including endpoints). Increasing this number will improve the resolution and vice versa. Next, the array of ycoordinates of the points is obtained via
y = sin(x)
The last part we already know:
clf()
plot(x, y)
show()
The output is shown in Fig. 7.
4.5
The plot can be made nicer by adding a label, and also the color and the line style can
be changed. Let us start with adding a label:
plot(x, y, b-, label = "Solid blue line")
legend()
show()
The output is shown in Fig. 8.
28
Last let us stay with green color but make the dots larger:
clf()
plot(x, y, go, label = "Bigger green dots")
legend()
show()
The output is shown in Fig. 11.
4.6
In the previous plots, function graphs were fitted into the display window, which
means that the horizontal and vertical axes were scaled differently. This can be changed
by including the axis(equal) command after calling plot(). Also, grid can be
displayed by using the grid() command:
30
Plot limits can be set using the xlim() and ylim() functions after plot(). For example, we can stretch the sine function from Fig. 12 to span the entire width of the canvas
as follows:
31
4.8
This can be done very easily, just do not use the clf() command between the plots
and you can have as many graphs in one figure as needed. Let us do three:
32
Fig. 14: Plotting graphs of functions 1/x, 1/(1 + x2 ) and ex in interval (0.5, 5).
The plot() command in Pylab is much more powerful, we just saw a small fraction of its functionality. For a complete list of options visit the Pylab page http://
www.scipy.org/PyLab.
33
4.9
y(t) = t sin(t)
34
4.10
For 3D plots it is practical to use the mplot3d toolkit of the Python library Matplotlib.
Let us begin with parametric 3D curves since this is analogous to how we handled planar curves in the previous paragraph. 3D curves are sequences of linearly interpolated
3D points represented via three arrays of x, y and z coordinates. As an example we will
plot the curve x(t), y(t), z(t) where
x(t) = (1 + t2 ) sin(2t), y(t) = (1 + t2 ) cos(2t), z(t) = t,
and where the parameter t lies in the interval (2, 2).
# Import Numpy and Matplotlib:
from numpy import *
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
# Set legend font size (optional):
mpl.rcParams[legend.fontsize] = 15
# Setup the 3D plot:
fig = plt.figure()
ax = fig.gca(projection=3d)
# Define interval for parameter t and its
# division:
t = linspace(-2, 2, 100)
#
x
y
z
4.11
There are several ways to plot graphs of functions of two variables, first let us do this
with Matplotlibs mplot3d toolkit, then we will use WebGL. We will plot the graph of
the function
f (x, y) = sin(x) sin(y)
in the square (, ) (, ).
# Import Numpy and Matplotlib:
from numpy import *
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
# Setup the 3D plot:
fig = plt.figure()
ax = fig.gca(projection=3d)
36
#
#
x
y
Solid surface plot can be obtained by replacing in the above code plot_wireframe
with plot_surface. The output is shown in Fig. 18.
38
We have only mentioned the most basic Matplotlibs functionality, for more options we
refer to the tutorial at http://matplotlib.sourceforge.net/mpl_toolkits/
mplot3d.
4.12
For this functionality, your browser has to support WebGL (most of modern browsers
do, with the exception of Internet Explorer). See the introductory tutorial Welcome to
NCLab on the page http://femhub.com/nclab-tutorials/ for detailed instructions on how to enable WebGL. In the following example, we plot the graph of the
function
f (x, y) = sin
p
x2 + y 2
39
40
4.13
Pie charts are an elegant way to report the breakdown of an ensemble into parts (percentages). We use the Pylabs function pie for that. The simplest example of a pie chart
involves seven lines of code:
from pylab import *
data = [450, 550, 300]
labels = [cats, dogs, mice]
clf()
axis(equal)
pie(data, labels=labels)
show()
The output is shown in Fig. 21.
41
# Import libraries:
from pylab import *
# Remove eventual previous plots:
clf()
# We will have five sections:
labels = [TVs, Monitors, Cameras, Printers, Scanners]
# Fractions in percent:
fractions = [15, 30, 5, 40, 10]
# Optional. "Monitors" section will be highlighted by moving
# out of the chart by 0.05:
explode = (0, 0.05, 0, 0, 0)
# Create the pie chart. The "autopct" parameter formats the
# numerical percentages. Shadow can be suppressed by setting
# it to False:
pie(fractions, explode=explode, labels=labels, \
autopct=%1.1f%%, shadow = True)
# Create title:
color = [220, 220, 220] # This is light-grey color.
title(Company\s last year production, \
bbox={facecolor: color, pad: 20})
# Fetch the plot from the server:
show()
42
Fig. 22: Sample pie chart showing the breakdown of a companys production.
The autopct option determines the numerical format in which the numbers inside the
pie chart will be displayed. The letter f stands for a floating-point number. The 1.1
means that one decimal digit will be present after the decimal point (1.2 would print
the percentages with two digits after the decimal point, etc.). The parameter shadow
indicates whether a shadow will be used. Iy can be set to True or False. The color
parameter in title defines a color using its RGB components which are between 0
(darkest) and 255 (lightest). The parameter pad defines padding.
4.14
Bar charts are a great way to visualize time-dependent data such as, for example, the
yearly growth of a companys revenues, number of daily visits to a web page, weekly
rate of unemployment in the state, etc. The simplest bar chart involves 5 lines of code:
from pylab import *
data = [450, 550, 300]
clf()
bar([1, 2, 3], data)
show()
43
The array [1, 2, 3] specifies the positions on the horizontal axis where the bars
begin. The default width of the bars is 0.8 and it can be adjusted via the parameter
width of the bar() function. The output is shown in Fig. 23.
Next let us present a more advanced bar chart that shows a companys growth both in
the total number of employees and the yearly increments.
# Import libraries:
from numpy import max
from pylab import *
# Number of years:
N = 5
# Totals and increments:
total = (20, 25, 32, 42, 61)
increment = [5, 7, 10, 19, 30]
44
45
5
5.1
Variables
Objectives
Learn to assign values to variables.
Understand dynamic type interpretation.
Learn more about local and global variables.
Understand why global variables should be avoided.
Learn about shadowing of variables.
The reason for using variables is to store useful information for later use. This is the
same across all programming languages. The way we work with variables in Python is
almost the same as in Karel the Robot all that we learned about variables with Karel
applies here. Moreover, Python has interesting new features that we will explore in this
section.
46
5.2
Creating variables
Variables can store Boolean values (True of False), text strings, integers, real numbers,
and more. In Python, the type of a variable does not have to be indicated in advance
(such as for example in C/C++). The type of a variable will be figured out at runtime
based on the value that is stored in it. This is called dynamic type interpretation. Let us
look at the following code:
a = 5
print a
a = "Hi!"
print a
a = Hello!
print a
a = True
print a
The output is
5
Hi!
Hello!
True
Initially, the type of the variable a was an integer, then it was changed to a text string,
and finally it became a Boolean variable. Being able to do things like this makes Python
programming very flexible. However, we should not abuse our freedoms unless there
is a valid reason for it.
Avoid abuse of dynamic type interpretation. A variable, once created for a purpose,
should serve that purpose. If you need another variable for something else, just create
another variable.
Also:
Have names of variables reflect their contents. For example, phone_number is a good
name for a variable where phone numbers are stored. Using the name x17 for such a
variable is not against any rules, but your code becomes unreadable.
In general, do not be too inventive with names of variables nor with algorithms. Make
sure that your code is crystal clear. Write comments as much as you can. You should
47
not leave anything for the reader to figure out by himself/herself. Otherwise no one
will understand your code not even yourself when you return to it after some time.
5.3
In Python, several variables can be created at the same time and initialized with the
same value:
x = y
print
print
print
= z = 0.0
"x =", x
"y =", y
"z =", z
Output:
x = 0.0
y = 0.0
z = 0.0
Any variable must be defined (have a value assigned) before it can be used. If we try
to use a variable that the interpreter has not seen before, such as w in
x = w / 2.
then an error message will follow:
Traceback (most recent call last):
File "<nclab>", line 2, in <module>
NameError: name w is not defined
Initializing a new variable with existing one(s) is indeed possible:
w = (x + y + z + 1) / 2.
print "w =", w
yields
w = 0.5
48
5.4
The simplest way to increase the value of a numerical variable in Python by a given
number is to use the += command:
v = 1
v += 3
print "v =", v
Output:
v = 4
We can also subtract a number from a numerical variable:
v -= 1
print "New value of v is", v
Output:
New value of v is 3
We can multiply a numerical variable with a number:
v *= 4
print "Now v is", v
Output:
Now v is 12
And finally, we can divide a numerical variable with a number:
v /= 6
print "Finally, v is", v
Output:
Finally, v is 2
49
5.5
Variables defined inside a function are local to that function. If we try to access such a
variable outside the function, even though the function was already called, the variable
is unknown. Look at the following code:
def add(a, b):
c = a + b
return c
print "Sum of 3 and 4 is", add(3, 4)
print c
50
5.6
Once a variable is used in the main program, then it is global, meaning that you can use
it in any function without passing it as an argument. Like in the following code:
val = 5.0
def msg():
print "val =", val
msg()
Yuck! This code is not only ugly but also a source of future problems. Imagine that
your programming project grows and the definition of the variable val is moved to a
different module. Then, at some point you realize that you should get rid of the global
variable val because using global variables is not a good programming practice. But
when you remove it, the function msg() stops working!
On the other hand, it is very easy to write the code in a clean fashion:
51
def msg(out):
print "val =", out
val = 5.0
msg(val)
Now the function msg() is well defined one does not need to look elsewhere in the
program to understand what it does. The output is:
val = 5.0
In summary:
Avoid using global variables in functions. Any function that operates on some data
should always obtain all the data as its parameters.
5.7
Variable shadowing
Sometimes we may end up having two different variables of the same name in the
code. Usually this happens in large software projects, but we can only illustrate it on a
short program:
c = 5
def add(a, b):
c = a + b
print "The value of c inside is", c
return c
add(1, 2)
print "The value of c outside is", c
The output is
The value of c inside is 3
The value of c outside is 5
We say that the global variable c defined in the first line of the code is in the function
add() shadowed by the local variable c. Simply said, local variables in functions have
52
priority. What actually happens when the above code is interpreted, is that the interpreter gives to the two c variables different names. For the interpreter, they are two
completely different objects.
5.8
Overriding constants
In Python, constants such as pi or e are in fact just global variables and in principle
there is no problem redefining their values in our program. Of course this is not a good
programming practice as our code becomes confusing. A variable pi should contain
the value of as everyone expects.
But, mistakes happen. If we define a function where we create a local variable pi,
this is in fact another example of variable shadowing and our code will work fine:
from numpy import sqrt, pi
def hypotenuse(x, y):
pi = sqrt(x**2 + y**2)
return pi
print hypotenuse(3, 4)
print pi
The output is
5.0
3.14159265359
6
6.1
evaluate to True or False. These expressions are used to determine the relationship
between two values.
Lets begin with creating an integer variable and printing it:
a = 1
print a
Output:
1
Now type
print a > 0
Output:
True
In the above example, > is a comparison operator. It is used to evaluate whether the
value on the left is greater than the value on the right.
Although the syntax looks a bit unusual, this is a correct Python code since a is equal
to 1, the Boolean expression a > 0 is True. This is the value that was printed by the
interpreter.
We can try it the other way round:
print a < 0
Output:
False
True and False are the two possible values of logical (Boolean) expressions. In the
next paragraph we will learn to store them in variables, and in Paragraph 6.4 we will
use them with logical operations.
54
6.3
Boolean variables
Similar to numbers and strings, Boolean values can be stored in variables. For example:
b = a < 0
print b
Output:
False
Boolean expressions involving numbers often contain the following operators:
Symbol
>
>=
<=
<
==
!=
<>
Meaning
greater than
greater than or equal to
less than or equal to
less than
equal to
not equal to
not equal to (same as !=)
A common source of confusion for new Python programmers is the difference between the == and = operators. The assignment operator = is used to assign a
value to a variable. The comparison operator == is used to compare two values and
determine if they are equal.
6.4
Boolean operations
When solving real-life problems, our algorithms often contain conditions that include
more than one logical expression. For example, consider an algorithm that calculates
the area of a triangle with edge lengths a, b and c. These three numbers are provided
by the user. Clearly, the result is undefined if any of the three numbers is negative or
zero. It is also undefined if the three numbers are positive but do not satisfy the triangle inequality (the sum of the lengths of two shorter edges must be greater than the
length of the longest edge). Hence, before we calculate the area, we need to introduce
the following logical variables:
A=a>0
B=b>0
55
C=c>0
D =a+b>c
E =a+c>b
F =b+c>a
The numbers a, b, c form an admissible input if the following Boolean expression is
True:
A and B and C and (D or E or F )
We can see that logical operations indeed are useful. Now let us revisit them one by
one, starting with logical and:
If A and B are logical expressions, then A and B is True only if A as well as B are True,
otherwise it is False:
a = 1
v1 = a > 0
v2 = a < 5
print v1 and v2
Output:
True
Logical or of expressions A and B is True if at least one of A, B is True. Otherwise it is
False:
v3 = a > 10
print v1 or v3
Output:
True
Negation is a logical operation that changes the value of expression A to False if A is
True, and vice versa:
56
v4 = not v1
print v4
Output:
False
Sometimes logical expressions can be more complicated, but this is no problem as we
always can use round brackets:
v5 = not ((v1 and v2) or (v3 and not v4))
6.5
Monte Carlo methods are popular methods of scientific computing. They employ large
numbers of random values to calculate approximately results that are difficult or impossible to obtain exactly. Sounds complicated? On the contrary, Monte Carlo methods
are very simple! For demonstration, let us calculate the area of an ellipse.
An ellipse centered at the origin (0, 0) whose major and minor half-axes a and b
coincide with the x and y axes is given by the formula
x2 y 2
+ 2 = 1.
a2
b
In other words, all points (x, y) in the plane that satisfy this equation form the ellipse.
It is also true that all points in the plane that satisfy
x 2 b2
+
<1
a2 y 2
form the interior of the ellipse. Obviously the ellipse is enclosed in the rectangle (a, a)
(b, b). The idea of the Monte Carlo algorithm is very simple: We will fill the rectangle with random points, and count how many of them fall into the ellipse. The latter
number will be denoted by m. With a sufficiently large n, such as 100, 000 or more, the
ratio of m and n will be close to the ratio of the area of the ellipse E and the area of the
rectangle R = 4ab. Hence we obtain a simple formula
m
E
n
R
from which we can express the area of the ellipse as
57
ER
m
.
n
The for loop in Python is much more powerful than the repeat loop in Karel and it
will be discussed in detail in Section 10. Now let us return to our Monte Carlo method:
# Import libraries:
from random import random
# Monte Carlo algorithm for
# ellipse area calculation:
def area(a, b, n):
# Initialize m by zero:
m = 0
# Repeat n times:
for i in range(n):
# Random number between 0 and 1:
x = random()
# Transform it between (-a, a):
x = (x - 0.5) * 2 * a
# Random number between 0 and 1:
y = random()
# Transform it between (-b, b):
y = (y - 0.5) * 2 * b
# If the point (x, y) lies in
# ellipse, increase m by one:
if is_inside(x, y, a, b):
m += 1
# Area of rectangle (-a, a)x(-b, b):
print m
R = 4.0 * a * b
# Calculate the approximate area:
E = R * m / n
# Return it:
return E
The code is ready and we can test it. Let us do it for a = 2, b = 1 and various values of n:
59
7
7.1
Conditional Loop
Objectives
Review the difference between counting and conditional loops.
Review what we know about conditions from Karel the Robot.
Learn about the new elif statement in Python.
Learn how to terminate a loop with the break statement.
Learn to use the continue statement to skip the rest of the loop.
60
Every procedural programming language has two types of loops that serve different
purposes: The counting loop (repeat in Karel, for in Python and many other languages) is used when the number of cycles is known in advance. Such as when we
need to write the first 10 even integers.
On the contrary, the conditional loop (while in Karel, Python, and many other languages) is used when it is not known how many cycles will be needed. Instead of the
number of repetitions, the conditional loop has a condition that must be fulfilled for
the loop to go on. It is used, for example, when we need to keep halving a real number
while the result is greater than 105 .
We first saw the for loop in Paragraph 6.5 about the Monte Carlo method, it will
be used with text strings in Section 8, and additional details will be provided in Section 10. In the following paragraphs of this section we will focus on conditions and the
conditional loop.
In summary:
Always use the counting loop when you know how many repetitions will be done.
Only if you do not know, use the conditional loop.
7.3
Conditions in Python are almost the same as in Karel the Robot. The if - else statement has been used in the previous sections, so there is no need to explain it here again.
But there is one practical new feature in Python the elif statement that simplifies
cases with more than two options. If you think that "elif" sounds a lot like "else if" then
you are absolutely right! In general
if <logical_expression_1>:
<do_action_1>
elif <logical_expression_2>:
<do_action_2>
else:
<do_action_3>
means exactly the same as
61
if <logical_expression_1>:
<do_action_1>
else:
if <logical_expression_2>:
<do_action_2>
else:
<do_action_3>
Clearly, the latter involves more indentation. The advantage of the elif statement
becomes more visible as the number of cases grows. Let us therefore show a concrete
example with five cases:
Imagine that we have five wooden boxes: Box A is for apples that weight under 5
ounces, box B for apples that weight at least five but less than 10 ounces, box C for apples that weight at least 10 but less than 15 ounces, etc. Apples weighting 20 ounces or
more will all be put into box E. We need to write a function box(weight) that, given
the weight of an apple, chooses the correct box for it and returns the corresponding
letter:
def box(weight):
if weight < 5:
return "A"
elif weight < 10:
return "B"
elif weight < 15:
return "C"
elif weight < 20:
return "D"
else:
return "E"
Note the mandatory colon : after every if, elif and else statement. Here is how
the same code would look like without the elif statement:
62
def box(weight):
if weight < 5:
return "A"
else:
if weight < 10:
return "B"
else:
if weight < 15:
return "C"
else:
if weight < 20:
return "D"
else:
return "E"
In summary:
The elif statement simplifies conditions with multiple cases.
7.4
Sample output:
0.383771890647
0.068637471541
0.0850385942776
0.682442836322
0.168282761575
0.121694025066
0.185099163429
0.606740825997
0.209771333501
0.186191737708
0.608456569449
0.591009262698
Running the program once more gives another output:
0.637423013735
0.533383497321
0.240830918488
0.343139647492
0.718014397238
0.698931548709
0.363558456088
In summary:
The while loop should be used only when the number
of repetitions is not known in advance.
7.5
The break statement can be used to exit a loop at any time, no questions asked. If
multiple loops are embedded, then it only exits the closest one that contains it. For illustration, let us rewrite the above program to use the break statement:
64
7.6
Sometimes we know that finishing all commands in the loops body is not necessary.
Python has the continue command for this. To illustrate its use, let us write a program
that will generate triplets of random numbers between zero and one until all three of
them are greater than 0.9. We also want to know how many attempts were needed.
Clearly, after the first number is generated and it is less or equal to 0.9, it does not
make any sense to generate the other two. Thats when we use the continue command. If the first number is greater than 0.9 but the second one is less or equal to 0.9, it
is time to use the continue command once again. Here is the code:
from random import *
counter = 0
while True:
counter += 1
a1 = random()
if a1 <= 0.9:
continue
65
a2 = random()
if a2 <= 0.9:
continue
a3 = random()
if a3 <= 0.9:
continue
print "Finally the desired triplet:"
print a1, a2, a3
print "It took", counter, "attempts to get it!"
break
Sample output:
Finally the desired triplet:
0.921077479893 0.956493808495 0.917136354634
It took 1168 attempts to get it!
7.7
The following code has seen the light of the world too many times:
counter = 0
while counter < 20:
# Do something with the counter, here
# for simplicity we just print it:
print counter
# Increase the counter:
counter += 1
Although there is nothing syntactically wrong with this code, and it even produces
the desired result, it is an example of bad programming. The person who wrote such
a code probably did not understand why programming languages have two types of
loops. The code emulates a counting loop and whoever reads it, will be confused. Why
was the while loop used when the number of repetitions was known in advance? The
correct code for this situation is:
for counter in range(20):
print counter
66
7.8
As our programming skills get stronger, we are able to tackle more difficult problems.
Now it is our task to find an angle x that is equal to its own cosine. In other words, we
need to solve the equation
cos(x) = x.
This equation cannot be solved on paper. But we will see that it can be solved with the
help of the computer rather easily. As the first step, let us visualize the graphs so that
we know where approximately the solution can be expected:
from numpy import pi, cos
from pylab import *
x = linspace(0, pi/2, 100)
y = cos(x)
z = x
clf()
plot(x, y, label="cos(x)")
plot(x, z, label="x")
legend()
show()
The output is shown in Fig. 25.
Fig. 25: Graphs of the functions cos(x) and x in the interval (0, /2).
67
The solution that we are after is the value of x where the two graphs intersect. Looking at the picture, clearly the solution is somewhere between 0.6 and 0.8. An engineer
would not be extremely happy with such an answer though we need to make this
guess much more accurate.
Looking at the graphs again, we can see that in order to reach the intersection point,
we can depart from zero and march with very small steps to the right while the value
of cos(x) is greater than the value of x. We stop as soon as cos(x) becomes less than x.
Clearly, the while loop needs to be used as we do not know exactly how many steps
will be taken.
Lets do this. Our step will be called dx, and our marching point on the x-axis will
be called simply x. We will also count steps via the variable n. Choosing dx = 1e-6
will give us the result accurate to five decimal digits:
from numpy import cos
x = 0
dx = 1e-6
n = 0
while cos(x) > x:
x += dx
n += 1
print "Result is approximately", x
print "Steps made:", n
Output:
Result is approximately 0.739086
Steps made: 739086
In other words, the while loop ran 739086 times! Can you imagine doing this on your
pocket calculator?
It is worth mentioning that the numerical method that we used was rather naive
and in fact it took quite a bit of CPU time. Scientific computing is an exciting field
where researchers develop new methods that can solve problems like this more accurately and using less CPU time. In particular, for our problem there are much more
powerful methods that can do the same or better job using just five or six steps (!). One
of them is the Newtons method. If you like what we did here, we encourage you to explore more math functionality and in particular numerical methods in NCLab. There
are displayed projects for the Newtons method and other methods to solve nonlinear
equations and nonlinear equation systems.
68
8
8.1
Strings
Objectives
Using quotes
Since we have already seen usage of simple strings before, let us now understand how
to use quotes in strings. The safest way is to use them with a backslash:
print "I said \"yes\"."
Output:
I said "yes".
Another example:
print "It doesn\t matter."
Output:
"It doesnt matter."
8.3
If we want to use multiline strings, the best way is to enclose them in triple quotes:
69
edgar = """
Once upon a midnight dreary, while I pondered weak and weary,
Over many a quaint and curious volume of forgotten lore,
While I nodded, nearly napping, suddenly there came a tapping,
As of some one gently rapping, rapping at my chamber door.
Tis some visitor, I muttered, tapping at my chamber door Only this, and nothing more.
"""
print edgar
Output:
Yes, there is one empty line on top and one on bottom. The reason is that Python inserted newline symbols there. If we want to avoid these empty lines, we have to include a backslash after the first triple quote, and also at the end of the last line before
the closing triple quote. The backslash prevents Python from inserting a newline symbol into the string. Let us show one more example on backslashes. The string
"""\
This is the first line,
and this is the second line.\
"""
will render as
This is the first line,\nand this is the second line.
When a backslash is included at the end of the first line of text,
70
"""\
This is the first line,\
and this is the second line.\
"""
we obtain
This is the first line,and this is the second line.
As we see, we need to watch for empty characters. Inserting one before the second
backslash
"""\
This is the first line, \
and this is the second line.\
"""
brings us to the desired outcome:
This is the first line, and this is the second line.
8.4
Strings can be concatenated (glued together) with the + operator, and repeated with
the * operator. For example,
word = Help + me!
print "I yelled" + 3 * word
yields
I yelledHelpme!Helpme!Helpme!
Again, empty spaces matter. So lets try again:
word = \"Help + me!\"
print "I yelled " + 3 * word
71
will render
I yelled "Help me!" "Help me!" "Help me!"
8.5
Individual letters forming a string can be accessed via indices. The indices start from
zero. It is also handy to use the index -1 for the last index, -2 for the one-before-last
etc. Typing
word = "breakfast"
print "First character:", word[0]
print "Second character:", word[1]
print "Last character:", word[-1]
print "One-before-last character:", word[-2]
produces the following output:
First character: b
Second character: r
Last character: t
One-before-last character: s
Before we move on, make sure that you remember that
Indices in Python start from zero.
8.6
The length of a string is obtained using the function len(). For illustration, the code
word = "breakfast"
n = len(word)
print "Length of the string:", n
yields
Length of the string: 9
72
Since every string has a known length, the right loop to parse strings is the for loop.
The following code parses the string word letter by letter and prints all the letters:
word = "breakfast"
for c in word:
print c
The same can be achieved using the range() function that we already know from
Paragraph 6.5:
word = "breakfast"
n = len(word)
for i in range(n):
print word[i]
Output:
b
r
e
a
k
f
a
s
t
To see that the two above programs are equivalent, we need to understand a bit more
about the for loop. First, a text string is a sequence of characters. The for loop can
parse sequences using the general scheme for <element> in <sequence>. The
function range(n) creates a sequence of integer numbers 0, 1, ..., n-1. Lets try this
with n = 3:
print range(3)
Output:
[0, 1, 2]
73
Another example:
print range(10)
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
So, for i in range(n) goes through integer indices i = 0, 1, ..., n-1 and for each
one, word[i] is the next character in the text string.
8.7
Slicing strings
74
cycle
This is enough about strings for now, but we will return to them again later. In particular, Python provides many useful built-in operations with text strings that will be
shown in Paragraph 12.7
9
9.1
Tuples
Tuples are perfect for sequences of data that does not change such as the names of
weekdays, or names of months. To define a tuple, enclose comma-separated items in
round brackets:
months = (January, February, March, April, May, \
June,July, August, September, October, November, \
December)
All items in this tuple are text strings, but a tuple can be heterogeneous it can contain
text strings, integers, real numbers, other tuples, etc.
Working with tuples is a lot similar to working with text strings. To begin with,
items in a tuple can be referenced by indices. Remember that indices always start from
zero:
print "First month:", months[0]
print "Second month:", months[1]
print "Third month:", months[2]
75
Output:
First month: January
Second month: February
Third month: March
As in text strings, index -1 refers to the last item, -2 to the one before last, etc.:
print "One before last month:", months[-2]
print "Last month:", months[-1]
Output:
One before last month: November
Last month: December
We can slice tuples same as we sliced text strings:
months[2:5]
Output:
(March, April, May)
As in text strings, the length of a tuple is obtained using the function len():
len(months)
Output:
12
9.3
Lists
Lists are similar to tuples, and all indexing and slicing operations work in the same
way. The only difference is that we can change a list by adding and deleting entries,
we can reorder items in a list, etc. A tuple, once created, cannot be changed.
76
A list is created by enclosing its items into square brackets. For example, an empty
list L is defined as follows:
L1 = []
A list L2 consisting of the first five prime numbers is created as follows:
L2 = [2, 3, 5, 7, 11]
A list cls containing ten students in a class is created via:
cls = [John, Pam, Emily, Jessie, Brian, \
Sam, Jim, Tom, Jerry, Alex]
Lets say that after some time, Emily moves to a different city:
del cls[2]
print cls
Output:
[John, Pam, Jessie, Brian, Sam, Jim,
Tom, Jerry, Alex]
After some time, a new student Jack moves in:
cls.append(Jack)
print cls
Output:
[John, Pam, Jessie, Brian, Sam, Jim,
Tom, Jerry, Alex, Jack]
The function pop() deletes an item and returns it for further use (as opposed to del
which just deletes the item):
77
name = cls.pop(2)
print name
print cls
Output:
Jessie
[John, Pam, Brian, Sam, Jim,
Tom, Jerry, Alex, Jack]
New item can be inserted at an arbitrary position using the function insert():
cls.insert(3, Daniel)
print cls
Output:
[John, Pam, Brian, Daniel, Sam, Jim,
Tom, Jerry, Alex, Jack]
A list can be sorted via the function sort():
cls.sort()
print cls
Output:
[Alex, Brian, Daniel, Jack,
Jerry, Jim, John, Pam, Sam, Tom]
The function reverse() reverses a list:
cls.reverse()
print cls
Output:
[Tom, Sam, Pam, John, Jim,
Jerry, Jack, Daniel, Brian, Alex]
78
The function count() counts the number of occurences of an item in the list:
cls.count(Jerry)
Output:
1
The function index() returns the index of the first occurence of an item:
cls.index(Jerry)
Output:
5
If the item is not found, error is thrown:
cls.index(Kevin)
Output:
Traceback (most recent call last):
File "<string>", line 2, in <module>
ValueError: Kevin is not in list
Another useful operation with lists is their zipping. The zip() function takes two lists
as arguments and creates a new list of pairs. Example:
A = [1, 2, 3]
B = [x, y, z]
print zip(A, B)
Output:
[(1, x), (2, y), (3, z)]
79
If the lists are not equally-long, the superfluous items in the longer list are skipped:
A = [1, 2, 3, 4, 5]
B = [x, y, z]
print zip(A, B)
Output:
[(1, x), (2, y), (3, z)]
9.4
Dictionaries
Sometimes we want to store information for people. Such information may be their
phone number, age, address, hobbies, family status and so on. Pythons dictionary is a
perfect tool to do this. The peoples names are said to be keys and the additional information are the corresponding values.
Cars in a used car store can serve as another example: For each car, the key can be its
VIN (or something else that is unique to each car). The corresponding value can be a
list containing the price of the car, age, mileage, gas consumption, etc.
An empty dictionary D is defined as follows (note the curly brackets):
D = {}
An example of a phone book could be:
phonebook = {Peter Parson: 8806336, Emily Everett: 6784346, \
Lewis Lame: 1122345}
Once a new phone book was created, we may want to add a new person to it:
phonebook[Silly Sam] = 1234567
print phonebook
Output:
{Peter Parson: 8806336, Emily Everett: 6784346,
Lewis Lame: 1122345, Silly Sam: 1234567}
80
It is important to realize that dictionaries are not ordered in any special way. While a
list can be sorted, a dictionary can not. Dictionaries are designed to store keys and values, and to be able to get the value for a given key quickly. The length of a dictionary
can be obtained using the function len():
len(phonebook)
Output:
3
There are additional functions that one can use with dictionaries. However, what we
mentioned so far is enough for an introductory course and we refer to the Python
tutorial1 for more details.
10
10.1
The range() function was first mentioned in Paragraph 6.5. After learning about tuples, lists and dictionaries in Section 9, the reader will not be surprized when we state
that this function produces a Python list of integers. For example:
range(10)
produces the following output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
It is possible to start the list from a nonzero integer:
1
http://docs.python.org/tutorial
82
range(3, 10)
Output:
[3, 4, 5, 6, 7, 8, 9]
The for loop in Python is a counting loop analogous to the repeat loop in Karel the
Robot. Thus it should be used when we know how many repetitions there will be.
However, in Python, the counting loop is not restricted to integer numbers only. It is
much more general it goes over the items of aa arbitrary list or tuple.
10.3
When used in combination with the range() function, it goes over integer indices.
Example:
for i in range(5, 10):
print i
Output:
5
6
7
8
9
As usual, note indentation of the body of the for loop, which has the same purpose
as indentation in the while loop tell the interpreter which commands should be
repeated.
10.4
Remember our tuple of months? We can use the for loop to print them:
for m in months:
print m
Output:
83
January
February
March
April
May
June
July
August
September
October
November
December
The for loop works in the same way with lists it does not distinguish between these
two data types at all.
10.5
Remember that it is easy to extract keys and values from a dictionary using the keys()
and values() functions? In either case, the result of this operation is a Python list,
which in turn can be used with the for loop. That was easy. Let us do something more
interesting perhaps convert an English-Spanish dictionary into a Spanish-English
one:
ES = {city: ciudad, fire: fuego, sun: sol}
SE = {}
for english_word in ES:
spanish_word = ES[english_word]
SE[spanish_word] = english_word
print "Spanish-English dictionary:"
print SE
The output of this program is:
Spanish-English dictionary:
{ciudad: city, sol: sun, fuego: fire}
That was easy, wasnt it?
84
11
Exceptions
11.1
Objectives
Understand what exceptions are, when they can occur, and how to catch them.
Learn to never underestimate the user.
Understand ZeroDivisionError and other exceptions.
Learn to use the assert() function and catch the AssertionError exception.
Learn how to raise exceptions using the raise statement.
1
.
9 x2
Situations like this (dividing by zero, taking square root of a negative number etc.)
cause runtime exceptions. An exeption, when not caught and handled, will terminate
our program with an error. However, Python offers an elegant way to catch exceptions,
that we will explain in the next paragraph.
11.2
Exceptions handling
The assert() function raises an exception whenever the Boolean statement used as
its argument is False. This is a powerful tool to raise our own exceptions. These exceptions can be caught using the try command as all other exceptions:
86
def f(x):
assert(x != 3 and x != -3)
return 1. / (9 - x**2)
try:
result = f(a)
except AssertionError:
print "Assertion failed, performing emergency scenario!"
else:
print "Assertion passed, going on normally."
When called with a equal to 1, this code gives:
Assertion passed, going on normally.
When called with a equal to 3, this is what happens:
Assertion failed, performing emergency scenario!
11.4
Python does not have a command to stop program execution. Sometimes this is useful
though, such as when the user calls our function with incorrect data. To illustrate this,
let us return to the function f() that was defined above, but now we include a raise
command in it:
def f(x):
if x == 3 or x == -3:
raise ValueError("Division by zero detected.")
return 1. / (9 - x**2)
When the function f(x) is called with 3 or -3, the output will be
Traceback (most recent call last):
File "<string>", line 7, in <module>
File "<nclab>", line 3, in f
ValueError: Division by zero detected.
87
Incorrect values of user input are the most common reason to raise exceptions on our
own. So far we have seen ZeroDivisionError, AssertionError and ValueError.
There are additional types of exceptions in Python let us mention the most important
ones in the next paragraph.
11.5
and others. All of them can be caught using the try command.
Let us experiment with MemoryError for a moment. The following code will try
to allocate in the memory a 2D array of real numbers of size n n with n = 1000000:
from numpy import zeros
def array(n):
a = zeros((n, n))
return a
A = array(1000000)
The size of this array would be around 8 TB (one TeraByte is 1024 GigaBytes), which is
more runtime memory than all NCLab currently has. Since no exceptions handling is
present, Python will throw a MemoryError exception and the code will simply crash:
Traceback (most recent call last):
File "<string>", line 6, in <module>
File "<nclab>", line 4, in array
MemoryError
Can we implement such a program in a smarter way? Of course! The following implementation catches the MemoryError exception if it happens, and tells the user that so
88
12
Object-Oriented Programming
12.1
Objectives
Since the very beginning of this course, we have put emphasis on designing simple
algorithms and writing clean, transparent code. This included:
89
The programming style we have been using so far is called procedural programming.
The name, of course, comes from using procedures to solve various tasks that lead to
the solution of the problem at hand. Procedure is an activity, a sequence of operations
done with data that is supplied to it. Procedures do not own the data they operate with.
This, however, means that the data must be stored somewhere else. In other words,
the range of validity of the data extends beyong the borders of the function where it
is processed. Can you see an analogy to using local and global variables? It is great
to keep variables local, and in the same way it would be great to make data local to
procedures that operate with them. But wait, this is called object-oriented programming!
12.3
Here is a real-life example demonstrating the difference between procedural and objectoriented programming. Imagine that you are moving and all your things need to be
packed, boxed, loaded on a truck, hauled a 1000 miles, unloaded, and brought into
your new home.
Procedural approach: You (the procedure) go rent a truck this is the data that the
procedure does not own. Then you pack everything, load it on the truck, drive to the
other city, unload your things, and carry them into your new home. Then you go return
the truck (thats the return statement at the end of the procedure).
Object-oriented approach: You call a moving company "C". This means that you just
created an object C. Note that the object C owns the truck. They will come to your
home and use methods C.pack(), C.box(), C.load(), C.haul(), C.unload(), C.carry() and
perhaps even C.unpack() to solve your problem. Notice the following benefits of the
object-oriented approach:
The work is being done by the company, you do not have to worry (delegation of
work).
You do not have to be able to drive a truck (better code structure).
You do not need to know how the company does the moving (reduced flow of data).
You can concentrate on solving problems in your area of expertise (greater efficiency).
You do not risk crashing the truck (safer programming).
90
12.4
Let us stay with the moving example for a little while longer. The moving company
that you heard of, or that you saw in an advertisement, is a class or in other words
a concept. Formally, we say that class is an entity comprising data and functionality
that uses the data. But a concept will not get your things moved. For that you need a
concrete team of movers. This is called an object or an instance of the class.
When the movers appear at your doorstep, thats when an instance of the class is
created. When they pack, box, and load your things, the object is using methods of the
class. Technically, methods belong to the class because thats where they are defined,
but often we say that an objects uses its methods to ...". Once again, methods are
defined in a class but used by instances of the class. Methods of a class can operate on data
owned by the class (the truck) as well as on data that does not belong to the class (your
things that are being moved.
Similarly with variables variables are defined in a class, but they do not have
concrete values there. In the class definition, they are part of a concept. Only after an
instance of the class is created, the variables are filled with concrete values.
12.5
Lets see how all this is implemented in Python. We will say goodbye to the movers
and play with some simple geometrical concepts instead. Let us create a class circle.
The data owned by this class will be:
Radius R,
center with coordinates Cx, Cy,
two arrays ptsx, ptsy to plot the circle.
The methods of this class will include
Do not be disturbed by the funny way the constructor __init__ is defined in Python,
or by the argument self that is present in all methods. Constructors are used in all
object-oriented languages to pass external parameters (such as the radius and the center point in this case) into newly created instances. In other words, each instance of the
class circle can have a different radius and a different center.
The keyword self must be included in each method of the class and this is a reference to the concrete instance through which all data and methods of the instance
91
are accessed. Such a reference is present in other object-oriented languages as well including C++ where the programmer does not have to mention it explicitly like in
Python. It is added there by the compiler.
12.6
93
12.7
We first met text strings in Section 8. Now that we know how classes are defined and
used, we can reveal that text string is a class! In fact it has many great methods that
really make working with texts easy and fun. Let us show some of them. Below, arguments enclosed in brackets are optional, and if they are used, then without the brackets:
Method capitalize()
Return a copy of the string with only its first character capitalized.
Example:
str = "sentences should start with a capital letter."
print str.capitalize()
Output:
Sentences should start with a capital letter.
Method count(sub[, start[, end]])
94
Return the number of occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Example:
str = "John Stevenson, John Lennon, and John Wayne."
print str.count("John")
Output:
3
Method find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found, such that sub is
contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
Example:
str = "This happened during the summer."
print str.find("sum")
Output:
25
Method index(sub[, start[, end]])
Like find(), but raise ValueError when the substring is not found.
Method isalnum()
Return true if all characters in the string are alphanumeric and there is at least one
character, false otherwise.
Example:
95
str1 = "mypassword123"
if str1.isalnum():
print str1, "is alphanumeric."
else:
print str1, "is not alphanumeric."
str2 = "mypassword123+"
if str2.isalnum():
print str2, "is alphanumeric."
else:
print str2, "is not alphanumeric."
Output:
mypassword123 is alphanumeric.
mypassword123+ is not alphanumeric.
Method isalpha()
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
Example:
str1 = "John"
if str1.isalpha():
print str1, "is alphabetic."
else:
print str1, "is not alphabetic."
str2 = "My name is John"
if str2.isalpha():
print str2, "is alphabetic."
else:
print str2, "is not alphabetic."
Output:
John is alphabetic.
My name is John is not alphabetic.
96
Method isdigit()
Return true if all characters in the string are digits and there is at least one character,
false otherwise.
Example:
str1 = "2012"
if str1.isdigit():
print str1, "is
else:
print str1, "is
str2 = "Year 2012"
if str2.isdigit():
print str2, "is
else:
print str2, "is
a number."
not a number."
a number."
not a number."
Output:
2012 is a number.
Year 2012 is a number.
Method join(seq)
Return a string which is the concatenation of the strings in the sequence seq. The base
string (object whose method is used as separator).
Example:
str = "..."
str1 = "This"
str2 = "is"
str3 = "the"
str4 = "movie."
print str.join([str1, str2, str3, str4])
Output:
97
This...is...the...movie.
Method lower()
Return a copy of the string converted to lowercase.
Example:
str = "She lives in New Orleans."
print str.lower()
Output:
she lives in new orleans.
Method replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the
optional argument count is given, only the first count occurrences are replaced.
Example:
str = "First word, second word, and third word."
print str.replace("word", "thing")
Output:
First thing, second thing, and third thing.
Method swapcase()
Return a copy of the string with uppercase characters converted to lowercase and vice
versa.
Example:
str = "The abbreviation is MENSA"
print str.swapcase()
98
Output:
tHE ABBREVIATION IS mensa
Method title()
Return a titlecased version of the string: Words start with uppercase characters, all remaining cased characters are lowercase.
Example:
str = "this is the title of my new book"
print str.title()
Output:
This Is The Title Of My New Book
Method upper()
Return a copy of the string converted to uppercase.
Example:
str = "this is the title of my new book"
print str.upper()
Output:
THIS IS THE TITLE OF MY NEW BOOK
For additional useful text string methods see the Python documentation at http://docs.
python.org/release/2.5.2/lib/string-methods.html.
Before we leave this section, notice that lists, tuples, dictionaries and many other data
structures in Python are classes as well.
99
13
13.1
Class Inheritance
Objectives
Instead of repeating the same drawing functionality in all classes, we create a base class
geometry as follows:
from pylab import clf, plot, legend, axis
# Base class:
class geometry:
# Constructor:
def __init__(self):
self.ptsx = []
self.ptsy = []
# Plotting method:
def draw(self, label):
axis(equal)
plot(self.ptsx, self.ptsy, label = label)
legend()
100
This base class really cannot do much, but this is fine. We will use it to derive several
new (descendant) classes. The benefit of inheritance is that if we decide in the future to
change the plotting mechanism, we will just have to change it at one place in the base
class geometry and the change will propagate automatically into all its descendants.
Remember that humans are extremely prone to mistakes. Having the same code at
several different places in the program is about the worst thing a programmer can ever
do.
13.3
There is more to the story. Triangles, quadrilaterals, rectangles and squares are all
polygons. Hence let us create the class polygon to be a descendant of the base class
geometry. This class will represent general non-convex counter-clockwise (CCW) oriented polygons. Notice the syntax of the inheritance: one types class polygon(
geometry): instead of just class polygon:
# Class polygon derived from class geometry,
# represents general, possibly non-convex
# polygon. Boundary needs to be CCW oriented.
class polygon(geometry):
# Constructor (here L is list of vertices):
def __init__(self, L):
self.ptsx = []
self.ptsy = []
# Convert L into plotting arrays:
for pt in L:
self.ptsx.append(pt[0])
self.ptsy.append(pt[1])
# To close the loop in plotting:
self.ptsx.append(L[0][0])
self.ptsy.append(L[0][1])
101
13.4
Next let us derive the class circle from the class geometry. Obviously it cannot be
derived from polygon because circles are not polygonal geometries:
102
The polygon class defined above is very general. Of course we could use it directly
to render triangles, quads, rectangles, and squares. But these geometries are simpler
and thus we also want their instantiation to be simpler. Let us begin with the class
triangle.
This class is very simple it takes three points as parameters, forms a list containing these three points, and then the list is passed into the constructor of the parent class
polygon. Notice the way the constructor of the polygon class is called from its descendant triangle via polygon.__init__(self, L):
103
13.6
Next, rectangle is a special case of quad, so let us derive the rectangle class from the
quad class:
# Class rectangle derived from class quad.
# Represents rectangle (0, a) x (0, b):
class rectangle(quad):
# Constructor:
def __init__(self, a, b):
quad.__init__(self, [0, 0], [a, 0], [a, b], [0, b])
13.7
Taking this one step further, square is a special case of rectangle. Therefore we can derive the square class from the rectangle class:
104
13.8
13.9
Finally let us create sample instances of the classes defined above, inquire about their
areas and perimeters, and let them plot themselves:
105
# Create a triangle:
T = triangle([-2, -0.5], [0, -0.5], [-1, 2])
print "Area and perimeter of the triangle:", \
T.area(), T.perimeter()
# Create a quad:
Q = quad([-3, -1], [0, -1], [-1, 1], [-2, 1])
print "Area and perimeter of the quad:", \
Q.area(), Q.perimeter()
# Create a rectangle:
R = rectangle(3, 1)
print "Area and perimeter of the rectangle:", \
R.area(), R.perimeter()
# Create a square:
S = square(1.5)
print "Area and perimeter of the square:", \
S.area(), S.perimeter()
# Create a circle:
C = circle(2.5, 0, 0.5)
print "Area and perimeter of the circle:", \
C.area(), C.perimeter()
# Plot the geometries:
clf()
T.draw("Triangle")
Q.draw("Quad")
R.draw("Rectangle")
S.draw("Square")
C.draw("Circle")
ylim(-3, 4)
legend()
show()
106
Area
Area
Area
Area
Area
and
and
and
and
and
perimeter
perimeter
perimeter
perimeter
perimeter
of
of
of
of
of
the
the
the
the
the
Bzier curves
:
Bzier curves are the most widely used approach to define curves in engineering design. Let us begin with the linear case. Linear Bzier curve is a straight line that connects two control points P1 and P2 . All Bzier curves are parameterized from the interval [0, 1], so in the linear case the exact mathematical definition is
B(t) = P1 + t(P2 P1 )
You can easily check that the curve starts at P1 (substitute t = 0 to the above formula),
and that it ends at P2 (substitute there t = 1).
Quadratic Bzier curves are defined using three control points P1 , P2 and P3 . Again
they are parameterized from [0, 1], and their definition is
107
14
Python Libraries
14.1
Objectives
Using libraries is an indivisible part of Python programming. As opposed to commercial products, Python libraries are free. We have used some of them already, such as
Pylab and Matplotlib in Section 4 and Numpy in Section 7.
14.2
The Python Standard Library has vast functionality related to built-in functions, builtin types, built-in constants, built-in exceptions, string services, numerics and mathematics modules, files, data compression, cryptographic services, and many others.
Just introducing a table of contents would take several pages. To learn more, to visit
http://docs.python.org/library/. Also, a long list of packages for Python programmers can be found at http://pypi.python. org/pypi/.
14.3
The Pylab library can be used for numerical computation but as there are other and
stronger tools, we recommend to use it mainly for plotting, along with the Matplotlib
library. For more details on Pylab visit http://www.scipy.org/PyLab. This page
is not dedicated to plotting though, more on concrete plotting functionality can be
found on the home page of Matplotlib, http://matplotlib.sourceforge.net.
This page contains an exhaustive overview of plotting-related functionality, many examples, gallery, and documentation.
108
14.4
Scipy is a general library for scientific computing with Python. Numpy can be viewed
as its "heart" containing numerical algorithms and methods. These methods comprise
interpolation, integration, optimization, Fourier transforms, signal processing, linear
algebra, eigenvalue problems, graph theory routines, statistics, ordinary and partial
differential equations, image processing, etc. To learn more, visit http://www.scipy.
org and http://numpy.scipy.org/.
Sympy is an excellent library for symbolic mathematics covering high-school algebra, calculus, matrix algebra and differential equations. To learn more about Sympy,
visit its home page (http://www.sympy.org).
15
There are many topics that we have decided to skip in the first reading of the Python
language. There is more to learn to almost every command, function aned concept described in this document. If you like Python, your nexr resource should be the original
Python tutorial at http://docs.python.org.
16
What Next?
Congratulations, you made it! We hope that you enjoyed the textbook and the exercises. If you can think of any way to improve the application Karel the Robot or this
tutorial, we would be very happy to hear from you. If you have an interesting new
game or exercises for Karel, please let us know as well.
Although you may feel like an Almighty Programmer right now, we would recommend staying humble. Even the most experienced programmers are learning new
things all the time. There is much more to Python that we managed to cover in this
introductory textbook. You already know about the Internet resources where you can
learn more.
Alternatively, you may dive into a next programming language! We would recommend Javascript since this is the most popular language for web development. Of
course there are many more languages to explore, including C/C++, Java, Perl, Ruby,
Lua and others.
In any case, our team wishes you good luck, and keep us in your favorite bookmarks!
Your Authors
109
110
Part II
Programming Exercises
Introduction
All exercises from this textbook can be downloaded from NCLabs public database
through the File menu in File manager or in the Python module. In the Search box that
appears, enter the keywords "textbook python". Solution Manual is available in the
Python modules Help menu starting with Basic Plan.
To warm up, in this section we will experiment with the print command.
1.1
Python is fun
Big word
Write a program that prints the word "Python" in large block letters as shown below:
XXXXX
X
X
XXXXX
X
X
1.3
Y
X XXXXX X
X
Y
X
X
X
X
XXXXX
X
XXXXX
X
X
X
X
XXXXX
X
X
X
XXXXX
X
X
X
X
X
X
XXXXX
X
X
XX X
X X X
X XX
X
X
Military exercise
Save the program from the previous exercise under the name "George Smith" and adjust it to print the name of a famous American general who during the World War 2
commanded U.S. Army Troops in North Africa and Europe.
In this section we will practice using Pythons interactive shell for simple as well as
advanced arithmetic operations.
113
2.1
Grocery shopping
Tax in the amount of 8% applies to items 1 and 4. Calculate the total cost of your purchase!
2.2
Oil change
You decided to do oil change today since your favorite place offers 20% off. The oil
costs $45 plus 8% tax. The work is 25 dollars. Do not forget to take the 20% off the total.
How much will you pay for this oil change?
2.3
Age average
You go on a hike with a group of people of different ages. Your are (say) 15 years old.
Two other people are 21 years old, one is 35, one is 42, and one is 55. Calculate the
average age in the group!
2.4
Your savings account grows at a rate of 3% annually. Three years ago you started by
inserting $1,250 into the account. One year later you added another $500, and a year
ago you withdrew $300. How much money is in your savings account now?
2.5
Growing town
For the last 20 years, the population of a city has been growing steadily by 5% per year,
and 20 years ago it had 10,000 inhabitants. How many people live in the city now?
Round the result to be an integer number.
2.6
Coffee maker
How many cups of coffee will you be able to make from a one kilogram pack when 11
grams are needed for one cup? How many grams will be left?
114
2.7
Gardening
You are buying plants for an orchard restoration project. How many plants can you
purchase with $250 if the price of one is $17? How much money will you have left?
2.8
Setting tiles
You are setting tiles in a room of rectangular shape whose edges measure 19 and 27
feet. The tiles are 1.25 1.25 foot squares and they will be aligned with the walls in the
simplest possible pattern. You need to leave a quarter inch between the tiles for grout.
How many whole tiles are you going to use? Hint: integer part of a real number x is
obtained via int(x).
2.9
The famous Archimedes law states that the upward buoyant force exerted on a body
immersed in a fluid is equal to the weight of the fluid the body displaces. Imagine that
you submerge a soccer ball neglecting its own weight, this is the force that you need
to employ to keep it under water! Lets calculate this force, assuming that the ball is a
perfect sphere of diameter 22 cm. The density of water is 1000 kg/m3 and gravitational
acceleration is 9.81 ms2 .
2.10
Fastest runner
Arguably, the fastest human runner in history achieved a speed of 12.1 m/s. Calculate
how much time in seconds such a runner would need to cross a football field at this
speed, running diagonally from one corner to the opposite one. The measures of a
football field are 109.7 m and 48.8 m.
2.11
Triangle area
Herons formula is a famous formula that allows you to calculate the area S of a general
triangle knowing its edge lengths a, b and c:
S=
p
p(p a)(p b)(p c)
where p = (a + b + c)/2. Calculate in this way the area of a triangle with sides 2.5 m,
3.7 m and 4.1 m!
115
2.12
Math functions
Random numbers
Random numbers are generated using the function random() from the random library. This function returns a random real number between 0 and 1. Use this function
to generate a random integer between 10 and 20!
2.14
Python has a built-in function gcd() to calculate the greatest common divisor (GCD)
of two integers. It is imported via from fractions import gcd. Use the function
to find the GCD of 1554 and 2331!
2.15
Fractions
Python makes operations with fractions very simple via the Fraction function that
is imported from the fractions library. Then a fraction 1/3 is defined simply as
Fraction(1, 3) and so on. Fractions can be used with the same operations as numbers, and the result of such an operation is a Fraction. Now to your task: Use Fractions to calculate
1 1 1 1 1 1
+ + .
2 3 4 5 6 7
Functions
Circle
3.2
Square
Write a Python function squarearea(a) that returns the area of a square whose edge
is a cm long. You know that most of the time the edge length wil be 1 cm, so make this
function callable without any arguments.
3.3
Rectangle
Sales prediction
The East Coast sales division of a company usually generates P percent of total sales
each year. Write a function sales_prediction(P, S) to predict how much the East
Coast division will generate if the company has S dollars in sales the next year. Use
your function with the numbers P = 62 % and S = 4.6 million dollars.
3.5
Sales tax
Write a function sales_tax(P, ST, CT) that calculates the total sales tax on a P
dollars purchase. Assume the state sales tax is ST percent, and the county sales tax is
CT percent. Use the function with the following numbers: P = 52 dollars, ST = 5 %,
CT = 2 %.
3.6
Restaurant bill
In Europe, gas consumption of a car is reported in liters per 100 kilometers. In the U.S.
it is reported in miles per gallon. Write a function conversion_eu_to_us(C) that
converts a given European gas consumption C into the U.S. scale. One mile is 1.609344
kilometers, and one gallon is 3.78541178 liters.
117
3.8
In Europe, gas consumption of a car is reported in liters per 100 kilometers. In the U.S.
it is reported in miles per gallon. Write a function conversion_us_to_eu(C) that
converts a given U.S. gas consumption C into the European scale. One mile is 1.609344
kilometers, and one gallon is 3.78541178 liters.
3.9
A car with a G gallon gas tank averages A miles per gallon when driven in town and
B miles per gallon when driven on the highway. Write a function distance(G, A,
B) that returns the distance the car can travel on one tank of gas when driven in town
and when driven on the highway. Use your function with G = 20 gallons, A = 21.5
miles per gallon, B = 26.8 miles per gallon.
3.10
Gross pay
Stock gain
Kathryn bought N shares of stock at a price of A dollars per share. One year later
she sold them for B dollars per share. Write a function stock_gain(N, A, B) that
calculates and displays the following:
The total amount paid for the stock.
The total amount received from selling the stock.
The total amount of money she gained.
Use your function with the values N = 600, A = 21.77 dollars and B = 26.44 dollars.
118
3.13
Time in seconds
Time in hours
Write a function time_in_hours(H, M) where H, M are integer numbers representing hours and minutes. Convert this time period into hours and return it. For example,
time_in_hours(1, 30) will return 1.5.
3.17
Distance
Write a function distance(x1, y1, x2, y2) that calculates and returns the distance d of two points (x1 , y1 ) and (x2 , y2 ) using the formula
p
d = (x2 x1 )2 + (y2 y1 )2 .
119
3.19
Angle conversion
Length conversion
Area conversion
Write a function memory_conversion(GB, MB, KB, B) that converts a digital storage size consisting of GB gigabytes, MB megabytes, KB kilobytes, and B bytes to bytes.
Return the result. Recall that one kilobyte equals to 1024 bytes, one megabyte equals
to 1024 kilobytes, and one gigabyte is the same as 1024 megabytes.
3.23
Savings account
In this section we will practice plotting of various objects including polygons, function
graphs, 2D and 3D curves, surfaces, and even pie and bar charts.
4.1
Polygon
Write a Python function polygon(R, n) that returns two arrays x and y. These arrays will contain the x and y coordinates of the vertices of a polygon with n equallylong edges, that is inscribed into a circle of center [0, 0] and radius R > 0. Here n >
2 is an integer number and R > 0 is a real number. The polygon should be oriented
counter clock-wise and the first vertex should be [R, 0]. Use this function to plot a sample polygon with parameters R = 2, n = 6. Make sure that axes are scaled equally.
120
4.2
Consider an arbitrary Python function f(x) that for a real number x returns a real
value. For example, such a function could be f (x) = ex :
def f(x):
return exp(-x)
Write a Python function plotfun(a, b, f, n) that will return two arrays xpts
and ypts. The former will contain x-coordinates of n-point linear subdivision of the
interval [a, b], the latter will contain the corresponding function values. Use the
function plotfun to plot the graph of the function f(x) defined above, in the interval
[1, 1]. Axes should be scaled equally.
4.3
Planar curve
Consider two arbitrary Python functions f(t) and g(t) that for a real number t
in the interval [0, 1] return a real value. For example, such functions could be f (t) =
t2 cos(10t) and g(t) = t2 sin(10t):
def f(t):
return cos(2*pi*t)
def g(t):
return sin(2*pi*t)
Write a Python function planarcurve(f, g, n) that returns two arrays xpts and
ypts. These arrays will contain x and y coordinates of n points lying on the planar
curve [f (t), g(t)]. These points correspond to a linear subdivision of the parameterization interval [0, 1] with n points. Use the function planarcurve to plot the curve
corresponding to the functions f(t) and g(t) defined above. Axes should be scaled
equally.
4.4
Random triangle
The function random() from the random library returns a random number between 0
and 1. Write a Python function tria(a, b, c, d) that returns six numbers x1, y1,
x2, y2, x3, y3. These numbers represent vertices [x1, y1], [x2, y2], [x3, y3] of a random
triangle that lies in the rectangle (a, b)x(c, d). Plot the triangle. Make sure that axes are
scaled equally.
121
4.5
Wireframe plot
Write Python function wireframeplot(f, x1, x2, y1, y2, nx=30, ny=30)
where f(x, y) is a real function of two variables, (x1, x2)x(y1, y2) is the plotting rectangle, and nx, ny are plotting subdivisions in the x and y axial directions. Test
it on the function
f (x, y) = ex
2 y 2
Write Python function solidsurfaceplot(f, x1, x2, y1, y2, nx=30, ny=30)
where f(x, y) is a real function of two variables, (x1, x2)x(y1, y2) is the plotting rectangle, and nx, ny are plotting subdivisions in the x and y axial directions. Test
it on the function
f (x, y) = 5 (x2 + y 2 )
in the square (2, 2) (2, 2).
4.7
Contour plot
WebGL plot
Solve this exercise only if WebGL works on your computer (WebGL Tester can be found
on NCLab front page). Write Python function webglplot(f, x1, x2, y1, y2, nx=30, ny=30)
where f(x, y) is a real function of two variables, (x1, x2)x(y1, y2) is the plotting rectangle, and nx, ny are plotting subdivisions in the x and y axial directions. Test it on the
function
f (x, y) = ex
in the square (2, 2) (2, 2).
122
2 y 2
4.9
A family spends each month 25% of their budget on clothing, 20% on food, 10% on
car payments, 20% on mortgage, 5% on utilities, and they save 20%. Plot a pie chart
representing their spendings, and highlight the savings part via the explode function.
Variables
Arithmetic sequence
Geometric sequence
1 qn
1q
5.3
Graph length
5.4
3D curve length
5.5
Triangle area
Write a Python function trianglearea(v1, v2, v3) that for three 3D points (lists)
calculates the area of the corresponding triangle. Hint: Use Herons formula
A=
p
p(p a)(p b)(p c)
where p is half of the triangles perimeter and a, b, c are its edge lengths.
5.6
Roof area
Write a Python function roofarea(f, x1, x2, y1, y2, nx, ny) that calculates
approximately the area of a roof. The building has a rectangular footprint (x1, x2)x(y1,
y2), and the roof is given via a function f(x, y).
124
This task may seem difficult but we can use similar trick as in Exercises 05.03 and 05.04:
Split the rectangle (x1, x2)x(y1, y2) into nx times ny equally-sized small rectangles.
Moreover, split each of these small rectangles diagonally into two triangles (there are
two diagonals but it does not matter which one you choose). Over each triangle, span
a linear plane that in the corners coincides with the function f(x, y). Use the function
from Exercise 05.05 to calculate the triangle area. After adding the area of all these
triangles together, you will have an approximation of the roof surface. Return it as a
result of the function. Similarly to Exercises 05.03 and 05.04, experiment with various
values of nx and ny until you are confident that the surface that you calculated is exact
to two decimal digits! Test your program on the function f(x, y) = sin(x)*sin(y) in the
interval (0, Pi)x(0, Pi) that is shown below.
In this section we practice usage of logical operations and useful operations with random numbers.
6.1
Even or odd
6.2
Mysterious parabola
Point in circle
Slot machine
Write a Python function slotmachine() that simulates a simple slot machine by returning three random integers between 0 and 9. Use the function random() from the
random library that returns a random real number between 0.0 and 1.0. Hint: Split the
interval (0, 1) into 10 equally-long parts. Return 0 if the generated random number falls
into the first one, 1 if it falls into the second one, etc. Integer part of a real number x is
obtained via int(x).
6.5
Dice game
Write a Python function dicegame() that simulates a throw of two dice by returning
a pair of random numbers 1 - 6. Make sure that every number has the same probablity. Use the function random() from the random library that returns a random real
number between 0.0 and 1.0. Hint: Split the interval (0, 1) into six equally-long parts.
Return 1 if the generated random number falls into the first one, etc. Integer part of a
real number x is obtained via int(x).
6.6
Cheat dice
Write a Python function cheatdice(p1, p2, p3, p4, p5, p6) that simulates a
throw of two dice by returning a pair of random numbers 1 - 6. However, this time,
you are using artificially altered dice where the probability of obtaining 1 is p1 instead
of 1/6, probability of obtaining 2 is p2 instead of 1/6, etc. The sum of all p1, p2, ..., p6
equals to 1.0. Again use the function random() from the random library. Hint: Split
the interval (0, 1) into six parts which now will not be equally-long. Their lengths will
be p1, p2, ..., p6. If the generated random number falls into the first one, return 1, etc.
126
6.7
Probabilistic methods are often called Monte Carlo methods. Write a Python function
calculate_pi(n) that will calculate and return an approximation of using the
following algorithm: Generate n random points inside the square (1, 1) (1, 1).
Count the number m of points that lie in the circle or radius r = 1 centered at the
origin, as shown in the figure below.
Clearly the ratio of m and n is approximately the same as the ratio of the area C of the
circle to the area S of the square.
C
m
n
S
At least for large values of n such as 10,000 this will be close. Assume that the number
satisfies C = r2 . Knowing that S = 4, we can calculate
m
n
4
and thus
4m
.
n
Hence, use the last formula to calculate an approximation of using the numbers n
and m.
6.8
Maximum of a function
Write a Python function maxfun(f, a, b, n) to calculate and return an approximate maximum of the function f (x) in the interval (a, b). Hint: Cover the interval (a, b)
with n equidistant points. Loop over the points, evaluate the function f at every one
of them, and find the maximum value.
127
6.9
Hint: Use the function maximum(f, a, b, n) from Exercise 6.8 to find an approximate maximum M of the function f in the interval (a, b). Generate n2 random points
in the rectangle (a, b) (0, M ). By m denote the number of points which lie under the
function graph. Clearly, for larger n2 such as 10000 the ratio of m and n2 will be approximately the same as the ratio of the area A under the graph and the area R of the
rectangle (a, b) (0, M ). Hence we obtain
A
m
.
2
n
R
From here, it is easy to express A as
A
6.10
Rm
n2
Trapezoids
Write a Python function trapezoids(f, a, b, n) to calculate and return an approximate area under the graph of the function f (x) in the interval (a, b). First split the
interval (a, b) into n equally-long parts, and then add together the areas of all trapezoids under the graph of the function f , as shown in the image below.
128
You can notice that in some cases the entire trapezoid does not lie under the curve, but
this is OK. It is important that the upper two vertices of each trapezoid always lie on
the function graph. Hint: The area of a trapezoid with basis (c, d) and function values
f (c), f (d) at the upper vertices is
area = (d c)
f (c) + f (d)
.
2
Test your code with the function f (x) = sin(x) in the interval (0, ). In this case the
exact area under the graph is area = 2.
Conditional Loop
In this section we solve problems that include iterations (repetitions) whose number is
not known in advance.
7.1
Water jar
There is a jar of volume V that is full of water. Every day, P per cent of the water
volume evaporates. Write a function waterjar(V, P, R) that prints the remaining
water volume day by day. The process stops when the volume is less than or equal to a
residual volume R. Your function should return the number of days the process took.
Include a condition at the beginning of the function that will output a warning and
return zero if R > V or V <= 0 or R <= 0.
7.2
Throwing stones
Imagine that you stand on a very high bridge H meters above a river and throw a stone
with velocity v in horizontal direction. The coordinates of the flying stone as functions
of time t are x(t) = tv and y(t) = H 0.5gt2 where g = 9.81 kgms2 is the gravitational
129
Missing numbers
Trapezoids revisited
Infinite sum
It is a well known fact in mathematics that the sum of the infinite sequence
1
1
1
1
+ 2 + 2 + 2 + ...
1 2
3
4
is a finite number. But what is this number? Lets find out! Write a Python function
sum(err) that will keep adding the numbers in the above sequence together until the
last increment is less than err. Then stop, and return two values: the latest value of
the sum and the number of entries added.
Strings
8.1
Spelling
Write a function spell(str) that prints the string str one character per line, and
returns the number of characters in the string.
8.2
Inserting spaces
Counting chars
Counting words
Write a function countwords(str, word) that will count all occurences of the string
word in the string str, and return their number. You can assume that len(str) is always greater or equal to len(word).
8.5
Write a function searchandreplace(str, word1, word2) that will find all occurrences of the string word1 in the string str, and replace them with the string
word2. Return the new string and the number of replacements made.. Hint: Do not
change the string str - instead, create a new string str2 and add into it what is
needed.
In this section we will solve problems related to tuples, lists and dictionaries.
9.1
List reverse
Write a Python function listreverse(L) that reverts the list L and returns the result.
Use of the Python built-in list reverse function is not allowed.
9.2
String to list
Write a Python function str2list(str) that for any text string str returns the list of
words that it contains, in the order they appear. Repetitions are allowed. Words can be
separated by empty character , comma, period, question mark or exclamation mark.
131
10
In this section we strengthen our understanding of the counting loop by solving problems that include repetitions whose number is known in advance.
10.1
Analyze string
Write a Python function analyze_string(str) that for the text string str returns
the number of decimals 0 - 9.
10.2
Multiplication table
Write a Python function multable(N) that returns a 2D array A containing the multiplicative table of the numbers 1, 2, . . . , N . In other words, A[i 1][j 1] = ij for all
i, j = 1, 2, ..., N . Hint: Use the Numpy command zeros to create the 2D array:
from numpy import zeros
A = zeros((N, N))
Entry at position r, s in A is accessed via A[r][s]. Keep in mind that indices start
from zero.
10.3
Approximating
Prime numbers
Write a Python function primes(n) that for a positive number n returns the list of
first n prime numbers starting with 2.
10.5
List maximizer
Write a Python function maximizer(L1, L2) that takes two lists of real numbers
and finds a number n1 in L1 and a number n2 in L2 such that the product of n1 and
n2 is maximal. Return the numbers n1 and n2.
132
10.6
Fibonacci
Write a Python function fibonacci(n) that returns a list of integer numbers representing the Fibonacci sequence. Recall that this sequence starts with 0, 1 and each next
number is the sum of the two last numbers in the sequence.
10.7
Adding fractions
Write a Python function addfractions(L) where L is a list of integer pairs (twoelement lists). Each integer pair represents the numerator and denominator of a fraction. Your function should add all these fractions together and obtain the numerator
and denominator of the resulting fraction. Further, the numerator and denominator
should be divided by the greatest common divisor to reduce the fraction to the simplest possible form. Hint: The function fraction.gcd(numerator, denominator) can be
used to find the greatest common divisor of two integers.
11
Exceptions
Sure plot
11.2
Syntax check
12
Object-Oriented Programming
Bank account
Implement a Python class Account to simulate a bank account. It should have two
variables savings and checking, and the following methods:
Constructor __init__(self) that creates an empty checking and savings account.
add_to_checking(self, amount): Add amount to checking.
add_to_savings(self, amount): Add amount to savings.
get_balance_checking(self): Return the balance in the checking account.
get_balance_savings(self): Return the balance in the savings account.
transfer_to_checking(self, amount): Transfer amount from savings to checking and return True. If there are insufficient funds, do not perform the operation,
write a warning, and return False.
transfer_to_savings(self, amount): Transfer amount from checking to savings and return True. If there are insufficient funds, do not perform the operation,
write a warning, and return False.
withdraw_from_checking(self, amount): Withdraw amount from checking and return True. If there are insufficient funds, do not perform the operation,
write a warning, and return False.
withdraw_from_savings(self, amount): Withdraw amount from savings
and return True. If there are insufficient funds, do not perform the operation, write
a warning, and return False.
12.2
Word magic
Number magic
Implement a Python class Numbermagic whose data is just one integer number, and
whose methods are as follows:
Constructor __init__(self, num) that takes one integer number as parameter
and stores it in the object. If the user supplies a non-integer number, print a warning
and round it to an integer. Hint: Use Python bbuilt-in function isinstance(n,
int) to determine whether the number n is integer.
insert(self, num): Method that replaces the number stored in the object with
num. As in constructor, make sure that the number is an integer.
ispositive(self): Boolean method that returns True if the number stored in
the object is greater than zero, False otherwise.
iseven(self): Boolean method that returns True if the number stored in the
object is even, False otherwise.
isprime(self): Boolean method that returns True if the number stored in the
object is a prime, False otherwise.
12.4
Vector magic
Implement a Python class Vectormagic whose data are two three-dimensional vectors. All vectors are represented by lists of length three. The class has the following
methods:
Constructor __init__(self, u, v) that takes two vectors as parameters and
stores them in the object. If the length of any of the two vectors is not three, raise a
ValueError exception.
insert(self, u, v): Method that replaces the vectors in the object with new
ones. Make sure that u, v are 3D vectors same as in the constructor.
135
13
Class Inheritance
In this section we solve problems involving creating descendants of classes in objectoriented programming.
13.1
Number master
Vector master
136
Part III
Review Questions
Introduction
5. Where does the name "Python" of the programming language come from?
A1
A2
A3
A4
1989
1995
2000
2005
They are translated into Javascript and run in your web browser.
They are interpreted on a remote server.
They are interpreted on your PC computer / laptop / tablet.
They are translated into Flash and run in your web browser.
11. What are the types of cells that a Python worksheet can contain?
A1 Error message cells.
140
A2 Output cells.
A3 Code cells.
A4 Descriptive cells.
12. How can all code cells in a Python worksheet be evaluated at once?
A1
A2
A3
A4
13. If your Python worksheet has multiple code cells, how can a single code cell be evaluated?
A1
A2
A3
A4
16. What is the correct way to remove a code, output, or descriptive cell?
A1
A2
A3
A4
141
18. What is the correct way to print the text string "I like Python" ?
A1
A2
A3
A4
print
write
write
write
"I
"I
I
I
like
like
like
like
Python"
Python"
Python
Python
34
10
0
14
2.75
2
3
Error message.
32
32
3*2
3**2
142
2
8
-8
Error message
-8
11.313708498984761
-11.313708498984761
Error message
Rounding up
Remainder after integer division
Integer division
Rounding down
5
5
5
5
/ 2
% 2
& 2
&& 2
0
1
2
4
143
A1
A2
A3
A4
1
0
4
1
1
12
4
3
11. What is the correct way to import all functionality from the Numpy library ?
A1
A2
A3
A4
from
from
from
from
numpy
numpy
numpy
numpy
import
import
import
import
all
everything
*
functions
sin
sin, pi
import sin
import sin, pi
13. What is the correct way to use the fractions library to add the fractions 5/27 + 5/9 +
21/81?
A1 from fractions import Fraction
Fraction(5/27) + Fraction(5/9) + Fraction(21/81)
A2 from fractions import Fraction
Fraction(5/27 + 5/9 + 21/81)
144
gcd
Fraction, gcd
*
*
5
20
25
Error message
16. Which code will generate a random real number between 0 and 1 ?
A1 from random import
random(0, 1)
A2 from random import
random()
A3 from random import
random(1.0)
A4 from random import
rand()
random
random
random
rand
145
17. With the random() function imported, which code will generate a random integer number
between 5 and 10 ?
A1
A2
A3
A4
5 + int(5 * random())
5 + 5 * int(random())
int(5 + 5 * random())
int(10 * random()) - 5
18. Which of the following is / are correct way(s) to define a complex number?
A1
A2
A3
A4
2
2
2
2
+
+
+
+
3j
3J
3*j
3*J
Functions
Only when the two text strings have the same length.
Always.
Only when the two text strings have different lengths.
Never.
Never.
Always.
Always except for numbers and text strings.
Only when default arguments are used.
6. We need a function f(X) that accepts a number X and returns three values: 3*X, 5*X,
7*X. Which of the following functions will do that?
A1 def f(X):
return
return
return
A2 def f(X):
return
A3 def f(X):
return
3*X
5*X
7*X
3*X, 5*X, 7*X
3*X + 5*X + 7*X
147
A4 def f(X):
3*X, 5*X, 7*X
return
7. Which of the following four function definitions are syntactically correct?
A1 from numpy import sqrt
def hypotenuse(a, b):
return sqrt(a**2 + b**2)
A2 from numpy import sqrt
def hypotenuse(a=5, b):
return sqrt(a**2 + b**2)
A3 from numpy import sqrt
def hypotenuse(a, b=5):
return sqrt(a**2 + b**2)
A4 from numpy import sqrt
def hypotenuse(a=5, b=5):
return sqrt(a**2 + b**2)
8. For the function compose defined below, what function call(s) will not cause an error message?
def compose(a, x = 1, y = 2, z = 3):
return a + x + y + z
A1
A2
A3
A4
print
print
print
print
compose(1)
compose(1, y = 10)
compose(1, x = 20, z = 5)
compose(1, 10, x = 20, z = 5)
A3 [0, 0.5, 0]
A4 [0, 0.5, 1]
2. Which of the following RGB values define(s) a shade of grey?
A1
A2
A3
A4
3. Which of the following RGB values define(s) color that is closest to purple?
A1
A2
A3
A4
[1, 0.8, 0]
[0.5, 0.6, 0.1]
[0.5, 0, 0.5]
[1, 0.5, 1]
4. Which of the following codes will draw a square with vertices [0, 0], [1, 0], [1, 1], [0, 1]?
A1 from pylab import *
x = [0.0, 1.0, 1.0,
y = [0.0, 0.0, 1.0,
clf()
plot(x, y)
show()
A2 from pylab import *
x = [0.0, 0.0, 1.0,
y = [0.0, 1.0, 1.0,
clf()
plot(x, y)
show()
A3 from pylab import *
x = [0.0, 1.0, 1.0,
y = [0.0, 0.0, 1.0,
clf()
plot(x, y)
show()
0.0]
1.0]
1.0]
0.0]
0.0, 0.0]
1.0, 0.0]
149
[0
[0
[0
[0
0
0
1
0
0]
0 0]
0 -1 0]
0 0 0]
8. What Pylab function is used to enforce equal scaling of the horizontal and vertical axes?
A1
A2
A3
A4
axes = "equal"
equal(axes)
axes(equal)
axis(equal)
9. What Pylab function is used to show the legend? Should it be used before or after the
plot() function?
A1
A2
A3
A4
10. Which of the following codes will plot a cosine function in the interval (0, ) using a dashed
green line?
A1 from numpy import *
from pylab import *
x = linspace(0, pi, 100)
y = cos(x)
axis=("equal")
clf()
plot(x, y, g-, label="cos(x)")
legend()
show()
A2 from numpy import *
from pylab import *
x = linspace(0, pi, 100)
y = cos(x)
clf()
plot(x, y, g--)
show()
A3 from numpy import *
from pylab import *
x = linspace(0, pi/2, 100)
y = cos(x)
151
axis=("equal")
clf()
plot(x, y, g--, label="cos(x)")
legend()
show()
A4 from numpy import *
from pylab import *
x = linspace(0, pi, 100)
y = cos(x)
axis=("equal")
clf()
plot(x, y, b--, label="cos(x)")
legend()
show()
11. We have two arrays x and y created via the linspace function. What Numpy function
will create a 2D Cartesian product grid of them?
A1
A2
A3
A4
X,
X,
X,
X,
Y
Y
Y
Y
=
=
=
=
meshgrid(x, y)
cartesiangrid(x, y)
productgrid(x, y)
product(x, y)
12. The arrays X and Y represent a 2D Cartesian product grid. How can we assign values of the
function 1/(1 + x2 + y 2 ) to the grid points?
A1
A2
A3
A4
Z
Z
Z
Z
=
=
=
=
1.
1.
1.
1.
/
/
/
/
(1
(1
(1
(1
+
+
+
+
exp(X) + exp(Y))
X*X + Y*Y)
X2 + Y2)
X**2 + Y**2)
13. Only one of the following codes will display a simple pie chart. Which one is it?
A1 from pylab import *
data = [20 %, 40 %, 40 %]
labels = [bronze, silver, gold]
clf()
axis(equal)
152
pie(data, labels=labels)
show()
A2 from pylab import *
data = [bronze, silver, gold]
labels = [20, 40, 40]
clf()
axis(equal)
pie(data, labels=labels)
show()
A3 from pylab import *
data = [20, 40, 40]
labels = [bronze, silver, gold]
clf()
axis(equal)
pie(data, labels=labels)
show()
A4 from pylab import *
data = [20, 40, 40]
labels = [bronze, silver, gold]
clf()
axis(equal)
pie()
show()
14. Which of the following codes will display a simple bar chart with the values 5, 7, 3, 9 with
bars starting at 0, 2, 4, and 6 on the horizontal axis?
A1 from pylab import *
data = [5, 7, 3, 9]
clf()
bar([0, 2, 4, 6], data)
show()
A2 from pylab import *
data = [5, 7, 3, 9]
clf()
bar_chart([0, 2, 4, 6], data)
show()
A3 from pylab import *
data = [0, 2, 4, 6]
153
clf()
bar([5, 7, 3, 9], data)
show()
A4 from pylab import *
data = [0, 2, 4, 6]
clf()
bar_chart([5, 7, 3, 9], data)
show()
Variables
1. What are correct ways to assign the value 2.0 to a variable var?
A1
A2
A3
A4
val := 2.0
val == 2.0
val(2.0)
val = 2.0
2. What of the following are correct ways to store the text string Pontiac in a variable
car?
A1
A2
A3
A4
car
car
car
car
= Pontiac
= "Pontiac"
= Pontiac
:= "Pontiac"
3. What is the correct way to create a Boolean variable answer whose value is True?
A1
A2
A3
A4
answer
answer
answer
answer
=
=
=
=
True
True
1
"True"
4. None of the variables a, b was declared before. Which of the following codes are correct?
A1 a = b = 1
154
A2 a = 1 = b
A3 a = a
A4 a + b = 5
5. What of the following is the correct way to increase the value of an existing integer variable
val by 10 and print the result?
A1
A2
A3
A4
val + 10
print val + 10
print val += 10
val += 10
print val
6. When can a given variable have different types in various parts of a Python program?
A1
A2
A3
A4
Any time.
Never.
Only when variable shadowing takes place.
Only when the types are real number and integer number.
7. There are two variables a and b whose values need to be swapped. Which of the following
codes will do it?
A1 a =
A2 a =
b =
A3 a =
c =
b =
A4 c =
a =
b =
b = a
b
a
b
a
a
a
b
c
9.0
5.0
Error message
9.0
5.0
156
30
2.718281828459045
32.718281828459045
Error message
False
Undefined
True
Error message
A4 Undefined
3. What value will the variable d have after the following code is run?
d = True
if d != False:
d = not(d)
A1
A2
A3
A4
True
False
True in Python 2.7 and False in Python 3.0
Undefined
Correct result.
Wrong result.
5
Error message
5. What will be the value of the variable var after the following code is run?
n = 10 + 5
m = 4 * 5
var = n == m
A1
A2
A3
A4
15
20
False
True
158
6. Let a and b be Boolean variables. What is the output of the following code?
c = (a or b) or not (a or b)
print c
A1
A2
A3
A4
False
Undefined.
False or True, depending on the values of a and b.
True
8. Which of the four values below will be closest to the output of this program?
from random import random
n = 1000000
m = 0
# Repeat n times:
for i in range(n):
# Generate random real number between -2 and 2:
x = 4 * random() - 2
if x**2 - 1 < 0:
m += 1
# Print the ratio of m and n:
print float(m) / n
A1
A2
A3
A4
0.0
4.0
0.5
1.0
159
Conditional Loop
160
A1
A2
A3
A4
64
128
1
This is an infinite loop, there is no output.
Continue repeating the body of the loop after the loop has finished.
Skip the rest of the loops body and continue with next cycle.
Continue to the next command.
Continue to the first line after the loops body.
161
a = 0
while True:
a += 1
if a < 8:
continue
print a
break
A1 0
1
2
3
4
5
6
7
8
A2 1
2
3
4
5
6
7
8
A3 1
2
3
4
5
6
7
A4 8
8. What is the Newtons method in scientific computing?
A1
A2
A3
A4
Strings
"I
"I
"I
"I
say
say
say
say
know".
know".\
know".
know"."
163
s1 = "intermediate"
s2 = s1[7] + s1[4] + s1[3] + s1[6] + s1[5]
print s2
A1
A2
A3
A4
dreem
dream
dieta
tamer
print
print
print
print
length(str)
len(str)
abs(str)
str[0]
164
print range(2, 5)
A1
A2
A3
A4
[2,
[2,
[2,
[5,
3, 4, 5]
3, 4, 5, 6]
3, 4]
6]
A1
A2
A3
A4
List.
Tuple.
Dictionary.
None of the above.
165
var =
print
print
print
A1 B
(1, 2, 3)
(alpha, beta, gamma)
A2 C
(1, 2, 3)
(alpha, beta)
A3 B
(1, 2, 3)
(C, alpha, beta, gamma)
A4 B
(1, 2, 3)
(alpha, beta)
3. Can new items be added to a tuple?
A1
A2
A3
A4
length(T)
tlength(T)
len(T)
tlen(T)
A2 Tuple.
A3 Dictionary.
A4 None of the above.
6. Identify the output of the following code!
names = ["John", "Jake", "Josh"]
name = names.del[1]
print name
A1
A2
A3
A4
John
Jake
Josh
Error message.
[Jake, Josh]
(John, Jake, Josh)
John
Error message.
167
168
1
2
(1, 4)
(2, 5)
1
(1, -1)
(1, 4)
(2, 5)
15. What is the correct way to define a dictionary D containing the English words "city", "fire",
"sun" and their Spanish translations "ciudad", "fuego", and "sol" ?
A1
A2
A3
A4
D
D
D
D
=
=
=
=
16. What is the correct way to add to a dictionary D new key "school" whose value is "escuela"?
A1 D.append(school: escuela)
A2 D.append_key(school)
D.append_value(escuela)
A3 D[school] = escuela
A4 D.add(school: escuela)
17. What is the correct way to print the value for the key "city" in the dictionary D?
D = {fire: fuego, city: ciudad, sun: sol}
A1
A2
A3
A4
D.print(city)
print D[city]
print D(city)
print D.get_key(city)
18. What is the correct way to ascertain whether or not the key "sun" is present in the dictionary D?
D = {fire: fuego, city: ciudad, sun: sol}
A1
A2
A3
A4
D.contains(sun)
D.key(sun)
D.try(sun)
D.has_key(sun)
19. What is the correct way to print all keys present in the dictionary D?
D = {fire: fuego, city: ciudad, sun: sol}
A1
A2
A3
A4
print
print
print
print
D.get_keys()
D.get_all()
get_keys(D)
D.keys()
170
20. What is the correct way to print all values present in the dictionary D?
D = {fire: fuego, city: ciudad, sun: sol}
A1
A2
A3
A4
10
print
print
print
print
D.get_values()
D.get_all()
get_values(D)
D.values()
1. What language element in Karel the Robot is most similar to the for loop in Python?
A1
A2
A3
A4
171
11
Exceptions
IndentationError
UnboundLocalError
TimeoutError
OverflowError
4. What is the correct way to raise a ValueError exception when x is greater than five?
A1 if x > 5:
ValueError("x should be <= five!")
A2 if x > 5:
raise ValueError("x should be <= five!")
A3 if x > 5:
exception ValueError("x should be <= five!")
A4 if x > 5:
raise_exception ValueError("x should be <= five!")
172
12
Object-Oriented Programming
5. Can methods of a class operate with data not owned by the class and when?
A1
A2
A3
A4
Yes, always.
Yes, but only if they also operate with data owned by the class.
Yes, but only if they do not operate with data owned by the class.
No.
173
6. What is a constructor?
A1
A2
A3
A4
7. What is the correct way to define a constructor that initializes a variable A in a class with a
value a?
A1
A2
A3
A4
def __init__(a):
A = a
def __init__(self, a):
A = a
def __init__(self, a):
self.A = a
def __init__(self, self.a):
self.A = self.a
8. A class contains a variable A. What is the correct way to define a method printdata of
this class that prints the value of the variable?
A1
A2
A3
A4
def printdata():
print "A =", A
def printdata():
print "A =", self.A
def printdata(self):
print "A =", A
def printdata(self):
print "A =", self.A
9. Given a text string S, what is the correct way to count and print the number of appearances
of another string word in S?
A1 print S.count("word")
A2 print S.find("word")
A3 print S.count(word)
174
A4 print S.parse_string("word")
10. What is the way to check whether a string S is a number?
A1
A2
A3
A4
S.isdigit()
S.isnumber()
isdigit(S)
isnumber(S)
11. What is the way to replace in a text string S a string s1 with another string s2?
A1
A2
A3
A4
13
S.uppercase()
S.raise()
S.upper()
S.capitalize()
Class Inheritance
2. What is the correct way to define a new class B which is a descendant of class A?
A1 class B(A):
175
A2 class A(B):
A3 class B: public A:
A4 class B = descendant(A)
3. What is the correct way to call from a descendant class B the constructor of its parent class
A?
A1 def __init__(self):
A.__init__(self)
A2 def __init__(self):
__init__(A)
A3 def __init__(self):
__init__(self, A)
A4 def __init__(A):
self.__init__(A)
176