Many programs perform arithmetic calculations. The following table summarizes the arithmetic operators, which include some symbols not used in algebra.
*
)Rather than algebra’s center dot (·
), Python uses the asterisk (*) multiplication operator:
In [1]: 7 * 4
Out[1]: 28
**
)The exponentiation (**) operator raises one value to the power of another:
In [2]: 2 ** 10
Out[2]: 1024
To calculate the square root, you can use the exponent 1/2
(that is, 0.5
):
In [3]: 9 ** (1 / 2)
Out[3]: 3.0
/
) vs. Floor Division (//
)True division (/) divides a numerator by a denominator and yields a floating-point number with a decimal point, as in:
In [4]: 7 / 4
Out[4]: 1.75
Floor division (//) divides a numerator by a denominator, yielding the highest integer that’s not greater than the result. Python truncates (discards) the fractional part:
In [5]: 7 // 4
Out[5]: 1
In [6]: 3 // 5
Out[6]: 0
In [7]: 14 // 7
Out[7]: 2
In true division, -13
divided by 4
gives -3.25
:
In [8]: -13 / 4
Out[8]: -3.25
Floor division gives the closest integer that’s not greater than -3.25
—which is -4
:
In [9]: -13 // 4
Out[9]: -4
Dividing by zero with /
or //
is not allowed and results in an exception—a sign that a problem occurred:
In [10]: 123 / 0
-------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-10-cd759d3fcf39> in <module>()
----> 1 123 / 0
ZeroDivisionError: division by zero
Python reports an exception with a traceback. This traceback indicates that an exception of type ZeroDivisionError
occurred—most exception names end with Error
. In interactive mode, the snippet number that caused the exception is specified by the 10
in the line
<ipython-input-10-cd759d3fcf39> in <module>()
The line that begins with ----> 1
shows the code that caused the exception. Sometimes snippets have more than one line of code—the 1
to the right of ---->
indicates that line 1 within the snippet caused the exception. The last line shows the exception that occurred, followed by a colon (:
) and an error message with more information about the exception:
ZeroDivisionError: division by zero
The “Files and Exceptions” chapter discusses exceptions in detail.
An exception also occurs if you try to use a variable that you have not yet created. The following snippet tries to add 7
to the undefined variable z
, resulting in a NameError
:
In [11]: z + 7
-------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-11-f2cdbf4fe75d> in <module>()
----> 1 z + 7
NameError: name 'z' is not defined
Python’s remainder operator (%) yields the remainder after the left operand is divided by the right operand:
In [12]: 17 % 5
Out[12]: 2
In this case, 17
divided by 5
yields a quotient of 3
and a remainder of 2
. This operator is most commonly used with integers, but also can be used with other numeric types:
In [13]: 7.5 % 3.5
Out[13]: 0.5
In the exercises, we use the remainder operator for applications such as determining whether one number is a multiple of another—a special case of this is determining whether a number is odd or even.
Algebraic notations such as
generally are not acceptable to compilers or interpreters. For this reason, algebraic expressions must be typed in straight-line form using Python’s operators. The expression above must be written as a / b
(or a // b
for floor division) so that all operators and operands appear in a horizontal straight line.
Parentheses group Python expressions, as they do in algebraic expressions. For example, the following code multiplies 10
times the quantity 5 + 3
:
In [14]: 10 * (5 + 3)
Out[14]: 80
Without these parentheses, the result is different:
In [15]: 10 * 5 + 3
Out[15]: 53
The parentheses are redundant (unnecessary) if removing them yields the same result.
Python applies the operators in arithmetic expressions according to the following rules of operator precedence. These are generally the same as those in algebra:
Expressions in parentheses evaluate first, so parentheses may force the order of evaluation to occur in any sequence you desire. Parentheses have the highest level of precedence. In expressions with nested parentheses, such as (a / (b - c))
, the expression in the innermost parentheses (that is, b - c
) evaluates first.
Exponentiation operations evaluate next. If an expression contains several exponentiation operations, Python applies them from right to left.
Multiplication, division and modulus operations evaluate next. If an expression contains several multiplication, true-division, floor-division and modulus operations, Python applies them from left to right. Multiplication, division and modulus are “on the same level of precedence.”
Addition and subtraction operations evaluate last. If an expression contains several addition and subtraction operations, Python applies them from left to right. Addition and subtraction also have the same level of precedence.
We’ll expand these rules as we introduce other operators. For the complete list of operators and their precedence (in lowest-to-highest order), see
https:/ / docs.python.org/ 3/ reference/ expressions.html#operator-precedence
When we say that Python applies certain operators from left to right, we are referring to the operators’ grouping. For example, in the expression
a + b + c
the addition operators (+
) group from left to right as if we parenthesized the expression as (a + b) + c
. All Python operators of the same precedence group left-to-right except for the exponentiation operator (**
), which groups right-to-left.
You can use redundant parentheses to group subexpressions to make the expression clearer. For example, the second-degree polynomial
y = a * x ** 2 + b * x + c
can be parenthesized, for clarity, as
y = (a * (x ** 2)) + (b * x) + c
Breaking a complex expression into a sequence of statements with shorter, simpler expressions also can promote clarity.
Each arithmetic operator may be used with integers and floating-point numbers. If both operands are integers, the result is an integer—except for the true-division (/
) operator, which always yields a floating-point number. If both operands are floating-point numbers, the result is a floating-point number. Expressions containing an integer and a floating-point number are mixed-type expressions—these always produce floating-point numbers.
(Multiple Choice) Given that y = ax3 + 7, which of the following is not a correct statement for this equation?
y = a * x * x * x +
7
y = a * x **
3 +
7
y = a * (x * x * x) +
7
y = a * x * (x * x +
7
Answer: d is incorrect.
(True/False) In nested parentheses, the expression in the innermost pair evaluates last.
Answer: False. The expression in the innermost parentheses evaluates first.
(IPython Session) Evaluate the expression 3 * (4 - 5)
with and without parentheses. Are the parentheses redundant?
Answer:
In [1]: 3 * (4 - 5)
Out[1]: -3
In [2]: 3 * 4 - 5
Out[2]: 7
The parentheses are not redundant—if you remove them the resulting value is different.
(IPython Session) Evaluate the expressions 4 ** 3 ** 2
, (4 ** 3) ** 2
and 4 ** (3 ** 2)
. Are any of the parentheses redundant?
Answer:
In [3]: 4 ** 3 ** 2
Out[3]: 262144
In [4]: (4 ** 3) ** 2
Out[4]: 4096
In [5]: 4 ** (3 ** 2)
Out[5]: 262144
Only the parentheses in the last expression are redundant.