[SOLVED] How do I use the same variable in and out of functions?

Issue

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.

Solution

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

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

Answered By – Andrey

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.