1

我正在尝试用 Python 编写一个简单的“密码”程序,该程序允许 3 次尝试使用递归函数“登录”。我不知道为什么它不起作用......(是的,侏罗纪公园的灵感)

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 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 回答
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 回答