By the Way: Importing Near the Beginning
A good rule of thumb for importing modules—custom or standard—into your Python
script is to do it at the top of the script. Therefore, in Python scripts, put in all your
import statements after the leading documentation lines.
Try It Yourself: Create and Use a Custom Module in Python
In the following steps, you are going to create a custom module. In essence, you will be
following the seven steps just described to create it, test it, and then move it into
production.
Pretend that you have two great functions. One, called discountp, that shows the
actual price of an item if you give it the original price and the listed discount. The
other function, priceper, shows the price per item when the prices at a store are
shown for a group of items (for example, 3 for $11).
You decide to put these two useful functions into their own module so that you can use
them in several scripts. Next, you determine that shopper would be a good module
name. It is a nice, short name, and it is not a Python keyword. Next, you need to put the
two functions into a file called shopper.py. This is where you start in the following
steps:
- If you have not already done so, power up your Raspberry Pi and log in to the
system. - If you do not have the LXDE GUI started automatically at boot, start it now by typing
startx and pressing Enter. - Open the LXTerminal by double-clicking the LXTerminal icon.
- At the command-line prompt, type nano py3prog/shopper.py and press
Enter. The command puts you into the nano text editor and creates the custom module
shopper.py in the /home/pi/py3prog directory. - Type the following code into the nano editor window, pressing Enter at the end of
each line:
By the Way: Be Careful!
Be sure to take your time here and avoid making typographical errors. You can
make corrections by using the Delete key and the up- and down-arrow keys.
Click here to view code image
def discountp(percentage, price):
return round(price -((percentage /100) * price),2)
def priceper(no_items, price):
return round(price / no_items,2)
- Double-check to make sure you have entered the code into the nano text editor
window as shown above. Make any corrections needed.