Random
Programs often need some source of random numbers. Think of generating a user name or ID—a random sequence can be helpful.
Random
functionFor Python developers there is a pseudo-random number generator. We call randint and random.choice
. These are built-in, as Python is "batteries included."
With the random module (and randint) we easily generate random numbers. The randint()
method receives 2 arguments. They are both inclusive (including the numbers).
import random i = 0 while i < 10: # Get random number in range 0 through 9. n = random.randint(0, 9) print(n) i += 17 0 (Min) 9 (Max) 3 4 6 5 4 4 8
Random.choice
In this Python example, we use random.choice()
on a list and a tuple. When we execute this program, it gives a different result—unless the random choices are the same.
random.choice
method supports lists and tuples. As we see next, it also chooses a random character from a string
.import random # 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) # Display. print(n, y)100 4
Random
lowercase letterThis program generates a random lowercase char
. It only supports the chars A through Z, but it is easily modified.
char
from any set, you can just change the string
literal in this program.import random # 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) print(letter)v t j y s l m r a j
Random
phrasesRandom.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
.
import random # Create a list of words. words = [] words.append("hello,") words.append("cat,") words.append("food") words.append("buy") words.append("free") words.append("click") words.append("here") # 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 += "!" print(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.