1

再帰関数を使用して「ログイン」を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)
4

3 に答える 3

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.
于 2012-04-21T06:09:14.413 に答える
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
于 2012-04-21T06:39:39.577 に答える
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. "
于 2012-04-21T06:07:24.220 に答える