1

I have this code:

num = 1
def function():
  num = num - 1
print (function())

Is there a way to use the variable num in and out of the function without it giving this error message:

UnboundLocalError: local variable 'num' referenced before assignment

I'm a beginner coder, and if the solution is complicated and difficult just throw me a link to a page that teaches how. If it's not worth the trouble, say so.

Mrmcmuffin
  • 21
  • 5
  • Also: https://stackoverflow.com/questions/423379/using-global-variables-in-a-function – Craig Jan 21 '22 at 04:28
  • And: https://stackoverflow.com/questions/13881395/in-python-what-is-a-global-statement – Craig Jan 21 '22 at 04:29
  • Thanks, this makes a lot more sense now. – Mrmcmuffin Jan 21 '22 at 04:36
  • But you shouldn't use `global` anyway. It makes debugging hard and reusing code even harder. Functions should get allt the data they need as parameters and give back a result with `return`. – Matthias Jan 21 '22 at 09:24

2 Answers2

1
num = 1
def function():
  global num
  num = num - 1
  return num
print (function())

You should add return if you want to see the result.

Andrey
  • 400
  • 2
  • 8
0

Try this StackOverflow question you will get an idea UnboundLocalError on local variable when reassigned after first use

Athul Joy
  • 33
  • 5