random number

Chris Angelico rosuav at gmail.com
Mon Mar 26 02:25:06 EDT 2012


On Mon, Mar 26, 2012 at 5:08 PM, Nikhil Verma <varma.nikhil22 at gmail.com> wrote:
> Hi All
>
> How can we generate a 6 digit random number from a given number ?
>
> eg:-
>
> def number_generator(id):
>     random.randint(id,999999)
>
> When i am using this it is sometimes giving me five digit and sometimes 6 .
> I want to avoid encryption . Can i have alphanumeric 6 digit random number
> from this .

The easiest two ways to guarantee six digits are:
1) Pad the number with leading zeroes:
def number_generator():
  return "%06d"%random.randint(0,999999)
2) Set a minimum and a maximum:
def number_generator():
  return random.randint(100000,999999)

I don't know what your id there is, but the first argument to randint
is the minimum value to return.

Alphanumeric is quite different. To generate a six-character random
alphanumeric string, one easy technique is to use base 36 conversion
on a random integer.

Hope that helps!

Chris Angelico



More information about the Python-list mailing list