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

    Join Date
    Sep 2012
    Posts
    66
    Rep Power
    2

    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. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,841
    Rep Power
    480
    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!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

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

    (0,dice) and then

    (1,sides)

    what is 0 and what is 1
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,841
    Rep Power
    480
    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!

IMN logo majestic logo threadwatch logo seochat tools logo