Python uses the Mersenne Twister as the core random generator. The module random contains a fair number of methods (or functions) that help you to do random things. Here are some examples ...
Experimenting with Random Things (Python)
# doing random things
# tested with Python24 vegaseat 04jul2005
import random
print "List the functions/methods and constants of module random:"
for funk in dir(random):
print funk
print
print "more info on seed():"
help('random.seed')
print
# seed the random generator (default from system time)
random.seed()
# floating point random numbers are 0 to < 1.0
print "Display a couple of random floating point numbers:"
for k in range(10):
print random.random()
print
print "Pick a floating point number in the range 1.0 to < 100.0:"
print random.uniform(1.0, 100.0)
print
print "Pick a random integer 1, 2 or 3:"
for k in range(10):
r = random.randint(1,3)
print r,
print
print "\nPick a random integer in the range 0 to 9:"
randomInt = random.randrange(10)
print randomInt
print
print "Pick an even random integer in the range 10 to 99:"
randomInt = random.randrange(10, 100, 2)
print randomInt
print
print "Create a list of 10 unique random integers in the range 0 to 99:"
randomIntList = random.sample(xrange(100), 10)
print randomIntList
print
str1 = "If you throw it away, you will need it the next day."
print str1
print "Two random characters picked from the string above =", random.sample(str1, 2)
print
# strings are immutable (cannot be directly changed), so you have to go to a list
# of characters, do the operation, and join the changed list back to a string
str1 = "Mississippi"
charList = list(str1)
random.shuffle(charList)
str2 = "".join(charList)
print "String '%s' after random shuffle = '%s'" % (str1, str2)
print
print "Pick a fruit at random from a list of fruits:"
fruitList = ['apple', 'pear', 'banana', 'grape', 'cherry']
print fruitList
print "Picked", random.choice(fruitList)
print
# coin toss ...
count = 0
toss = int(raw_input("Enter number of tosses: "))
while (count < toss):
print random.choice(('head', 'tail'))
count += 1
print
# random fun, add this to your sober program to lighten up the day
oldList = []
oldList.append('Old Swimmers have one more stroke!')
oldList.append('Old Plumbers go down the drain!')
oldList.append('Old Exorcists give up the ghost!')
oldList.append('Old Ministers go out to pastor!')
oldList.append('Old Composers decompose!')
oldList.append('Old Golfers lose their balls!')
oldList.append('Old Fishermen have limp rods!')
oldList.append('Old Farmers go to seed!')
oldList.append('Old Editors do it with a red pen!')
oldList.append('Old Eskimoes get cold feet!')
oldList.append('Old Accountants lose their balance!')
print random.choice(oldList)
sainandan 0 Newbie Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.