Importing a Module
For the next few examples, we’ll be working with the math module, which is one of Python’s built-in modules. This specific module has functions and variables to help us with any problem related to math, whether it’s rounding, calculating pi, or many other math-related tasks. For this first cell, we’re going to import the entire math module and its contents:
# import the entire math module import math print( math.floor(2.5) ) # rounds down print( math.ceil(2.5) ) # rounds up print(math.pi)
Go ahead and run the cell. We’ll get an output of “2”, “3”, and “3.14”. When we imported math, we were able to access all of math’s functions, variables, and classes. In this example, we call two functions and one variable that are stored within the math module. In order to import the entire module and its contents, you simply put the keyword import before the name of the module. Whenever you’d like to access any of its contents, you need to use dot syntax. Now we can use any of math’s code.
Importing Only Variables and Functions
When you know that you won’t need to use the entire module, but rather a couple functions or variables, you can import them directly. You should always make sure you import only what you need. In the previous cell, we imported the entire math module; however, we didn’t really need to, as we only used two functions and a variable from it. To import something specifically, you’ll need to include the from keyword and the name of what you’d like to import:
# importing only variables and functions rather than an entire module, better efficiency from math import floor, pi print( floor(2.5) )
# print( ceil(2.5) ) will cause error because we only imported floor and pi, not ceil and not all of math
print(pi)
Go ahead and run the cell. We’ll get an output of “2” and “3.14”. The import statement changes slightly when importing specific parts of the module. To separate multiple imports from a single module, you use a comma. We comment out the print statement for ceil because it won’t work. We only imported floor and pi directly, but not the ceil function. Notice that we don’t need to reference the math module with dot syntax before the names either. This is because we imported the floor function and pi variable directly, so we can now reference them without using dot syntax. Remember to only import what you need.
Note you can import classes from modules the same way as earlier; simply use the name of the class.
ChAptEr 9 AdvAnCEd topiCs ii: ComplExity
Do'stlaringiz bilan baham: |