使用 Python 中的用户输入填充函数参数

Populating a function argument with user input in Python

我正在尝试创建一段代码来执行简单的减法并根据用户的输入打印一条消息,但我一直无法弄清楚如何让用户输入正确地用作函数参数。

我不断收到以下错误,即使我已经将 int 与用户输入一起包含在内:

TypeError: '>=' not supported between instances of > 'NoneType' and 'int'

你知道我遗漏了什么吗?

我正在处理的确切代码如下所示:

def withdraw_money(current_balance, amount):
    if (current_balance >= amount):
        current_balance = current_balance - amount
        return current_balance

balance = withdraw_money(int(input("How much money do you have")), int(input("How much do your groceries cost")))

if (balance >= 0): 
    print("You're good")
else: 
    print("You're broke")

您在 else

中缺少 return

所以每当你破产时,你的功能是 return 什么都不做,你什么也不比较 (None)

def withdraw_money(current_balance, amount):
    if (current_balance >= amount):
        current_balance = current_balance - amount
        return current_balance
    else: # need to return something if the above condition is False
        return current_balance - amount

balance = withdraw_money(int(input("How much money do you have")), int(input("How much do your groceries cost")))

if (balance >= 0): 
    print("You're good")
else: 
    print("You're broke")

PS: 如果你在函数之外检查这个人是否破产,为什么要检查函数内部的差异? (你的 fnc 只能 return 差异,然后你可以在外面检查它是 -ive 还是 +ive)