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

Python实现轮盘赌颜色投注模拟时全局变量调用问题求助

解决方案

核心问题说明

  • Python中如果要在函数内部修改全局变量的值,必须提前使用global关键字声明该变量,否则解释器会将其识别为当前函数的局部变量,触发未定义报错
  • 你代码中的bet是start()函数内的局部变量,simulate()函数默认无法访问,所以也需要设置为全局变量,或者通过参数传递

修正后可运行代码

import random

balance = 100
# 提前声明bet为全局变量
bet = 0

# user decides how much they will bet
def start():
    global bet, balance
    print("Place your bet:")
    bet = int(input(">"))
    if bet > balance:
        insufficient_funds()
    else:
        simulate()

# if user placed too much
def insufficient_funds():
    print("Oops, you don't have enough funds to place a bet")
    start()

# color choose and roulette simulation
def simulate():
    global balance, bet
    print("Choose Red or Black:")
    answer = input("> ")
    result = random.randint(1, 2)
    if result == 1 and answer == "Red":
        print("You won")
        balance += bet
        print(f"Your balance now {balance}")
        start()
    elif result == 2 and answer == "Black":
        print("You won")
        balance += bet
        print(f"Your balance now {balance}")
        start()
    else:
        print("You lost!")
        balance -= bet
        print(f"Your balance now {balance}")
        start()

start()

改动说明

  • 代码顶部提前定义全局变量bet,初始值设为0
  • 在start()和simulate()函数开头都添加global bet, balance声明,告知解释器这两个变量使用全局作用域的变量
  • 修正了原有代码中Choose Red or for Black的冗余拼写错误

可选优化(避免过多全局变量)

如果不想把bet设为全局变量,也可以通过参数传递的方式改写,改动更小:

# 仅展示改动部分
def start():
    global balance
    print("Place your bet:")
    bet = int(input(">"))
    if bet > balance:
        insufficient_funds()
    else:
        # 把bet作为参数传给simulate
        simulate(bet)

def simulate(bet):
    global balance
    # 剩下的逻辑保持不变即可,不需要再声明global bet

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:24:08