2013-06-28 55 views
-1
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 ")) 

我在這裏做了什麼錯?UnboundLocalError:分配前引用的局部變量「餘額」

+1

我建議你重構你的代碼消除對全局變量的需求,或者至少是'global'關鍵字。 –

+0

@JustinEthier,在技術上來說這些函數是全局變量:) –

+2

@gnibbler - 你剛剛實際上是我嗎? - http://tirania.org/blog/archive/2011/Feb-17.html –

回答

2

您還應該嘗試在方法範圍之外定義balance,在您的導入語句下方。

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 
相關問題