gpt4 book ai didi

python - 需要帮助用计数器将 else 放入 while

转载 作者:太空宇宙 更新时间:2023-11-04 10:41:10 28 4
gpt4 key购买 nike

password = str()

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

请问我的代码有一些 helo 吗?

我希望它在密码错误 5 次时打印“Though Shall Not Pass Into Mordor”。有人可以帮帮我吗!有人也可以放一个计数器吗?

最佳答案

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

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

关于python - 需要帮助用计数器将 else 放入 while,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20479259/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com