Error: UnboundLocalError: local variable 'generate' referenced before assignment
为什么它会给我这个错误
代码
import string
import random
Password = ""
lettere = string.ascii_letters
numeri = string.digits
punteggiatura = string.punctuation
def getPasswordLenght():
lenght = input("How log do you want your password...\n>>> ")
return int(lenght)
def passwordGenerator(lenght):
caratteri = ""
requestPunteggiatutaIclusa = input("Punteggiatura (YES | NO)\n>>> ")
if requestPunteggiatutaIclusa.upper() == "YES" :
caratteri = f"{lettere}{numeri}{punteggiatura}"
generate(lenght)
elif requestPunteggiatutaIclusa.upper() == "NO" :
caratteri = f"{lettere}{numeri}"
generate(lenght)
else :
print("Error")
passwordGenerator(lenght)
return Password
def generate(lenght) :
caratteri = list(caratteri)
random.shuffle(caratteri)
Password = ""
for i in range(lenght):
Password = Password + caratteri[i]
i = i + 1
return Password
passwordGenerator(getPasswordLenght())
print(Password)
结果
How log do you want your password...
8
Punteggiatura (YES | NO)
yes
Traceback (most recent call last):
File "/Users/paolo/Desktop/COde/PY/passwordGenerator.py", line 46, in <module>
passwordGenerator(getPasswordLenght())
File "/Users/paolo/Desktop/COde/PY/passwordGenerator.py", line 33, in passwordGenerator
generate(lenght)
File "/Users/paolo/Desktop/COde/PY/passwordGenerator.py", line 19, in generate
caratteri = list(caratteri)
UnboundLocalError: local variable 'caratteri' referenced before assignment
你知道什么是
local variable
吗caratteri = ""
创建仅存在于passwordGenerator()
内部的局部变量,但在使用list(caratteri)
时,尝试在generate()
中使用它在
generate()
中,当您使用caratteri = list(...)
时也会创建局部变量,但在尝试从caratteri
中获取值后会创建局部变量,这会产生错误local variable 'caratteri' referenced before assignment
更好地显式使用变量-将它们作为参数发送
和
Password
有同样的问题您创建了全局变量
Password = ""
,但在generate()
内部您创建了局部变量Password = ""
。在generate()
中,您可以使用global Password
来处理全局Password
,而不是创建局部Password
,但不能使用从函数返回的值我的版本有很多其他的变化
PEP 8 StyleGuide for Python Code
相关问题 更多 >
编程相关推荐