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

Python中如何在一个函数内使用另一个函数的返回值?

解决方法

你的问题在于get_bet函数里的amount是deposit函数的局部变量,外部函数无法直接访问。要使用deposit的返回值,需要把它作为参数传递给get_bet,具体步骤如下:

  • 先定义MIN_BET和MAX_BET这两个常量(你的代码里用到了但未定义,必须补上)
  • 修改get_bet函数,让它接收一个balance参数
  • 调用deposit()获取余额,再把这个值传给get_bet

修改后的完整代码示例:

# 定义全局常量
MIN_BET = 1
MAX_BET = 100

def deposit():  # amount he wants to bet with
    while True:
        amount = input("What would you like to deposit? $")
        if amount.isdigit():
            amount = int(amount)
            if amount > 0:
                break
            else:
                print("Amount must be greater than 0$")
        else:
            print("Please enter a number")

    return amount

def get_bet(balance):  # 接收balance参数
    while True:
        bet = input("What would you like to bet on each line? $")
        if bet.isdigit():
            bet = int(bet)
            if MIN_BET <= bet <= MAX_BET and bet <= balance:
                break
            elif bet > balance:
                print(f"Bet must be within your balance of ${balance} ")
            else:
                print(f"Bet must be between ${MIN_BET} - ${MAX_BET} ")
        else:
            print("Please enter a number")

    return bet

# 主程序调用逻辑
user_balance = deposit()
user_bet = get_bet(user_balance)
print(f"You've placed a bet of ${user_bet}, remaining balance: ${user_balance - user_bet}")

另外,我合并了get_bet里的嵌套条件判断,让代码逻辑更简洁清晰。

内容的提问来源于stack exchange,提问作者Ahmed Khanji

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 09:05:13