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
Asked
Active
Viewed 136 times
-2

OneCricketeer
- 179,855
- 19
- 132
- 245

Roman
- 41
- 7
-
1You do understand what `+=` does, right? – OneCricketeer May 26 '18 at 07:37
-
1Spoiler: [How to reverse a string in Python](https://stackoverflow.com/questions/931092/reverse-a-string-in-python) – OneCricketeer May 26 '18 at 07:38
-
The issue is, you didn't initialize the variable `a`. Set `a = 0` after `def reverse(text):` – Melvin Abraham May 26 '18 at 08:17
2 Answers
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 = ''