Test Your Knowledge: Answers

 

 
  1. The value will be 14, the result of 2 * 7, because the parentheses force the addition to happen before the multiplication.
  2. The value will be 10, the result of 6 + 4. Python’s operator precedence rules are applied in the absence of parentheses, and multiplication has higher precedence than (i.e., happens before) addition, per Table 5-2.
  3. This expression yields 14, the result of 2 + 12, for the same precedence reasons as in the prior question.
  4. Functions for obtaining the square root, as well as pi, tangents, and more, are available in the imported math module. To find a number’s square root, import math and call math.sqrt(N). To get a number’s square, use either the exponent expression X ** 2 or the built-in function pow(X, 2). Either of these last two can also compute the square root when given a power of 0.5 (e.g., X ** .5).
  5. The result will be a floating-point number: the integers are converted up to floating point, the most complex type in the expression, and floating-point math is used to evaluate it.
  6. The int(N) and math.trunc(N) functions truncate, and the round(N, digits) function rounds. We can also compute the floor with math.floor(N) and round for display with string formatting operations.
  7. The float(I) function converts an integer to a floating point; mixing an integer with a floating point within an expression will result in a conversion as well. In some sense, Python 3.0 / division converts too—it always returns a floating-point result that includes the remainder, even if both operands are integers.
  8. The oct(I) and hex(I) built-in functions return the octal and hexadecimal string forms for an integer. The bin(I) call also returns a number’s binary digits string in Python 2.6 and 3.0. The % string formatting expression and format string method also provide targets for some such conversions.
  9. The int(S, base) function can be used to convert from octal and hexadecimal strings to normal integers (pass in 8, 16, or 2 for the base). The eval(S) function can be used for this purpose too, but it’s more expensive to run and can have security issues. Note that integers are always stored in binary in computer memory; these are just display string format conversions.