1.3 A Python Program with a Library Function
13
y/x would take place, and the result of that division would replace the text y/x.
Thereafter, the result is assigned to angle on the left-hand side of =.
Note that the trigonometric functions, such as atan, work with angles in
radians. Thus, if we want the answer in degrees, the return value of atan
must be converted accordingly. This conversion is performed by the computation
(angle/pi)*180. Two things happen in the print command: first, the computation of (angle/pi)*180 is performed, resulting in a number, and second, print
prints that number. Again, we may think that the arithmetic expression is replaced
by its result and then print starts working with that result.
Running the Program If we next execute ball_angle_first_try.py, we get
an error message on the screen saying
NameError: name ’atan’ is not defined
WARNING: Failure executing file:
We have definitely run into trouble, but why? We are told that
name ’atan’ is not defined
so apparently Python does not recognize this part of the code as anything familiar.
On a pocket calculator the inverse tangent function is straightforward to use in a
similar way as we have written in the code. In Python, however, this function is one
of many that must be imported before use. A lot of functionality 9 is immediately
available to us (from the Python standard library) as we start a new programming
session, but much more functionality exists in additional Python libraries. To
activate functionality from these libraries, we must explicitly import it. In Python,
the atan function is grouped together with many other mathematical functions in a
library module called math. To get access to atan in our program, we may write an
import statement:
from math import atan
Inserting this statement at the top of the program and rerunning it, leads to a new
problem: pi is not defined. The constant pi, representing π, is also available in the
math module, but it has to be imported too. We can achieve this by including both
items atan and pi in the import statement,
from math import atan, pi
With this latter statement in place, we save the code as ball_angle.py:
from math import atan, pi
x = 10.0
# Horizontal position
y = 10.0
# Vertical position
angle = atan(y/x)
print((angle/pi)*180)
This script correctly produces 45.0 as output when executed.
9 https://docs.python.org/3/library/functions.html.
Précédent

- 35/350

Suivant