2012-04-21 51 views
1

我想在Python中編寫一個簡單的「密碼」程序,允許3次嘗試在遞歸函數中「登錄」。我不明白爲什麼它不工作,但...(是的,侏羅紀公園的啓發)如何使用Python中的遞歸計數器?

def magicWord(count): 
    int(count) 
    answer = raw_input("What is the password? ") 
    if answer == 'lucas': 
     print 'ACESS GRANTED' 
    else: 
     count =+ 1 
     if count > 2: 
      while count > 2: 
       count+=1 
       print "na na na you didn\'t say the magic word. " 
     else: 
      magicWord(count) 

magicWord(0) 
+2

你的意思是'數+ = 1'後別的':'? – 2012-04-21 06:04:31

+1

帶有int(count)的行不做任何事情:'int(..)'返回它的參數轉換爲一個整數,它不影響它的參數。 – huon 2012-04-21 06:15:14

+1

你爲什麼要使用遞歸?在這裏似乎並不需要。這是作業嗎? – Shep 2012-04-21 06:27:51

回答

2

你非常接近。有隻是一對夫婦輕微修正起坐:

def magicWord(count): 
    answer = raw_input("What is the password? ") 
    if answer == 'lucas': 
     print 'ACESS GRANTED' 
    else: 
     count += 1 
     if count > 2: 
      print "na na na you didn\'t say the magic word. " 
      return 
     else: 
      magicWord(count) 

這裏有一個樣本會話:

>>> magicWord(0) 
What is the password? alan 
What is the password? ellie 
What is the password? ian 
na na na you didn't say the magic word. 
+1

噢,你刪除了與侏羅紀公園登錄失敗有關的原始無限循環! – Darthfett 2012-04-21 06:12:11

+0

哦,語法錯誤+ =。謝謝! – amorimluc 2012-04-21 16:32:14

1

你真的需要一個遞歸嗎?我的變種不使用它,它似乎更容易

def magic_word(attempts): 
    for attempt in range(attempts): 
     answer = raw_input("What is the password? ") 
     if answer == 'lucas': 
      return True 
    return False 

if magic_word(3): 
    print 'ACESS GRANTED' 
else: 
    print "na na na you didn\'t say the magic word. " 
+0

是的問題確實說使用遞歸。 – jamylak 2012-04-21 06:08:26

1

在這裏你去!遞歸沒有硬編碼函數內的嘗試次數:

def magicword(attempts): 
    valid_pw = ['lucas'] 
    if attempts: 
     answer = raw_input('What is the password?') 
     if answer in valid_pw: 
      return True 
     else: 
      return magicword(attempts -1) 

if magicword(3): 
    print 'you got it right' 
else: 
    print "na na na you didn't say the magic word" 

回報:

What is the password?ian 
What is the password?elli 
What is the password?bob 
na na na you didn't say the magic word 
>>> ================================ RESTART ================================ 
>>> 
What is the password?ian 
What is the password?lucas 
you got it right 
+0

+1優雅和封裝。 – gauden 2012-04-21 07:48:47