需要帮助将其他人与计数器放在一起 [英] Need help putting the else into the while with a counter

查看:149
本文介绍了需要帮助将其他人与计数器放在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

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

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?

推荐答案

使用 break 来结束一个循环,并使用表示,其中范围()

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

for 循环的 else 分支是<当你没有使用 break 来结束循环时执行strong> 。

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

演示:

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

这篇关于需要帮助将其他人与计数器放在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆