首页 > 解决方案 > 密码猜测程序问题

问题描述

我最近开始编程,我正在尝试创建一个简单的程序,要求您猜测密码。您最多可以尝试 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 次尝试都错误,它也有效。除此之外,它不起作用。我做错了什么?

标签: python

解决方案


当您要求用户重试时,您不会更新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())。


推荐阅读