
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How do Python modules work?
Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).
When you import a module, say `hello`, the interpreter searches for a file named hello.py in the directory containing the input script and then in the list of directories specified by the environment variable PYTHONPATH.
Create a file called fibonacci.py and enter the following code in it:
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
Now open your terminal and use cd command to change to the directory containing this file and open the Python shell. Enter the following statements:
>>> 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]
You imported the module and used its functions.
- Related Articles
- How does variable scopes work in Python Modules?
- How do we use easy_install to install Python modules?
- How do I get IntelliJ to recognize common Python modules?
- How do I share global variables across modules in Python?
- How do nested functions work in Python?
- How do Python dictionary hash lookups work?
- How do list comprehensions in Python work?
- How do cookies work in Python CGI Programming?
- How do backslashes work in Python Regular Expressions?
- How to use remote python modules?
- How do muscles work?
- How do lungs work?
- How do modules improve monolithic and micro kernel approaches?
- How do map, reduce and filter functions work in Python?
- How do you dynamically add Python modules to a package while your programming is running?
