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

Mathematical Expressions

Оглавление

In the previous section, we saw several examples where assignment statements created variables of different data types based on the values assigned to them. In addition to literal values, we use mathematical expressions to assign values to variables. When writing mathematical expressions, we use arithmetic operators, shown in Table 2.4. Arithmetic operators include symbols to add, subtract, multiply, divide, and exponentiate (raise to a power) values.

Table 2.4

When writing mathematical expressions, you must be careful with the order of operations, which follow the PEMDAS rule (Parenthesis first, then Exponentiation, next Multiplication and Division, and then Addition and Subtraction). Figure 2.5 illustrates how adding two numbers and multiplying by a third number can lead to two different results.

Figure 2.6 shows the output that results from the execution of the Python code in Figure 2.5. The first result (result1) of the value 20 reflects the fact that the multiplication of the second and third numbers occurs first before the addition of the first number to the result of the multiplication. The second result (result2) of the value 24 reflects the fact that the addition of the first two numbers occurs before the multiplication of the intermediate result and the third number. This example illustrates why we must be careful when applying mathematical expressions. When in doubt, we can use extra parentheses to make sure that specific calculations occur before others within an expression.

Description

Figure 2.5 PEMDAS Example


Figure 2.6 Output from Execution of PEMDAS Example

Introduction to Python Programming for Business and Social Science Applications

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