The Wrong
Your mistake isnt the variable definition, its rather with line 5
print("but didn't like being " + character_age + ".")
Lets take a look at your error message
TypeError: can only concatenate str (not "int") to str
This is a TypeError, and it was raised because you cannot use "+" to add an int and a str, hence "TypeError"
The Why
An int (integer) is a number, whilst a str (string) is a word. Now, your error becomes obvious; It makes no sense to add a word and a number.
we can add two integers, or two strings together with the "+" operator, it has to be the same type.
Lets take a look here:
word = "this is a string" # Making a string example
number = 5 # This is an example int
print(word + number)
And its output
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
Here we get the same Error message, because we try to add an int
and a str
Now, lets try a different example
print(5 + 5) # Adding two integers
print("Hello " + "World!") # Adding two strings
print(5 + "Hello!") # Adding a string and an integer
And this example's output
>>> print(5 + 5) # Adding two integers
10
>>> print("Hello " + "World!") # Adding two strings
Hello World!
>>> print(5 + "Hello!") # Adding a string and an integer
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
Here, adding two numbers works, so do the strings. But, we get an error with the last one, adding a string and an int.
The Correct
We can just completely avoid using integers in this case, since we don't plan on adding that variable to another integer.
character_age = "50" # Now its a string
And Heres the output
>>> character_name = "Mike"
>>> character_age = "50"
>>> is_male = False
>>> print("He really liked the name " + character_name + ", ")
He really liked the name Mike,
>>> print("but didn't like being " + character_age + ".")
but didn't like being 50.
Or, if we needed to use integers, we can convert it to a string while we add them
print("but didn't like being " + str(character_age) + "."). # This will not affect the variable, but it will return a string version of character_age
And this has the same output
Another answer is to use an f-string
in python 3.6+
>>> print("The restaurant received a {5} star rating")
The restaurant received a 5 star rating
You can read more about f-strings here
Conclusion
You need to convert the int value to a string for them to add, or just use a string in the first place. f-strings
are an excellent way to do this without string concatenation and a simpler syntax.