Enter an integer and find all palindromes lesser than or equal to the given number

I do not understand why my code is not working, could anyone help me with this one? It is supposed to print a list of palindromes (numbers that are equal to themselves if read backwards) lesser than or equal to the input. When I try to execute it, it writes: /bin/sh: python: command not found.

w = input('Enter a number: ')
n = int(w)
g = []
for n in range(n, 0, -1):
    r = 0
    while n != 0:
        a = n % 10
        r = r * 10 + a
        n //= 10
    if n == r:
        g.append()
print(g)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You’re almost there. Actually your if n == r: is always computing like if 0 == r:. Hence, in your for loop assign your n to a temp variable. Try this:

w = input('Enter a number: ')
n = int(w)
g = []
for n in range(n, 0, -1):
    temp = n
    r = 0
    while n != 0:
        a = n % 10
        r = r * 10 + a
        n //= 10
    
    if temp == r:
        g.append(temp)
print(g)

Method 2

You can use the following solution, which is simpler than using a while loop:

n = int(input("Enter a number:n"))

g = []
for i in range(0, n+1):
    if str(i)==str(i)[::-1]:
        g.append(i)
print(g)

Method 3

I don’t think your code works anyway. Here is another way to find palindromes less than w:

w = input('Enter a number: ')
n = int(w)
palindromes = []
for i in range(n+1):
    if str(i) == str(i)[::-1]:
        palindromes.append(i)
print(palindromes)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x