You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行HP - EnemyAttack时触发TypeError:int与function不支持减法运算

解决Python中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 integer HP. 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 EnemyAttack function 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 returning None, which still can't be subtracted from an integer.

解决方法

Let's fix both problems step by step:

  1. Update the EnemyAttack function 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 15
    
  2. Correctly 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. Replace HP - EnemyAttack with:

    HP -= EnemyAttack()
    

    Using -= ensures the HP value is actually updated—just using - would calculate the difference but leave the original HP variable 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:49:09