Home > Net >  Why this custom sum function gives me error
Why this custom sum function gives me error

Time:10-08

I just try to do a sum of n natural number with my own custom function like this.

n = int(input("Enter value of n.\n"))
def sumof(n):
    for i in range(1,n 1):
        s = s    n -i
    if (n - i)<0:
        break
    return s

print(sumof(n))

error looks like this.

s = s    n -i
UnboundLocalError: local variable 's' referenced before assignment

it looks like error because of variable 's'. Then I realise that I didn't assigned that variable. so I assigned it s=0 as a global variable but I am still getting same error.

Please tell me what am I did'nt wrong here. I am new to python so sorry for silly mistake in my program. If error come from.

CodePudding user response:

You need to initialize s before referencing it.

n = int(input("Enter value of n.\n"))
def sumof(n):
    s = 0 # <--- Add this line
    for i in range(1,n 1):
        s = s    n -i
        if (nthterm - i)<0:
            break
    return s

print(sumof(n))

CodePudding user response:

I find these :

  • you need to write s=0 in the first line of function
  • check if and break in for like below. (you can write break in for or while then when arrive to break you can exit from loop.)
  • (where do you define nthterm?)
n = int(input("Enter value of n.\n"))
def sumof(n):
    s = 0
    for i in range(1,n 1):
        s = s    n -i
        # if (nthterm - i)<0:
        #    break
    return s

print(sumof(n))

If you want use variable in function as gloabl write like below:

s = 0
def sumof(n):
    global s
    ...
  • Related