How to fix NameError: name 'password' is not defined

How to fix NameError: name 'password' is not defined

这是我的第一个代码。如果我正确输入所有内容,效果会很好。但是,如果我在某些点输入了错误的值,则会收到错误 "NameError: name 'password' is not defined"。此外,如果您可以查看我的代码并向我提供一些关于如何让它变得更好的反馈,以及一个可能的解决方案,那就太棒了。

不知道为什么没有定义密码。 我尝试过的解决方案: 1. 分配变量名。 2. 阅读我正在学习的书,但根据书,我的代码没问题。 3.阅读类似的帖子,但他们的代码更高级,所以我无法理解代码或解决方案。 4.各种缩进。`5。 ""中的字符匹配得很好。

只是好像没有在密码中存储值,如何在密码中存储值?

我的代码:

def PWCategory():
    print("[pw category]")
    for i in range(0, len(category)):
        print(i+1, ".", category[i])
    print()

def NumPWMaking():
  num_random = string.digits
  password = ""
  for i in range(lang):
    password += random.choice(num_random)
  print(password)


def AlphaPWMaking():
  string_random = string.ascii_letters
  password = ""
  for i in range(lang):
    password += random.choice(string_random)
  print(password)

def NumAlPWMaking():
  string_random = string.ascii_letters + string.digits
  password = ""
  for i in range(lang):
    password += random.choice(string_random)
  print(password)

def NumAlUniPWMaking():
  string_random = string.ascii_letters + string.digits + string.punctuation
  password = ""
  for i in range(lang):
    password += random.choice(string_random)
  print(password)

print("pw making")
lang = int(input("pw digit(4~8): "))

if(lang < 4):
  print("Input value is less than 4.")

elif(lang > 8):
  print("Input value is greater than 8.")

else:
  if __name__ == '__main__':

    category = ("only number", "only alphabet", "number+alphabet", 
"number+alphabet+Special Characters")
    PWCategory()
    select = int(input("Select the number. (exit : 0) : "))
    if(select==0):
      print("exit")

    elif(select==1):
      NumPWMaking()

    elif(select==2):
      AlphaPWMaking()

    elif(select==3):
      NumAlPWMaking()

    elif(select==4):
      NumAlUniPWMaking()

print("pw matching")
searchpw = re.compile("[a-z]+")
matchingpw = searchpw.search(password)
password
if matchingpw == password:
  print("matched pw: ")
  print(matchingpw.group())

else:
  print("I couldn't find it.")

在函数内部创建的变量仅在函数内部有效,因此将 NumPWMaking() 编辑为:

def NumPWMaking():
  num_random = string.digits
  password = ""
  for i in range(lang):
    password += random.choice(num_random)
  print(password)
  return password

并转换:

elif(select==1):
      NumPWMaking()

收件人:

elif(select==1):
      password=NumPWMaking()

其他功能也同样如此。