Introduction to Python Programming for Business and Social Science Applications. Frederick Kaefer
Чтение книги онлайн.
Читать онлайн книгу Introduction to Python Programming for Business and Social Science Applications - Frederick Kaefer страница 13
Functions
Python Built-in Functions
Python comes with over 60 built-in functions (Python Software Foundation, 2019, “Built-in Functions”). For example, the max() function will return the maximum value of a list of numbers. If you execute the Python code statement “max(1, 2),” the value 2 is returned. A list of built-in functions may be found at https://docs.python.org/3/library/functions.html. Table 2.6 presents some of the commonly used built-in functions along with a brief description of each.
Table 2.6
We already have made use of the type function in the examples shown in Figures 2.1 and 2.3 earlier in the chapter. An example from our Taxi Trips data set will help to illustrate the usage of some of the other Python built-in functions. Referring to Table 1.2 and Table 1.3, several fields in the Taxi Trips data set involve taxi trip cost-related information (Fare and Tips). These fields have the data type “Money” in the SODA API (which is discussed later in the textbook), but there is not a Python basic data type “Money.” If we assign the value $4.75 to a variable, an error will occur, because the Python interpreter doesn’t recognize the usage of a dollar sign symbol. We will address this in the next chapter after we go further in depth with compound data types and strings.
For now, let us examine a Python program that prompts the user to enter in amounts for the taxi fare and tip amount for a taxi trip. The Python code in Figure 2.14 does this in lines 3 and 4 and then reports back to the user the amounts entered (in lines 5 and 6) as well as the data types of the variables (in lines 7 and 8). Note that code lines that span more than one physical line in the file have special symbols on the left-hand side in Figure 2.14. The output of these statements is in Figure 2.15. The data types for each of the variables are strings (even though the values entered appear to be numbers). In order to add these two values together, we must convert the values to a data type that supports addition. Line 11 of the code in Figure 2.14 shows one way to do this, by using the float built-in function to convert the string data-type representations of the numeric values into float data-type values and then adding those values and assigning the result of the addition to the variable trip_total. The trip_total variable will be a float data-type variable. An additional conversion is necessary to report the result back to the user. As we saw in Figures 2.10 and 2.11, if we try to combine two different types with the “+” operator, a TypeError exception will result.
When we use the “+” operator with two or more string data-type arguments, we concatenate the string components into a larger string. The string operation concatenation combines multiple strings into one string. For example, concatenating the two strings “Hey,” and “Taxi!” and assigning the result to a variable would be performed using the statement variable_name = “Hey,” + “Taxi!” Line 12 of the Python code in Figure 2.14 uses the str built-in function to convert the trip_total float value into a string and then uses the “+” operator to concatenate the “$” character with the string value. The last line of the output in Figure 2.18 displays the outcome of this print statement.
Figure 2.14 Python Code to Add Up Trip Costs
Figure 2.15 Output from Execution of Python Code to Add Up Trip Costs
SCU 2.6 Use a Built-in Function
Download the file “SCU 2_6.py” from the companion website and save it either on your computer or on a removable storage device. Open the file in the Python IDLE editor and add a function call around the string to print the length. Hint: Use the Python built-in function len. Execute the modified program after the change to verify that the revised code runs and produces the correct result.
User-Defined Functions
We have used small Python code examples up until this point to illustrate basic coding elements of Python. As Python programs become more complex and involve more lines of code, errors can be more difficult to identify, and the code can be more difficult to modify and to test. To address these issues, a programming best practice is to package code into small units, which are often one printed page or less. In Python, we accomplish this by placing portions of code into functions, which are subroutines of code developed to perform specific tasks.
Function Syntax
Functions play a very important role in Python programming, and as we will see in the coming chapters, the use of packages depends significantly on the use of the functions that are within those packages. To thoroughly understand how functions work, we need to carefully examine function syntax. We show the syntax for defining a function in Python in Figure 2.16.
Figure 2.16 Python Function Syntax
Syntax specifications involve several prominent features, including Python keywords in bold font, user-specified information in italicized font, and optional components specified within square brackets. The first line of every function definition in Python begins with the keyword def, followed by the function name and a set of parentheses in which you can specify an optional set of parameters, and then ends with a colon. The indented code statements that follow are part of the function. Optionally, a function can return one or more values. If you return more than one value, you need to separate each value with a comma. The specification of the function ends when a nonindented line of code occurs or if you reach the end of the file. We show a flowchart of the logic in using a function in Figure 2.17 to help visualize how a function works.
Figure