首页 > 解决方案 > 在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 循环之外吗?

标签: python

解决方案


你或多或少有正确的想法。只是您需要在password_length循环外部分配一个值。

想一想:当您的代码运行时,解释器会进入while循环并尝试对涉及password_length. 但是,此时password_length还不存在,因为它第一次获取值是循环内。因此,您应该在进入循环之前将其初始化为一个合理的值,例如 0。

补充两点:

  1. 您正在计算前一个密码的密码长度,因此如果您输入一个太短/太长的密码,然后输入一个可接受的密码,则打印的长度将是不可接受的密码。

  2. 一般来说,更喜欢 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}.')

推荐阅读