Python Code for OTP Generation : In 4 Steps only

Python code for OTP Generation

We all need OTP in application these days. In order to simplify this problem Data Science Learner’s team created this simple Python code for OTP Generation. Here you may Generate numeric OTP and Alpha Numeric OTP both.

Python code for OTP Generation :

Steps 1 –

Import the required libraries. Using the import statement in python 

import math, random

Steps 2 –

Define the complete corpus for OTP. Let’s understand corpus meaning here. Corpus is a set that contains all possible symbols in OTP. For example –

# for nuemeric OTP only

corpus= "0123456789"   

 # for alpha nuemeric OTP 

corpus= "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

Here you may add more symbols in the corpus variable. Whatever you add, That may come randomly in OTP.

Steps 3 –

Define the size you want for OTP. I mean the number of characters or symbols in OTP.

size = 5              # user may change this value

Step 4-

Now we need to run a loop for randomly choosing value position in the corpus. Here corpus is a string.

generate_OTP = ""
length = len(corpus)
for i in range(size) :
 generate_OTP+= corpus[math.floor(random.random() * length)]

Complete Code –

import math, random
# for alpha nuemeric OTP 
corpus= "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
generate_OTP = "" 
length = len(corpus) 
for i in range(size) : 
  generate_OTP+= corpus[math.floor(random.random() * length)] 

Output for the complete code is below .

OTP python code
OTP python code


The above code is Python 3 compatible . But with just change the print statement you may easily run the code in Python two as well . You use this function to create Rest API for OTP generation using python . Well I hope this article is most useful for Python Backend developers . Anyways There are so many ways to generate OTP using sum fix set of symbols . People may use the above code for capcha  generation as well .

I hope you have enjoyed this article – Python code for OTP Generation  . In case you have some suggestions on OTP generation logic , Please write back to Data Science Learner Team .


Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Abhishek ( Chief Editor) , a data scientist with major expertise in NLP and Text Analytics. He has worked on various projects involving text data and have been able to achieve great results. He is currently manages, where he and his team share knowledge and help others learn more about data science.
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner