### Thread: Explain some code 2

1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2012
Posts
66
Rep Power
6

#### 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
2. 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.
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2012
Posts
66
Rep Power
6
ok.... but why is it

(0,dice) and then

(1,sides)

what is 0 and what is 1
4. 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.```