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

时间:2010-11-05 22:02:19

标签: python loops conditional

我刚刚开始使用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

4 个答案:

答案 0 :(得分: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

您可能还想考虑使用getpass模块。

答案 1 :(得分:3)

我不反对loop / if的“命令式”感觉,但我会将你的“业务逻辑”与你的“演示文稿”区分开来:

count = 0

# Business logic
# The correct password and the maximum number of tries is placed here
DENIED, VALID, INVALID = range(3)
def verifyPassword(userPassword):
    global count
    count += 1

    if count > 3:
        return DENIED
    elif password == 'SecretPassword':
        return VALID

    return INVALID

# Presentation
# Here you do the IO with the user
check = INVALID
while (check == INVALID):
    password = raw_input('Please enter a password: ')
    check = verifyPassword(password)

    if check == INVALID:
        print 'You have entered invalid password %i times.' % (count)
    elif check == VALID:
        print 'Access Granted'
    else # check == DENIED
        print 'Access Denied'

答案 2 :(得分:2)

granted = False # default condition should be the least dangerous
for count in range(3):
    password = raw_input('Please enter a password: ')
    if password == 'SecretPassword': # no need to test for wrong answer
        granted = True
        break
    print 'You have entered invalid password %i times.' % (count+1) # else

if granted:
    print 'Access Granted'
else:
    print 'Access Denied'

答案 3 :(得分:0)

您可以将if语句从while循环中删除。

# Password Guessing Program
# Python 2.7

count = 0
access = False

while count < 3 and not access:
    password = raw_input('Please enter a password: ')
    if password != 'SecretPassword':
        count += 1
        print 'You have entered invalid password %i times.' % (count)
    else:
        access = True

if access:
    print 'Access Granted'
else:
    print 'Access Denied'