Python Generate Random Number

July 25, 2019
import random

Random value between 0.0 - 1.0 (inclusive)

random.random()

Random Integer

random.randrange(0, 2)  # 0 or 1, will not get 2
random.randrange(0, 10) # 0-9
random.randrange(10)    # 0-9
random.randrange(1, 10) # 1-9
random.randrange(1, 1_000_000_000) # 1-999_999_999

Even number only

random.randrange(2, 10, 2)  # 2,4,6,8

Random from a list

items = [1, 7, 9, 12]
random.choice(items)

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.