Random Stuff

Back to index

Sometimes it is good to be random. In fact, sometimes that is exactly what you want and Python actually helps you to be random on those occasions where randomless is desired!

So, get the sample program displayed down below up and running. See if you can figure out how it ticks on your own before reading the info posted below it, further down this page.

#!/usr/bin/python import random d1 = ["huge", "small", "large", "enormous", "gigantic", "tiny", "microscopic"] d2 = ["green", "ugly", "pathetic", "disgusting", "annoying", "repulsive"] n = [ "trees", "cars", "houses", "horses", "hands", "spiders", "dogs", "ducks", "people"] p = [ "park", "store", "library", "lake", "carnival", "zoo" ] u = raw_input("Enter q to quit or any other key to continue. ") while u != "q": print "\n\n\n" print "Mary saw several " + d1[random.randrange(0,len(d1))] + ", " + d2[random.randrange(0,len(d2))] print n[random.randrange(0,len(n))], "while she was at the", p[random.randrange(0,len(p))] + "." print "\n\n\n" u = raw_input("Enter q to quit or any other key to continue. ") print ("\n\nThanks for your patronage.")
The first thing you will notice is the "import random" line. This line imports a standard library of code called random. There are lots of standard libraries available for use with Python. This one provides tools which make it easy to generate random numbers. As you see several lines later, "random.randrange(start,end)" gets called a total of four times. You will notice that each call to random.randrange goes a little something like this:
d2[random.randrange(0,len(d2))]
To index a value contained in the d2 list, we could write a fixed value such as d2[3], which would be the index of "disgusting". (The first item in a list has an index value of zero.) However, since we want to pick values at random, instead of the same value each time, we generate a random value so that each time the line of code gets executed a different word gets selected. That's what's so awesome about generating random numbers.

As you probably realize len(d2) returns an integer corresponding to the length of d2.

In a previous lesson you saw how to add things to a list using append(). You can also remove things from a list in three different ways: del, remove, and pop. Here's an example that uses pop. Get it up and running and analyze it until you can explain how it works.

#!/usr/bin/python import random names = ["Syd", "Joe", "Sue", "Jill", "Bob", "Sally", "Edna"] while names: r = random.randrange(0,len(names)) print (names.pop(r))

ASSIGNMENT:

PART ONE: Modify the guessing game from a previous assignment so that it generates a random number which the user guesses.

PART TWO: Write a program which allows the user to do the following to a list of names: append, pop, display.