dimanche 17 octobre 2021

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

I'm trying to build if/elif/else statements based on an input statement and a function I defined. When I run the code, the input statement and the function definition and call run fine, but then I get to my if/elif/else statements and I get a NameError, telling me that a variable I call up in the if/elif/else statements is not defined (even though I thought I defined it in the function).

For context, I'm new to Python, and I'm building code in Atom and running it in Command Prompt.

My input and function definition code looks like this:

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()

These are my if/elif/else statements:

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 Command Prompt 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

Where am I going wrong? I thought that by defining net_affect in the function, I could then use it as a variable in my program.

Thank you for your help!

Aucun commentaire:

Enregistrer un commentaire