Reverse Assignment


#1

I am wondering why this code wouldn’t work for reversing the text.
def reverse(text):
leng = len(text) - 1
char = []
while leng >= 0:
char.append(text[leng])
leng -= 1
else:
print .join(char)

Edit: I just realized I should be returning the value.


#2

Those two lines can be replaced with a return statement. Remember the separator string on join.

return "".join(char)

#3

Thank-you. I am guessing the else is redundant right?


#4

We could say that, yes. It is not needed because there is no alternate action to the loop. Using else in a while adds more control.

n = 0
while n < 1:
    n = random.random() + 0.1
    if n < 0.2: 
        print (n, 'break')
        break
    print (n, "Yup")
else:
    print (n, "Nope")

print ('Done')
0.1399662619565696 break
Done

0.9603827945569794 Yup
0.2685997075270028 Yup
1.0645272307275004 Yup
1.0645272307275004 Nope
Done

https://repl.it/@mtf/while-else-demo


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.