Why does print "string" + variable doesn't work?

Hi, I’m currently on the Updating Variables on the Python 2 course.

I was attempting to print saying that Annual Rainfall as of June and added the variable, I assumed it to display the variable beside the string but doesn’t work. Why is this?

january_to_june_rainfall = 1.93 + 0.71 + 3.53 + 3.41 + 3.69 + 4.50
annual_rainfall = january_to_june_rainfall
print "Annual Rainfall as of January to June: " + annual_rainfall

It only works with this:

january_to_june_rainfall = 1.93 + 0.71 + 3.53 + 3.41 + 3.69 + 4.50
annual_rainfall = january_to_june_rainfall
print "Annual Rainfall as of January to June: " 
print annual_rainfall

Is there a rule that variable can only be shown with its own command print? But I also tried doing + print annual_rainfall and it says error. Just curious as to why it does that. Thanks!

Hi there.

Knowing what the error message you’re receiving is would be helpful, but I suspect that your original code is throwing you a TypeError similar to the one below:

TypeError: cannot concatenate 'str' and 'float' objects

The reason for this is because the statement "Annual Rainfall as of January to June: " + annual_rainfall is evaluated by the print statement before Python attempts to output the result to the console.

You can’t concatenate a string - "Annual Rainfall as of January to June: " - with a float.

What you can do is use string formatting to inject the variable into the string:

# string formatting example
january_to_june_rainfall = 1.93 + 0.71 + 3.53 + 3.41 + 3.69 + 4.50
annual_rainfall = january_to_june_rainfall
print "Annual Rainfall as of January to June: {}".format(annual_rainfall)

You can also do what’s called printf-style formatting:

# printf example
january_to_june_rainfall = 1.93 + 0.71 + 3.53 + 3.41 + 3.69 + 4.50
annual_rainfall = january_to_june_rainfall
print "Annual Rainfall as of January to June: %s" % annual_rainfall

You could also convert the variable to a string, and concatenate them:

# variable conversion and concat example
january_to_june_rainfall = 1.93 + 0.71 + 3.53 + 3.41 + 3.69 + 4.50
annual_rainfall = january_to_june_rainfall
print "Annual Rainfall as of January to June: " + str(annual_rainfall)

Lastly, if you want print to print multiple things you can simply separate them with a comma and Python will output them all with a space between the statements:

# comma separated output example
january_to_june_rainfall = 1.93 + 0.71 + 3.53 + 3.41 + 3.69 + 4.50
annual_rainfall = january_to_june_rainfall
print "Annual Rainfall as of January to June:",annual_rainfall

All of these examples produce the same output:

Annual Rainfall as of January to June: 17.77

Hope that helps.

3 Likes

And If you studied Python 3 instead of 2, you could of done it by using f-string:

january_to_june_rainfall = 1.93 + 0.71 + 3.53 + 3.41 + 3.69 + 4.50
annual_rainfall = january_to_june_rainfall
print(f"Annual rainfall as of January to June: {annual_rainfall}")

2 Likes