如何在Python中分配之前修复参考

时间:2018-11-24 20:02:35

标签: python python-3.x variables reference variable-assignment

我正在尝试使用命令提示符界面制作轮盘游戏。轮盘赌与博彩有关,因此游戏中很大一部分与您输赢有关。我试图做一个变量来告诉玩家在我再次下注之前我有多少钱。我尚未完成游戏,因此只有3个可用选项,但是我想在继续之前解决此错误。 我不断收到错误“ UnboundLocalError:分配前引用了本地变量'money'” 这是代码:     来自随机进口randint     从进口睡眠     从操作系统导入系统

def how_much():
    print("How much money do you want to place on this bet?")
    global amount
    amount = int(input())


def game():
    def bet():
        bet = input("What type of bet do you want to make?\n")
        how_much()
        #Start Bet type 1
        if bet == "1":
            roll = randint(1,36)
            if roll <= 3:
                print("You bet correcty!")
                money = money + amount
                game()
            else:
                print("You lose!")
                money = money - amount
                game()
        #Start bet type 2
        elif bet == "2":
            roll = randint(1, 36)
            if roll <= 4:
                print("You bet correcty!")
                money = money + amount
                game()
            else:
                print("You lose!")
                money = money - amount
                game()
        #Start bet type 3
        elif bet == "3":
            roll = randint(1, 36)


        else:
            print("Invalid argument.")
            bet()


    global money
    money = int(1000)
    print("Welcome to Roulette")
    print("Your Wallet has", money, "Euros in it.")
    print("1. First 3 Numbers\n2. First 4 Numbers\n3. One Number\n4. Upper-half or Lower-half\n5. Dozens\n6. Odd or Even\n7. Column\n8. Line\n9. 2 Lines\n10. Red or Black\n11. 2 Neighbors\n12. 4 Neighbors\n0. Exit")
    bet()


game()

1 个答案:

答案 0 :(得分:0)

代码的问题是您忘记将global money放在bet函数中。您已经在global money函数中声明了game,但是bet函数不知道此变量。您需要做的就是将global money放在bet函数的第一行