import math # Typically best to put this line of code at the TOP of the file
NB: 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
math
object using “dot” notation, that is,. (any parameters).
For example:
12) math.sqrt(
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:
12) math.sqrt(
3.4641016151377544
2.5) # returns largest whole number less than the argument math.floor(
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
# will return a number between 0 and 1 random.random()
0.3599068479674543
1, 100) # this will return a random integer in the range 1-100 random.randint(
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
99) sqrt(
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
65000) SquareRoot(
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.lower() # convert user input to lowercase
string = 0
count for i in range(len(string)):
if string[i] == "a" or string[i] == "e" or \
== "i" or string[i] == "o" or \
string[i] == "u":
string[i] += 1 # increment count
count return count