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
In python, you cannot concatenate two completely different data types.
1) 1 + 1 = 2
2) '1' + '1' = '11' (string within quotes)
3) '1' + 1 = ??
Think about it...
Well, in other programming languages like C, the integer would be converted into char (or character) and would undergo operation 2...
So, in this case, you need to explicitly cast the str
(or string) data type other than into an integer (or int
) using the function int()
.
Syntax: int('<some string>')
Example: int('7')
would yield 7
So, you either need to take the input as integer or else convert the string to integer while computing finalAge
:
age = int(input('age: '))
Or
finalAge = int(age) + factor
Python 3.7 this will do what you want.
userName = input('Name: ')
age = int(input('age: '))
factor = 2
finalAge = age + factor
print("In", + factor, "years you will be", + finalAge, "years old " + userName + "!")
TypeError: Can only concatenate str (not “int”) to str
This Error states that it can only concatenate string to string. In your program you have tried to concatenate a sting and integer
Input command would only fetch string from the user, and the age the user enters should be taken as string. Examples: '45', '25', 36 etc..
This program is trying to concatenate '45' + 2 . Which throws this error.
Instead you can try converting the user input to int and then concatenate.
userName = input('Name: ')
age = int(input('age: '))
finalAge = age + factor
factor = 2
finalAge = age + factor
print('In ', factor, 'years you will be', finalAge, 'years old', userName, '!')
You add a string to an int, because the input()
function returns a string. Use int(input('age: '))
.
In python, you cannot concatenate two completely different data types.
1) 1 + 1 = 2
2) '1' + '1' = '11' (string within quotes)
3) '1' + 1 = ??
Think about it...
Well, in other programming languages like C, the integer would be converted into char (or character) and would undergo operation 2...
So, in this case, you need to explicitly cast the str
(or string) data type other than into an integer (or int
) using the function int()
.
Syntax: int('<some string>')
Example: int('7')
would yield 7
So, you either need to take the input as integer or else convert the string to integer while computing finalAge
:
age = int(input('age: '))
Or
finalAge = int(age) + factor
userName = input('Name: ')
age = input('age: ')
factor = 2
finalAge = int(age) + factor
print('In', factor, 'years you will be', finalAge, 'years old', userName+'!')