Python program that uses random.choice
# Use random.choice on a list.
arr = [1, 5, 9, 100]
n = random.choice(arr)
# Use random.choice on a tuple.
tup = (2, 4, 6)
y = random.choice(tup)
Random lowercase letter. This program generates a random lowercase char. It only supports the chars A through Z, but it is easily modified.
Tip: To generate a random char from any set, you can just change the string literal in this program.
Tip 2: A list could also be used: we could add in a loop (or list comprehension) all the desired letters.
Python program that generates random lowercase letter
# This string literal contains all lowercase ASCII letters.
values = "abcdefghijklmnopqrstuvwxyz"
for i in range(0, 10):
# random.choice returns a random character.
letter = random.choice(values)
Random phrases. Random.choice can be used to easily create random text or phrases. Here we populate a list with seven words and then add five random choices to a string.
Strip, capitalize: We call strip to remove trailing punctuation and spaces. Capitalize improves the phrase's appearance.
Python program that creates random phrases
# Create a list of words.
words = 
# Create sentence of five words.
result = ""
for i in range(0, 5):
result += random.choice(words) + " "
# Fix trailing punctuation and capitalize.
result = result.strip(" ,")
result = result.capitalize()
result += "!"
Hello, here cat, buy free!
The randint and random.choice methods are excellent choices for pseudo-random numbers. They are clear. They are easy to remember and need few comments.
One key thing to remember: the randint method receives two arguments that are inclusive. So the highest number is included. This differs from other languages like Java.