-1
limit = int(input("enter the number of sequence"))
    
pattern = []
for i in range(limit):
    pattern.append(int(input("Enter the sequence")))
print(pattern)
sumof = 0

def sumofpat(r):
    if r == 0:
       return sumof
    else:
       sumof += pattern[r-1]
       sumofpat(r-1)
    
print(sumofpat(limit))

When I run the code above, I got the following error:

Traceback (most recent call last):
  File "C:/Users/muham/pythonProject2/venv/recurtion aptgtern.py", line 17, in <module>
    print(sumofpat(limit))
  File "C:/Users/muham/pythonProject2/venv/recurtion aptgtern.py", line 14, in sumofpat
    sumof += pattern[r-1]
UnboundLocalError: local variable 'sumof' referenced before assignment

when I try to use the recursion function, I get an error like this.

shamil
  • 1
  • 1
  • `sumof` is a local variable, this definition `sumof = 0` does not affect it. Define it inside a function. Also your `else` clause has no effect. – matszwecja Aug 29 '22 at 07:21
  • I suggest reading some tutorial about recursion, for example https://www.programiz.com/python-programming/recursion to explain the basics of this mechanic. – matszwecja Aug 29 '22 at 07:24

1 Answers1

0

Follow this link, it will help you understand and how to use local variable or/and global variable. UnboundLocalError: local variable 'sumOfOdd' referenced before assignment in Python3

limit = int(input("enter the number of sequence"))
    
pattern = []
for i in range(limit):
    pattern.append(int(input("Enter the sequence")))
print(pattern)
sumof = 0

def sumofpat(r):
    global sumof
    if r == 0:
        return sumof
    else:
        sumof += pattern[r-1]
        sumofpat(r-1)
    
print(sumofpat(limit))
JaySean
  • 125
  • 1
  • 15