Rajan Kumar

Rajan Kumar published an article

3 months, 3 weeks ago

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. 


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



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


arrow_upward Upvote

comment Comment

arrow_downward downvote

Go back to feed

HackersFriend Updates

update Aug. 15, 2019, 1:47 p.m.

Full view page of article has been changed to match style of homepage feed. open_in_new

update Aug. 14, 2019, 12:52 a.m.

Total number posts on homepage is incresed to 10 by default and text-decoration of link to post and author is changed. open_in_new

update Aug. 7, 2019, 1:51 a.m.

We changed our homepage. Now, you can see newly published articles, directly on home page. open_in_new

View more


event Nov. 28, 2018, 5:30 p.m.

Python from zero to hero

place Delhi

View details

event Aug. 13, 2018, 5:30 p.m.

Python from zero to hero

place Bangalore ( HackersFriend office BTM Layout)

View details