Python Programming Exercises, Gently Explained
42
running sum result. This variable starts at 0, and while the program loops over each number in the
numbers parameter, each number is added to this running sum. The same is done in
calculateProduct()
, except the result variable starts at 1 and is multiplied by each number.
Special Cases and Gotchas
You might be tempted to use a variable named sum to store the running sum. However, in
Python this name is already used for the built-in sum() function. Reusing this name for a local
variable means we’d lose the ability to call the original sum() function for the rest of the function’s
code because we have overwritten sum to the value we put in it rather than Python’s sum() function.
You want to avoid reusing the names of Python’s built-in functions by overwriting them, as it could
cause odd bugs in your code. Some commonly overwritten Python names are all, any, date,
email
, file, format, hash, id, input, list, min, max, object, open, random, set, str,
sum
, test, and type. Don’t use these names for your own variables.
Also, the sum of an empty list of numbers should be 0. The product of an empty list of numbers
should be 1. When calculating the product of several numbers, begin the running product result at 1
and not 0. If you start it at 0, all multiplications result in 0 and your calculateProduct()
function will return 0 every time. In mathematics, the numbers 0 and 1 are called the
additive identity
and
multiplicative identity, respectively. Adding the additive identity (0) to a number results in that same
number, while multiplying the multiplicative identity (1) with a number results in that same number.
For example, 12 + 0 is just 12 and 12 × 1 is just 12 too.
Now try to write a solution based on the information in the previous sections. If you still have
trouble solving this exercise, read the
Solution Template section for additional hints.
Dostları ilə paylaş: