[Tutor] Random

Gerrit Holl Gerrit <gerrit@nl.linux.org>
Wed, 9 Feb 2000 17:08:08 +0100


JoanCarles p Casasín wrote on 949953271:
> Alexandre Passos wrote:
> 
> >How can I make a random number?
> 
> import random
> 
> listofn = range(1,1000) #a list containing integers from 1 to 999
> a = random.choice(listofn) #choice a random element from a list
> print a
> 
> 
> I don't know if there's a better way for doing it but this works for me...

It works, but the following has much better performance:
>>> import random
>>> random.randint(0, 1000)
67
It doesn't need to create a list. Consider:
>>> random.random() * 1000
786.880856997
>>> round(random.random() * 1000)
30.0
>>> int(round(random.random() * 1000))
74

regards,
Gerrit.

-- 
Homepage: http://www.nl.linux.org/~gerrit
-----BEGIN GEEK CODE BLOCK----- http://www.geekcode.com
Version: 3.12
GCS dpu s-:-- a14 C++++>$ UL++ P--- L+++ E--- W++ N o? K? w--- !O
!M !V PS+ PE? Y? PGP-- t- 5? X? R- tv- b+(++) DI D+ G++ !e !r !y
-----END GEEK CODE BLOCK----- moc.edockeeg.www//:ptth