Need help putting the else into the while with a counter

家住魔仙堡 提交于 2020-01-16 03:32:05

问题


password = str()

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

Could I please have some helo with my code.

I want it to print "Though Shall Not Pass Into Mordor" when the password is incorrect 5 times. Can someone please help me! Can someone also please put a counter in?


回答1:


Use break to end a loop, and use for with a 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")

The else branch of a for loop is only executed when you did not use break to end the loop.

Demo:

>>> # 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


来源:https://stackoverflow.com/questions/20479259/need-help-putting-the-else-into-the-while-with-a-counter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!