TypeError: Can't convert 'int' object to str implicitly error python
Question:
i read other questions but the thing im trying to do is different
im trying to make a calculator thingy in python and trying to make the variable input thing into a integer so i can add it. this is my code also its not finished yet and im a beginner:
print("Hello! Whats your name?")
myName = input()
print("What do you want me to do? " + myName)
print("I can add, subtract, multiply and divide.")
option = input('I want you to ')
if option == 'add':
print('Enter a number.')
firstNumber = input()
firstNumber = int(firstNumber)
print('Enter another number.')
secondNumber = input()
secondNumber = int(secondNumber)
answer = firstNumber + secondNumber
print('The answer is ' + answer)
what it does:
Hello! Whats your name?
Jason
What do you want me to do? Jason
I can add, subtract, multiply and divide.
I want you to add
Enter a number.
1
Enter another number.
1
Traceback (most recent call last):
File "C:/Python33/calculator.py", line 17, in <module>
print('The answer is ' + answer)
TypeError: Can't convert 'int' object to str implicitly
any help would be appreciated 🙂
Answers:
As the error message say, you can’t add int object to str object.
>>> 'str' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
Explicitly convert int object to str object, then concatenate:
>>> 'str' + str(2)
'str2'
Or use str.format
method:
>>> 'The answer is {}'.format(3)
'The answer is 3'
i read other questions but the thing im trying to do is different
im trying to make a calculator thingy in python and trying to make the variable input thing into a integer so i can add it. this is my code also its not finished yet and im a beginner:
print("Hello! Whats your name?")
myName = input()
print("What do you want me to do? " + myName)
print("I can add, subtract, multiply and divide.")
option = input('I want you to ')
if option == 'add':
print('Enter a number.')
firstNumber = input()
firstNumber = int(firstNumber)
print('Enter another number.')
secondNumber = input()
secondNumber = int(secondNumber)
answer = firstNumber + secondNumber
print('The answer is ' + answer)
what it does:
Hello! Whats your name?
Jason
What do you want me to do? Jason
I can add, subtract, multiply and divide.
I want you to add
Enter a number.
1
Enter another number.
1
Traceback (most recent call last):
File "C:/Python33/calculator.py", line 17, in <module>
print('The answer is ' + answer)
TypeError: Can't convert 'int' object to str implicitly
any help would be appreciated 🙂
As the error message say, you can’t add int object to str object.
>>> 'str' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
Explicitly convert int object to str object, then concatenate:
>>> 'str' + str(2)
'str2'
Or use str.format
method:
>>> 'The answer is {}'.format(3)
'The answer is 3'