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 次尝试都错误,它也有效。除此之外,它不起作用。我做错了什么?
解决方案
当您要求用户重试时,您不会更新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()
)。
推荐阅读
- r - 如何使用 mutate 将向量与数据框匹配
- python - Python中的语音识别错误(位置参数错误)
- reactjs - 有没有办法将用户从一个页面重定向到另一个页面的底部
- java - 模式匹配开关是否需要在 java 中总是详尽无遗?
- java - 查找 ArrayList 中出现频率最高的数字
- mysql - 将csv文件导入MYSQL工作台时行导入失败1265、1366
- mysql - 从视图中获取 SHOW CREATE TABLE,就好像它是一张表一样
- python - 使用 SQLAlchemy 显示所有表
- xml - 按参数值拆分谷歌 XML 项目
- python - 意外的关键字参数