本问题已经有最佳答案,请猛点这里访问。
我正在尝试编写一个简单的python代码块,我希望在将来的程序中重用它。 它将检查密码是否正确以及是否未返回到第一行代码并再次启动该过程。 我试图完成的方式给了我一个错误。 谁能帮我找到更好的解决方案? 这是我目前使用的代码:
def password_checker():
program_acceptance ="Welcome to the Program! "
acceptable_password ="Godisgood"
print("Please Enter the Password")
while True:
password = input("Password: ")
if password == acceptable_password:
print(program_acceptance)
break
if password != acceptable_password:
print("Invalid password, please try again..."
break
想想功能而不是线条,它会更容易
循环自动完成。 你明确地用break退出循环。
循环块应该是缩进的
在许多情况下,答案是continue语句,它会跳回循环控制语句。
应该删除最后一个break语句,以确保程序在提供假密码时保持循环。
def password_checker():
program_acceptance ="Welcome to the Program! "
acceptable_password ="Godisgood"
print("Please Enter the Password")
while True:
password = input("Password: ")
if password == acceptable_password:
print(program_acceptance)
break
if password != acceptable_password:
print("Invalid password, please try again...")
password_checker()
你应该提供一个解释,而不仅仅是代码。