OTP generation using Random module in Python 3.x or earlier

The world is changing so rapidly. There have been various advancements in technology. Due to which OTP has become an integral part of everything to ensure security and privacy. Here we have shown how to create OTP using Python Random module.

One-time Passwords (OTP) are valid only for one login session. They are used during transactions in an application or a digital device or a website. It is generally a combination of 4 or 6 numeral digits or a 6-digit alpha-numerals.

OTP Generation

In this tutorial we will be generating OTP with the help of random() function included in the random module of Python 3.x or earlier can be used to generate random OTP which is predefined in the random library. Let’s see how to generate OTP using Python 3.x. or earlier.

4 Digit Numeric OTP generate using Python

import random as r
# function for otp generation
def otpgen():
    for i in range(4):
    print ("Your One Time Password is ")
    print (otp)


Your One Time Password is

Every-time you run the above function you get a random four-digit number as a result. We can also generate a 6 digit numeral OTP by changing the no of iterations of for loop from 4 to 6.

Now we look at generating a 6-digit Alpha-numeric OTP.

Build a Number Guessing Game in Python using Random module.

6 Digit Alpha-numeric OTP Python Code

# import modules 
import math as m
import random as r
# function to generate OTP 
def OTPgen() : 
    # Declare a string variable   
    # which stores all alpha-numeric characters 
    string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    OTP = "" 
    varlen= len(string) 
    for i in range(6) : 
        OTP += string[m.floor(r.random() * varlen)] 
    return (OTP) 
# main function 
if __name__ == "__main__" : 
    print("Your One Time Password is ", OTPgen())


Your One Time Password is KJturX

Every-time you run the above function you get a random 6 digit Alpha-numeric value as a result.

For more quality content stay tuned, till then you may learn

3 responses to “OTP generation using Random module in Python 3.x or earlier”

  1. Kamal Tej says:

    while creating OTP in first method, it isnt necessary to check whether the sending one is already sent or not?? Please clarify this one

    • Pavitra Walia says:

      It totally depends on the use case. In case you are using it for highly confidential process then you must maintain a list of past OTP’s generated so as to avoid security issues.

  2. this_name says:

    How would you create a fifty character OTP capable of handling sentences?

Leave a Reply

Your email address will not be published. Required fields are marked *