Why should this repeating structure that should turn a word upside down not come back at all?

Asked

Viewed 27 times

1

phrase = str(input("Type your phrase: ")).upper().strip()
words_phrase = phrase.split()
words_together = ''.join(words_phrase)
phrase_inverse = ""
for letra in range(len(words_together) - 1, -1, -1):
    phrase_inverse = words_together[letra]
print(phrase_inverse)
if words_together == phrase_inverse:
    print("Esta frase é um palíndromo")
else:
    print("Não é um palíndromo")

This program had the purpose of making a sentence look the other way, but when I run the code and the program tries to show the sentence backwards it only returns the first letter, and the phrase_inverse is inside the loop, it would be easier to leave:

phrase_inverse = words_together[letra:]

But exercise doesn’t allow.

1 answer

1


The problem is on the line you reverse the word:

phrase_inverse = words_together[letra]

Note that you always assign the value of the last letter read in the variable, but do not accumulate the values, with this you end up having only the first letter of the sentence typed.


To fix this, just accumulate the letters during the inversion, this can be done using += that concatenates the already present value of the variable with the new inserted:

phrase_inverse += words_together[letra]

The complete code would look more or less like this:

phrase = input("Type your phrase: ").upper().strip()
words_phrase = phrase.split()
words_together = "".join(words_phrase)
phrase_inverse = ""

for letra in range(len(words_together) - 1, -1, -1):
    phrase_inverse += words_together[letra]

if words_together == phrase_inverse:
    print("Esta frase é um palíndromo")
else:
    print("Não é um palíndromo")

Note: Note that removes the str of the input function, because the input function already returns a string, therefore this conversion is not necessary

See online: https://repl.it/@Dadinel/BelatedMeanWordprocessing

Browser other questions tagged

You are not signed in. Login or sign up in order to post.