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)
6
  • 1
    You need to use the global keyword and "import" the globals into the function. Commented Jun 23, 2017 at 2:37
  • indentation. is the problem Commented Jun 23, 2017 at 2:42
  • @Carcigenicate Exactly how do I go about doing that? Commented Jun 23, 2017 at 2:46
  • @KariFox Lookup how to use the global keyword. Honestly, you should avoid using it when possible, but it's an option if you really need it. Commented Jun 23, 2017 at 2:47
  • @Carcigenicate thank you. Commented Jun 23, 2017 at 2:50

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
@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.
@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.
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")

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.