0

I'm new with python and I've a question: If I've a lot of variables, how can I add all the variables in a function without declare with "global" each variable one by one?

world = 0
how = 1
are = 2
you = 3

def print_hello_world():
    global hello,world,how,are,you
    hello = "hello"
    world = "world,"
    how = "how"
    are = "are"
    you = "you ?"
    print(hello,world,how,are,you)

print_hello_world()

For example, how can I insert "hello, world, how, are, you" in the function without "global hello,world,how,are,you" ?

Polipizio
  • 46
  • 1
  • 5

3 Answers3

0

You need to use global only when you are assigning something to the values. You can print them without it. If you want to use arguments instead, you can do this:

def print_hello_world(hello, world, how, are, you):
    print(hello, world, how, are, you)

h1 = "hello"
w = "world"
h2 = "how"
a = "are"
y = "you"
print_hello_world(h1, w, h2, a, y)

I used different variable names to demonstrate that it is the arguments that are being used. You could use the same variable names, too. It doesn't make a difference.

zondo
  • 19,901
  • 8
  • 44
  • 83
0

You should study up about Python scoping rules

In your particular example, you don't have to declare these variables as global, because python will look in the local scope first, fail to find the variables, then it will search the enclosing scope and find the variables there and use them.

Of course you'll run into a problem if you decide to assign any of those names inside the function:

>>> x = 42
>>> def wont_work():
...     x = x + 1
...
>>> wont_work()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in wont_work
UnboundLocalError: local variable 'x' referenced before assignment

In that case you would need to declare global x.

You can also define your variables as function arguments. You do this by putting them inside the parenthesis in your function definition:

def print_hello_world(hello, world, how, are, you):
    print(hello, world, how, are, you)

You would have to change the way you call the function. Assuming you're using the code that you have defined already you can do this in one of two ways. The first is pretty typical:

print_hello_world(hello, world, how, are you)

The second makes use of keyword argument unpacking:

print_hello_world(**globals())

But that's a bit on the sketchy side. You could also use *args and argument unpacking in a slightly different way:

def print_hello_world(*args):
    print(*args)

print_hello_world(hello, world, how, are, you, 'today', 'you', 'can', 'add', 'many things here')
Community
  • 1
  • 1
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
-1

Use parameters.

def print_hello_world(hello, world, how, are, you):
    print(hello, world, how, are, you)