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

