You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Modules are a way to store and install reusable Python code. You can create your own modules by defining a set of functions that may be useful to other developers, and packaging these functions in a specific way so the other developers can download and easily integrate your code into their projects.
5
+
6
+
To define a module, lets create a new file called ```fibo.py``` in your current directory. Lets add the following code:
7
+
8
+
```python
9
+
deffib(n): # write Fibonacci series up to n
10
+
a, b =0, 1
11
+
while a < n:
12
+
print(a, end='')
13
+
a, b = b, a+b
14
+
print()
15
+
16
+
deffib2(n): # return Fibonacci series up to n
17
+
result = []
18
+
a, b =0, 1
19
+
while a < n:
20
+
result.append(a)
21
+
a, b = b, a+b
22
+
return result
23
+
```
24
+
25
+
Now that we have some functions defined, how do we access them? Let's open the Python shell (or create a new file), and run/create:
26
+
27
+
```python
28
+
import fibo
29
+
30
+
fibo.fib(10)
31
+
32
+
res = fibo.fib2(10)
33
+
print(res)
34
+
```
35
+
36
+
Now we have created and called our very own Python module! We can also import specific functions instead of the whole module, like this:
37
+
38
+
```python
39
+
from fibo import fib
40
+
41
+
fib(10)
42
+
```
43
+
44
+
In further labs, we will see how you can view the contents of a given module using the dir() functionality.
0 commit comments