How to Generate Random Numbers in Python


In this example we will show how to generate random numbers in Python.

2. Functions

  • random.random() is used to generate a random floating-point number n, 0 <= n < 1.
  • random.uniform(a, b) is used to generate a random floating-point number n within a specified range,  a<=n<=b.
  • random.randint(a, b) is used to generate an integer n within a specified range, a<=n<=b. If a>b, an error is reported.
  • random.randrange(start, stop, step) can generate a random number from the specified range [start, stop), which incremented by the specified base, and the default value of the base is 1. start and step are optional.
  • random.choice(sequence) can generate a random element from the sequence. The parameter sequence generally refers to list, tuple, string, etc.
  • random.shuffle(x, random) is used to shuffle an element in a list, which will change the original list.
  • random.sample(sequence, k) randomly fetches k elements from the specified sequence as a fragment, without changing the original sequence.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import random

print(random.randint(0,99))
# Randomly select an even number between 0 and 100
print(random.randrange(0, 101, 2))

# Random floating point number
print(random.random())
print(random.uniform(1, 10))

# Random character
print(random.choice('abcdefg&#%^*f'))
#Select a specific number of characters from multiple characters
print(random.sample('abcdefghij',3))

# Randomly select a string
print(random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] ))

items = [1, 2, 3, 4, 5, 6]
random.shuffle(items)
print("shuffle:", items)

# Randomly fetching k elements from a specified sequence as a fragment
list = []
list = random.sample(items,2)
print(list)

Output:

63
82
0.06683296164578978
9.111134747394525
a
['a', 'f', 'e']
lemon
shuffle: [6, 4, 3, 5, 2, 1]
[4, 3]
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments