Objectives
- Create pseudorandom numbers within a given range
- Use pseudorandom numbers to solve problems
Function | Purpose |
---|---|
seed(None) | seed the random number generator |
getrandbits(n) | returns a random int with n bits |
randrange(start, stop) | returns a random integer from start through stop-1 |
randrange(start, stop, step) | returns a random integer from start through stop-1 which is a multiple of step from the start value |
randint(low, high) | returns a random integer between low and high (inclusive) |
choice(seq) | returns a random element from the supplied sequence |
shuffle(seq) | shuffles the specified sequence in place |
sample(population, k) | returns a list of k unique items from the specified population (a sequence or a set) |
random() | returns a random float in the range 0.0 to less than 1.0 |
uniform(low, high) | returns a random float in the range low to high (inclusive) |
import random print(random.randint(1, 6))
import random print(random.randint(1, 6) + random.randint(1, 6))
for i in range(11): print(random.randint(1, 100))
import random print() freq = [0] * 13 for roll in range(0, 1000): count = random.randint(1,6) + random.randint(1,6) freq[count] = freq[count] + 1 for ndx in range(2, 13): print("{0:2}: {1}".format(ndx, "*" * round(freq[ndx]/10)))
import random suit = [ "Spades", "Diamonds", "Clubs", "Hearts" ] rank = [ "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" ] deck = [] for st in suit: for rk in rank: deck.append(rk + " of " + st) random.shuffle(deck) print(deck)