1

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)
  • What command do you use to execute it? – Ukulele Apr 30 '22 at 10:00
  • https://stackoverflow.com/questions/53233973/bin-sh-python-command-not-found should answer this... – Ukulele Apr 30 '22 at 10:06
  • Look at your `while` loop. The loop condition is `n != 0`. That means that `n` must be `0` when the loop exits. Now look at the `if` after the loop. It's checking to see if `n == r`, which is equivalent to `r == 0` (since `n` is `0`). Do you see why this doesn't work? – Tom Karzes Apr 30 '22 at 10:08
  • What command do you use to execute it?: I just click on the Run Code button in Visual Studio Code –  Apr 30 '22 at 10:23

3 Answers3

0

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)
Cardstdani
  • 4,999
  • 3
  • 12
  • 31
0

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) 
Avinash
  • 875
  • 6
  • 20
-1

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)
Nin17
  • 2,821
  • 2
  • 4
  • 14