Skip to content

Commit 54b055d

Browse files
Zachary T KesselZachary T Kessel
authored andcommitted
Merge branch 'master' of https://github.com/CoderDojoTC/python
2 parents 0e5dc55 + 8609cf1 commit 54b055d

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

docs/intermediate/07-modules.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,47 @@
11
# Introduction to Intermediate Python
22

33
# Modules
4+
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+
def fib(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+
def fib2(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.
45+
46+
47+
* Lab heavily inspired (code credited to): [https://docs.python.org/3/tutorial/modules.html](https://docs.python.org/3/tutorial/modules.html)

0 commit comments

Comments
 (0)