0

How would I globalize globalme1, 2 and 3 variables?

def example(globalme1, globalme2, globalme3=''):
       print("")

I tried globalizing them before the function.

globalize: Make accessible to other functions

  • What do you mean by "globalize"? Please explain in more detail what you expect this code to do. – mkrieger1 Apr 23 '21 at 21:17
  • 1
    if by 'globalize' you mean making the variables accessible in the outer scope: please don't try, use `return` values instead – asdf101 Apr 23 '21 at 21:20
  • A Python function *never* receives variables - it merely receives values. Whether or not those values came from variables is not something the function should (or can!) care about. – jasonharper Apr 23 '21 at 22:03
  • @jasonharper I agee but these values arent not being used by other functions :( – Grandma Kisses Apr 23 '21 at 22:06
  • @asdf101 return as in a return statement. Those are only allowed once in each function. Sorry im new to coding so – Grandma Kisses Apr 23 '21 at 22:07
  • @GrandmaKisses they can occur multiple times in a function, it's just that the first one that is encountered exits the function. You can return multiple values at once: `return value1, value2, ... etc`, then use `values = example(arguments)` to get a tuple of the return values or `value1, value2, ... etc = example(arguments)` to automatically unpack them – asdf101 Apr 23 '21 at 22:10
  • Why would you want to use a global variable. In my many years of programming I have never needed a global variable. – dhperry Apr 24 '21 at 00:38
  • @GrandmaKisses why is the answer no longer accepted? is something wrong? – asdf101 Apr 26 '21 at 10:39
  • 1
    @asdf101 I dont know I tried accepting the answer below and some how I ended up here lol. Not the best stackoverflow person – Grandma Kisses Apr 27 '21 at 00:21

1 Answers1

1

Don't, instead use return values:

def example(argument1, argument2, argument3 = ""):
    print("")
    # do some things with your inputs
    return argument1, argument2, argument3

Then you can call the function like this to automatically unpack the function output:

value1 = "example"
value2 = 42
value3 = "yay, return values"

value1, value2, value3 = example(value1, value2, value3)

or like this to get a tuple:

values = example(value1, value2, value3)

see also Why are global variables evil?

asdf101
  • 569
  • 5
  • 18