Читать книгу Introduction to Python Programming for Business and Social Science Applications - Frederick Kaefer - Страница 65

Using Modules of Python Code

Оглавление

As discussed in Chapter 1, Guido van Rossum’s vision for Python was that users could create their own coding modules and make those coding modules available to others. The previous section detailed how to create functions and to use them in Python code. In addition to using functions created within a Python file, you can use functions that others develop that are in other files. There are numerous modules available for Python, and users can even create their own. There are also built-in modules that come with Python. For example, the random module lets you generate pseudo-random numbers, which you can use to add an element of chance to a program or generate simulation data. Additionally, the fractions module enables the programmer to perform arithmetic on fractions stored as strings like “4/5,” and the math module provides functions like sin, cos, and tan. We explain and give an example of using several useful packages later in this book. A searchable index of Python modules is available at https://pypi.org/.

We use functions in modules by importing modules. The Python code in Figures 2.28 and 2.29 illustrate how you accomplish this.

Description

Figure 2.28 Module with find_average Function

Description

Figure 2.29 Find Average using Function in Module

Figure 2.28 is a Python module that has the find_average function defined within it. The Python module name uses extra underscore characters so that it does not have any spaces in it. This is important, because when you import Python modules, the file name referenced can’t have any spaces in it. Figure 2.29 shows how to import and use a function from a different Python code module. Line 1 of Figure 2.29 uses the import statement to import the code in the Python module and creates the alias “fam” for the module. Line 9 of the Python code in Figure 2.29 uses the function in the imported module by referencing the alias, which indicates that the function is in that module. Figure 2.30 shows the output of executing the code in Figure 2.29, showing the same output as seen in Figure 2.27. We will make extensive use of Python code modules beginning in Chapter 4.


Figure 2.30 Output from Execution of Code using Function in Module

Introduction to Python Programming for Business and Social Science Applications

Подняться наверх