Skip to content

Learning Python: Day 21

Storing your functions in modules

  • functions separate blocks of code, and make your code easier to follow with descriptive names
  • module – a separate file where you can store your functions
  • import statement – tells Python to make the code in a module available in the currently running program file
  • using modules allows you to share and reuse functions in many different programs
  • can use libraries of functions other programmers have written

Importing an entire module

  • module – is a file ending in .py that contains code you want to import into your program
  • let’s make a module that contains the function make_pizza()
  • to make module, we’ll remove everything from the file pizza.py, except for make_pizza()

pizza.py

def make_pizza(size, *toppings):

….”””Summarize the pizza we are about to make.”””

….print(f”\nMaking a {size}-inch pizza with the following toppings:”)

….for topping in toppings:

……..print(f”-{topping}”)

  • make a separate file called making_pizzas.py in the same directory as pizza.py
  • this file imports the module and makes calls to make_pizza()

making_pizzas.py

import pizza

pizza.make_pizza(16, ‘pepperoni’)

pizza.make_pizza(12, ‘mushrooms’, ‘green peppers’, ‘extra cheese’)

  • line import pizza tells Python to open the file pizza.py and copy all its functions into this program
  • any function defined in pizza.py will now be available in making_pizzas.py
  • enter the name fo the module you imported, pizza, followed by the name of the function, make_pizza(), separated by a dot to call a function from an imported module

Making a 16-inch pizza with the following toppings:

– pepperoni

Making a 12-inch pizza with the following toppings:

– mushrooms

– green peppers

– extra cheese

  • first approach to importing, in which you write import followed by the name fo the module, makes every function from the module available in your program
  • if used to import an entire model name modeul_name.py, each function is available

module_name.function_name()

End of study session.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *