RK Founder at HackersFriend Updated Aug. 2, 2019, 4:19 p.m. ⋅ 5909 views

# How to generate OTP (One time password) using python

In this article I'll talk about how can you generate random OTP using Python. OTP is used in a lot of works, like resetting password, email verification, mobile verification and a lot.

If you are developing something in which you need to register users, you are going to need to generate OTP.

OTP is expected to be hard to guess and it should be random. It can be all digit, all chracter, or mixture of it. In this article, I'll talk about generating numeric OTP and alphanumeric OTP.

Approach

We will use python's random function to generate random numbers and this number will be used to generate our OTP.

Implementation

Generating 4 digit, all numeric OTP.

``````import math, random

def OTPgenerator() :
digits_in_otp = "0123456789"
OTP = ""

# for a 4 digit OTP we are using 4 in range
for i in range(4) :
OTP += digits[math.floor(random.random() * 10)]

return OTP

# Main function

print("Your 4 digit OTP is: ", OTPgenerator())
``````
``Your 4 digit OTP is: 5342``

Generating alphanumeric OTP of 8 digit:

``````import math, random

def OTPgenerator() :

digits_in_otp = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
OTP = ""
length = len(string)
for i in range(8) :
OTP += string[math.floor(random.random() * length)]

return OTP

# Main Function

print("Your 8 digit alphanumeric OTP is: ", OTPgenerator())
``````
``Your 8 digit alphanumeric OTP is: IaPtE2D8`` Join the community of 1 Lakh+ Developers