
Importing a Module
To access functions and constants from the math module, you must first import it into your Python script using theimport keyword. Although the import statement can be placed anywhere in your code, it must appear before you use any functions or variables from the module. Here’s how to import and use the math module:
Remember that the
math.sin function expects the angle in radians. To compute the sine of 90 degrees, convert the angle using math.radians, like so: math.sin(math.radians(90)).sin and pi are referenced via the math namespace, which keeps them separate from your program’s global namespace to avoid any naming conflicts.
Importing Specific Entities from a Module
If you prefer to avoid using the module prefix each time you call a function or access a constant, you can import specific entities directly into your namespace using thefrom keyword. For example, to import only pi:
pi to your namespace. To use other functions like sin, you must import them explicitly. You can also import multiple entities by listing them separated by commas:
Importing All Entities
Another approach is to import all the names from a module using an asterisk (*). This allows you to use the module’s entities without the module name prefix:
Using Aliases to Avoid Naming Conflicts
If a module’s name or an imported entity conflicts with an existing name in your code, or if you prefer a shorter name for ease of use, you can assign an alias using theas keyword. For example: