Welcome to CodeYourCraft's Python Tutorial! Today, we'll dive into one of the fundamental aspects of Python programming - the import statement. This concept is crucial for organizing your code and utilizing external libraries. Let's get started!
In Python, the import statement allows you to bring modules, packages, or functions from external libraries into your current script. This makes it easier to reuse pre-written code and helps keep your projects organized.
import module_nameUsing the import statement has several benefits:
Let's import a popular Python library, math, which contains functions for mathematical operations.
import math
# Using the imported function
print(math.sqrt(16)) # Output: 4.0š” Pro Tip: If you want to use a specific function from the imported module, you can use the syntax module_name.function_name.
Absolute imports are used when you want to import a module from the top-level package, while relative imports are used when you want to import a module from a sub-package.
import my_package.my_modulefrom . import my_moduleIn the above examples, replace my_package and my_module with your actual package and module names.
You can import multiple modules from a package using the as keyword.
import math as m
print(m.sqrt(16)) # Output: 4.0You can import all functions from a module using the wildcard syntax. However, it's generally discouraged as it may lead to naming conflicts and unintended usage of functions.
import math as m
for name in dir(m):
if not name.startswith('_') and callable(getattr(m, name)):
print(name)This will print all the callable functions in the math module.
What does the `import` statement do in Python?
We hope you enjoyed learning about the import statement in Python! In the next lesson, we'll delve deeper into Python functions. See you there! š