-2
def reverse(text):

    for i in range(1, len(text) + 1):
       a += text[len(text) - i]
    return a

print(reverse("Hello World!"))

#error local variable 'a' referenced before assignment
OneCricketeer
  • 151,199
  • 17
  • 111
  • 216
Roman
  • 41
  • 7

2 Answers2

2
a += text[len(text) - i]

is equivalent to

a = a + text[len(text) - i]
#   ^ 
#   |
#   +-- what's a here?

and when this line first runs it has to look up the value of a where I've pointed but it can't because a has never been assigned before.

Put a = '' at the very beginning of your function so that it has a starting value to work from.

Alex Hall
  • 33,530
  • 5
  • 49
  • 82
0

Try to execute like this:

def reverse(text):

    a = ''
    for i in range(1, len(text) + 1):
       a += text[len(text) - i]
    return a


print(reverse("Hello World!"))

Output:

!dlroW olleH

Explanation:

Define the a which you are updating in for-loop as a = ''