The noob coder
The noob coder

Reputation: 15

How to detect a variable in a function from a variaible outside it?

Here is an example

new = '1'
def test():
    n = 'Hello world'
    new = n
print(new)
test()

The result:

>>>1

I wanted the 'new' variable in the function will change the value of the 'new' variable outside so the new can replace number 1 and change it to the string: 'Hello world'

Upvotes: 0

Views: 46

Answers (2)

Other answers have suggested using global variables, but global variables can introduce bugs that can be difficult to trace.

Better to pass any data into your function as an argument, and have the function return the result.

In your simple example there is no argument to be passed, so we just need to return the required value:

new = '1'
def test():
    return 'Hello world'
    
new = test()
print(new)

Upvotes: -1

BrokenBenchmark
BrokenBenchmark

Reputation: 19233

You can use the global keyword. (That being said, in general, I wouldn't suggest using global unless you have a strong reason for doing so.)

new = '1'
def test():
    global new
    n = 'Hello world'
    new = n
test()
print(new)

Upvotes: 1

Related Questions