How It Works

When you invoke chS.py with just the in_fridge function defined, you won't see any output. However, the function will be defined, and it can be invoked from the interactive Python session that you've created.

To take advantage of the in_fridge function, though, you have to ensure that there is a dictionary called fridge with food names in it. In addition, you have to have a string in the name wanted_food. This string is how you can ask, using in_fridge, whether that food is available. Therefore, from the interactive session, you can do this to use the function:

>>> fridge = {'apples':10, 'oranges':3, 'milk':2} >>> wanted_food = 'apples' >>> in_fridge() 10

>>> wanted_food = 'oranges' >>> in_fridge() 3

>>> wanted_food = 'milk' >>> in_fridge() 2

This is more than just useful — it makes sense and it saves you work. This grouping of blocks of code under the cover of a single name means that you can now simplify your code, which in turn enables you to get more done more quickly. You can type less and worry less about making a mistake as well.

Functions are a core part of any modern programming language, and they are a key part of getting problems solved using Python.

Functions can be thought of as a question and answer process when you write them. When they are invoked, a question is often being asked of them: "how many," "what time," "does this exist?" "can this be changed?" and more. In response, functions will often return an answer—a value that will contain an answer, such as True, a sequence, a dictionary, or another type of data. In the absence of any of these, the answer returned is the special value None.

Even when a function is mainly being asked to just get something simple done, there is usually an implied question that you should know to look for. When a function has completed its task, the questions "Did it work?" or "How did it work out?" are usually part of how you invoke the function.

Was this article helpful?

0 0

Post a comment