Page 228 -
P. 228

modular programming


           So how do you create a module...?


           Remember: a module is just a file containing some Python code. So, take the
           code that you want to share out of the gym_pos.py file:




                           def save_transaction(price, credit_card, description):
                               file = open("transactions.txt", "a")





           Then save this code in a file called transactions.py. You have just
           created a new module.



          ...and how do you use it?

           Once you’ve created the module, you then need to tell the programs to use it.
           When you were using library code you needed to import it. You do the same
           thing with your own modules. So, instead of using library code from the
           Standard Python Library, you’re really just using library code that you’ve
           written yourself. You can add this line to the top of each of your programs:


                                         This means “run the code in

           This line needs to be added   the named module."
           to any program that uses the                                  This means “treat everything inside
          “transactions.py” module.   from transactions import *         the module as if it is code within
                                                                         your program."




           With this line, you are telling Python that you want to run the code in the
           transactions.py file and this allows you to access whatever code the
           module contains as if  it is just part of  your program.

           It’s time to fix the programs.









                                                                                      you are here 4    193
   223   224   225   226   227   228   229   230   231   232   233