0
character_name = "George"
character_age = 50
is_Male = True
print("There was once a man named " + 
character_name + ",")
print("He was " + character_age + " years old. 
")

character_name = "Mike"
print("He really liked the name " + 
character_name + ",")
print("but didn't like being " + character_age + ".")

I am following the learnPython course on youtube, and he states early in the video that for variables, you can either put text in between parentheses or you can just do a number which does not require strings. However when I try to run the above code, it gives the error that it cannot concatenate. Please help.

Hoboson
  • 1
  • 2
  • 1
    change `print("He was " + character_age + " years old.")` to `print("He was", character_age, "years old."}` – Chris Charley Jul 13 '20 at 19:48
  • Does this answer your question? [How can I concatenate str and int objects?](https://stackoverflow.com/questions/25675943/how-can-i-concatenate-str-and-int-objects) – plum 0 Jul 13 '20 at 20:01

2 Answers2

0

You cannot concatenate an int and a str. So, you convert the int to a str by str(<int_variable) i.e str(character_age)

character_name = "George"
character_age = 50
is_Male = True
print("There was once a man named " + 
character_name + ",")
print("He was " + str(character_age) + " years old.")

character_name = "Mike"
print("He really liked the name " + 
character_name + ",")
print("but didn't like being " +str(character_age) + ".")

Output:

There was once a man named George,
He was 50 years old.
He really liked the name Mike,
but didn't like being 50.
bigbounty
  • 16,526
  • 5
  • 37
  • 65
0

You will need to convert your ints to strings for concatenation using the str() method.

print("He was " + str(character_age) + " years old.")

Alternatively, if you are using python 3.6+ you could use python f-strings like so:

print(f"but didn't like being {character_age}.")

Also, with python3 print being a function in stead of a statement, you can pass in multiple arguments to achieve this result without concatenation. Arguments will be separated by a space by default. This can be modified by adding the sep kwarg to the print call.

print("He was", character_age, "years old.")
# or with explicit separator kwarg set to space
print("He was", "character_age", "years old", sep=" ")
plum 0
  • 652
  • 9
  • 21