1

I'm trying to use an already set global variable inside a function, but keep getting an error "Local variable "password" referenced before assigned". Is there something I'm missing to where it can't find the actual global variable?

password = ""
def random_characters(letters):
    add = random.choice(letters)
    password = password + add
letters_strong = string.ascii_letters + string.digits + string.punctuation
for i in range(16):
    random_characters(letters_strong)
print(password)
Kari Fox
  • 39
  • 1
  • 6

3 Answers3

2
password = password + add

This creates a new local variable which shadows the global variable of the same name. To solve the problem, either use a different name for the local variable or pass a parameter. I strongly suggest the later.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • I'm specifically trying to use the global variable though. I want the information to be stored there, not in a local variable to the function. – Kari Fox Jun 23 '17 at 02:47
  • @KariFox Because explicitly passing in the information that's required for a fucntion to run is good habit. It makes it clear when reading the function what data is, and isn't relevant to the operation of the function. Plus, manipulating globals is a bad habit. It leads to a lot of problems down the road. – Carcigenicate Jun 23 '17 at 02:52
  • @KariFox I agree with the above comment. Global variables are considered a bad programming practice. You should definitely take the time to learn how to pass values as parameters and return values from functions. You can make a program with these tools that gives the same results as trying to do this with globals. And the program will be better designed. – Code-Apprentice Jun 23 '17 at 02:57
1

In your case, global an assigned variable within a function is strongly recommended.

#coding: utf-8

_str = ""

def test(var):
    global _str
    _str += var
    return _str

test("output")
EUPHORAY
  • 453
  • 6
  • 15
0

use global password in the random_characters function.

So, for example,

password = ""
def random_characters(letters):
    global password
    add = random.choice(letters)
    password = password + add
letters_strong = string.ascii_letters + string.digits + string.punctuation
for i in range(16):
    random_characters(letters_strong)
print(password)
rma
  • 1,853
  • 1
  • 22
  • 42