Finding Palindromes Using Python

Finding Palindromes Using Python

ECX 30 Days of Code

Day 3

Palindromic Numbers

Task

A palindromic number is a number that remains the same when its digits are reversed. Write a function that prints out all palindromic numbers less than a given input, and returns the total number of palindromes found.

My Approach

First, we define the function, palindromic(). Next, we create a counter starting from zero which will count the number of palindromes found. We then start checking from zero to (num – 1) for palindromes using the for loop, and converting each to a string so that we can use string slicing. We then check if the number (now a string) is the same in the right order as in the reverse order. If it is the same, we increment the counter and print the palindrome. This continues until we get to (num – 1). Finally, we call the function.

def palindromic(num):
    """This prints the palindromes and the number of the palindromes of the function argument, num."""

    count = 0                       # Counter for the number of palindromes
    for i in range(num):
        j = str(i)                  # Converts the integer to string.

        # Check if the string in normal order and reverse order are same.
        # j[::-1] is the string in the reverse order.
        if j[0:] == j[::-1]:
            count = count + 1
            print(j, end=" ")

    print('\nThe total number of palindromes is', count)


# Function to print the palindromes of numbers less than 500
palindromic(500)

Output

0 1 2 3 4 5 6 7 8 9 11 22 33 44 55 66 77 88 99 101 111 121 131 141 151 161 171 181 191 202 212 222 232 242 252 262 272 282 292 303 313 323 333 343 353 363 373 383 393 404 414 424 434 444 454 464 474 484 494 
The total number of palindromes is 59

Run the code on Replit