需要帮助将其他人与计数器放在一起

时间:2013-12-09 19:43:04

标签: python if-statement

password = str()

while password != "changeme":
    password = input("Password: ")
print("Thou Shall Pass Into Mordor")
else print("Thou Shall Not Pass Into Mordor")

请问我的代码可以使用。

我希望它在密码错误5次时打印“虽然不会传入Mordor”。有人可以帮帮我吗!有人也可以把柜台放进去吗?

1 个答案:

答案 0 :(得分:4)

使用break结束循环,并将forrange()一起使用:

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")

当您未使用else结束循环时,for循环的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