Kari Fox
Kari Fox

Reputation: 59

Using a global variable inside a function

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)

Upvotes: 1

Views: 102

Answers (3)

EUPHORAY
EUPHORAY

Reputation: 483

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

Upvotes: 1

rma
rma

Reputation: 1958

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)

Upvotes: 0

Code-Apprentice
Code-Apprentice

Reputation: 83517

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.

Upvotes: 2

Related Questions