1

I am confused about using *. The first_example works, but why doesn't the second_example work?

The error states:

UnboundLocalError: local variable 'a' referenced before assignment

What can I do to fix this error?

a, b, c, d, e, f, g, h, i = range(1,10)
alphabet = [a, b, c, d, e, f, g, h, i]

def first_example(*alphabet):
    j = g + i
    print (j)
    second_example(*alphabet)

def second_example(*alphabet):
    a = a + 1
    print (a)

first_example(*alphabet)
Colin Basnett
  • 4,052
  • 2
  • 30
  • 49
Johnny Kang
  • 145
  • 1
  • 12
  • 2
    The `*` isn't the problem. `a = a + 1` is – OneCricketeer Apr 20 '17 at 22:26
  • What can I do to fix it? – Johnny Kang Apr 20 '17 at 22:28
  • add 'global a' in second_example(). – Abhishek Balaji R Apr 20 '17 at 22:30
  • 1
    Note that neither of your functions actually do anything with their `alphabet` parameter. The `alphabet` parameter is not involved in any way with variable lookup for `a`, `g`, `i`, or any of the other variables. – user2357112 Apr 20 '17 at 22:40
  • Your first_example() works because you're creating a new variable called 'j' and only reading 'g' and 'i'. But since you're trying to read _and_ modify 'a' -- not defined in the scope of your function second_example(), you'd have to add the 'global' keyword. – Abhishek Balaji R Apr 20 '17 at 22:40
  • Looks like you stumbled upon python's (non-C-like) scoping rules. See: http://www.python-course.eu/python3_global_vs_local_variables.php for a good explanation – sgrg Apr 20 '17 at 23:34

1 Answers1

1

Not sure what you're trying to do (since alphabet parameter is unused), or why you think * is the issue, but this'll fix the problem.

def second_example(*alphabet):
    global a  # add this
    a = a + 1
    print (a)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245