-1

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.

2 Answers2

1

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)
NHL
  • 277
  • 1
  • 6
-1

Here you haven't called functions which declares the variable u and v So try like this:

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
u = contract_u(m)
v = contract_v(m)
if u>v:
  m=m+1
else:
  print(m)
Wasif
  • 14,755
  • 3
  • 14
  • 34
  • 1
    One important thing since you struggle with functions: The names of the variables in the function and outside of the function can be different. So you could do `foo = contract_u(m)` and then do the comparison with `if foo > v:`. – Matthias Oct 19 '20 at 16:20
  • 1
    Calling the functions has nothing to do with this. `u` and `v` are defined _inside_ the function scope, and assigning the return value of the functions to `u` and `v` outside is what assigns those values to those names outside the function – Pranav Hosangadi Oct 19 '20 at 16:20