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')