首页 > 解决方案 > Python - 检查字符串中是否至少包含 3 个数字

问题描述

我对下面的代码有一些问题。我正在使用 PyCharm。该程序应该获取用户密码的输入,并检查它是否至少有 3 个大写字符和至少 3 个数字。第二个任务是我遇到的麻烦。

import sys


def num(s):
regex = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
for k in regex:
    if regex == s:
        print(y)
        y = y + 1
return y


passw = input("Enter password")
passw2 = list(passw)
lenght = (len(passw2))
if lenght < 8:
print("Password needs to be at least 8 chars long")
else:
    i = 0
    for x in passw2:
        if x.isupper():
            i += 1
if i < 3:
    print("You need at least 3 upper cased chars in your password")
    sys.exit()
else:
    numpassw2 = num(passw2)
    if numpassw2<3:
        print("At least 3 numbers needs to be given")
    else:
        print("OK,lets continue")

它卡在调用 num() 函数并给出以下错误:

Traceback (most recent call last):
File "H:/szkola/python/projects/password/passwchecker.py", line 27, in <module>
numpassw2 = num(passw2)
File "H:/szkola/python/projects/password/passwchecker.py", line 10, in num
return y
UnboundLocalError: local variable 'y' referenced before assignment

标签: pythonpython-3.x

解决方案


在您的函数中num(s)声明一个名为y. 因为它在您的函数中丢失并且它正在引发错误。

def num(s):
    y = 0 # DECLARE y BEFORE CALL IT.
    regex = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    for k in regex:
        for c in s:
            if c == k:
                print(y)
                y = y + 1
    return y

推荐阅读