0
votes

I tried running a block of code and got the above error for this line of code:

print("Congratulations! You swapped out a", box3, "for", + str( randomPersuade2 ) + " Dollars. Enjoy!")

box3 holds a value from a list of items

box1,box2,box3,box4, box5 = ["Car", "TV", "DVD", "Overseas Holiday", "Box of chocolates"]

randomPersuade2 is a variable that holds a value from a random.randint() funct.

randomPersuade2 = random.randint(200,5000)

As mentioned in the title, I get the error

TypeError: bad operand type for unary +: 'str'

How would I resolve this? Any help would be much appreciated!

3
Why is there a + before the str() call? - tkausl
Remove the plus or the comma - dan-klasson

3 Answers

2
votes

This part is problematic : You have a comma AND a plus sign. You need to get rid of one of them.

box3, "for", + str(randomPersuade2)

Explaning the error

Here, Python thinks you want to use the "unary" + operator.

This operator is not the same as the one is num_a + num_b. You use it like this : +num.

And it just.. doesn't change the value of a number. Yeah not really useful. But here, you have a str object, which is not a number. The object on which the operator is called is an "operand".

So here you go : "Bad operand type for unary +: 'str'".

0
votes

You have 2 variables that you want to use in print message. A clean way to do it is:

print('Congratulations! You swapped out a, {}, for, {}  Dollars. 
       Enjoy!'.format(var1,var2))
0
votes

, operator automatic add space after string so remove + sign after , operator:

print("Congratulations! You swapped out a", box3, "for", str( randomPersuade2 ) + " Dollars. Enjoy!")