392,054 views
16 votes
16 votes
Your task is to build a palindrome from an input string.A palindrome is a word that readsthe same backward or forward. Your code will take the first 5 characters of the user input, and create a 9-character palindrome from it.Words shorter than 5 characters will result in a runtime error when you run your code. This is acceptablefor this exercise, however you already know how to validate user input with an IF statement.Some examplesof input words and the resulting palindromes:

User Ahmad Sultan
by
3.6k points

1 Answer

11 votes
11 votes

Answer:

The program in Python is as follows:

word = input("Word: ")

if len(word) < 5:

print("At least 5 characters")

else:

pal = word[0:5]

word = word[0:4]

word = word[::-1]

pal+=word

print(pal)

Step-by-step explanation:

This gets the word from the user

word = input("Word: ")

This checks if the length of the word is less than 5.

if len(word) < 5:

If yes, this tells the user that at least 5 characters is needed

print("At least 5 characters")

If otherwise

else:

This extracts the first 5 characters of the word into variable named pal

pal = word[0:5]

This extracts the first 5 characters of the word into variable named word

word = word[0:4]

This reverses variable word

word = word[::-1]

This concatenates pal and word

pal+=word

This prints the generated palindrome

print(pal)

User Salar
by
3.2k points