95
E X E R C I S E # 3 1 : C O N V E R T I N T E G E R S T O
S T R I N G S
convertIntToStr(42)
→
'42'
In Python, the values 42 and '42' are two different values: you can perform mathematics on
the integer 42, but the string '42' is the same as any other two-character text string. You can
perform mathematical
addition on integer values, but not on strings. And you can concatenate or
replicate string values, but not integers. A common programming task is to obtain the string
equivalent of a number. You can use the str() function to do this conversion but
in this exercise
you’ll recreate this function yourself.
Exercise Description
Write a convertIntToStr() function with an integerNum parameter.
This function
operates similarly to the str() function in that it returns a string form of the parameter. For
example, convertIntToStr(42) should return the string '42'. The function doesn’t have to
work for floating-point numbers with a decimal point, but it should work for negative integer values.
Avoid using Python’s str() function in your code, as that would do the conversion for you and
defeat the purpose of this exercise. However, we use str() with assert statements to check that
your convertIntToStr() function works the same as str() for all integers from -10000 to
9999
:
for i in range(-10000, 10000):
assert convertIntToStr(i) == str(i)
Try to write a solution based on the information in this description. If you still have trouble
solving
this exercise, read the
Solution Design and Special Cases and Gotchas sections for
additional hints.
Prerequisite concepts: dictionaries, while loops, string concatenation,
integer division
Dostları ilə paylaş: