Reputation: 33655
In Python how can I create a random pin four digits long?
I know Python has the random.randint function but I can't see a way to make the number four digits.
Upvotes: 5
Views: 6420
Reputation: 4984
Try this:
import random
pin = str(random.randint(0, 9999)).rjust(4, '0')
Upvotes: 0
Reputation: 636
These days, you'd want to use the secrets
module if the purpose is to generate a secure PIN:
import secrets
pin = '{:0>4}'.format(secrets.randbelow(10**4))
The formatting pads with zeros from the left, for the case where the number is below 1000.
Upvotes: 4
Reputation: 9
#python module
import random
# function to generate PIN
def generatePIN():
#varible PIN store all random digits
PIN = ""
#you change the length of pin by changing value of range
for i in range(4):
#randint generates a random number between 0,9
PIN = PIN + str(random.randint(0,9))
return(f"4 digits PIN:{PIN}")
print(generatePIN())
Upvotes: 0
Reputation: 11694
An integer output would need to deal with missing leading zeros so it is best to output a string or list of ints:
If you want any possible combination do:
from random import randint
[randint(0,9) for _ in range(4)]
or
''.join(str(randint(0,9)) for _ in range(4))
If you do not want any duplicate digits.
from random import sample
sample(range(10), 4)
or
''.join(sample("0123456789", 4))
Upvotes: 6
Reputation: 7369
You could try:
import random
pin = random.sample(xrange(10), 4)
print pin
example output:
[6,7,4,2]
Upvotes: 2
Reputation: 34166
Try this:
import random
pin = random.randint(999, 9999)
print pin
randint(a, b)
will give a random number from a
to b
. See Python docs for more information about random
module.
Upvotes: 5