Special Cases and Gotchas Python’s print() function accepts multiple arguments to display. These arguments can be
strings, integers, Booleans, or values of any other data type. The print() function automatically
converts the argument to a string. However, keep in mind that you can only concatenate a string value
to another string value. So while these two lines of code are valid:
print(numberOfBottles, 'bottles of beer,')
print(str(numberOfBottles) + ' bottles of beer,')
This line of code produces a TypeError: unsupported operand type(s) for +:
'int' and 'str'
error message because numberOfBottles holds an integer and the + operator
cannot concatenate integers to strings.
print(numberOfBottles + ' bottles of beer,')
The latter line of code is trying to pass a single argument to print(): the expression
numberOfBottles + ' bottles of beer,'
evaluates to this single value. This differs from
the first two examples where two arguments, separated by a comma, are passed to print(). The
difference is a subtle but important. While print() automatically converts arguments to strings,
string concatenation doesn’t and requires you to call str() to perform this conversion.
Even the word ―convert‖ is a bit of a misnomer here: function calls return brand new values
rather than change an existing value. Calling len('hello') returns the integer value 5. It’s not that
the string 'hello' has been changed to the integer 5. Similarly, calling str(42) or int('99')
doesn’t change the argument but returns new values.
This is why code such as str(numberOfBottles) doesn’t convert the integer in the
numberOfBottles
variable to a string. Instead, if you want to change the variable, you need to
assign the return value to the variable like:
numberOfBottles = str(numberOfBottles)
Don’t think of this as modifying the value in numberOfBottles, but rather replacing it with
the value returned from the str() function call.
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.