-3

I get an UnboundLocalError: when using NaN in my if-statements. If I set NaN to 0 then the code works fine. However the code needs to work with NaN and not 0.

I've read most of the topics regarding UnboundLocalError: but I did't find what I was looking for.

import math
from math import nan as NaN
def interest(A, P, R, N):
    if R == NaN:
        val = (A/P)**(1/float(N))-1
    elif P == NaN:
        val = A/(1+R)**N
    elif A == NaN:
        val = P * (1 + R)**N
    elif N == NaN:
        val = (math.log(A)- math.log(P))/ math.log(1+R)
    return val

    print(interest(1000, 200, NaN, 5))
Chukkee
  • 3
  • 5

2 Answers2

1

As others mentioned in the comments, your code is missing the logic to handle the case where none of the conditions evaluates to True.

Also math.nan == math.nan evaluates to False so your function call will never result in any of the if statements being True so val is never initialized which is why you get UnboundLocalError.

Have an else clause which should either return some appropriate value or just None.

Finally comparing nan to nan seemed redundant to me as in your function call the third argument passed is NaN.

This is just a slight modification to your code and it works.

import math
from math import nan


def interest(A, P, R, N):
    if R is nan:
        val = (A / P) ** (1 / float(N)) - 1
    elif P is nan:
        val = A / (1 + R) ** N
    elif A is nan:
        val = P * (1 + R) ** N
    elif N is nan:
        val = (math.log(A) - math.log(P)) / math.log(1 + R)
    else:
        val = None
    return val

print(interest(1000, 200, 'test', 5))
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
Rohit
  • 3,659
  • 3
  • 35
  • 57
  • Well then yeah, but since `nan == nan` is False, having `== nan` in every condition seems completely redundant, imo. – TrebledJ Jan 28 '19 at 10:14
  • It might be necessary since OP might want to check if each argument is NAN – Rohit Jan 28 '19 at 10:17
0

First, print statement in your code will never print anything due to wrong indentation, but I suppose you are aware of this.

Second, you get UnboundLocalError, because val is not assigned before it is returned. Interesting question is, why. The problem here is with R == NaN (and following), because by definition NaN == NaN is False. Therfore, val is never assigned. When you want to check, if some variable is NaN, you can use R is NaN or R in [NaN] (see Why in numpy `nan == nan` is False while nan in [nan] is True?).

Just note, that using else (which is good manner generally) could give you a hint, what happened here.