Beginners Query - Simple counter problem
David Barr
david.barr456 at btinternet.com
Thu Sep 6 15:18:24 EDT 2007
Scott David Daniels wrote:
> David Barr wrote:
>> I am brand new to Python (this is my second day), and the only
>> experience I have with programming was with VBA. Anyway, I'm posting
>> this to see if anyone would be kind enough to help me with this (I
>> suspect, very easy to solve) query.
>>
>> The following code is in a file which I am running through the
>> interpreter with the execfile command, yet it yeilds no results. I
>> appreciate I am obviously doing something really stupid here, but I
>> can't find it. Any help appreciated.
>>
>>
>> def d6(i):
>> roll = 0
>> count = 0
>> while count <= i:
>> roll = roll + random.randint(1,6)
>> count += 1
>>
>> return roll
>>
>> print d6(3)
> A) your direct answer: by using <=, you are rolling 4 dice, not 3.
> B) Much more pythonic:
>
> import random
>
> def d6(count):
> result = 0
> for die in range(count):
> result += random.randint(1, 6)
> return result
>
> -Scott David Daniels
> Scott.Daniels at Acm.Org
I was surprised by the speed and number of posts. Thanks for the
solutions provided!
>>> def roll(times=1, sides=6):
... return random.randint(times, times*sides)
Although this would probably be quicker than the other approaches, I'm
not using the dice to generate numbers per say, I actually want to
emulate the rolling of dice, bell-curve (normal distribution) as well as
the range.
Thanks again, I already like what (very) little I can do in Python and
it seems to have a great community too.
Cheers,
Dave.
More information about the Python-list
mailing list