Search code examples
while-looppython-3.5index-error

Python while loop index error


I've made a reverse function, it reverses the sentence, however it generates index error.

what the program does is append the last word from s and puts it into rev[], it then deletes the word s[-1].

s = "This is awesome"

def Reverse1(s):

s = s.split(" ") #reverses the word instead of letters
rev = []                    
while True:
    rev.append (s[-1])
    del s[-1]
    print (rev)
return  
reverse1(s)

its returning index error as it tries to continue when s is empty so I think its the while loop statement.

any ideas?


Solution

  • You need to stop the while loop, you can use something like this

    while n in range(len(s)):