2015-12-03 67 views
0

我有一個寫函數的問題,以確定是否首先,列表中的東西,其次,有關用戶有銀行餘額。如果在列表函數 - python

本質上,該功能需要做的是允許用戶使用他們的餘額投注一個團隊,並檢查他們輸入的團隊是否在團隊列表中。

這是我到目前爲止,如果有人可以幫助我這個。我覺得它可能需要兩個功能,但不能解決,其他線程沒有幫助我,謝謝。

team_list = ["Team1", "Team2", "Team3"] 

def Team(): 
    team = input("Please choose a team to bet on.") 
    if team in team_list: 
     print("You have selected",team) 
    else: 
     print("That team is not in the list please select one in the list") 
     return Team() 

def Stake(): 
    bank = float(50.0) 
    stake = float(input("Please enter a stake")) 
    if stake <= bank: 
     print("Your bet has been placed.", stake, "on", team) 
     bank -= stake 
     print(bank) 
    else: 
     print("You don't have enough money to place this") 
     return Stake() 

Team() 
Stake() 
+0

您需要實際返回「團隊」值,稍後再使用它。 – shuttle87

+0

謝謝你,我怎樣才能做到這一點,只需在'團隊()'的利益函數開始時調用它? – Bob457678y

+0

看起來你正在混合兩件事:你將'team'和'stake'當作全局對象(但沒有聲明它們是這樣的,所以它不起作用),而且你也試圖返回它們(但是隻有在遞歸時,再次不起作用)。如果你想讓它們成爲全局的,那麼在函數中聲明它們是「全局的」。 –

回答

1

您需要了解更多關於變量範圍的信息。 team變量是Team函數的局部變量,意味着team只存在於由Team定義的範圍內。這意味着在Stake中不存在名爲team的變量。

要處理這個問題,你需要傳遞一些變量來使用返回語句和參數。首先,你需要從Team返回team變量:

def Team(): 
    team = input("Please choose a team to bet on.") 
    if team in team_list: 
     return team 

然後你就可以在以後使用,通過第一存儲返回值,然後將它作爲參數傳遞給Stake

selected_team = Team() 
print("You have selected", selected_team) 
Stake(selected_team) 

哪裏Stake是修改爲可以採取參數:

def Stake(team): 
    #now team variable *is* accessible through the parameter 
1

team的範圍變量使用的是Team僅限於自身。 它不能在Stake函數中訪問。 爲了解決這個問題,在這裏你可以做什麼:

team_list = ["Team1", "Team2", "Team3"] 
bank = 50.0 

def Team(): 
    team = input("Please choose a team to bet on.") 
    if team in team_list: 
     print("You have selected",team) 
     Stake(team) 
    else: 
     print("That team is not in the list please select one in the list") 
     return Team() 

def Stake(team): 
    bank = float(50.0) 
    stake = float(input("Please enter a stake")) 
    if stake <= bank: 
     print("Your bet has been placed.", stake, "on", team) 
     bank -= stake 
     print(bank) 
    else: 
     print("You don't have enough money to place this") 
     return Stake(team) 
Team() 

此外,如果要合併這兩個功能,你可能要工作位。但是,首先 - 您應該瞭解variable scoping
查看官方文檔:variable scoping
它可能是舊的,但它仍然是相關的。