0

Why does my code not throw an error message when I use variables within a def that are defined outside of the function?

import numpy as np


y_model=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0
,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,1
,0,0,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1
,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1]
y_test=[0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0
,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,0,1
,0,0,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,1,1
,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,1]

def return_recall_and_precision(y_predict,y_actual):
    import numpy as np
    # get array of matches
    TP=(y_model==y_test) # Shouldnt this thrown an exception error? y_model is not in the local # scope
    print("tp is",TP)
    TP=np.sum(TP)

    return TP



TP=return_recall_and_precision(y_model,y_test)
print(TP)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
onion117
  • 7
  • 1
  • 2
    Functions can reference global variables. – Tom Karzes Sep 05 '21 at 19:28
  • Welcome to Stack Overflow. Please read the [formatting help](https://stackoverflow.com/help/formatting). Also, there is no such thing as "a def function" or "a def"; it's *a function*. `def` is just part of the syntax you use to write it. – Karl Knechtel Sep 05 '21 at 19:28
  • Heads Up. Since you import `numpy` globally, you don't need (or want) to import it in your function – JonSG Sep 05 '21 at 19:29
  • As for your question, it should be adequately addressed by working through any ordinary Python tutorial. You should by now be familiar with the basics; if you have never heard of a *global variable* then you should go back and study before trying to use more sophisticated tools like Numpy. – Karl Knechtel Sep 05 '21 at 19:30
  • The code that you show isn't actually using Numpy arrays at all; it's using ordinary Python lists. If you just wanted a function to add up the values in a Python list, that is built-in; it's called `sum` and you *don't need Numpy for it*. – Karl Knechtel Sep 05 '21 at 19:31

0 Answers0