import math # Typically best to put this line of code at the TOP of the fileNB: Importing Functions
Importing
Calling a function from the “math” library is straightforward:
- Import Python’s Math library with the command
import math - Call methods from the imported
mathobject using “dot” notation, that is,. (any parameters).
For example:
math.sqrt(12)Put all of your import statements at the very top of your code, before anything else, other than any header comments (which you should have).
Here are some example math functions:
math.sqrt(12)3.4641016151377544
math.floor(2.5) # returns largest whole number less than the argument2
Here’s an example using the random library (a class).
import random # Typically best to put this line of code at the TOP of the filerandom.random()# will return a number between 0 and 1 0.3599068479674543
random.randint(1, 100) # this will return a random integer in the range 1-10018
Importing Specific Functions
If you know what specifics function you are going to use from a library, you can import them directly, like so:
from math import sqrtThis has two effects: 1. It reduces the memory used by the library in your program. 2. It allows you to call the function directly, with the object dot notation.
from math import sqrtsqrt(99)9.9498743710662
Aliasing
To avoid having the function name conflict with an existing function in your program,
you can alias the imported function like so:
from math import sqrt as SquareRootSquareRoot(65000)254.95097567963924
Extra
def square(number):
return number * number # square a number
def addTen(number):
return number + 10 # Add 10 to the number
def numVowels(string):
string = string.lower() # convert user input to lowercase
count = 0
for i in range(len(string)):
if string[i] == "a" or string[i] == "e" or \
string[i] == "i" or string[i] == "o" or \
string[i] == "u":
count += 1 # increment count
return count