Python có cách đặt định nghĩa trong file và dùng chúng trong script hoặc instance tương tác của interpreter. File như vậy gọi là module; định nghĩa từ module có thể import vào module khác hoặc vào main module (tập biến truy cập được trong script chạy ở top-level và chế độ calculator).
Khi import module, ví dụ hello, interpreter tìm file hello.py trong thư mục chứa script input, sau đó trong danh sách thư mục của biến môi trường PYTHONPATH.
Tạo file fibonacci.py với code:
def fib(n):
# write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n):
# return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
Mở terminal, cd đến thư mục chứa file, mở Python shell. Nhập:
>>> import fibonacci >>> fibonacci.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibonacci.fib2(100) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Bạn đã import module và dùng hàm của nó.