-2
def convert(target):
    #Some code here
    target = 20


convert(x)
print(x)

I expected the output to be 20, but there is always an error. "NameError: Name x is not defined" Is there some way that I could fix that?

  • 1
    *"there is always an error"*. Can you quote that error here? – Austin Jun 18 '19 at 17:23
  • 2
    This won't work (at least not in simple way). You should return 20 from `convert()` and set `x` to the value with `x = convert()`. – Mark Jun 18 '19 at 17:23
  • The duplicate answer addresses your direct question I think. The error you're getting is another matter. I expect that you're getting the error `NameError: name 'x' is not defined` because you aren't defining `x` before you reference it by calling `convert(x)` – CryptoFool Jun 18 '19 at 17:40

1 Answers1

-1

It sounds like you are trying to pass the value by reference, which goes against the grain of Python, which passes variable by assignment. The easiest "solution" is to refactor your code so it returns the new value, as others have suggested.

In some languages (e.g. PHP), you can specify that certain arguments are to be passed by reference (e.g. by prefixing the variable name with a "&"), but in practice this often makes the code harder to read and debug.

For more information, see: How do I pass a variable by reference?

Everett
  • 8,746
  • 5
  • 35
  • 49