Physics Class Project (Step 10)

This is my code

print(“A-1kg bomb supplies” + " " + str(bomb_energy) + " Joules.")

I’m not sure why you need a string. This step also was in another lesson. I’m thinking Python. If someone can explain why the str goes there than maybe I’ll learn why.


In python if the variable is not a string type, you can’t “add” it to another string type.
You need to turn it into a string type first. One reason could be because:

  • Strings are immutable: This means they can’t be changed when declared. As a result, when you add strings together inside the print(), it creates a new string object. Therefore you are trying to add an int-Type to a string-Type to make a new string type. It won’t work. You have to change the type first.
    *Additionally, python does not auto convert data types to strings. Some programming languages like java do.

However that is not the only way to add variable into your output. You can also do:

print(“A-1kg bomb supplies {} Joules.".format(bomb_energy))

This should feel better.

Also, try this excerise:

number = 1
string = “number”
new_string = string + number

you will get

Traceback (most recent call last):
File “”, line 1, in
TypeError: Can’t convert ‘int’ object to str implicitly

Just to see that it is not only confined to the print line.
Hope, the explanation is helpful. :slight_smile: