In python there are different ways to generate id’s. Let’s see how different types of Id’s can be generated using python without using inbuilt Python libraries.
1. Generating Random Integer as Ids’
Code #1 : Print 10 random values of numbers between 1 and 100.
Python3
import random
for x in range ( 10 ):
print (random.randint( 1 , 101 ))
|
Output :
76
72
7
78
77
19
24
23
77
96
Code #2 : Print random numbers between 1 and 100 which are multiple of 5.
Python3
import random
for x in range ( 10 ):
print (random.randint( 1 , 20 ) * 5 )
|
Output :
60
30
35
100
85
25
100
20
90
85
Drawbacks :
- Generating Random numbers is not unique, Same number can repeat itself.
- It generates only Integer values.
2. Generating Random String as Ids’
Generating Random string id’s consists of letters and digits. This can be useful in generating passwords as its provide the encryption and decryption technique.
Code #1 : Show how to generate random string id’s.
Python3
import random
import string
random = ''.join([random.choice(string.ascii_letters
+ string.digits) for n in range ( 32 )])
print (random)
|
Output :
Rf2IdqUNkURNN6mw82kSpyxQe9ib3usX
Code #2 : Using Function call
Python3
import random
import string
def ran_gen(size, chars = string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range (size))
print (ran_gen( 8 , "AEIOSUMA23" ))
|
Output :
S2M2IEAO
Generating Random id’s using UUID in Python
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
28 Sep, 2021
Like Article
Save Article