Is the str() function necessary when using print()?

I’m halfway through completing the Python Syntax: Medical Insurance Project (https://www.codecademy.com/paths/data-science/tracks/dscp-python-fundamentals/modules/dscp-python-syntax/projects/ds-python-syntax-project).

After calculating the difference in insurance based on the factor age, the next set of instructions are:

We want to display this information in an informative way similar to the output from instruction 3. On the next line, print the following string in the terminal, where XXX is replaced by the value of change_in_insurance_cost :

The change in cost of insurance after increasing the age by 4 years is XXX dollars.

Doing this will tell us how 4 years in age affects medical insurance cost estimates assuming that all other variables remain the same.

You will need to concatenate strings and use the str() method.

The hint uses the following piece of code:

print("The change in estimated insurance cost after increasing the age by 4 years is " + str(change_in_insurance_cost) + " dollars")

However, I’ve formatted it like this:

print("The change in estimated insurance cost after increasing the age by 4 years is", change_in_insurance_cost, "dollars")

I haven’t used the str() function to include the variable change_in_insurance, but it doesn’t throw up a syntax error. What’s the point of using str() if this is the case?

Hi there, welcome to the forums.

If you take a look at the documentation for the print() function you’ll see that by default it’s behaviour is to print each object it is provided with separated with a space.

In your second example

print("The change in estimated insurance cost after increasing the age by 4 years is", change_in_insurance_cost, "dollars")

you are asking the print() function to print three objects: 2 string literals and the value of the change_in_insurance_cost variable.

You don’t need to use the str() function here because you’re not concatenating the variable into the two string literals. Python is sort of doing that for you within the print() function.

The use of str() is required if you were to concatenate the change_in_insurance_cost variable into the output - because + means different things when we are working with strings and numerical formats.

Hope that answers your question. :slight_smile:

2 Likes

Thank you so much! I’ve just had a play around with it independent of the print() function and it makes sense now :blush:

1 Like