0

I was wondering if there is anyway to set a variable from a function. Let me explain with the following code:

number = 0
print number

def number_parse():
    number = number + 1
    return number

print number
number_parse()
print number
number = number_parse()
print number

I get the following output:

0
0
0
1

So what I am really trying to ask is, is there a way to set a variable from a function without having to call it from the line:

number = number_parse()

Can I not define a variable's value just by calling the function? What if I would like to set multiple variables (e.g. number, number_2, number_3 etc)

I am new to python and can't seem to figure this one out

user2864740
  • 60,010
  • 15
  • 145
  • 220

1 Answers1

0

You can use the global keyword.

number = 0
print number

def number_parse():
    global number
    number = number + 1
    return number

print number
number_parse()
print number

Remember it's a bad attitude and you generally should not use it.

You can read more about it here: http://blog.adku.com/2011/11/scope-and-variable-binding-in-python-1.html

Shortly, the rules are:

  • Can read from current / higher scope.
  • Can't write to higher scope.
  • Can't read from higher scope, than write to the current scope new variable with the same name.

That's about it.

Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64