Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

string - Subtracting From Variables - Thonny Python

I need help with subtraction with variables in python.

The response to what happens is here:

Traceback (most recent call last):
  File "/home/pi/Desktop/TheBacsShop.py", line 16, in <module>
    balance_a -= 40
TypeError: unsupported operand type(s) for -=: 'str' and 'int'
>>> 

And here is what I put:

balance_a -= 40

I really don't know whats wrong with my code. If you don't know what I am trying to do. I will explain:

So basically I want the 'player's balance' to start at any number ABOVE 40. But then subtract 40 from it. Without setting it to something. What would I do to achieve it?

(Whatever I am doing may be right just not available in THONNY PYTHON)

[EDIT]: OMG, the first of the awnser's u gave me are correct. But then (cue fail music) ANOTHER ERROR came up?!?!?!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The error

TypeError: unsupported operand type(s) for -=: 'str' and 'int'

is telling you that balance_a is a str (type string) and not an int (type integer). You need to make sure that balance_a is an integer. For example, '3' is a string; 3 is an integer.

int(balance_a) will cast the string ('3') into an integer (3), which you can then use for your subtraction.

The final code you're looking for is:

balance_a = int(balance_a) - int(gunCost)
print("You balance is now: $" + str(balance_a) + ".") 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...