Python Programming Tips

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 # […]

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 […]

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 […]

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 […]

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) […]