Page - 18 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 18 -
Text of the Page - 18 -
18 1 TheFirstFewSteps
1.4.3 ImportswithNameChange
Whetherweimport forusewithorwithoutprefix,wemaychangenamesof the im-
porteditemsbyminoradjustmentsof the importstatements. Introducingsuchname
changes in our program and saving this final version ascheck_functions.py, it
reads
import numpy as np
import math as m
x = np.exp([0, 1, 2]) # do all 3 calculations
print(x) # print all 3 results
y = m.cos(0)
print(y)
Effectively, the module names in this program now become np and m (by our
own choice) instead of numpy and math, respectively. We still enjoy the safety
of prefixing and notice that such name changes might bring computer coded
expressionscloser to mathematicalwritingand thusease humaninterpretation.
When importinglibrary itemsforusewithoutprefix,namechangescanbedone,
e.g., like
from math import cos as c, sin as s
print(c(0) + s(0))
1.4.4 ImportingfromPackages
Modules may be grouped into packages, often together with functions, variables,
and more. We may import items (modules, functions, etc.) from such packages
also, but the appearance of an import statement will then depend on the structure
of the package in question. We leave out the details14 and just exemplify with two
packagesoftenused in thisbook.
Thenumpy library used above is, in fact, a packageand we saw how it could be
used with different import statements, just as if it had been a module.Note that the
import statement
import numpy as np # standard way of importing numpy
is the standard way of importingnumpy, i.e., also the “nickname”np is standard.
Thiswillbe thestandardimport techniquefornumpyalso inourbook,meaningthat
we will generally usenumpy items with thenpprefix. We will deviate from this at
times, typically during brief interactive sessions (see Sect.2.1), in which case we
will import itemsexplicitlyspecifiedbyname.
Anotherpopularpackageyouwill meetoften in thisbook, is the plotting library
matplotlib (Sect.1.5), used for generating and handling plots. The standard
import statement, including the“nickname”, is then
import matplotlib.pyplot as plt # standard way of importing pyplot
14 If you are curious, check for more details athttps://docs.python.org/3.6/tutorial/modules.html.
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
- Title
- Programming for Computations – Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik