使用break
結束一個循環,並使用for
有range()
:
for attempt in range(5):
password = input("Password: ")
if password == "changeme":
print("Thou Shall Pass Into Mordor")
break
else:
print("Thou Shall Not Pass Into Mordor")
一個for
循環的else
分支當你沒有使用break
結束僅環執行。
演示:
>>> # Five failed attempts
...
>>> for attempt in range(5):
... password = input("Password: ")
... if password == "changeme":
... print("Thou Shall Pass Into Mordor")
... break
... else:
... print("Thou Shall Not Pass Into Mordor")
...
Password: You shall not pass!
Password: One doesn't simply walk into Mordor!
Password: That sword was broken!
Password: It has been remade!
Password: <whispered> Toss me!
Thou Shall Not Pass Into Mordor
>>> # Successful attempt after one failure
...
>>> for attempt in range(5):
... password = input("Password: ")
... if password == "changeme":
... print("Thou Shall Pass Into Mordor")
... break
... else:
... print("Thou Shall Not Pass Into Mordor")
...
Password: They come in pints?! I'm having one!
Password: changeme
Thou Shall Pass Into Mordor
你應該改變'input'到'raw_input'。 'input'將嘗試評估輸入是什麼,但raw_input將簡單地將其作爲一個字符串。在這種情況下,你想'raw_input'。 –
@KyleNeary OP是使用python 3. – roippi
@KyleNeary:我已經在你現在刪除的答案中評論了這個。 'raw_input'在Python 3中沒有了,它已經被重命名爲'input()',並且來自Python 2的舊'input()'不見了。 –