1

For example, in my folder, I have my ipython notebook "program.ipynb" and a python file "functions.py" which has some functions in it, for example, "func"

from numpy import sqrt
def func(x):
    return N + sqrt(x)

that is going to be used in "program.ipynb" which looks like that

from functions import func
N = 5
func(2)
--> name 'N' is not defined

To fix the bug i need to define the variable N in my functions.py file but isn't there a way around? I want to define all my global variables in my main programm (program.ipynb).

3
  • Did you try global N then N=5. In general global variables are a bad practice as it gets harder to debug. Commented Oct 31, 2019 at 11:54
  • I tried _ global N _ , _ N=5 _ , _ func(2) _ and still got the same error Commented Oct 31, 2019 at 12:00
  • BTW: all variables created outside functions are global. We use word global inside function (not outside) to inform function that we want to use external/global variable. Commented Oct 31, 2019 at 12:20

1 Answer 1

2

You can't access a variable like that, the best way would be:

functions.py

from numpy import sqrt
def func(x, N):
    return N + sqrt(x)

program.ipynb

from functions import func
N = 5
func(2, N)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.