Hello (this is my first question on the site so apologies if i have not followed an rules) Below are two codes (using for loop) that I have written to print reverse of a string input by the user. One code gives me an error and the other works fine. I cannot understand why. Why is the function "range" seem to make the difference? Appreciate if someone can help me understand the logic - many thanks
Code 1: That gives me error:
string = input('Enter a Word ')
length = len(string)
reverse = []
for i in string:
x=string [-1-i]
reverse.append(x)
print (reverse)
*Enter a Word Python
TypeError Traceback (most recent call last) in 4 5 for i in string: ----> 6 x=string [-1-i] 7 reverse.append(x) 8 TypeError: unsupported operand type(s) for -: 'int' and 'str'
Code 2: This works fine
string = input('Enter a Word ')
length = len (string)
reverse = []
for i in range(length):
x=string [-1-i]
reverse.append(x)
print (reverse)
*Enter a Word Python
['n', 'o', 'h', 't', 'y', 'P']*