- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
- How does variable scopes work in Python Modules?
- How do we use easy_install to install Python modules?
- How do Python dictionary hash lookups work?
- How do nested functions work in Python?
- How do I get IntelliJ to recognize common Python modules?
- How do backslashes work in Python Regular Expressions?
- How do cookies work in Python CGI Programming?
- How do wind turbines work?
- How do bitcoin ATMs work?
- How do AC locomotives work?
- How do exceptions work in C++
- How do interfaces work in C#?
- How do arrays work in C#?