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
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)] print(generate_OTP)
Complete Code –
import math, random # for alpha nuemeric OTP corpus= "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" generate_OTP = "" size=5 length = len(corpus) for i in range(size) : generate_OTP+= corpus[math.floor(random.random() * length)] print(generate_OTP)
Output for the complete code is below .
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.