Skip to main content
 首页 » 编程设计

python之如何检查变量是否包含不允许输入的字符

2025年01月19日10qq号

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

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 

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

请您参考如下方法:

您需要更改最后一个 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``行 的更短方法是使用 any:

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

最后要注意的是,为了可读性,您应该尽量将缩进 的宽度保持在恒定的4 空格。我没有在这些片段中这样做,因为您将能够使用现有代码测试它们,但理想情况下您应该更改它们。