C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Argument 1: The first argument to randint is the inclusive lower value of the range. Randint can return this value.
Argument 2: The second argument to randint is the inclusive upper value of the range. Randint can also return this value.
Python program that uses random, randint
import random
i = 0
while i < 10:
# Get random number in range 0 through 9.
n = random.randint(0, 9)
print(n)
i += 1
Output
7
0 (Min)
9 (Max)
3
4
6
5
4
4
8
List, tuple: The random.choice method supports lists and tuples. As we see next, it also chooses a random character from a string.
ListTuplePython program that uses random.choice
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)
Output
100 4
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
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)
Output
v
t
j
y
s
l
m
r
a
j
Strip, capitalize: We call strip to remove trailing punctuation and spaces. Capitalize improves the phrase's appearance.
StripLower, UpperNote: I encourage you to research Markov chains for better random text generation. This program is not good.
Quote: Markov processes can also be used to generate superficially real-looking text given a sample document.
Markov chain: WikipediaPython program that creates random phrases
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)
Output
Hello, here cat, buy free!