Python Generate Random Integer, Float and String – A Simple Guide to Python Beginners

By | July 17, 2019

Python generate random integer, float and string is widely used in python applications, such as generate password, delay time and initialize weights in deep learning. In this tutorial, we will write a simple example to generate them.

python generate random number

Preliminaries

#import libraries
import random
import string

Generate a random integer

print(random.randint(1,50))
#37

Generate a random integer with 2 steps

print(random.randrange(0, 101, 2))
#22

Generate a random float

print(random.random())
#0.9285431485395974

Generate a random float with uniform distribution

print(random.uniform(1, 10))
#1.344220194940056

Select a random char from a string

print(random.choice('abcdefghijklmnopqrstuvwxyz!@#$%^&*()'))
#w

Generate random string list with length limit

print(random.sample('zyxwvutsrqponmlkjihgfedcba',5))
#['x', 'l', 't', 'e', 'h']

Generate random string with length limit

ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))
print (ran_str)
#fQ3aSgTi

Select a random element from a list

print(random.choice(['tutorial', 'example', 'https://www.tutorialexample.com']))
#https://www.tutorialexample.com

Random list order

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
random.shuffle(items)
print(items)
#[1, 0, 9, 6, 7, 8, 4, 5, 3, 2]

Leave a Reply