[英]How do you make use of a counter with recursion in Python?
I'm trying to write a simple "password" program in Python that allows 3 attempts at "logging in" with a recursive function. 我正在尝试用Python编写一个简单的“密码”程序,允许3次尝试使用递归函数“登录”。 I can't figure out why it's not working though... (And yes, Jurassic Park inspired) 我无法弄清楚为什么它不起作用......(是的,Jurassic Park的灵感来源)
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)
You were very close. 你非常接近。 There were just a couple minor fix-ups: 只有几个小修复:
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)
Here's a sample session: 这是一个示例会话:
>>> 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.
Do you really need a recursion? 你真的需要递归吗? My variant don't use it and it seems easier 我的变体不使用它,它似乎更容易
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. "
Here you go! 干得好! Recursion without hardcoding the number of attempts within the function: 递归而不对函数内的尝试次数进行硬编码:
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"
returns: 收益:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.