密码猜测程序问题

时间:2019-06-24 23:29:00

标签: python

我最近开始编程,我正在尝试创建一个简单的程序,要求您猜测密码。您最多可以尝试3次,如果您无法猜出密码,那么您将被拒绝访问。 (我最初在Wikibooks中看到过类似的程序,但我想自己做)。所以这是我的代码:

  # Write a password guessing program to keep track of how many times the 
  # user has entered the password wrong.
  # If it is more than 3 times, print You have been denied access and 
  # terminate the program.
  # If the password is correct, print You have successfully logged in and 
  # terminate the program.

  guess_count = 0

  correct_pass = 'password'

  pass_guess = str(input("Please enter your password: "))
  guess_count += 1

  while True:
      if pass_guess == correct_pass:
          guess_count += 1
          print('You have successfully logged in.')
          break

      elif pass_guess != correct_pass:
          if guess_count < 3:
              guess_count += 1
              str(input("Wrong password. Try again. "))
          elif guess_count >= 3:
              print("You have been denied access.")
              break

正如我所说,我是编程的新手,对循环的理解也不是很好。该代码仅在我第一次尝试输入正确的密码时才有效,并且如果我的3次尝试均不正确,则该代码也有效。除此之外,它不起作用。我做错了什么?

1 个答案:

答案 0 :(得分:0)

当您要求用户重试时,您不会更新pass_guess变量。他们输入了新密码,但是程序继续测试第一个猜测。更改

str(input("Wrong password. Try again. "))

收件人:

pass_guess = str(input("Wrong password. Try again. "))

调用str()时也不需要使用input(),因为它总是返回一个字符串(我假设您使用的是Python 3.x-如果您使用的是2 .x,您应该使用raw_input()而不是input())。