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

Code Examples

Оглавление

We now present a couple of code examples to illustrate the use of the elements just discussed. Figure 2.1 illustrates some Python code statements in a file (Fig 2_1 Python code example 1.py).

Description

Figure 2.1 Python Code Example 1

Several details in the Python code in Figure 2.1 are fundamental to writing programs in Python. Lines 1, 3, and 5 have comments that take up an entire line, and line 4 shows an example of a comment that makes a note at the end of a line of code. Line 4 is an assignment statement in which the right-hand side is a value in quotes. The value within quotation marks is a string-type value. When the code in line 4 executes, the trip_id variable will be a string. Line 5 illustrates the use of two built-in functions to report the data type of the just created trip_id variable. Specifically, a type function is within a print function. We already used the Python built-in print function in the example presented in Chapter 1. The type function in Python determines the data type of an object. Line 8 of the Python code in Figure 2.1 is an assignment statement in which the right-hand side is a number. When the code in line 8 executes, the trip_seconds variable will be an integer. The type function is also in line 9, which reports the data type for the just constructed trip_seconds variable. The output of these code statements is in Figure 2.2.

Description

Figure 2.2 Output from Execution of Python Code in Figure 2.1

Examining the output shown in Figure 2.2, we see that the data type for the trip_id variable is a string and the data type for the trip_seconds variable is an integer. The output messages specifically indicate that trip_id is of class “str” and that trip_seconds is of class “int.”

Our next example is like the first example but illustrates the construction of float and Boolean variables. Line 2 in Figure 2.3 assigns the value 1.1 to the variable trip_miles and line 3 prints out the data type of the trip_miles variable. Line 6 assigns the value True to the variable trip_completed. Note that True is a Python keyword shown in Table 2.1 and is in blue font in Figure 2.3. Also note that there are not parentheses around True, because if there were, it would be a string instead of the logical value True. Line 7 then prints out the data type of the trip_completed variable.

Description

Figure 2.3 Python Code Example 2

Examining the output shown in Figure 2.4, we see that the data type for the trip_miles variable is in fact a float and the data type for the trip_miles variable is a Boolean.

Description

Figure 2.4 Output from Executing Code Example 2

Introduction to Python Programming for Business and Social Science Applications

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