How to Generate Cryptographically Secure Random Numbers in Python

Generating a cryptographically secure random number is very easy in python 3.6 and above. You can use the new secrets module and the function randbelow() for it. This function returns a random number below the specified value. The following python 3.6+ program demonstrates the use of secrets module for secure random numbers,

import secrets

# generate 5 secure random numbers between 100 and 999
for i in range(0,5):
v = 100+ secrets.randbelow(900) # 100+0 to 100+899
print(v)

In python 3.5 and below, we can use random module and SystemRandom class. This uses the os.urandom() under the covers and hence the cryptographic strength depends on the underlying operating system implementation.

import random

rand_gen = random.SystemRandom()
for i in range(0,5):
v = 100+ rand_gen.randint(0,899) # 100+0 to 100+899
print(v)

Python Program to Check for Armstrong Number

What is an Armstrong number?

An Armstrong number is an n-digit number such that the sum of it digits raised to the power n is the number itself. For example, 153 is a 3 digit Armstrong number since,

153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

Another example is the 4 digit Armstrong number – 1634,

1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634

Armstrong numbers are also known as narcissistic numbers in recreational mathematics.

Python Program to Check for Armstrong Numbers

The following python program checks whether a given number is an Armstrong number. It also prints the order of the Armstrong number.

number = int(input("Please enter a number: "))

num_str = str(number)
num_len = len(num_str)

sum_of_digits = 0
for d in num_str:
sum_of_digits += int(d) ** num_len # power operation

if number == sum_of_digits:
print("{} is an Armstrong number of order {}".format(number,num_len))
else:
print("{} is NOT an Armstrong number".format(number))

Following are the steps in the above program,

• We first accept an input from user and convert it into a number
• We convert the number to a string and find its length
• We then iterate through each digit character and then find the sum of the digits raised to the power of length of the string(which is the number of digits in the number)
• Finally we check whether the sum is same as the original number. If they are same, this number is an Armstrong number!

Python Program to Print All 3 Digit Armstrong Numbers

The following python program prints all the 3 digit Armstrong numbers. We have extracted the logic used in the above program to a separate function named is_arm(),

def is_arm(number):
num_str = str(number)
num_len = len(num_str)

sum_of_digits = 0
for d in num_str:
sum_of_digits += int(d) ** num_len # power operation

if number == sum_of_digits:
return True
else:
return False

for n in range(100,1000): # 100 to 999
if is_arm(n):
print("{} is an Armstrong number of order {}".format(n,len(str(n))))

Following is the output from the above python program,

153 is an Armstrong number of order 3
370 is an Armstrong number of order 3
371 is an Armstrong number of order 3
407 is an Armstrong number of order 3

Python Program to Print All Armstrong Numbers Below a Specified Number

The following python program prints all Armstrong numbers below a specified number. It also prints the order of the Armstrong number.

def is_arm(number):
num_str = str(number)
num_len = len(num_str)

sum_of_digits = 0
for d in num_str:
sum_of_digits += int(d) ** num_len # power operation

if number == sum_of_digits:
return True
else:
return False

limit = int(input("Please enter the limit for Armstrong number check: "))

for n in range(1,limit+1): # 1 to limit (inclusive)
if is_arm(n):
print("{} is an Armstrong number of order {}".format(n,len(str(n))))

Following is the sample output from the above python program,

Please enter the limit for Armstrong number check: 9999
1 is an Armstrong number of order 1
2 is an Armstrong number of order 1
3 is an Armstrong number of order 1
4 is an Armstrong number of order 1
5 is an Armstrong number of order 1
6 is an Armstrong number of order 1
7 is an Armstrong number of order 1
8 is an Armstrong number of order 1
9 is an Armstrong number of order 1
153 is an Armstrong number of order 3
370 is an Armstrong number of order 3
371 is an Armstrong number of order 3
407 is an Armstrong number of order 3
1634 is an Armstrong number of order 4
8208 is an Armstrong number of order 4
9474 is an Armstrong number of order 4

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: 
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: 
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]