python - 在while循环中定义变量
问题描述
我正在学习 python 课程,并试图在我的代码中正确使用 while 循环
我的代码应该检查密码是否最小长度 = 6 和最大长度 = 14,它还将检查密码是否只有数字或字母。如果它具有两者的组合,则它应该打印“强密码”,如果它只有数字或字母,它将打印“弱密码”。
MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 14
while password_length >= MIN_PASSWORD_LENGTH or password_length <= MAX_PASSWORD_LENGTH:
password_length = len(password)
password = input("Enter your password: ")
if password.isalpha():
print("Your password is weak!")
elif password.isnumeric():
print("Your password is weak!")
else:
print("Your password is strong!")
print("Number of characters used in password: ", password_length,"the min length expected is: ",MIN_PASSWORD_LENGTH,
"the max length is: ", MAX_PASSWORD_LENGTH)
当我运行我的代码时,它带有错误消息:'name password_length is not defined'。我不知道该怎么办?我的代码是否正确?我应该将 password_length 放在 while 循环之外吗?
解决方案
你或多或少有正确的想法。只是您需要在password_length
循环外部分配一个值。
想一想:当您的代码运行时,解释器会进入while
循环并尝试对涉及password_length
. 但是,此时password_length
还不存在,因为它第一次获取值是在循环内。因此,您应该在进入循环之前将其初始化为一个合理的值,例如 0。
补充两点:
您正在计算前一个密码的密码长度,因此如果您输入一个太短/太长的密码,然后输入一个可接受的密码,则打印的长度将是不可接受的密码。
一般来说,更喜欢 f-strings 或
str.format
对字符串连接的调用,因此,对于您的print
,这可能会更好:
print(f'Number of characters used in password: {password_length}; '
'the min length expected is {MIN_PASSWORD_LENGTH} and the '
'max length expected is {MAX_PASSWORD_LENGTH}.')
推荐阅读
- c# - 从为 ASP.NET Core 应用程序生成的调试文件夹中恢复 .cs 文件
- postgresql - Postgresql 损坏的 pg_catalog 表
- pega - 如何搜索表中是否存在值
- php - 为什么我们必须使用 url 来访问 php 文件而不是本地文件访问?
- javascript - 使用 JWT 的 API 身份验证总是给出 WebTokenError
- android - 如何知道使用sharedpreference在android中点击的最后一个按钮?
- python - Python中2D平面中点的透视变换
- excel - 将多个指定文件中的数据合并到 1 个主工作表中
- javascript - 部署Node App后如何在Heroku上安装依赖项?
- javascript - 如何保存应用程序的登录次数?(nodejs,JS,mongodb)