You need to enable JavaScript to run this app. Python取款函数报错:'<'不支持NoneType与int实例比较该如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python取款函数报错:'<'不支持NoneType与int实例比较该如何解决

问题原因及修复方案

报错原因

  • 你的withdrawl函数只有在取款成功(余额≥取款金额)的分支才会返回余额数值,当余额不足的分支触发时,函数没有显式写return语句,Python会默认返回None
  • 当你每次取款都把函数返回值赋值给current_bal,一旦触发余额不足的情况,current_bal就会被覆盖为None,下一次执行balance < amount判断时,就会出现None和整数比较的类型错误。

修复方法

只要在余额不足的分支也返回当前的余额即可,避免返回值为None覆盖原有余额,修改后的代码如下:

current_bal = 100

def withdrawl(balance, amount):
    if balance < amount:
        print('You have not enough money')
        # 余额不足时返回原余额
        return balance
    else:
        balance -= amount
        print('You have withdrawn {}. Your new balance is {}'.format(amount, balance))
        return balance

current_bal = withdrawl(current_bal, 100)
# 后续重复执行取款逻辑也不会出现类型错误
current_bal = withdrawl(current_bal, 10)

内容的提问来源于stack exchange,提问作者KaiLiang Koh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 05:24:03