python:如果条件不满足while循环

时间:2018-10-05 04:04:37

标签: python-3.x

我正在尝试编写有关输入密码的代码。用户尝试输入密码三次。如果新的尝试是正确的,或者用户尝试了3次,则循环应结束。但是,我的代码无法运行用于输入正确密码的部分,那么如何摆脱中断呢?请帮帮我!

passwd='pass1'

enter=input('Please enter the password:')

counter = 0

while counter in range(3):

if counter==0:

  if enter==passwd:

     print('Access granted')

     break

  elif enter!=passwd:

     result=input('That is incorrect, please try again:')

     counter=counter+1

elif counter==1:

  if enter==passwd:

     print('Access granted')

     break
  elif enter!=passwd:

     result=input('That is incorrect, please try again:')

     counter=counter+1

elif counter==2:

  if enter==passwd:

    print('Access granted')

    break

 elif enter!=passwd:

    print('Access denied')

    counter=counter+1

3 个答案:

答案 0 :(得分:0)

您可能想写

passwd='pass1'

enter=input('Please enter the password:')

counter = 0
flag = False

while counter in range(3):


  if enter==passwd:

     print('Access granted')
     flag = True

     break

  elif enter!=passwd:

     result=input('That is incorrect, please try again:')

     counter=counter+1

if not Flag:
  print("3 attempts exhausted")

答案 1 :(得分:0)

尝试此代码。

pass = ‘pass1’
count = 0
while count in range(3):
    enter = input(‘insert password: ‘)
    if enter == pass:
       print(‘Access Granted’)
       break
    else:
       print(‘invalid password’)
       count+=1

在您的代码中,您使用“输入”来保留输入内容,然后得出结果。第一次通过后,“输入”从未改变。

答案 2 :(得分:0)

考虑基于所需结果而不是计数器的循环:

counter = 1
passwd  = 'pass1'
enter   = ''

while enter != passwd:
    enter = input('Please enter the password:')
    if (enter != passwd):
        counter += 1
        if (counter > 3):
            print("Access denied")
            break
        else:
            print('That is incorrect, please try again:')
    else:
        print("Access is granted")

我试图保留您的相同信息,这使代码更加复杂。显然,可以通过简化所需步骤来进一步减少它。