Python字符串反转报错:local variable referenced before assignment如何解决?
Fixing the "local variable 'a' referenced before assignment" Error in Your String Reverse Code
Let's break down what's going wrong here first:
The error you're seeing happens because you're trying to use the variable a in the line a += text[len(text) - i] before you've initialized it. Python has no idea what a is supposed to be at that point—you haven't told it to create an empty string or any other value for a yet.
Here's the fixed version of your original code:
def reverse(text): a = "" # Initialize empty string first! for i in range(1, len(text) + 1): a += text[len(text) - i] return a print(reverse("Hello World!")) # Outputs: !dlroW olleH
A more Pythonic way to reverse a string
While your loop approach works, Python has a much simpler built-in way to reverse strings using slicing. This is cleaner and faster for most cases:
def reverse(text): return text[::-1] print(reverse("Hello World!")) # Same output: !dlroW olleH
The slice [::-1] means "start from the end of the string and move backwards one character at a time"—perfect for reversing strings in one line!
内容的提问来源于stack exchange,提问作者Roman
相关产品推荐
相关产品推荐

