在下面的代碼中,我嘗試使用標志在 true(密碼正確)時跳出回圈,但將不正確嘗試的次數限制為 3。
def secretagent():
flag=False
while flag==False:
for i in range(3):
password=input("Enter password:")
if password=="secret007":
print("Access Granted!")
flag=True
break
else:
print("Impostor...access denied!")
print("Welcome Secret agent...let's get started...")
#print("You have tried 3 times and failed. Goodbye forever!")
secretagent()
為了方便起見,這里是小飾品:https ://trinket.io/python/8869529c45
任何人都可以建議一個合適的解決方案 - 最pythonic的方式和學習目的解釋最好的方法來解決這個問題。例如,for 回圈或while 回圈應該在外面嗎?為什么?
目前,它仍然允許無限次嘗試,所以我的 for 回圈顯然放錯了。
uj5u.com熱心網友回復:
使用int而不是bool
import sys
number_of_tries = 0
while True:
if number_of_tries == 3:
sys.exit() # exit the program
password=input("Enter password:")
if password=="secret007":
print("Access Granted!")
break
else:
print("Impostor...access denied!")
number_of_tries = 1
print("Welcome Secret agent...let's get started...")
或者更簡單的for回圈:
for _ in range(3):
password=input("Enter password:")
if password=="secret007":
print("Access Granted!")
break
else:
print("Impostor...access denied!")
else: # it means no break was called
sys.exit()
uj5u.com熱心網友回復:
Personnaly,而不是使用標志,我只會使用 for 回圈并迭代它 3 次并檢查答案的值。然后我會回傳 True 或 False,或者根據答案繼續回圈。然后我會根據函式的回傳值列印回應。像那樣的東西
def secretagent():
for i in range(3):
password=input("Enter password:")
if password=="secret007":
print("Access Granted!")
return True
elif i < 2:
print("Wrong password, try again")
else:
print("Impostor...access denied!")
return False
flag = secretagent()
if flag==True:
print("Welcome Secret agent...let's get started...")
else:
print("You have tried 3 times and failed. Goodbye forever!")
您的 while 回圈不是必需的,因為您已經知道您只想向代理提供 3 次嘗試。
希望這可以幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537560.html
標籤:Python循环
下一篇:在有條件的地圖地圖中迭代串列
