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.
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(): otp="" for i in range(4): otp+=str(r.randint(1,9)) print ("Your One Time Password is ") print (otp) otpgen()
Your One Time Password is 7311
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