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=0in the first line offunction - check
if and breakinforlike below. (you can writebreakinfororwhilethen when arrive tobreakyou can exit fromloop.) - (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
...
