
views
Using the from-import instruction
Find the module. Locate the module that you will be importing. A complete list of built in modules can be found here (v2.7) and here (v3.5).
To import a specific function from a specific module, write: from [module] import [function] This will tell the script you are using a specific function from a specific module. For example, to import the randint function from the random module and print a random number using that function, you would write: from random import randint print(randint(0, 5))
Separate multiple functions from the same module with commas (,). The structure looks like this: from [module] import [function], [otherFunction], [anotherFunction], ... For example, to import the randint and random functions from the random module and print random numbers using these functions, you would write: from random import randint, random print(randint(0, 5)) print(random())
Import entire modules using a * instead of a function name. The structure looks like this: from [module] import * For example, to import the entire random module and then print a random number with its randint function, you would write: from random import * print(randint(0, 5))
Import multiple modules by writing multiple from-import instructions. You should start a new line for each instruction to keep the code readable, although separating them with a ; also works. For example, to import the randint function from the random module and the sqrt function from the math module and then print a result from both functions, you would write: from random import randint from math import sqrt # Would also work, but hard to read: # from random import randint; from math import sqrt print(randint(0, 5)) print(sqrt(25))
Using the import instruction
Find the module. Locate the module that you will be importing. A complete list of built in modules can be found here (v2.7) and here (v3.5).
To import a module, write with the following structure: import [module] For example, to import the random module and then print a random number with its randint function: import random print(random.randint(0, 5))
Separate multiple modules with a comma (,). The structure is: import [module], [otherModule], [anotherModule], ... You can also make multiple import instructions on multiple lines if that appears more legible or makes more sense in your specific case. For example, to import the random and math modules and then print the results of the randint and sqrt functions that are included in these modules, you would write: import random, math print(random.randint(0, 5)) print(math.sqrt(25))
Comments
0 comment