How to fix local variable referenced before assignment error?

Here is the code: (WEEK 3 Problem 2 Part 6)

def calc_sum(x,N):
    sum=1
    for i in range(N):
        sum+=calc_1(x,N))
    return sum
    
i=float(input("Enter x: "))
j=int(input("Enter N: "))
print(calc_sum(i,j))

def diff(x2,N2):
    calc=float(calc_sum(x2,N2)-calc_sum(x2,N2-1))
    while calc>0.01:
        sum1=calc_sum(x2,N2)
    return sum1
a=float(input("Enter x: "))
b=int(input("Enter N: "))
print (diff(a,b)

Output:

Error-local variable ‘sum1’ referenced before assignment

you are getting this error because of your while loop i.e. when your condition doesn’t satisfy directly return sum1 is calling which means that your variable is returning without and assignment.

1 Like