1 Risposta
+ 1
in Python the import statement is used to bring in modules (built-in or external) so you can use their functions classes and variables. Here are the main ways you can use it:
1) Import a whole module
import math
print(math.sqrt(16))
2) Import with an alias (shorter name)
import numpy as np
arr = np.array([1, 2, 3])
3) Import specific functions or classes
from math import sqrt, pi
print(sqrt(25))
print(pi)
4) Import everything (not recommended)
from math import *
print(sin(0))
5) Dynamic import inside code
module_name = "random"
random_module = __import__(module_name)
print(random_module.randint(1, 10))
Best practice: Use specific imports or aliases so your code stays clean and readable. Good Luck!