0
def main(x1, x2, x3):
  a = ops() + 10
  return print("Result are ", a)

def ops():
  global x1,x2, x3
  y = (x1 + x2 + x3)
  return y

main(10, 7, 3)

    NameError: name 'x1' is not defined

As can be seen, I am declaring x1, x2 and x3 as global variables in the subordinate function and already including these variables as arguments for the main function. Appreciate any help.

  • 1
    Welcome to Stack Overflow! Please take the [tour]. What's your question? To me it's obvious that this won't work, but I have the benefit of experience. Why do you think this will work? And for that matter, what are you actually trying to accomplish? This seems like an [XY problem](https://meta.stackexchange.com/q/66377/343832), especially since [globals are usually bad](/a/485020/4518341). Like, why does `ops()` rely on non-locals in the first place? Why can't it take parameters?\ Please [edit] to clarify. For more tips, see [ask]. – wjandrea Dec 22 '21 at 17:22
  • As your code is written, `x1` (also `x2` and `x3`) are only available inside `main()`. This is because they are listed as parameters. Your `global` line inside `ops()` does nothing, since there is no global `x1` to be referenced. – gen_Eric Dec 22 '21 at 17:27
  • Why don't you just pass your variables (or a list or something) to `ops()`? – gen_Eric Dec 22 '21 at 17:27

1 Answers1

0

It is better/best practice to pass the x1, x2, x3 values as arguments in the ops function: Global variables are not good practice, and you should void them. Moreover it is better for the function to return a value.

def ops(x1, x2, x3):
  y = (x1 + x2 + x3)
  return y

def main(x1, x2, x3):
  a = ops(x1, x2, x3) + 10
  print("Result are ", a)
  return a

main(10, 7, 3)
Malo
  • 1,233
  • 1
  • 8
  • 25