2

这是一个非常新手的问题。因此,我正在尝试在 Python 中编写一个登录系统,它要求输入用户名(只有 1 个用户名可用),如果输入的用户名不正确,则表示用户名无效,如果正确,则要求输入密码,如果密码不正确,则提示密码错误并继续再次询问密码,如果输入的密码正确,则提示已登录。

到目前为止,我能够做的是:

a = 0

 while a < 1:             
     print ('Username:')  
     name = input()
     if name != 'Teodor': #checks the username typed in
         print ('Invalid username.') 
         continue
     else:
         print ('Hello, Teodor.')
         print ('Password:')
         a = a + 1

 password = input()

 b = 0
      while b < 1:
     if password != '1234': #checks the password typed in
         print ('Password incorrect.')
         b = b + 1
         continue

     else:
         print ('Password correct.')
         print ('Logging in...')
         print ('Logged in.')
         break

这很有效,尽管如果用户输入了错误的密码,它会做一些我不想要的事情。如果用户输入了错误的密码,我希望程序告诉用户“密码错误”并继续再次询问,但它没有这样做,它只是打印“密码错误”,然后终止. 不过,它在请求用户名的部分可以 100% 工作。

这是我错过的一件小事。我怎样才能解决这个问题?非常感谢!

4

4 回答 4

2

每次用户输入不正确的密码时,该语句b = b + 1都会终止您的循环。while真的没有必要。

您也可以将密码提示包装在一个while循环中:

while input("Enter password") != "1234":
    print("Password incorrect")
于 2017-06-27T00:09:58.623 回答
1

+ 1检查密码时不需要。那只会让你脱离循环。

相反,请尝试:

if password != '1234': #checks the password typed in
         print ('Password incorrect.')
         continue

一个更好的解决方案是使用布尔值,而不是使用+1and<1来打破循环。样本:

userCorrect = False
while not userCorrect:
    print ('Username:')
    name = raw_input()
    if name != 'Teodor': #checks the username typed in
        print ('Invalid username.')
        continue
    else:
        print ('Hello, Teodor.')
        print ('Password:')
        userCorrect = True

password = raw_input()

passCorrect = False
while not passCorrect:
    if password != '1234': #checks the password typed in
        print ('Password incorrect.')
        print ('Password:')
        password = raw_input()
    else:
        passCorrect = True
# Since password is correct, continue.
print ('Password correct.')
print ('Logging in...')
print ('Logged in.')
于 2017-06-27T00:07:07.137 回答
0

正如其他人已经指出的那样,问题在于b = b + 1打破条件while b < 1:,导致它不再要求另一个密码。简单删除行b = b + 1

想让它变得更好吗?

getpass()使用而不是避免“过肩”攻击input()。您的密码输入被屏蔽为****
ex。

from getpass import getpass
password = getpass()

Cryptify
好吧,除了听起来很酷之外,这并不能真正阻止某人修改代码以跳过密码阶段——但它可以阻止他们在代码中看到原始密码。

这篇文章有一个很好的例子passlib

这有助于保护非唯一/敏感密码(例如您用于 5x 其他事情的密码,或者您母亲的娘家姓……不要把她拖入其中)

于 2017-06-27T01:08:38.323 回答
0

此循环 ( while b < 1:) 在输入无效密码时终止。

看着

>     if password != '1234': #checks the password typed in
>         print ('Password incorrect.')
>         b = b + 1
>         continue

这行代码b = b + 1使它while b < 1:变为假,从而结束循环并终止您的程序。

于 2017-06-27T00:07:37.107 回答