-1

So i just started Python but encountered a problem.

Pycharm won't print values and numbers at the same time. Example:

Age = 45 print("He was" + Age) Result: TypeError: can only concatenate str (not "int") to str

If I save the Age as a string it does work tho. Age = "45" print("He was" + Age) Result: He was 45

Any idea why this ocurrs ?

  • your issue is that your literally trying to do a mathematical operation with a string, which will result in an error. You can either coerce the object into a string, or use string formatting like `print(f"He was {Age}")` – Umar.H Apr 16 '21 at 16:58
  • The `+` is not for the `print`. The `+` is evaluated first, and then the result becomes the argument to `print`. So either you let `print` do the concatenation by giving **two** arguments; or **you** do the concatenation first (*correctly!*). – debashish.ghosh Apr 16 '21 at 17:15

3 Answers3

1

As the error message already told you, you cannot concatenate an int (45) and a string ("He was"). Try using:

age = 45
print("He was {}".format(age))
lakedue
  • 44
  • 1
  • 5
1

Try this

Age = 45 
print("He was", Age)
Junaid
  • 139
  • 14
0

The problem is happening because you want to print a string with an integer by a ' + ' But you have to use ' , ' instead of '+'

so your codes should look like this :

age = 45 
print(" He was " , age  )

or you could try this with formatted string :

 age = 45
 print(f"He was {age}")
Abdulla Shafi
  • 41
  • 2
  • 6