Могу ли я улучшить текущий код Python? - PullRequest
2 голосов
/ 06 ноября 2010

Я только начинаю с Python и решил попробовать этот маленький проект из Python Wiki :

Напишите программу подбора пароля, чтобы отслеживать, сколько раз пользовательввел пароль неправильно.Если это более 3 раз, распечатать Вам было отказано в доступе.и прекратить программу.Если пароль правильный, распечатайте Вы успешно вошли в систему и завершите работу программы.

Вот мой код.Это работает, но с этими разрывами циклов и , вложенными в операторы .

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

7 голосов
/ 06 ноября 2010

Вы можете заменить цикл 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 .

3 голосов
/ 06 ноября 2010

Я не против «императивного» ощущения цикла / 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 голосов
/ 06 ноября 2010
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'
0 голосов
/ 06 ноября 2010

Вы можете вывести оператор 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'
...