Kootch
Kootch

Reputation: 31

TypeError: unsupported operand type(s) for +: 'int' and 'str' even after I change the string to an integer

I keep on getting an error for my program and I have looked around the site and I now understand the error is because I have tried to add a string to an integer but when I use the command int(variablename) I still get the error when trying to add them.

This is my code I am working on:

price = input("How much is that worth in keys\n Amount: ")
int(price)
spc()
while a == '1':
    if price.isdigit():
        print(price, 'keys')
        spc()
        yn = input("Is this correct?\n (y/n) Answer: ")
        while yn != 'y':
            spc()
            price = input("How much is that worth in keys\n Amount: ")
            spc()
            print(price, 'keys')
            spc()
            yn = input("Is this correct?\n (y/n) Answer: ")
            spc()

        break

    spc()
    print("That is not a valid key amount")
    spc()
    price = input("How much is that worth in keys\n Answer: ")
    total = 0
    total = total + price
    print(total)

If you are wondering what spc() is

def spc(): print(" ")

I get the error after that and there is other parts of the code but none of the errors relate to it so I have left it out.

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

Upvotes: 0

Views: 160

Answers (3)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799490

This line:

int(price)

doesn't change the value of price, it merely throws an exception if the value can't be converted to an int. And it's a good thing it doesn't change it, since the code calls the isdigit() method later, which is mostly pointless since we already know that it looks like an integer.

You need to decide whether you're going to parse the input by hand, or trust Python to throw an exception when the input is incorrect. I'd do the latter myself.

Upvotes: 2

sfedak
sfedak

Reputation: 676

I think your problem is you aren't reassigning the casted price back to the variable.

price = int(price)

This means that you do a fruitless operation and it's still considered a string.

Upvotes: 3

Vincent Beltman
Vincent Beltman

Reputation: 2112

Its propably on this line:

total = total + price

Price gains the balue of the method input(). input() returns a string. And since you cannot concatenate a string and a int with a + in python, it will give you that error. Replace total = total + price with this:

total += int(price)

Upvotes: 3

Related Questions