Skip to content

Random numbers in Python

wilsonshamim edited this page Jun 11, 2018 · 3 revisions

Random Number Functions
Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes following functions that are commonly used.

  • choice(seq) – A random item from a list, tuple, or string.
  • randrange ([start,] stop [,step]) – A randomly selected element from range(start, stop, step)
  • random() – A random float r, such that 0 is less than or equal to r and r is less than 1
  • seed([x]) – Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.
  • shuffle(lst) – Randomizes the items of a list in place. Returns None.
  • uniform(x, y) – A random float r, such that x is less than or equal to r and r is less than y

examples:
Choice:

from random import *
li = [1,2,3,4,5]
print(choice(li))
print(choice([1, 2, 3, 5, 9]))
-————————————————————-
randrange:
print(randrange(100, 1000, 2))
-————————————————————

random:
print(random())


shuffle:

list = [20, 16, 10, 5];
shuffle(list)
print("Reshuffled list : ", list)
-———————————————————

uniform
print(“-”,uniform(3,8))

Clone this wiki locally