Creating Modules
00:00
Open IDLE and start a new editor window. In the editor window, define a function named add() that returns the sum of its two parameters. def add(x, y): and then on the next line, indented, return x + y.
00:23
Save the file as adder.py on your computer in a new directory named myproject/.
00:33
Just like you learned a moment ago, adder.py is a Python module. So far so good. Now open another editor window and type the following code: value = add(2, 2) and then on the next line, print(value).
00:58
Save the file as main.py in the same myproject/ folder. That’s important. It must be in the same folder, so make sure to save it in the myproject/ folder on your computer.
01:15
Oops. Okay. When the module runs, you’ll see a NameError displayed in IDLE’s interactive window. The important part here is the last line of the traceback: NameError: Name 'add' is not defined.
01:29
The NameError occurs because add() is defined in adder.py and not in main.py. That’s the file you ran. So if you think a moment, then this error makes sense. How should Python know that you mean the add() function from the adder.py file?
01:46
In order to use add() in main.py, you must first import the module. So let’s do this.
Become a Member to join the conversation.
