#πŸ”’ How do I get this code working?

25 messages Β· Page 1 of 1 (latest)

dreamy sentinel
#

#Code to get a word/number and check if its a palindrome (words or numbers that are the same when reversed) example: dad

n = list(input("Enter word/number: "))
m = n.reverse()
if m == n:
print("The word is a Palindrome")
else:
print("Not a palindrome")

it always prints "Not a palindrome"
what have i done wrong

wild heronBOT
#

@dreamy sentinel

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

stone saddle
#

Are you still there?

#

It is not working because .reverse() reverses the original list instead of actually returning anything.

#

Try this:-

#
n = list(input('Enter word/number: '))
m = [*n]
m.reverse()
if m == n:
    print('The word is Pallindrome')
else:
    print('Not a palindrome')
dreamy sentinel
#

could you please explain me what the second line is doing?

stone saddle
#

In the second line m = [*n], we are unpacking the contents of n, ie. we are separating the elements in the list, and storing them as a list again.

#

Example:-

n = ['a', 'b', 'c']
m = [*n]
print(m)
# Output:- ['a', 'b', 'c']
dreamy sentinel
#

oh so is it a way of copying the first list?

stone saddle
#

Yes.

#

If you do m = n and then reverse it n or m by n.reverse(), the other will get reversed too.

#

!e

n = [1, 2, 3]
print(n)
m = n
print(m)
n.reverse()
print(n, '\n', m)
wild heronBOT
stone saddle
#

As you can see, m also got changed.

dreamy sentinel
#

ah got it

stone saddle
#

Unpacking also works like this:-

#

!e

n = [1, 2, 3]
a, b, c = [*n]
print(a)
print(b)
print(c)
wild heronBOT
dreamy sentinel
#

gotchu

#

tysm

stone saddle
#

Wels, you can close this if your problem is solved.

wild heronBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.

#

πŸ”’ How do I get this code working?