pythonfunctionundefinednameerrordefined

Python: NameError: name 'u' is not defined


i am completing a simple class asignment with functions. We have to find for which month m the functioncontract_v will be more advantageous than the contract_u. This is the code I wrote:

def contract_u(m):
  u=1000
  for i in range (m):
    u=u+80
  return u

def contract_v(m):
  v=1000
  for i in range (m):
    v=v*1.05
  return v

m=1
if u>v:
  m=m+1
else:
  print(m)

However, the computer says this:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-20-8909d368129a> in <module>()
     12 
     13 m=1
---> 14 if u>v:
     15   m=m+1
     16 else:

NameError: name 'u' is not defined

I do not understand what I have to modify and why the code is not functionning properly. If you do know what has been done wrong, please point that out. Thank you in advance.


Solution

  • your variables are defined locally in your functions, so they do not exist outside of them, so you should add these lines before your if statement :

    u=contract_u(m)
    v=contract_v(m)