Random numbers

posted by: Ms. Martin 22 March 2010 No Comment

Many interesting programs including most games have some sort of random component to them.  Some examples:

  • In Solitaire, the cards are shuffled randomly.
  • Every time you get hit in a shoot ‘em up game, your damage is randomly generated.
  • In a flash card studying program, cards are selected in a random order.
  • Your passwords are all encrypted using random numbers.

In reality, it’s impossible for a computer to generate a truly random number, so instead we rely on pseudorandom numbers.  Those are good enough for any situation where no money is involved (not for the lottery)!!

The random module

In order to use random numbers in Python, you must import everything from the random module like this:
from random import *

It’s typical to place all import statements at the top of your program.

Random functions

For now we’ll use two random functions: one to generate random integers and another to generate random floats.

random() – generate a random float in the range [0.0, 1.0). In other words, 0.0 can be generated but not 1.0.

randint(<bound1>, <bound2>) - generate a random integer in the range [<bound1>, <bound2> ]. In other words, both of the bounds can be generated as well as any whole number between the two.

You can read more about the random module in the official Python documentation.

Examples

Makes the turtle a random color then draws a line of that color.

from turtle import *
from random import *

color(random(), random(), random()) # make the turtle a random color
forward(100)

Asks the user for how many random numbers to print then prints them out.

from random import *

count = int(raw_input("How many random whole numbers between 1 and 100 do you want? "))
for i in range(count):
    rand = randint(1, 100)
    print(rand)
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>