如何检查变量是否包含不允许的字符?

时间:2017-11-16 20:39:58

标签: python python-3.x

我正在编写密码程序,如果满足某些要求,它将显示分数。但我仍然坚持如何检查是否允许某些字符。如果不允许,则应通知读者。 这是我的代码:

user_password = input("\nEnter your password:")
user_score = 0
user_length = len(user_password)
symbols = "$%^&*()_-+="

if len(user_password)>24:
    print("Your password is too long! It must be between 6 and 24")
elif len(user_password)<6:
    print("Your password is too short! It must be between 6 and 24")
elif len(user_password) >=6 and len(user_password) <= 24:
    lower = sum([int(c.islower()) for c in user_password])
    if lower > 0:
            user_score = user_score + 5
    upper = sum([int(c.isupper()) for c in user_password])
    if upper > 0:
            user_score = user_score + 5
    integer = sum([int(c.isdigit()) for c  in user_password])
    if integer > 0:
            user_score = user_score + 5
    for c in symbols:
            if c in user_password:
                    user_score = user_score + 5
    for c in user_password:
            if c not in symbols:
                    print("Some symbols you entered are not allowed")
                    break

我想要它,以便如果错误地输入符号,程序将结束。但是,当输入错误的符号时,它会显示符号输入次数的消息。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您需要更改上一个for-loop,以使其失败if c in symbols,那里有一个not正在抛出该程序......

for c in user_password:
            if c in symbols:
                    print("Some symbols you entered are not allowed")
                    break

使用2``lines执行此操作的较短方法是使用any

if any(c in symbols for c in user_password):
            print("Some symbols you entered are not allowed")

作为最后一点,您应该尝试将indentation宽度保持为4的常量readablility空格。我没有在这些片段中完成此操作,因为您可以使用现有代码测试它们,但理想情况下您应该更改它们。

答案 1 :(得分:0)

if c not in symbols:更改为if c in symbols:

user_password = input("\nEnter your password:")
user_score = 0
user_length = len(user_password)
symbols = "$%^&*()_-+="

if len(user_password)>24:
    print("Your password is too long! It must be between 6 and 24")
elif len(user_password)<6:
    print("Your password is too short! It must be between 6 and 24")
elif len(user_password) >=6 and len(user_password) <= 24:
    lower = sum([int(c.islower()) for c in user_password])
    if lower > 0:
            user_score = user_score + 5
    upper = sum([int(c.isupper()) for c in user_password])
    if upper > 0:
            user_score = user_score + 5
    integer = sum([int(c.isdigit()) for c  in user_password])
    if integer > 0:
            user_score = user_score + 5
    for c in symbols:
            if c in user_password:
                    user_score = user_score + 5
    for c in user_password:
            if c in symbols:
                    print("Some symbols you entered are not allowed")
                    break

希望这有帮助,欢迎来到SO!