password = str()
while password != "changeme":
password = input("Password: ")
print("Thou Shall Pass Into Mordor")
else print("Thou Shall Not Pass Into Mordor")
我可以给我的代码打个招呼吗?
当密码错误5次时,我希望它打印“尽管不会传递给Mordor”。有人可以帮帮我吗!有人也可以在柜台摆放吗?
最佳答案
使用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")
仅当您不使用
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