November 6th, 2012, 05:52 PM

Explain some code 2
Code:
import random
def roll(sides,dice):
result = 0
for result in range (0,dice):
result += random.randint(1,sides)
return result
So what I dont understand are the lines
"for result in range (0,dice)" and
"result += random.randint(1,sides)"
could somebody explain these to me thanks
November 6th, 2012, 07:06 PM

roll is a function. Call roll with 2 integer arguments. Suppose you need to simulate the sum of tossing 2 cubical dice.
Code:
sum_of_dice = roll(sides=6,dice=2) # appropriate expression
And now that I look a little more closely I also can't understand the function's purpose.
Let's pretend the function actually read as follows:
Code:
import random
def roll(sides,dice):
result = 0
for DIE in range (0,dice): #####changed variable!!!
result += random.randint(1,sides)
return result
result += expression
is the same as
result = result + expression
result starts as 0. By the end result is the tally of pips on all the dice.
for DIE in range(0,dice):
in the example means the body of the loop executes with DIE having the value 0 and then with DIE having the value 1. DIE isn't used in the loop. Therefor it just means to repeat the statements twice.
[code]
Code tags[/code] are essential for python code and Makefiles!
November 7th, 2012, 04:37 PM

ok.... but why is it
(0,dice) and then
(1,sides)
what is 0 and what is 1
November 7th, 2012, 07:57 PM

Code:
>>> import random
>>> help(random.randrange)
Help on method randrange in module random:
randrange(self, start, stop=None, step=1, int=<class 'int'>) method of random.Random instance
Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.
Do not supply the 'int' argument.
[code]
Code tags[/code] are essential for python code and Makefiles!