Thursday, May 27, 2010

Random Numbers

Random numbers.
Random numbers are a very important piece of any programming language.
The difficult part is importing the random module. You can write your own randomness module or use the supplied one. To do this simply type:

Import random

This imports the random module. Now to set a variable to a random number, simply type:

abcd= random.randint(1, 10)

The random.randint() gives a random integer between the two numbers you put in the parentheses. This is the simplest use of random numbers.
This can be used in conjunction with the elif command to give random output. Here is an example:


import random

abcd = random (1,10)

if abcd == 1:
 
print "hello"
 
elif abcd == 2:
print "hi"


Etc. Etc.
This is very helpful in many scenarios such as having something different said every time with the print command.
Next Post: to be announced

1 comment: