To understand the problem, let's go to a basic case, be the list:
lista = [0]
and now we insert the value of 1 in position 8:
lista.insert(8, 1)
for what we get:
[0, 1]
and we ask ourselves:
Have we inserted the value of 1 in position 8?
No, if you insert a value in an index greater than the maximum existing index is only added to the end, and that is what happens in your case, to observe it better I will add print
s within the for:
...
for c in cadena:
i = longitud - 1 - ciclo
lista.insert(i,c)
ciclo += 1
print("lista.insert({},{}): {}".format(i, c, lista))
...
And we get the following:
Esta función imprime la cadena inversa.
Introduce una cadena de texto o números:
1234567890
lista.insert(9,1): ['1']
lista.insert(8,2): ['1', '2']
lista.insert(7,3): ['1', '2', '3']
lista.insert(6,4): ['1', '2', '3', '4']
lista.insert(5,5): ['1', '2', '3', '4', '5']
lista.insert(4,6): ['1', '2', '3', '4', '6', '5']
lista.insert(3,7): ['1', '2', '3', '7', '4', '6', '5']
lista.insert(2,8): ['1', '2', '8', '3', '7', '4', '6', '5']
lista.insert(1,9): ['1', '9', '2', '8', '3', '7', '4', '6', '5']
lista.insert(0,0): ['0', '1', '9', '2', '8', '3', '7', '4', '6', '5']
0192837465
The behavior indicated by my example is seen until the list is half the final size, that is, until it has the size 5, and then it is inserted but not in the proper way, so the logic of insertion It's failing.
If we want to continue using your initial logic, the solution is to always insert in position 0:
...
for c in cadena:
lista.insert(0,c)
...
There are also simple ways without using for-loop:
-
Using slice notation :
def inverso():
print("Esta función imprime la cadena inversa.")
print("")
print("Introduce una cadena de texto o números: ")
cadena = input()
cadena_inversa = cadena[::-1]
print(cadena_inversa)
inverso()
-
Using reversed:
def inverso():
print("Esta función imprime la cadena inversa.")
print("")
print("Introduce una cadena de texto o números: ")
cadena = input()
cadena_inversa = "".join(reversed(cadena))
print(cadena_inversa)
inverso()