2013-02-21 60 views
0

我遇到了def語句的問題。我似乎無法真正瞭解他們。我必須製作類似於賭場老虎機的課程代碼。我有一個代碼可以做到這一點,但沒有我需要的def語句。我也不能使用全局變量。任何人都可以將我指向正確的方向嗎?需要使用def語句創建代碼? &不能使用全局變量

import random 

money='' 

b1='' 

def greeting(): 

     print("Project 2") 

def myMoney(money=0): 

    money=int(input("Let's play the slots!\nHow much money do you want to start with?\nEnter the starting number of dollars.")) 
    return money 
    while True: 
     if money>0: 
      break 
     if money==0: 
      break 


def getBet(bet=''): 

     b1=int(input("How much do you want to bet?")) 
     while True: 
      if bet==0: 
       break 
      while True: 
       if bet>money: 
        print("ERROR: You don't have that much left.") 
        print() 
        b1=int(input("How much do you want to bet?")) 
       if bet<money: 
        input("Press enter to pull the slot machine handle!") 
        break 
     return money 
     return bet 

    num1=random.randint(1, 5) 
    num2=random.randint(1, 5) 
    num3=random.randint(1, 5) 
    print("/---+---+---\ ") 
    print("|-"+str(num1)+"-|-"+str(num2)+"-|-"+str(num3)+"-|") 
    print("\---+---+---/") 

greeting() 

myMoney() 

getBet() 
+0

你的問題沒有意義。你發佈的東西中有很多'def's。你的代碼有什麼問題? – BrenBarn 2013-02-21 19:38:43

+0

我認爲他不能讓它與來自用戶的輸入一起工作 – 2013-02-21 19:39:12

+2

@BrenBarn:對我來說,主要問題似乎是他不理解'return'語句,更一般地說,函數是什麼。 – 2013-02-21 19:40:56

回答

0

在「def語句」(函數)中,您可以根據需要定義變量。他們不會是全球性的

def A_function(): 
    money = 0 
    #do all sorts of things 

基本上等同於:

money='' 
def Another_function(money=0): 
    #do all sorts of things 

這是你所擁有的。看看如何用第一個函數定義變量'money'裏面的的函數?在第二個,你重新定義變量是你需要的。最終效果是相同的,但是,首選是首選,因爲它有助於跟蹤所有變量並且不會全局定義變量。在你的代碼中,在頂部定義'b1'和'money'是不必要的,因爲你已經從位於每個函數中的輸入語句中獲得了一個值。