To create your own Python module, follow these steps:

  1. Open Notepad or any other text editor.
  2. Type the following code in the text editor:
# Variables to import later
length, width = 5, 10

# Functions to import later
def printInfo(name, age):
  print('{} is {} years old.'.format(name, age))
  1. Save the file with a name of your choice, but with a .py extension. For example, you could save it as 'mymodule.py'.

  2. Open Jupyter Notebook.

  3. In a new notebook cell, type ' %run mymodule.py' (replace 'mymodule' with the name you chose in step 3) and run the cell. This will execute the code in the module and make the variables and functions available for use in the notebook.

  4. In a new cell, type 'print(length, width)' and run the cell. This will print the values of the variables 'length' and 'width', which were defined in the module.

  5. In another new cell, type 'printInfo('Chan Taiman', 37)' and run the cell. This will call the function 'printInfo' from the module and print the output 'Chan Taiman is 37 years old.'

  6. To import the module, start a new cell and type 'import mymodule' (replace 'mymodule' with the name you chose in step 3). This will import the module and make its variables and functions available for use in the notebook.

  7. To use the variables and functions from the module, you can now refer to them using the module name. For example, you can type 'print(mymodule.length, mymodule.width)' to print the values of the variables 'length' and 'width', or 'mymodule.printInfo('Chan Taiman', 37)' to call the function 'printInfo' from the module.

Example 2.4: Restarting the Kernel and Using Import

  1. Restart the kernel in Jupyter Notebook.
  2. Do NOT use the '%run' command to run the module.
  3. Instead, use the 'import mymodule' statement at the beginning of your notebook cell.
  4. Modify your code to use the module's variables and functions as shown in the previous step (e.g., 'mymodule.length', 'mymodule.printInfo').
Python Module Creation: A Step-by-Step Guide

原文地址: http://www.cveoy.top/t/topic/lfrD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录