执行HP - EnemyAttack时触发TypeError:int与function不支持减法运算
TypeError: unsupported operand type(s) for -: 'int' and 'function'错误 Hey there! Let's break down why you're hitting this error and fix it up quickly.
错误原因
There are two key issues here:
- First, when you wrote
HP - EnemyAttack, you're trying to subtract the function itself (not the result of running the function) from your integerHP. In Python, a function name without parentheses is just a reference to the function object—you can't do math between an integer and a function, hence the type error. - Second, your
EnemyAttackfunction only prints a message right now—it doesn't return any attack damage value. Even if you added parentheses to call it, it would default to returningNone, which still can't be subtracted from an integer.
解决方法
Let's fix both problems step by step:
Update the
EnemyAttackfunction to return damage
Modify the function so it outputs the attack message and returns a numeric value representing how much damage the enemy deals. For example:def EnemyAttack(): print("The enemy", enemy, "Attacked!") # Replace 15 with whatever damage value you want, or add logic to calculate it return 15Correctly call the function and update HP
Use the subtraction assignment operator (-=) to call the function (with parentheses!) and reduce your HP by the returned damage. ReplaceHP - EnemyAttackwith:HP -= EnemyAttack()Using
-=ensures the HP value is actually updated—just using-would calculate the difference but leave the originalHPvariable unchanged.
修正后的完整代码片段
Here's how your fixed code might look (assuming HP and enemy are defined elsewhere in your script):
def EnemyAttack(): print("The enemy", enemy, "Attacked!") return 15 # Customize this damage value as needed # Example pre-defined variables HP = 60 enemy = "Wild Wolf" HP -= EnemyAttack() if HP <= 0: print("You Were torn to pieces by the", enemy, ".") else: print("You managed to withstand the attack by the", enemy, ". It growls in frustration.") BattleChoice()
内容的提问来源于stack exchange,提问作者JustCattoo

