python - random integer examples

Here's some helpful functions for generating random integers in python.

This has been tested on Python 2.7, but should work on newer Pythons also. Please comment if you run across any problems!

First, you have to import the random library.

import random

If you don't have it already in your library, download random.py and place it in the same folder as your python script.

The nice documentation for the random library can be found here.

Now you can generate floating point (float) random numbers from 0.0 to 1.0 with the command

random.random()

If you're looking for a way to generate random integers, here's a couple of ready functions for you!

# returns random integer from -variation to +variation
def rando(variation):
    return int(round((random.random()*2-1)*variation))

# random integer, from zero to maxval
def randzv(maxval):
    return int(round(random.random()*maxval))

# random integer, from minval to maxval
def randminmax(minval, maxval):
    return int(round(minval + random.random()*(maxval-minval)))


Hope this hels someone!

Comments

Popular posts from this blog

How to remove parts of string in Python

python - current date and time example