Python Programming Quantecon Org Python Essentials HTML
Python Programming Quantecon Org Python Essentials HTML
Python Programming Quantecon Org Python Essentials HTML
Python Essentials
.1. Overview
e have covered a lot of material quite quickly, with a focus on examples.
rograms need to distinguish between these two types for various reasons.
For example, floating point arithmetic is implemented on most machines by a specialized Floating Point Unit
(FPU).
general, floats are more informative but arithmetic operations on integers are faster and more accurate.
ython provides numerous other built-in Python data types, some of which weʼve already met
x = True
x
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
True
e can check the type of any object in memory using the type() function.
type(x)
bool
the next line of code, the interpreter evaluates the expression on the right of = and binds y to this value
y = 100 < 10
y
False
type(y)
bool
x + y
x * y
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
0
True + True
sum(bools)
x = complex(1, 2)
y = complex(2, 1)
print(x * y)
type(x)
5j
complex
.2.2. Containers
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
ython has several basic types for storing collections of (possibly heterogeneous) data.
('a', 'b')
type(x)
tuple
Python, an object is called immutable if, once created, the object cannot be changed.
x = [1, 2]
x[0] = 10
x
[10, 2]
x = (1, 2)
x[0] = 10
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[13], line 2
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
1 x = (1, 2)
----> 2 x[0] = 10
eʼll say more about the role of mutable and immutable data a bit later.
10
20
o access multiple elements of a sequence (a list, a tuple or a string), you can use Pythonʼs slice notation.
or example,
a[1:3]
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
['b', 'c']
['d', 'e']
a[::2]
sing a negative step, you can return the sequence in a reversed order
a[-2::-1] # Walk backwards from the second last element to the first element
s = 'foobar'
s[-3:] # Select the last three elements
'bar'
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
wo other container types we should mention before moving on are sets and dictionaries.
ctionaries are much like lists, except that the items are named instead of numbered
dict
d['age']
33
he objects that the keys are mapped to ( 'Frodo' and 33 ) are called the values .
ets are unordered collections without duplicates, and set methods provide the usual set-theoretic operations
s1 = {'a', 'b'}
type(s1)
set
s2 = {'b', 'c'}
s1.issubset(s2)
False
s1.intersection(s2)
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
{'b'}
{'bar', 'foo'}
ere
The built-in function open() creates a file object for writing to.
Both write() and close() are methods of file objects.
ecall that Python maintains a concept of the present working directory (pwd) that can be located from with Jupyte
IPython via
%pwd
'/__w/lecture-python-programming.myst/lecture-python-programming.myst/lectures'
f = open('newfile.txt', 'r')
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
out = f.read()
out
'Testing\nTesting again'
print(out)
Testing
Testing again
fact, the recommended approach in modern Python is to use a with statement to ensure the files are properly
cquired and released.
ontaining the operations within the same block also improves the clarity of your code.
Note
etʼs try to convert the two examples above into a with statement.
ote that we do not need to call the close() method since the with block will ensure the stream is closed at th
nd of the block.
Testing
Testing again
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
ow suppose that we want to read input from one file and write output to another. Hereʼs how we could accomplish
is task while correctly acquiring and returning resources to the operating system using with statements:
Line 0: Testing
e can simplify the example above by grouping the two with statements into one line
Line 0: Testing
uppose we want to continue to write into the existing file instead of overwriting it.
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
with open('output2.txt', 'a') as fo:
fo.write('\nThis is the end of the file')
Line 0: Testing
Note
Note that we only covered r , w , and a mode here, which are the most commonly used modes. Python provides
a variety of modes that you could experiment with.
.3.1. Paths
ote that if newfile.txt is not in the present working directory then this call to open() fails.
this case, you can shi the file to the pwd or specify the full path to the file
f = open('insert_full_path_to_file/newfile.txt', 'r')
.4. Iterating
ne of the most important tasks in computing is stepping through a sequence of data and performing a given action
ne of Pythonʼs strengths is its simple, flexible interface to this kind of iteration via the for loop.
o give an example, letʼs write the file us_cities.txt, which lists US cities and their population, to the present working
rectory.
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
%%writefile us_cities.txt
new york: 8244910
los angeles: 3819702
chicago: 2707120
houston: 2145146
philadelphia: 1536471
phoenix: 1469471
san antonio: 1359758
san diego: 1326179
dallas: 1223229
Overwriting us_cities.txt
uppose that we want to make the information more readable, by capitalizing names and adding commas to mark
ousands.
ere format() is a string method used for inserting variables into strings.
he reformatting of each line is the result of three di erent string methods, the details of which can be le till later.
1. The file object data_file is iterable, in the sense that it can be placed to the right of in within a for loop
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
2. Iteration steps through each line in the file.
any other kinds of objects are iterable, and weʼll discuss some of them later on.
or example,
1
4
9
preferred to
for i in range(len(x_values)):
print(x_values[i] * x_values[i])
1
4
9
hen you compare these two alternatives, you can see why the first one is preferred.
ne is zip() , which is used for stepping through pairs from two sequences.
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
The capital of Japan is Tokyo
The capital of Korea is Seoul
The capital of China is Beijing
we actually need the index from a list, one option is to use enumerate() .
letter_list[0] = 'a'
letter_list[1] = 'b'
letter_list[2] = 'c'
onsider the following example, where the list comprehension is on the right-hand side of the second line
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
['dogs', 'cats', 'birds']
range(8)
range(0, 8)
.5.1. Comparisons
any di erent kinds of expressions evaluate to one of the Boolean values (i.e., True or False ).
x, y = 1, 2
x < y
True
x > y
False
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
ne of the nice features of Python is that we can chain inequalities
1 < 2 < 3
True
1 <= 2 <= 3
True
x = 1 # Assignment
x == 2 # Comparison
False
1 != 2
True
ote that when testing conditions, we can use any valid Python expression
'yes'
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
x = 'yes' if [] else 'no'
x
'no'
he rule is:
Expressions that evaluate to zero, empty sequences or containers (strings, lists, etc.) and None are all
equivalent to False .
for example, [] and () are equivalent to False in an if clause
All other values are equivalent to True .
for example, 42 is equivalent to True in an if clause
hese are the standard logical connectives (conjunction, disjunction and denial)
True
False
True
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
not True
False
True
emember
True
False
True
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Note
all() returns True when all boolean values/expressions in the sequence are True
any() returns True when any boolean values/expressions in the sequence are True
eʼve all heard the saying about consistency and little minds.
A mathematical paper where the symbols ∪ and ∩ were reversed would be very hard to read, even if the autho
told you so on the first page.
Occasionally weʼll deviate from PEP8 in these lectures to better match mathematical notation)
.6.2. Docstrings
ython has a system for adding comments to modules, classes, functions, etc. called docstrings.
y running this
def f(x):
"""
This function squares its argument
"""
return x**2
f?
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Type: function
String Form:<function f at 0x2223320>
File: /home/john/temp/temp.py
Definition: f(x)
Docstring: This function squares its argument
f??
Type: function
String Form:<function f at 0x2223320>
File: /home/john/temp/temp.py
Definition: f(x)
Source:
def f(x):
"""
This function squares its argument
"""
return x**2
ith one question mark we bring up the docstring, and with two we get the source code as well.
.7. Exercises
olve the following exercises.
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Exercise 5.1
Part 1: Given two numeric lists or tuples x_vals and y_vals of equal length, compute their inner product
using zip() .
Part 3: Given pairs = ((2, 5), (4, 2), (9, 8), (12, 10)) , count the number of pairs (a, b)
such that both a and b are even.
Hint
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Solution to Exercise 5.1
Part 1 Solution:
x_vals = [1, 2, 3]
y_vals = [1, 1, 1]
sum([x * y for x, y in zip(x_vals, y_vals)])
Part 2 Solution:
One solution is
50
50
Some less natural alternatives that nonetheless help to illustrate the flexibility of list comprehensions are
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
50
and
50
Part 3 Solution:
Exercise 5.2
2 n i
p(x) = a 0 + a 1 x + a 2 x + ⋯ an x = ∑ ai x (5.1)
i=0
Write a function p such that p(x, coeff) that computes the value in (5.1) given a point x and a list of
coe icients coeff (a 1 , a 2 , ⋯ a n ).
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Solution to Exercise 5.2
Hereʼs a solution:
Exercise 5.3
Write a function that takes a string as an argument and returns the number of capital letters in the string.
Hint
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Solution to Exercise 5.3
def f(string):
count = 0
for letter in string:
if letter == letter.upper() and letter.isalpha():
count += 1
return count
def count_uppercase_chars(s):
return sum([c.isupper() for c in s])
Exercise 5.4
Write a function that takes two sequences seq_a and seq_b as arguments and returns True if every element
in seq_a is also an element of seq_b , else False .
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Solution to Exercise 5.4
Hereʼs a solution:
# == test == #
print(f("ab", "cadb"))
print(f("ab", "cjdb"))
print(f([1, 2], [1, 2, 3]))
print(f([1, 2, 3], [1, 2]))
True
False
True
False
# == test == #
print(f("ab", "cadb"))
print(f("ab", "cjdb"))
print(f([1, 2], [1, 2, 3]))
print(f([1, 2, 3], [1, 2]))
True
False
True
False
Of course, if we use the sets data type then the solution is easier
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Exercise 5.5
When we cover the numerical libraries, we will see they include many alternatives for interpolation and function
approximation.
In particular, without using any imports, write a function linapprox that takes as arguments
and returns the piecewise linear interpolation of f at x , based on n evenly spaced grid points a =
point[0] < point[1] < ... < point[n-1] = b .
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Solution to Exercise 5.5
Hereʼs a solution:
Parameters
==========
f : function
The function to approximate
n : integer
Number of grid points
Returns
=======
A float. The interpolant evaluated at x
"""
length_of_interval = b - a
num_subintervals = n - 1
step = length_of_interval / num_subintervals
# === x must lie between the gridpoints (point - step) and point === #
u, v = point - step, point
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Exercise 5.6
Using list comprehension syntax, we can simplify the loop in the following code.
import numpy as np
n = 100
ϵ_values = []
for i in range(n):
e = np.random.randn()
ϵ_values.append(e)
n = 100
ϵ_values = [np.random.randn() for i in range(n)]
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com