我可以改进当前的Python代码吗?
我刚开始学习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 个回答
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
我并不反对使用循环和条件判断这种“命令式”的写法,但我建议把你的“业务逻辑”和“展示部分”分开。
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'
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 这个模块。