-2
def FirstReverse(str):


    chaine = str.split(' ');

     for i in range(len(chaine), -1):
       inverse = chaine[i]
   return inverse ;    

print FirstReverse(raw_input())

i want to inverse a string but i have some difficulties , i got this error message

UnboundLocalError: local variable 'inverser' referenced before assignment

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
yok
  • 25
  • 7

3 Answers3

2

You need to pass a negative step argument to range to get a reversed range list.

range(len(chaine)-1, -1, -1)   #start from len(chaine)-1

As because range(len(chaine), -1) returns [], the loop never executes and inverse never gets defined.

Easiest way to inverse a string is to use the extended slice notation [::-1].

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • i fellowed your advice and changed it , but i got just the first word of the sentence.
    def FirstReverse(str): chaine = str.split(' '); for i in range(len(chaine)-1, -1, -1): inverse = chaine[i] print i return (inverse) print FirstReverse(raw_input())
    – yok Jan 09 '14 at 20:55
1

Your for statement is always false and inverse gets initialized only if for loop condition is met, so the code doesn't reach the point where inverse gets a value (and by that, gets defined/bound). You should introduce the variable in a place that always gets executed.

arun
  • 11
  • 1
0

A better way to reverse a list is to use slice notation with a step of -1:

def FirstReverse(s):
    words = s.split(' ')
    return words[::-1]

Notes:

  1. str is a Python built-in, avoid re-using it
  2. You don't need to finish statements with semicolons;
Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247