如何避免循环回代码行?

时间:2019-05-01 11:22:37

标签: python

我正在自学python,遇到了一个我似乎找不到解决方法的问题。 我创建了一段代码,将输入的密码与数据库中存储的密码进行比较。 我的代码应该有两种可能。

1)如果密码正确。 提示用户输入新密码,然后必须再次出现输入密码的提示(这次接受新密码)。

2)如果密码不正确,将提示用户输入密码,直到输入正确的密码为止。

在VBS中,我曾经能够使用GOTO命令。 我不确定是否可以在Python中使用它,是否可以避免使用它,因为它会使程序难以遵循。

password = "@123"
entry = input("Please Input The Password:")

if (password == entry):
    entry = input("Password correct you may enter a new password.")
else:
    entry = input("Password Incorrect, Try again.")

3 个答案:

答案 0 :(得分:2)

有多种方法可以完成此操作。这是使用while循环和break语句实现此目标的简单方法。

["en-US", "en"]

希望有帮助。

答案 1 :(得分:1)

while password != entry: # Executes until (password == entry), and does not execute if it is met, even for the first time.
    print('Sorry, wrong password.')
    entry = input('Enter password >') # or other source of data
print('Correct!')

编辑:执行此操作的其他方法:

while True: # forever loop, but
    entry = input('Enter password >') # or other source of data
    if password == entry:
        print('Correct!') # you can also put this outside of the loop
        break # exit the loop no matter what
        # do not put code after the break statement, it will not run!
    print('Sorry, wrong password') # will execute only if password != entry, break ignores the rest of the code in the loop

答案 2 :(得分:0)

最容易用while语句创建函数。

password = "@123"
def login():
    while True:
        answer = input("Please Input The Password:")
        if answer == password:
            print("Password correct you may enter a new password.")
        else:
            print("Password Incorrect, Try again.")
            break
login()