-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
  • 179,855
  • 19
  • 132
  • 245
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
  • 34,833
  • 5
  • 57
  • 89
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 = ''