I wrote this simple code and tried to execute in Windows 10 CMD ... and it gets the error message :
TypeError: Can only concatenate str (not \"int\") to str
Python is strongly typed, so it does not do type coercion unless you tell it to.
You get that error if you try to add a number to a string, because based on the first operand it figures you want to concatenate strings.
If you try to add a string to a number, you get “unsupported operand types” instead, but it’s the same problem.
If you want to turn a number-in-a-string into an int you can add, use int()
. If you want to turn a number value into a string you can concatenate, use str()
.
Convert age to int to do your maths:
finalAge = int(age) + factor
And as a bonus you could use the .format() option:
print("In {0} years you will be {1} years old, {2}!".format(factor, finalAge, userName))
I think this type of error: TypeError: can only concatenate str (not "float") to str
The reason was Python use comma (,) to stick all element in print() function together. little different from Java that they used plus (+) sign to stick and output the result.
Note: double check all print() function to see did you put + sign and it should be replace by ,
The input() command in line 2 of your code would turn any input provided by the user into a STRING. Therefore, when you try to add that STRING to a number (float or integer; in your case you have an integer i.e. factor=2) it won't (and shouldn't!) work.
Therefore, for the + operation to continue, both the quantities to the left and right of that + sign must be of the same type (strings, or numbers)
I had the same problem with django and I solved it by clearing the chrome cache