Search code examples
pythonfunctionif-statementcmdatom-editor

Why am I getting a NameError when I've defined my variable name in a function?


When I try to run this code, a NameError occurs at the if statement, telling me that net_affect is not defined.

h, m, s, t = input('Rate each of the following Emotions and hit enter:\nHappiness (1-7):'), input('Meaningfulness (1-7):'), input('Stressfulness (1-7):'), input('Tiredness (1-7):')
h_int=int(h)
m_int=int(m)
s_int=int(s)
t_int=int(t)
def na():
    add_h_m = h_int + m_int
    div_h_m = add_h_m/2
    add_s_t = s_int + t_int
    div_s_t = add_s_t/2
    net_affect = div_h_m - div_s_t
    print(net_affect)
na()

if net_affect >= 3:
    print("Doing Well")
elif net_affect <3 and net_affect >0:
    print("Doing Okay")
else:
    print("Not Good")

This is the complete terminal output:

C:\Users\mrkev\Desktop\PAI 724>python ex2.py
Rate each of the following Emotions and hit enter:
Happiness (1-7):6
Meaningfulness (1-7):7
Stressfulness (1-7):4
Tiredness (1-7):3
3.0
Traceback (most recent call last):
  File "C:\Users\mrkev\Desktop\PAI 724\ex2.py", line 16, in <module>
    if net_affect >= 3:
NameError: name 'net_affect' is not defined

Why does this happen? I thought that by defining net_affect in the function (and calling it), I could then use it as a variable in the rest of my program.


Solution

  • Look for the 'variable scope' in your documentation or tutorials.

    The net_affect variable is local to na function. You cannot access it from the outside, and it is deleted when the function returns.

    You can alternatively :

    • define the variable outside of the function, and indicate that you are using it in the function

      net_affect = None
      def na():
          ...
          global net_affect
          net_affect = div_h_m - div_s_t
      
      
    • return the value from the function and catch the returned value

      def na():
          ...
          net_affect = div_h_m - div_s_t
          ...
          return net_affect                # return the value
      
      ...
      net_affect_new = na()                # catch the value
      

      Note: net_affect_new could be called net_affectbut they are not the same variables, they are in two different scopes.