Introduction to Python Programming
Line 6 prints integer1’s location, type and value after the call to raw_input Python function id returns the interpreter’s representation of the variable’s location Func-
tion type returns the type of the variable. We print these values again (line 8), after con- verting the string value in integer1 to an integer value. Notice that both the type and the location of variable integer1 change as a result of the statement
integer1 = int( integer1 )
The change underscores the fact that a program cannot change a variable’s type. Instead, the statement causes Python to create a new integer value in a new location and assigns the name integer1 to this location. The location to which integer1 previously referred is no longer accessible. The remainder of the program prints the location type and value for variables integer2 and sum in a similar manner.
2.6 Arithmetic
Many programs perform arithmetic calculations. Figure 2.14 summarizes the arithmetic operators. Note the use of various special symbols not used in algebra. The asterisk (*) in- dicates multiplication and the percent sign (%) is the modulus operator that we discuss shortly. The arithmetic operators in Fig. 2.14 are binary operators, (i.e., operators that take two operands). For example, the expression integer1 + integer2 contains the binary operator + and the two operands integer1 and integer2.
Python is an evolving language, and as such, some of its features change over time. Starting with Python 2.2, the behavior of the / division operator will begin to change from “floor division” to “true division.” Floor division (sometimes called integer division), divides the numerator by the denominator and returns the highest integer value that is not greater than the result. For example, dividing 7 by 4 with floor division yields 1 and dividing 17 by 5 with floor division yields 3. Note that any fractional part in floor division is simply discarded (i.e., truncated)—no rounding occurs. True division yields the precise floating-point (i.e., numbers with a decimal point such as 7.0, 0.0975 and 100.12345) result of dividing the numerator by the denominator. For example, dividing 7 by 4 with true divi- sion yields 1.75. Python operation Arithmetic operator Algebraic expression Python expression Addition + f + 7 f + 7 Subtraction – p – c p - c Multiplication * bm b * m Exponentiation ** xy x ** y Division / // (new in Python 2.2) x / y or or x ÷ y x / y x // y Modulus % r mod s r % s Fig. 2.14 Fig. 2.14 Fig. 2.14
Fig. 2.14 Arithmetic operators.
x y --
In prior versions, Python contained only one operator for division—the / operator. The behavior (i.e., floor or true division) of the operator is determined by the type of the operands. If the operands are both integers, the operator performs floor division. If one or both of the operands are floating-point numbers, the operator performs true division.
The language designers and many programmers disliked the ambiguity of the / oper- ator and decided to create two operators for version 2.2—one for each type of division. The
/ operator performs true division and the // operator performs floor division. However, this decision could introduce errors into programs that use older versions of Python. There- fore, the designers came up with a compromise: Starting with Python 2.2 all future 2.x ver- sions will include two operators, but if a program author wants to use the new behavior, the programmer must state their intention explicitly with the statement
from __future__ import division
After Python sees this statement, the / operator performs true division and the // operator performs floor division. The interactive session in Fig. 2.15 demonstrates floor division and true division.
We first evaluate the expression 3 / 4. This expression evaluates to the value 0, because the default behavior of the / operator with integer operands is floor division. The expression 3.0 / 4.0 evaluates to 0.75. In this case, we use floating-point operands, so the / operator performs true division. The expressions 3 // 4 and 3.0 // 4.0 evaluate to 0 and 0.0, respectively, because the // operator always performs floor divi- sion, regardless of the types of the operands. Then, in line 13 of the interactive session, we change the behavior of the / operator with the special import statement. In effect, this statement turns on the true division behavior for operator /. Now the expression 3 / 4 evaluates to 0.75. [Note: In this text, we use only the default 2.2 behavior for the / oper- ator, namely floor division for integers (lines 5–6 of Fig. 2.15) and true division for floating-point numbers (lines 7–8 of Fig. 2.15).]
Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more informa- tion.
>>> 3 / 4 # floor division (default behavior) 0
>>> 3.0 / 4.0 # true division (floating-point operands) 0.75
>>> 3 // 4 # floor division (only behavior) 0
>>> 3.0 // 4.0 # floating-point floor division 0.0
>>> from __future__ import division
>>> 3 / 4 # true division (new behavior) 0.75
>>> 3.0 / 4.0 # true division (same as before) 0.75
Fig. 2.15 Fig. 2.15Fig. 2.15
Portability Tip 2.1
In Python version 3.0 (due to be released no sooner than 2003), the / operator can perform only true division. After the release of version 3.0, programmers need to update applications to compensate for the new behavior. For more information on this future change, see
python.sourceforge.net/peps/pep-0238.html 2.1
Python provides the modulus operator (%), which yields the remainder after integer division. The expression x % y yields the remainder after x is divided by y. Thus, 7 % 4 yields 3 and 17 % 5 yields 2. This operator is most commonly used with integer operands, but also can be used with other arithmetic types. In later chapters, we discuss many inter- esting applications of the modulus operator, 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.) [Note: The modulus operator can be used with both integer and floating-point numbers.]
Arithmetic expressions in Python must be entered into the computer in straight-line form. Thus, expressions such as “a divided by b” must be written as a / b, so that all con- stants, variables and operators appear in a straight line. The algebraic notation
is generally not acceptable to compilers or interpreters, although some special-purpose software packages do exist that support more natural notation for complex mathematical expressions.
Parentheses are used in Python expressions in much the same manner as in algebraic expressions. For example, to multiply a times the quantity b + c, we write
a * (b + c)
Python applies the operators in arithmetic expressions in a precise sequence deter- mined by the following rules of operator precedence, which are generally the same as those followed in algebra:
1. Expressions contained within pairs of parentheses are evaluated first. Thus, paren- theses may force the order of evaluation to occur in any sequence desired by the programmer. Parentheses are said to be at the “highest level of precedence.” In cases of nested, or embedded, parentheses, the operators in the innermost pair of parentheses are applied first.
2. Exponentiation operations are applied next. If an expression contains several ex- ponentiation operations, operators are applied from right to left.
3. Multiplication, division and modulus operations are applied next. If an expression contains several multiplication, division and modulus operations, operators are applied from left to right. Multiplication, division and modulus are said to be on the same level of precedence.
4. Addition and subtraction operations are applied last. If an expression contains sev- eral addition and subtraction operations, operators are applied from left to right. Addition and subtraction also have the same level of precedence.
a b ---
Not all expressions with several pairs of parentheses contain nested parentheses. For example, the expression
a * (b + c) + c * (d + e)
does not contain nested parentheses. Rather, the parentheses in this expression are said to be “on the same level.”
When we say that certain operators are applied from left to right, we are referring to the associativity of the operators. For example, in the expression
a + b + c
the addition operators (+) associate from left to right. We will see that some operators as- sociate from right to left.
Figure 2.16 summarizes these rules of operator precedence. This table will be expanded as additional Python operators are introduced. A complete precedence chart is included in the appendices.
Now let us consider several expressions in light of the rules of operator precedence. Each example lists an algebraic expression and its Python equivalent. The following is an example of an arithmetic mean (average) of five terms:
Algebra:
Python: m = ( a + b + c + d + e ) / 5
The parentheses are required because division has higher precedence than addition and, hence, the division will be applied first. The entire quantity ( a + b + c + d + e ) is to be divided by 5. If the parentheses are erroneously omitted, we obtain a + b + c + d +
e / 5, which evaluates incorrectly as
The following is an example of the equation of a straight line: Algebra:
Python: y = m * x + b
No parentheses are required. The multiplication is applied first, because multiplication has a higher precedence than addition.
The following example contains modulus (%), multiplication, division, addition and subtraction operations: Algebra: Python: z = p * r % q + w / x - y m a+b+c+d+e 5 --- = a b c d e 5 --- + + + + y = mx+b z = pr%q+w/x–y 1 2 4 3 5
The circled numbers under the statement indicate the order in which Python applies the operators. The multiplication, modulus and division are evaluated first, in left-to-right or- der (i.e., they associate from left to right) because they have higher precedence than ad- dition and subtraction. The addition and subtraction are applied next. These are also applied left to right. Once the expression has been evaluated, Python assigns the result to variable z.
To develop a better understanding of the rules of operator precedence, consider how a second-degree polynomial is evaluated:
y = a * x ** 2 + b * x + c
The circled numbers under the statement indicate the order in which Python applies the op- erators.
Suppose variables a, b, c and x are initialized as follows: a = 2, b = 3, c = 7 and
x = 5. Figure 2.17 illustrates the order in which the operators are applied in the preceding second-degree polynomial.
The preceding assignment statement can be parenthesized with unnecessary paren- theses, for clarity, as
y = ( a * ( x ** 2 ) ) + ( b * x ) + c Good Programming Practice 2.7
As in algebra, it is acceptable to place unnecessary parentheses in an expression to make the expression clearer. These parentheses are called redundant parentheses. Redundant paren- theses are commonly used to group subexpressions in a large expression to make that expres- sion clearer. Breaking a large statement into a sequence of shorter, simpler statements also
promotes clarity. 2.7
Operator(s) Operation(s) Order of Evaluation (Precedence)
( ) Parentheses Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.
** Exponentiation Evaluated second. If there are several, they are evalu- ated right to left.
* / // % Multiplication Division Modulus
Evaluated third. If there are several, they are evaluated left to right. [Note: The // operator is new in version 2.2]
+ - Addition
Subtraction
Evaluated last. If there are several, they are evaluated left to right.
Fig. 2.16 Fig. 2.16Fig. 2.16
Fig. 2.16 Precedence of arithmetic operators.
1 4 3
2.7 String Formatting
Now that we have investigated numeric values, let us turn our attention to strings. Unlike some other popular programming languages, Python provides strings as a built-in data type, thereby enabling Python programs to perform powerful text-based operations easily. We have already learned how to create a string by placing text inside double quotes ("). Python strings can be created in a variety of other ways, as Fig. 2.18 demonstrates.
Line 4 creates a string with the familiar double-quote character ("). If we want such a