random
¶random.choice()
¶import random
fruits = ['pear','mango','banana','strawberry','kumquat']
selection = random.choice(fruits)
print(selection)
banana
random.randint()
¶import random
print(random.randint(1, 10))
10
random.random()
¶print(random.random())
0.5002419706259531
If you need a random float between 0 and 100, just scale the random number:
print(random.random() * 100)
88.10581258132582
random.sample()
¶name = 'George Washington'
print(random.sample(name, 2))
['t', 'a']
print(random.sample(name, 5))
['a', 's', 'g', 'g', 't']
print(random.sample(name, len(name)))
['n', 'r', 's', 'G', 'n', 't', 'e', ' ', 'g', 'W', 'i', 'a', 'g', 'e', 'o', 'h', 'o']
random.sample
can be used to get a random sample from a collection.
If you sample all the items in the collection, you essentially get a shuffled version of the data.
import random
def shuffle(string):
"""
Use random.sample to get the letters in the string in a random order.
Then join the letters together with the empty string.
"""
shuffled_letters = random.sample(string, len(string))
return ''.join(shuffled_letters)
shuffle('12345')
'54123'
shuffle('CS110')
'1CS10'
apples.py
¶Write a program that takes a frequency (a number between 0 and 1) and a phrase as commandline arguments.
Randomly inject "umm" into a given sentence at the given frequency and print the result.
umm.py
¶random
choice
randint
random
sample
random.sample