TypeError: unsupported operand type(s) for +: 'int' and 'str' in Python

Dung Do Tien Oct 04 2021 123

Hello you guys, I am a newbie in Python and I'm also studying more about Python.
I have some lines of code and I want to create an array and remove any item from thay array. Function as below:

you = int(input("Enter your age: "))
mother = int(input("Enter your mother age: "))
father = int(input("Enter your father age: "))
wife = int(input("Enter your wife age: "))

lstage = [you, mother, father, wife]
print(lstage)
print("Now I will remove you father age....")
print(lstage.pop(2) + " has been removed")
print("And the list ages looks like: " + str(lstage))

But I get an exception TypeError: unsupported operand type(s) for +: 'int' and 'str' when I run code above.

Enter your age: 34
Enter your mother age: 56
Enter your father age: 65
Enter your wife age: 32
[34, 56, 65, 32]
Now I will remove you father age....
Traceback (most recent call last):
  File "main.py", line 9, in <module>
    print(lstage.pop(2) + " has been removed")
TypeError: unsupported operand type(s) for +: 'int' and 'str'

And I am using python 3.8.2

Anyone can explain it to me? How can I solve it?

Thanks for any suggestions.

Have 2 answer(s) found.
  • N

    Nitin Kumar Oct 04 2021

    Your code has some problem.

    1. In line 9 lstage.pop(2) is not return string so you have to cast it to string data type by using str() method. See like:

    print(str(lstage.pop(2)) + " has been removed")

    2. When concat string, please use , instate of + sign.

    Change: 

    print(str(lstage.pop(2)) + " has been removed")
    print("And the list ages looks like: " + str(lstage))

    To

    print(str(lstage.pop(2)), " has been removed")
    print("And the list ages looks like: ", str(lstage))

    And it worked for you.

  • k

    kolade afeez Oct 04 2021

    You need to change line:

    print(lstage.pop(2) + " has been removed")

    To

    rmitem = str(lstage.pop(2))
    print(rmitem, " has been removed")

    Because you need to convert lstage.pop(2) to string before concating them.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close