python简单密码登录有限试用与while循环

时间:2015-08-21 05:55:44

标签: python-2.7 login while-loop passwords

Z=1     #username can be ramdom as long as password is cyber
while (Z>0):
    Z=Z+1
    username=raw_input('key in your username: ')
    if username==(""):
        print '\nPlease do not leave it blank! \nPlease type again... \n'
    else:
        Z=0
else:
    Z=Z+1
P=0 #password part
while (P<3):
    pssw=raw_input('key in your password: ')
    if pssw=="cyber":
        P=3
    else:
        pssw=raw_input('\nWrong password, \nSecond chance: ')
        P=P+1
        if pssw=="cyber":
            P=3
        else:
            pssw=raw_input('\nWrong password, \nWrong again will terminate the program... \nType again: ')
            P=P+1
            if pssw=="cyber":
                P=3
            else:
                print "Bye..."
                exit('ASGN_1151102784_A01A.py')     #terminate program after 3 error pssw
print "\nWelcome "+username
#to be continue...

以上是我的登录代码,它需要任何随机用户名,但条件是密码必须仅限网络。但是,我的讲师拒绝接受这个代码,因为她说密码检查系统应该在while循环中完成,而不是在while循环中创建新的if else语句。

现在我真的很困惑。是否有任何解决方案从3用户的用户请求密码,如果密码正确,然后继续运行程序,只需简单的while循环退出程序?

1 个答案:

答案 0 :(得分:1)

可能是这样的:

...
P=0 #password part
pssw = None
messages = {
    0: 'key in your password: ',
    1: '\nWrong password, \nSecond chance: ',
    2: '\nWrong password, \nWrong again will terminate the program... \nType again: '
}
try:
    while (pssw != 'cyber'):
        pssw=raw_input(messages[P])
        P += 1
except KeyError:
    print "Bye..."
    exit('ASGN_1151102784_A01A.py')     #terminate program after 3 error pssw
else:
    print "\nWelcome "+username