How to Check Whether a String is a Palindrome Using Python

Checking for a palindrome string in python is trivial due to built-in functions and powerful string indexing and slicing. The following python program checks whether a string input by user is a palindrome,

input_str = input("Please enter a string: ").lower()
if input_str == input_str[::-1]:
    print("{} is a palindrome".format(input_str))
else:
    print("{} is NOT a palindrome".format(input_str))

Even though the above code is small, it does demonstrate a number of powerful python features,

  • The input is converted to lowercase using the lower() function of string. This is for case insensitive comparison for palindromes.
  • The input is compared to the reversed string. To reverse the string we use the slicing of the string. The slice takes 3 parameters - start index, end index and a step. Since start and end are not specified, it means the entire string and -1 for step indicates slicing backwards from the start index. This wraps around to the beginning of the string. The end result is that you get the reversed string.

The following python program achieves the same thing using lists and reversed() built-in function. The reversed() function returns a reversed iterator for the input sequence. We pass it to the list() function to get a list of characters. If it is same as the list of characters from the original string, we have a palindrome.

input_str = input("Please enter a string: ").lower()

if list(input_str) == list(reversed(input_str)):
    print("{} is a palindrome".format(input_str))
else:
    print("{} is NOT a palindrome".format(input_str))

Python Program to Find Largest of 4 Numbers

The following python program uses the built-in function max() to find the largest of 4 numbers. The max function can take any number of arguments and hence can be used to find maximum of 3 or 5 numbers as well,

num1 = 10
num2 = 20
num3 = 30
num4 = 40

print(max(num1,num2,num3,num4)) # prints 40

The following python program accepts any number of numbers from the user and prints the maximum value. In this example we add all the user inputs to a list and then the list is passed to the max function to get the maximum value. The program assumes that to stop input of numbers user will enter zero.

numbers = []
while True:
    number = int(input("Please enter a number. Enter 0 to finish.: "))
    if number == 0:
        break
    numbers.append(number)

print("maximum of {} is {}".format(numbers,max(numbers)))

Here is a sample output from the above program,

Please enter a number. Enter 0 to finish.: 5
Please enter a number. Enter 0 to finish.: 30
Please enter a number. Enter 0 to finish.: 10
Please enter a number. Enter 0 to finish.: 0
maximum of [5, 30, 10] is 30

How to Find Factors of a Given Number Using Python

The following python program prints all the positive factors of a given input number. This program demonstrates the use of functions, modulus operator, list data structure and if statement.

def get_all_factors(n):
    factors = []
    for i in range(1,n+1):
        if n%i == 0:
            factors.append(i)
    return factors

number = int(input("Please enter a number: "))
list_of_factors = get_all_factors(number)
print("factors of {} are: {}".format(number,list_of_factors))

Here is how the above program works,

  • We define a function get_all_factors() which takes a number as input and returns a list of factors.
  • This function initially creates an empty list. The function then iterates through number 1 to the input number using the built-in function range(). If the reminder is 0, we know that the number is a factor of input number and hence we add it to the factors list.
  • Finally the factors list is returned.
  • The program execution starts at the first line after the function declaration. We accept a user input using the built-in function input() and then convert to a number using the function int()
  • We then find all the factors of the number by calling the get_all_factors() function.
  • We use the built-in function print() with format() function to output the results.

Here is a sample output from the program,

Please enter a number: 25
factors of 25 are: [1, 5, 25]

We can easily extend the above program to print factors of all numbers below a given number,

def get_all_factors(n):
    factors = []
    for i in range(1,n+1):
        if n%i == 0:
            factors.append(i)
    return factors

number = int(input("Please enter the upper limit: "))

for i in range(1,number+1):
    list_of_factors = get_all_factors(i)
    print("factors of {} are: {}".format(i,list_of_factors))

Here is a sample output from the above program,

Please enter the upper limit: 6
factors of 1 are: [1]
factors of 2 are: [1, 2]
factors of 3 are: [1, 3]
factors of 4 are: [1, 2, 4]
factors of 5 are: [1, 5]
factors of 6 are: [1, 2, 3, 6]

We know that numbers with exact two factors are prime numbers! Hence we can extend the above program to indicate which of them are prime numbers,

def get_all_factors(n):
    factors = []
    for i in range(1,n+1):
        if n%i == 0:
            factors.append(i)
    return factors

number = int(input("Please enter the upper limit: "))

for i in range(1,number+1):
    list_of_factors = get_all_factors(i)
    if(len(list_of_factors) == 2):
        print("factors of {} are: {} and is prime!".format(i,list_of_factors))
    else:
        print("factors of {} are: {}".format(i,list_of_factors))

Sample output from the above program is,

Please enter the upper limit: 10
factors of 1 are: [1]
factors of 2 are: [1, 2] and is prime!
factors of 3 are: [1, 3] and is prime!
factors of 4 are: [1, 2, 4]
factors of 5 are: [1, 5] and is prime!
factors of 6 are: [1, 2, 3, 6]
factors of 7 are: [1, 7] and is prime!
factors of 8 are: [1, 2, 4, 8]
factors of 9 are: [1, 3, 9]
factors of 10 are: [1, 2, 5, 10]

How to Check Whether a Given Number is Prime in Python

A prime number is a natural number greater than 1 which has no positive divisors other than 1 and the number itself. For example, 3 is a prime number since the only positive divisors of 3 are 1 and 3 itself. The number 10 is NOT a prime number since it can be divided by 5 or 2 in addition to 1 and 10. Following are some of the first few prime numbers in the number sequence,

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41

There are a number of important practical applications of prime numbers such as in the implementation of strong encryption algorithms.

The following python program checks whether a given number is prime or not. It simply goes through all the numbers from 2 to number-1 and checks whether it is a divisor of the number. If one of them is a divisor, we immediately know that the number is not a prime number. We use the else clause of a for loop for printing the prime number status. This else clause is called only if the for loop is completely executed without calling break.

# python 3 code
def is_prime(n):
    for i in range(2,n):
        if n%i == 0:
            return False
    else:
        return True

number = int(input("Please enter a number above 1: "))
if(is_prime(number)):
    print("{} is a prime number".format(number))
else:
    print("{} is NOT a prime number".format(number))

We can easily extend the above program to print all the prime numbers under a given number,

# python 3 code
def is_prime(n):
    for i in range(2,n):
        if n%i == 0:
            return False
    else:
        return True

max_num = int(input("Please enter upper limit for prime numbers: "))
for i in range(2,max_num+1):
    if is_prime(i):
        print(i,end=', ')

Note the use of parameter end in print function to use comma between successive print() calls instead of the default newline.

How to Download a Webpage in Python

The following python program demonstrates the use of urllib module to download a webpage to a local folder. Please note that this program downloads the webpage html content only, it doesn't download the linked images or other resources. The following program also demonstrates use of exception handling.

# python 3 only
import urllib.request
from urllib.error import URLError

target_file_path = "/Users/user/downloaded.html" # downloaded page saved here

try:
    response = urllib.request.urlopen('http://www.google.com/')
    html_content = response.read()

    with open(target_file_path,"wb") as fp:
        fp.write(html_content)

except URLError as e:
    print("Unable to download page: "+str(e.reason))

If you are looking for a way to scrap entire web pages including resources, you should look at the scrapy library. If you are more interested in the parsing of the web content, you should look at Beautiful Soup.