我可以改进当前的Python代码吗?

Sah*_*bov 2 python conditional loops

我刚开始使用Python并决定从Python Wiki尝试这个小项目:

编写密码猜测程序,以跟踪用户输入密码错误的次数.如果超过3次,则打印您已被拒绝访问.并终止该程序.如果密码正确,请打印您已成功登录并终止程序.

这是我的代码.它工作正常,但这些循环中断嵌套if语句感觉不对.

# Password Guessing Program
# Python 2.7

count = 0

while count < 3:
    password = raw_input('Please enter a password: ')
    if password != 'SecretPassword':
        count = count + 1;
        print 'You have entered invalid password %i times.' % (count)
        if count == 3:
            print 'Access Denied'
            break
    else:
        print 'Access Granted'
        break
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 7

您可以使用以下函数替换while循环:

def login():
    for i in range(3):
        password = raw_input('Please enter a password: ')
        if password != 'SecretPassword':
            print 'You have entered invalid password {0} times.'.format(i + 1)
        else:
            print 'Access Granted'
            return True
    print 'Access Denied'
    return False
Run Code Online (Sandbox Code Playgroud)

您可能还需要考虑使用getpass模块.

  • 真的很小的挑剔:那应该是`.format(i + 1)`.此外,`getpass`是获取真实代码的方法,但对于初学者的练习并不是真正需要的. (2认同)