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
相关产品推荐
相关产品推荐

