简体   繁体   中英

how can i fix: UnboundLocalError: local variable 'generate' referenced before assignment

Error:  UnboundLocalError: local variable 'generate' referenced before assignment

why it's giving me this error?

Code

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)

Result

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

Do you know what is local variable ?


caratteri = "" creates local variable which exists only inside passwordGenerator() but you try to use it in generate() when you use list(caratteri) .

In generate() you create also local variable when you use caratteri = list(...) but you do this after trying to get value from caratteri - and this gives error local variable 'caratteri' referenced before assignment .

Better use variables explicitly - send them as arguments

generate(lenght, caratteri) 

And the same problem you may have with Password .

You created global variable Password = "" but inside generate() you create local Password = "" . In generate() you could use global Password to work with global Password instead of creating local Password but beetter use value which you return from function

Password = generate(lenghtt, caratteri)

My version with many other changes

import string
import random

# --- functions ---

def ask_questions():
    length = input("Password length\n>>> ")
    length = int(length)
    
    # In Linux it is popular to use upper case text in `[ ]` 
    # to inform user that if he press only `ENTER` 
    # then system will use this value as default answer. 
    # I inform user that `N` is default answer.
    # I don't like long answers like `yes`, `no` but short `y`, n`
    # and many program in Linux also use short `y`,`n`
    answer = input("Use punctuations [y/N]\n>>> ")  
    answer = answer.upper()

    characters = string.ascii_letters + string.digits
     
    if answer == "Y":
        characters += string.punctuation
    elif answer != "" and answer != "N":
        print("Wrong answer. I will use default settings")
    
    return length, characters

def generate(lenght, characters):
    characters = list(characters)
    random.shuffle(characters)
                
    password = characters[0:lenght]
    password = ''.join(password)
    
    return password

# --- main ---

# I seperate questions and code which generates password
# and this way I could use `generate` with answers from file or stream
length, characters = ask_questions()
password = generate(length, characters)
print(password)

PEP 8 -- StyleGuide for Python Code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM