Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #22158

Re: random number

References <CABgq=FyhR+Ldujj3YKRBpVXRVoeoayuXZviUUcNx-gXnFiHLSw@mail.gmail.com>
Date 2012-03-26 17:25 +1100
Subject Re: random number
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.979.1332743109.3037.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Mar 26, 2012 at 5:08 PM, Nikhil Verma <varma.nikhil22@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: random number Chris Angelico <rosuav@gmail.com> - 2012-03-26 17:25 +1100

csiph-web