Python
Programming Exercises,
Gently Explained
32
someVariable *= 42
someVariable = someVariable * 42
someVariable /= 42
someVariable = someVariable / 42
someVariable %= 42
someVariable = someVariable % 42
someVariable //= 42
someVariable = someVariable // 42
someVariable **= 42
someVariable = someVariable ** 42
For example, instead of typing someVariable = someVariable + 42, you could have the
equivalent someVariable += 42 as a more concise form. Python’s augmented assignment
operators include +=, -=, *=, /=, and %=.
The solution I give for this exercise includes the += augmented assignment operator.
Special Cases and Gotchas
Using an out-of-bounds index on a string results an error message: 'Hello'[9999] causes and
IndexError:
string index out of range
error. However, this doesn’t apply to slices.
Running 'Hello'[1:9999] results in 'ello' rather than an error message, even though 9999 is
greater than the largest index
of the string, 4.
Keep this in mind when comparing slices with strings. For example, the slice text[5:8] might
evaluate to a string of 3 characters because 8 - 5 is 3. But if this slice’s indexes are towards the end of
the text string, it could evaluate to a string of 2, 1, or 0 characters. So think of the slice text[5:8] as
being
at most 3 characters long.
For example, enter the following into the interactive shell for an example:
>>> 'elephant'[5:8]
'ant'
>>> 'gazelle'[5:8]
'le'
>>> 'turtle'[5:8]
'e'
>>> 'moose'[5:8]
''
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ş: