-1

I have a function like:

def function():
  var_a = 1
  var_b = 2
  var_c = 3
  return var_a, var_b, var_c

The purpose of the function is to assign to some variables. I need to be able to call on the function for quick assignment and then be able to use those variables in the rest of my code. However, if I now try:

function()
print(var_a)

I get an error message telling me that var_a is not defined.

If I instead try

values = function()
print(values)

this displays the values as a tuple, but doesn't give me access to separate values in separate variables. How can I make it work the way I want?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • When you run the function, why are you not saving the returned values? `var_a, var_b, var_c = function()` – Yoshikage Kira Jun 10 '21 at 17:39
  • 1
    Stack Overflow is not intended to replace existing documentation and tutorials. Repeat your tutorial on functions to learn how to use the values you return to the main program. – Prune Jun 10 '21 at 17:39
  • Are you expecting global variables to be assigned/created by calling `function`? You have to declare each variable as global with something like `global var_a, var_b, var_c` at the beginning of the function to avoid creating local variables. – chepner Jun 10 '21 at 17:42

1 Answers1

3

You need to assign the values that you return from the function.

a, b, c = function()

If you assign the three values to a single tuple, you can also destructure them from the tuple the same way:

values = function()
a, b, c = values
Samwise
  • 68,105
  • 3
  • 30
  • 44