Elements of Python3 Programming For Mechanical Engineers
Elements of Python3 Programming For Mechanical Engineers
Elements of Python3 Programming For Mechanical Engineers
Abstract
This document introduces Python as a procedural programming language so that
it can be used to implement engineering analysis programs or to write problem-
description files for large simulation programs that happen to use Python as a
scripting language. The notes are a summary of (and are complementary to) the
material presented in the first few lectures of the course MECH2700 Engineering
Analysis I. The intention is to describe just enough of the Python3 programming
language to implement the numerical methods that are introduced and used in the
later parts of the course.
1
CONTENTS 2
Contents
1 Introduction 3
3 An example program 7
3.1 Building a refined program . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
5 Data types 21
5.1 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.2 Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.3 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
5.4 Boolean values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
5.5 Other built-in types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
9 Flow-control statements 35
9.1 Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
9.2 Repetition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
9.3 Exceptions, assert statements . . . . . . . . . . . . . . . . . . . . . . . . . 40
10 Functions 41
11 Modules 44
11.1 The main module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
1 Introduction
Where to begin...
Steps in the problem-solving method, according to Feldman & Koffman [1].
Notes:
The whole process will be iterative. We probably won’t achieve the desired result,
even at iteration N.
Algorithm
An algorithm is a set of instructions, or procedural steps, for the solution of a
particular problem.
Solutions
Approaches to the task of devising a solution:
1. Top-down approach:
– Start from the problem specification and work, step by step, toward a
solution.
– At each step, subdivide the problem into smaller chunks.
– This approach is sometimes called stepwise refinement.
2. Bottom-up approach:
– Build small components, or tools, with limited functionality.
– Build bigger components from the smaller components until we have a tool
that will do the desired job.
As your experience increases and your collection of programming tools grows, the
bottom-up approach gets easier and becomes more natural.
2 THE PYTHON INTERPRETER 5
>>> dir()
[’__builtins__’, ’__doc__’, ’__loader__’, ’__name__’, ’__package__’,
’__spec__’, ’acos’, ’acosh’, ’asin’, ’asinh’, ’atan’, ’atan2’, ’atanh’,
’ceil’, ’copysign’, ’cos’, ’cosh’, ’degrees’, ’e’, ’erf’, ’erfc’,
’exp’, ’expm1’, ’fabs’, ’factorial’, ’floor’, ’fmod’, ’frexp’, ’fsum’,
’gamma’, ’hypot’, ’isfinite’, ’isinf’, ’isnan’, ’ldexp’, ’lgamma’,
’log’, ’log10’, ’log1p’, ’log2’, ’modf’, ’pi’, ’pow’, ’radians’, ’sin’,
’sinh’, ’sqrt’, ’tan’, ’tanh’, ’trunc’]
>>>
Most modules and functions are documented using special text within the code. For
example, help(sin) will get us a display of the documentation string for the sin function.
sin(...)
sin(x)
You may need to press q to quit from the text viewer on Linux. Now, to get the sine of
30 degrees, try
>>> sin(radians(30))
0.49999999999999994
>>>
Finally, to get out of the Python REPL, press Control-D in Linux and Control-Z in
Windows. For most of this course, we will use the interpreter from within the IDLE3
integrated development environment.
3 AN EXAMPLE PROGRAM 7
3 An example program
This example has come from Gruenburger & Jaffray’s book [3], Problem F14, The calcu-
lation of π.
2. Analysis:
π 1 1
= 4 tan−1 − tan−1
4 5 239
3. Algorithm
a1 = 1.0 / 5
a2 = pow(a1,3) / 3
a3 = pow(a1,5) / 5
b1 = 1.0 / 239
b2 = pow(b1,3) / 3
b3 = pow(b1,5) / 5
pi_1 = 16 * (a1 - a2 + a3) - 4 * (b1 - b2 + b3)
print("Truncated series estimate is ", pi_1)
1 # file : machin1 . py
2 """
3 MECH2700 : Using Python as a calculator .
4
9 P . A . Jacobs
10 School of Engineering , UQ .
11
$ idle3 machin2.py
Once IDLE3 is displaying the code module in an edit window, press F5 to run the module
to get the program to start and you get something like the following appearing in the
interpreter window.
Note that the simple ratio 355/113 gives us an estimate correct to 6 decimal places.
3 AN EXAMPLE PROGRAM 10
1 # file : machin2 . py
2 """
3 Sample Python program for MECH2700
4
14 #---------------------------------------------------------------
15 def atan_series (x , n ):
16 " Computes atan ( x ) with truncated series expansion , n terms ."
17 xpower = x
18 my_sum = x
19 sign = 1
20 for i in range (1 , n ):
21 xpower = xpower * x * x
22 sign = -1 * sign
23 term = sign * xpower / (2 * i + 1)
24 my_sum = my_sum + term
25 return my_sum
26
27 def machin ( n ):
28 " Computes pi using Machin ’ s formula ."
29 return 4 * (4 * atan_series (0.2 , n ) - atan_series (1.0/239 , n ))
30
31 #---------------------------------------------------------------
32 print (" Begin program Machin2 ...")
33 text = input (" Enter a value for the number of terms : ")
34 i = int ( text )
35 pi_1 = machin ( i )
36 print (" Truncated series estimate is " , pi_1 , " for n =" , i )
37 pi_2 = 4.0 * math . atan (1.0)
38 print (" Math library estimate is " , pi_2 )
39 print (" Difference is " , pi_1 - pi_2 )
40 print (" End of program Machin2 .")
3 AN EXAMPLE PROGRAM 11
$ idle3 machin2.py
Once IDLE3 is displaying the code module in an edit window, press F5 to run the module
to get the program to start. If you enter 3 for the number of terms, you get something
like the following appearing in the interpreter window.
As expected, the result becomes more accurate as the number of terms is increased.
1 # file : machin3 . py
2 """
3 Sample Python program for MECH2700 -- a modification of machin2 .
4
14 #---------------------------------------------------------------
15 def atan_series (x , n ):
16 " Computes atan ( x ) with truncated series expansion , n terms ."
17 xpower = x
18 my_sum = x
19 sign = 1
20 for i in range (1 , n ):
21 xpower = xpower * x * x
22 sign = -1 * sign
23 term = sign * xpower / (2 * i + 1)
24 my_sum = my_sum + term
25 return my_sum
26
27 def machin ( n ):
28 " Computes pi using Machin ’ s formula ."
29 return 4 * (4 * atan_series (0.2 , n ) - atan_series (1.0/239 , n ))
30
31 #---------------------------------------------------------------
32 if __name__ == " __main__ ":
33 # These lines are only run if this file is the main script .
34 # Thus we may import the functions above into other modules
35 # without having these lines execute .
36 print (" Begin program Machin3 ...")
37 text = input (" Enter a value for the number of terms : ")
38 i = int ( text )
39 pi_1 = machin ( i )
40 print (" Truncated series estimate is " , pi_1 , " for n =" , i )
41 pi_2 = 4.0 * math . atan (1.0)
42 print (" Math library estimate is " , pi_2 )
43 print (" Difference is " , pi_1 - pi_2 )
44 print (" End of program Machin3 .")
3 AN EXAMPLE PROGRAM 13
Note the if __name__ == "__main__": phrase on line 32. This allows us to reuse the
function definitions in another program without the clutter of the messages being printed.
Try it.
3 AN EXAMPLE PROGRAM 14
1 # file : machin4 . py
2 """
3 Sample Python program for MECH2700 , multiple - precision arithmetic
4
15 #---------------------------------------------------------------
16 def atan_series (x , n ):
17 " Computes atan ( x ) with truncated series expansion , n terms ."
18 xpower = x
19 my_sum = x
20 sign = 1
21 for i in range (1 , n ):
22 xpower = xpower * x * x
23 sign = -1 * sign
24 term = sign * xpower / (2 * i + 1)
25 my_sum = my_sum + term
26 return my_sum
27
28 def machin ( n ):
29 " Computes pi using Machin ’ s formula ."
30 return 4 * (4 * atan_series ( mpf ( ’0.2 ’) , n ) -
31 atan_series ( mpf (1)/239 , n ))
32
33 #---------------------------------------------------------------
34 if __name__ == " __main__ ":
35 # These lines are only run if this file is the main script .
36 # Thus we may import the functions above into other modules
37 # without having these lines execute .
38 print (" Begin program Machin4 ... using mpmath module ")
39 mp . dps = 750
40 text = input (" Enter a value for the number of terms : ")
41 i = int ( text )
42 pi_1 = machin ( i )
43 print (" Truncated series estimate is " , pi_1 , " for n =" , i )
44 pi_2 = mpf ( ’4.0 ’) * atan ( ’1.0 ’)
3 AN EXAMPLE PROGRAM 15
Notes:
We reply upon the open parenthesis on physical line 30 to let the compiler know
that physical line 31 is a continuation of the same logical line.
How many terms are required to get at least 707 decimal places correct?
4 PYTHON LANGUAGE ELEMENTS 16
2. record results;
Over the next few lectures, we will study the basic (procedural) elements of the Python
programming language. In particular, we will study:
Much of the material on the following pages is adapted from Alex Martelli’s text Python
in a Nutshell [6] and the online Python documentation. For online Python information,
start at https://www.python.org and to go directly to the online documentation go to
https://docs.python.org
David Beazley’s Essential Reference [7] is a more recent text that you should read and keep
under your pillow. If you want to know all there is to know about Python programming,
Mark Lutz’ text Learning Python [8] is a comprehensive guide. The fifth edition weighs
in at more than 1500 pages.
4 PYTHON LANGUAGE ELEMENTS 17
A comment starts with a pound/sharp/hash sign # and continues to the end of the
line.
Comments are ignored by the interpreter. They are just for us.
The end of a physical line normally ends a statement unless the statement is con-
tinued by:
Subsequent physical lines in the logical line are known as continuation lines.
The indentation of the first physical line in the logical line is used to indicate block
structure of the code.
A block is a contiguous sequence of logical lines, all indented by the same amount.
The block is ended by a logical line with less indentation.
4.3 Tokens
Each line is divided into a number of tokens. These are the smallest items with
meaning.
Tokens are used as identifiers, keywords, operators, delimiters and literals.
White space may be used between tokens and, in some cases, may be required to
separate the tokens. For example, the line from our introductory program
def atan_series(x, n):
requires the space to separate def and atan_series. The space between the comma
and the n is optional.
Identifiers
are names used to identify variables, functions, classes, modules or other objects. Some
rules:
They start with a letter or underscore, followed by zero or more letters, underscores
or digits.
The case of letters is significant.
Punctuation characters are not allowed.
Some recommendations:
Start most names with a lowercase letter.
Leading and trailing underscores are meant to be special.
Use an uppercase letter to start a class name.
Keywords
are identifiers that Python reserves for special syntactic purposes. The interpreter recog-
nises these specially. They are:
False True None
and as assert break class continue
def del elif else except finally
for from global if import in
is lambda nonlocal not or pass
raise return try while with yield
Operators
are nonalphabetic characters and character combinations.
+ - * / % ** //
<< >> & | ^ ~
< <= > >= != ==
=
+= -= *= /= %= **= //=
>>= <<= &= |= ^=
4 PYTHON LANGUAGE ELEMENTS 19
Literals
are data values that appear directly in the program text. For example:
42 # integer literal
Expressions
are phrases of code that can be evaluated to produce a value.
We’ll revisit the details later in Section 7.
4 PYTHON LANGUAGE ELEMENTS 20
4.4 Statements
A simple statement is one that contains no other statements.
You may put more than one simple statement on a logical line, so long as you
separate them by semicolons ;
Each compound statement has one or more clauses, aligned at the same indentation.
Each clause starts with a keyword and ends with a colon followed by a body, which
is a sequence of one or more statements.
– These statements should be placed on separate logical lines, after the header
line, and indented to the right from the header line.
– The block ends when the indentation returns to that of the clause header (or
further left).
The body can also be a simple statement following the colon, on the same line.
5 DATA TYPES 21
5 Data types
At the lowest level in the computer, all data are binary (bit patterns).
We layer meaning over the binary data by defining types and interpreting the various
bit patterns as particular values of those data types.
In Python, all data is represented as objects. Each object has a type which deter-
mines what operations you can perform on the data value.
The built-in function type(obj) returns a type object that represents the type of
obj.
Fundamental data types are built-in, however, the programmer may define other
types using the class definition facility. For MECH2700, we won’t be building our
own classes but we will be using many classes built by others.
5.1 Numbers
Integers
Integers are, by default, defined as base-10 values, using strings of digits. For
example, 1234.
Floating-point
Floating-point numbers have a decimal point in their literal representation.
For example: 3.14 and 2.
Complex
Literals of complex type use a j or J to denote the imaginary part. They are stored
as pairs of float values.
1+2j → (1+2j)
(3.14+4.0J).imag → 4.0
To get the complex math functions, we need to import the cmath module.
Others
from decimal import Decimal; Decimal(10.1) →
Decimal(’10.0999999999999996447286321199499070644378662109375’)
5.2 Sequences
A sequence is a container of ordered items.
Strings
A string is an immutable sequence of characters.
"hello1"
’hello2’
"""A string on
two lines."""
Quote characters can be inside a string delimited by the other quote character, but
remember to use the quote characters consistently.
"Peter’s little blue cart." → "Peter’s little blue cart."
"Peter’s little \"blue\" cart." → ’Peter\’s little "blue" cart.’
The backslash character can be used to escape from the usual interpretation of a
character.
5 DATA TYPES 23
>>> "\\"
’\\’
>>> print(_)
\
>>> "\n"
’\n’
>>> print(_)
>>>
Because strings are immutable, their content cannot change. Operations on a string
that result in a string will return a derived string.
For example:
Tuples
A tuple is an immutable, ordered collection of items.
For example:
(100, 200, 300) → a tuple with 3 items
(3.14, (’a’, ’b’)) → a nested tuple
() → an empty tuple
tuple(’hello’) → (’h’, ’e’, ’l’, ’l’, ’o’)
Lists
A list is a mutable, ordered sequence of items.
You construct a literal list much like a tuple, but you enclose the items with brackets.
For example:
[100, 200, 300] → a list with 3 items
[3.14,] → a list with one item
list() → an empty list
5 DATA TYPES 24
list(range(5)) → [0, 1, 2, 3, 4]
list(range(5,10)) → [5, 6, 7, 8, 9]
Numpy arrays
In the numerical methods part of the course, we will make extensive use of the array
type from the numpy extension module. http://www.numpy.org
For example:
import numpy as np
np.array([1,2,3]) → array([1, 2, 3]) a numeric array of 3 integers
np.array([1,2.0,3]) → array([ 1., 2., 3.]) a numeric array of float values
np.array([[1,2,3],[4,5,6]]) → a two-dimensional array of integers
np.zeros((2,4)) → a 2 × 4 array of zero float values
np.eye(3) → the 3 × 3 identity matrix
5.3 Dictionaries
A dictionary is an unordered collection of items, where each particular items is
indexed by a key. In other programming languages, it may be called a map or hash
table.
For example:
{’x’: 42, ’y’: 36} → a dictionary with 2 items
dict() → an empty dictionary
False
Every data value can be evaluated as a truth value. Any nonzero number or
nonempty collection evaluates as True.
For example:
bool([5, 6, 7, 8, 9]) → True
bool([]) → False
bool(-1) → True
Iterators and generators are advanced types and won’t be discussed in detail in
MECH2700. We will, however, make use of iterators implicitly, when we use for
loops in Section 9.
6 VARIABLES, ASSIGNMENTS, NAME SPACES 26
Using a name within an expression causes the value bound to the name to be used
in the evaluation of the expression.
>>> 2 * a → 10
a int 5
>>> a = ’hello’
>>> print(a)
hello
>>>
>>> del(a)
>>> dir()
[’__builtins__’, ’__doc__’, ’__loader__’, ’__name__’, ’__package__’,
’__spec__’]
>>> print(a)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print(a)
NameError: name ’a’ is not defined
>>>
Learn to read the Traceback details. They are usually very helpful by telling you
where something went wrong and what went wrong.
Multiple assignments can be made with one statement, by providing several names
separated by commas.
a = 1
b = 2
print("Before: a=", a, "b=", b)
b, a = a, b # swap values
print("After: a=", a, "b=", b)
7 EXPRESSIONS AND OPERATORS 28
Look up Section 6.15 1 of the Python language reference for the table of operator
precedence in expressions but, in general, don’t rely upon remembering the details
because...
If we apply two operands of different type, Python coerces the operand of the smaller
type to the larger type.
int → float → complex
For example:
>>> type(2 * 3)
<class ’int’>
>>> type(2 * 3.0)
1
https://docs.python.org/3/reference/expressions.html?#operator-precedence
7 EXPRESSIONS AND OPERATORS 29
<class ’float’>
>>> type(2 * 1j)
<class ’complex’>
>>> type(2.0 * 1j)
<class ’complex’>
>>>
>>> int(3.14)
3
>>> float(1)
1.0
>>> float("1")
1.0
>>> complex(1)
(1+0j)
For example:
>>> 2 * s
[1, 2, 33, 4.0, 1, 2, 33, 4.0]
>>> s
[1, 2, 33, 4.0]
>>> 33 in s
True
>>> 101 in s
False
>>>
Use integers to index items. The first item is index 0. You can use negative indices
to index from the right.
Think of the index labelling the divider before each item. So, the content of the list
s might be represented as:
The slice s[i:j] denotes a subsequence, from the item with index i up to, but
excluding, the item with index j.
>>> s[1]
2
>>> s[-1]
4.0
>>> s[len(s)-1]
4.0
>>> s[1:3]
[2, 33]
>>> s[:2]
[1, 2]
>>>
Indexing and slicing work on strings and tuples but we cannot rebind or delete
items.
Lists can be altered. Items in a list can be rebound to different objects or can be
removed from the list.
>>> s[1] = 42
>>> s
[1, 42, 33, 4.0]
>>> del s[2]
>>> s
[1, 42, 4.0]
>>>
7 EXPRESSIONS AND OPERATORS 31
List methods
With L being a list object, we have:
L.count(x) Returns the number of occurrences of x in L.
Returns the index of the first occurrence of x in L,
L.index(x)
or raises an exception is L has no such item.
L.clear() Remove all items from L.
L.append(x) Appends item x to the end of L.
L.extend(L2 ) Appends all of the items of list L2 to L.
L.insert(i, x) Inserts item x before index i in L.
L.remove(x) Removes the first occurrence of item x from L.
Returns the value of the item at index i and removes it from L;
if i is omitted, removes and returns the last item.
L.pop([i])
Note that the square brackets here indicate an optional parameter
and that they are not actually typed in.
L.reverse() reverses, in place, the items of L.
Sorts, in place, the items of L.
L.sort() There is also a built-in function sorted() that returns a new,
sorted list.
Matching of keys is done with comparison, so it’s not a good generally idea to use
floating-point numbers as keys.
Views are set-like. We can iterate over a view to do some work on each item.
Each replacement field contains either the numeric index of a positional argument,
or the name of a keyword argument. You can omit the positional indices if you used
the arguments in order.
There is a mini-language for the format specification. Look up the online documen-
tation for the Python Standard Library, Section 6.1.3 Format String Syntax.
The trailing letter g in the example below denotes general format for floating-point
values.
For example:
print("A rough estimate of pi is {value} (error {error})".format(
value=my_pi, error=pi-my_pi))
print("A better estimate is {0:.6g} (error {1:.3g})".format(
better_pi, pi-better_pi))
produces the output:
A rough estimate of pi is 3.142857142857143 (error -0.0012644892673496777)
A better estimate is 3.14159 (error -2.67e-07)
8 THE PRINT FUNCTION AND STRING FORMATTING 34
9 Flow-control statements
Flow is the order in which the program’s code executes. To control this flow, we have the
statements:
exceptions
9.1 Selection
The if statement asks a question and selects one of the alternate flow paths.
Each clause in the compound statement begins with a keyword and ends with a
colon and is followed by one or more statements.
if cond :
statement(s) for True
else :
statement(s) for False
Note that the whole structure is bounded, with only one entry and one exit path.
The if statement may be extended to select one of several flow paths with elif clauses.
if cond :
statement(s) for True
elif cond2 :
statement(s) for elif True
else :
statement(s) for elif False
For example:
x = 11
if x < 0:
print("x is negative.")
elif x % 2:
print("x is positive and odd")
else:
print("x is even or zero")
Notes:
9.2 Repetition
while statement
while cond :
statement(s)
Sometimes it will be handy to interrupt a loop manually. Use the Control-C key
combination to interrupt execution of the interpreter.
break statement
It can appear in the body of a loop.
For example:
x = 0; my_sum = 0
while True:
my_sum = my_sum + x
print("x=", x, "my_sum=",my_sum)
if x > 9: break
x += 1
9 FLOW-CONTROL STATEMENTS 38
continue statement
It can also appear in the body of a loop.
If it executes, the remaining part of the current iteration of the loop is skipped and
execution continues with a new loop iteration.
For example:
x = -9
while x < 9:
x += 1
if x == 0: continue
print("x=", x, "1/x=", 1/x)
pass statement
The body of a compound statement cannot be empty; it must consist of at least
one statement.
When you want to perform no action, you can use this pass statement as a place
holder.
For example:
x = -9
while x < 9:
if x == 0:
pass
else:
print("x=", x, "1/x=", 1/x)
x += 1
9 FLOW-CONTROL STATEMENTS 39
for statement
General form:
for target in iterable :
statement(s)
target is usually a identifier that names the control variable of the loop.
The for statement successively rebinds the control variable name to each item in
the iterator, in order, and the body of the loop executes once for each of these items.
Examples:
for y in range(4):
print(’y=’, y)
D = {’x’:42, ’y’:’hello’}
for (key,val) in D.items():
print(’key=’, key, ’value=’, val)
9 FLOW-CONTROL STATEMENTS 40
Exceptions
Sometimes we end up with a value which our code cannot reasonably handle. Raising
an exception is a one way to throw the responsibility elsewhere.
For MECH2700, we’ll just consider the simple format for signalling one of the built-
in exceptions:
raise RuntimeError(args)
If we give the exception some text as its argument, that text is available to be
printed if the exception is raised and caught.
We’ll let the Python interpreter handle any exceptions that we raise.
For example:
x = 0
if x == 0:
raise RuntimeError("Zero value for x")
else:
y = 1/x
print("x=", x, "y=", y)
Assert
The assert statement helps us to check the assumptions built into our code.
For example:
x = 0
assert x != 0, "Zero value for x"
y = 1/x
print("x=", x, "y=", y)
10 FUNCTIONS 41
10 Functions
A function is a group of statements that executes on request (the request being the
function call).
When called, a function may be passed arguments that specify data for part of its
computation.
A function always returns a value (which may be the special value None).
Functions are objects, and can be named. They can passed to and received from
other functions.
The function body is a non-empty sequence of statements. These are executed later,
when the function is called. When the def statement is executed, they are compiled
into the function object.
Calling functions
A function call is an expression of the form:
function-name(arguments)
The arguments are zero or more expressions, separated by commas, giving values
for the functions formal arguments.
When a function is called, the parameters are bound to these values, the function
body is executes and the value of the function call expression is whatever the function
returns.
If several values are returned as a tuple or a list, we may use multiple assignment
to catch them, assigning the values to several names.
Assigning other objects to these names inside the function does not affect the caller.
– Parameter names in the function header become new, local names when the
function executes.
– There is no aliasing between the function parameter names and like names in
the caller because the function has its own (local) name space.
Changing a mutable object that has arrived as an argument may, however, impact
the caller.
For example, the code below:
Results in:
Before: X= 1 L= [1, 2]
After: X= 1 L= [’spam’, 2]
10 FUNCTIONS 43
Explain why using the name-space and object-space model that was introduced in
Section 6.
print("call as f(1)")
f(1)
print("call as f(1,4,5)")
f(1,4,5)
print("call as f(a=1)")
f(a=1)
print("call as f(1,c=6)")
f(1,c=6)
11 Modules
To help us organize our code:
Each source file corresponds to a module, which contains code and data.
A module is a Python object with named attributes that you can bind and reference.
The module body is the sequence of statements in the module’s source file.
A module’s body executes immediately, the first time that the module is imported
in a given run of a program.
The import statement creates a new name space that contains all of the attributes
of the module object.
To access a attribute in this name space, use the name of the module as a prefix (in
the fully-qualified name).
import math
y = math.sin(1.0)
If the first statement in the module body is a string literal, the Python compiler
binds that string as the module’s documentation string attribute.
The from statement lets us import specific attributes from a module into the current
name space.
We can conditionally execute code in a script by checking the global variable __name__.
For example:
if __name__ == "__main__":
print("code to be executed if the module is run")
print("as the main module.")
# blah...
This is often used as a place to put testing or demonstration code for a module.
12 SCOPE AND NAME RESOLUTION 46
Each module is a global scope, that is, a name-space where variables created at the
top-level of the module exist.
Each call to a function is a new local scope, that is, a name-space where variables
created inside the function usually live.
Name resolution:
The LEGB Rule: name references search local, then enclosing functions (if any),
then global and then built-in name-spaces.
Built-in (Python)
Names pre-assigned in the built-in names module.
References
[1] Michael B. Feldman and Elliot B. Koffman. Ada95: problem solving and program
design. Addison-Wesley, Reading, Massachusetts, 1996.
[3] Fred Gruenberger and George Jaffray. Problems for computer solution. John Wiley &
Sons, New York, 1965.
[4] Fredrik Johansson et al. mpmath: a Python library for arbitrary-precision floating-
point arithmetic., December 2013. http://mpmath.org/.
[5] Steven R. Lerman. Problem solving and computation for scientists and engineers : an
introduction using C. Prentice-Hall, Englewood Cliffs, New Jersey, 1993.
[7] David M. Beazley. Python Essential Reference. Sams Publishing, Indianapolis, Indi-
anna, 2006.