Introduction to Python Programming for Business and Social Science Applications. Frederick Kaefer. Читать онлайн. Newlib. NEWLIB.NET

Автор: Frederick Kaefer
Издательство: Ingram
Серия:
Жанр произведения: Зарубежная деловая литература
Год издания: 0
isbn: 9781544377452
Скачать книгу
correct results. Figure 2.13 prints out the message that the average of 4 and 8 is 8! The true average of 4 and 8 is 6 and results when you add the two numbers together prior to dividing the sum by 2. Reviewing the order of operations discussed earlier, we need to put parentheses around the addition of first_number and second_number to correct this error, which adds the numbers together first. As it is now (without those parentheses), we first divide second_number by 2 (resulting in the value 4) and then add that result to first_number (resulting in a final value of 8), which is incorrect. To ensure that code executes with the correct results, programmers need to develop test cases and verify that the expected outcomes for each test case do in fact occur.

       Stop, Code, and Understand!

      SCU 2.5 Logic Errors

      Download the file “SCU 2_5.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 execute the program to see that it runs but does not have the correct result. Add parentheses around the two values being added in the assignment statement in the line indicated to resolve the issue. Execute the modified program to verify that the revised code runs and produces the correct result.

      Lessons learned: In this section, we learned there are three types of errors in Python: syntax errors, exceptions, and logic errors. Syntax errors are the easiest types of errors to resolve and result when we do not follow the rules for correctly specifying Python code. Exceptions are the types of errors that occur when we attempt to do something in Python that is not possible or not allowed. Logic errors occur when code executes without terminating with an error message but has incorrect results. We will encounter each of these error types often as we develop code but will learn and become better at diagnosing them and improving our code.

      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.

      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.

      A screenshot displays the Python code in a Python file for adding up trip costs.Description

      Figure 2.14 Python Code to Add Up Trip Costs

      A screenshot displays the output from the execution of a Python code for adding up trip costs.Description

      Figure 2.15 Output from Execution of Python Code to Add Up Trip Costs

       Stop, Code, and Understand!

      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.

A screenshot displays two lines of code in Python IDLE editor as follows. Line 1: # Add function call around the string to print the length. Hint: the function is called ‘len’. Line 2: print(“length of string”).

      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