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.

Python Program to Access Environment Variables

Python provides a number of built-in modules and functions for commonly needed programming tasks. For example, to access operating system properties, python provides the module os. You can use the environ object of os module to access operating system environment variables.

The object os.environ behaves like a dictionary of environment variable names and its values. The following python program prints all the environment variables and its values when it is run,

import os

env_obj = os.environ
for x in env_obj:
    print(x,env_obj[x],sep=' => ')

If you want to get the value of an environment variable and if it doesn’t exist, a default value, you can use the getenv() method of os module,

temp_dir = os.getenv('TMPDIR','defaultvalue')
print(temp_dir)

How to Find Sum of Digits of a Number in Python

Python’s built-in support for lists, strings and data conversion enables us to write very concise code which usually takes much more code in other languages. For example, the following python 3 code computes sum of digits of a number using a generator expression and an implicit iterator.

# python3 code
number = int(input("Please enter a number:"))
sum_of_digits = sum(int(digit) for digit in str(number))
print("Sum of digits of {} is {}".format(number,sum_of_digits))

The above program illustrates a number of cool features of python language,

  • Convert a number to a string using the built-in str() function
  • Implicitly convert a string to a sequence of characters to a list when used in looping context
  • Use int() built-in function to convert each digit character to a number
  • The use of generator expression which return sequence items on demand
  • The sum() aggregate built-in function which finally computes the sum of digits

Following is a more traditional way of computing sum of digits of a number in python. Note the use of divmod() function which can compute the remainder and modulus in a single call. The resultant tuple is unpacked into 2 variables.

# python3 code
number = int(input("Please enter a number:"))

sum_of_digits = 0
n = number
while n:
    n,remainder = divmod(n,10)
    sum_of_digits += remainder

print("Sum of digits of {} is {}".format(number,sum_of_digits))