password = str()
while password != "changeme":
password = input("Password: ")
print("Thou Shall Pass Into Mordor")
else print("Thou Shall Not Pass Into Mordor")
请问我的代码可以使用。
我希望它在密码错误5次时打印“虽然不会传入Mordor”。有人可以帮帮我吗!有人也可以把柜台放进去吗?
答案 0 :(得分:4)
使用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