UnboundLocalError:赋值前引用的局部变量'balance'

时间:2013-06-28 14:03:13

标签: python

import random
import time

def set_balance():

    print("Welcome to balance manager")
    print()
    print("1, Demo mode (10,000 play chips)")
    print("2, Real mode (PayPal, BTC deposit)")
    print()
    choice = int(input("Please enter your selection: "))

    if choice == 1:
        global balance 
        balance = 10000
        demomode = 1

    elif choice == 2:
        global balance

        balance = int(input("\nEnter the ammount to pay in £"))

def spin_wheel():

    print("\n\n\n\n\n\n\n\nLETS PLAY ROULETTE, YOUR BANK IS, £", balance)
    print()
    print("Red, 1")
    print("Black, 2")
    print("Please select your colour from the menu below")

    choice = int(input("\nOption selected "))

我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

您还应该尝试在导入语句下面的方法范围之外定义balance

答案 1 :(得分:1)

我猜有些代码丢失,但你不需要在set_balance中使balance(或demomode)全局。

像这样称呼它

balance, demomode = set_balance()

如果您愿意,您仍然可以使用相同的名称余额作为set_balance的本地变量,并将其返回

def set_balance():

    print("Welcome to balance manager")
    print()
    print("1, Demo mode (10,000 play chips)")
    print("2, Real mode (PayPal, BTC deposit)")
    print()
    choice = int(input("Please enter your selection: "))

    if choice == 1:
        balance = 10000
        demomode = True

    elif choice == 2:

        balance = int(input("\nEnter the ammount to pay in £"))
        demomode = False

    return balance, demomode