NB: Importing Functions

Importing

Calling a function from the “math” library is straightforward:

  1. Import Python’s Math library with the command import math
  2. Call methods from the imported math object 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:

import math # Typically best to put this line of code at the TOP of the file
math.sqrt(12)
3.4641016151377544
math.floor(2.5) # returns largest whole number less than the argument
2

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 file
random.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-100
18

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 sqrt

This 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 sqrt
sqrt(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 SquareRoot
SquareRoot(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