python - 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
解决方案
在您的函数中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
推荐阅读
- html - 导航栏仅在滚动后显示
- hadoop - 如何快速检查 HDFS 的内容是否发生了变化?
- javascript - 在更大的屏幕上使 material-ui 网格换行
- python - 没有名为“kivy”的模块
- python - 在 termux 中运行具有依赖项的 python 应用程序
- kubernetes - 尝试安装 cp-helm-charts:设置被忽略
- reactjs - 在 React js 中显示范围日历日期的问题
- c# - 如何将自定义列添加到 WinForms DataGrid(注意:不是 DataGridView)
- javascript - 苗条的头衔后缀
- php - 使用 PHP 获取 IIS 服务器配置主机设置