Importing a function
Contents
Importing a function#
There’s only a few functions built into Python. You may notice that there’s no trigonometry functions. Python’s capabilities can be massively extended by importing a module. Many very powerful modules are available, but for an example we’ll use the math module. Functions in the module are accessed with a similar syntax to methods. We’ll see ways of shortening this later.
Over the course of the next few weeks we’ll be introducing and using many of the most commonly used modules in python. However, it is not intended that you know or remember every module available. A big part of coding is knowing when to Google to find our whether the thing you want to code has already been written and can be directly used.
Once you know the name of the module you want to use we just the import command. It is best practice that import commands go at the top of any python code. There’s a few different “styles” of using import, for now we’ll just stick with showing how to get to our maths functions, which we’re definitely going to need!
import math # That's it! We now have access to all the functions in the math library
# An example of using the math library to call a trigonometric function:
print(math.cos(math.pi/3))
# Note that this computes cos(x) assuming x in "radians". If you wanted to do cos of 30 degrees you would do:
num_degrees = 60
print(math.cos(num_degrees * (2*math.pi / 360.)))
0.5000000000000001
0.5000000000000001
Note that to access things within the math library we do math.XXX. We actually used one function and one variable from the math library in the call above. math.cos is a function to compute cos(x) and math.pi is the constant \(\pi\).
I can use Google to find the documentation of the math module here:
https://docs.python.org/3/library/math.html
which tells me all the things in that library.
Exercise#
Use the math library to compute \(\cos^2 \theta + \sin^2 \theta\) for many values of \(\theta\). What are these all equal to? Did you already know that?