Python - creating 2 dice to roll fairly and add them together?

3.5k views Asked by At

So I had to make code that roll a die fairly and counted how many 4's I got. With the help of people on here I got it to work. Well now I have to created another die and roll them and then add they products together. This is the instructions I've been given.

"Then write another function that simulates rolling two fair dice. The easy way is to call the function you just wrote, twice, and add the numbers you get. This should return a number between 2 and 12."

I've added rolling the dice a second time but how do I add the sums of the two rolls together is my question? And this is my code.

from random import randrange
def roll():
    rolled = randrange(1,7)
    if rolled == 1:
        return "1"
    if rolled == 2:
        return "2"
    if rolled == 3:
        return "3"
    if rolled == 4:
        return "4"
    if rolled == 5:
        return "5"
    if rolled == 6:
        return "6"

def rollManyCountTwo(n):
    twoCount = 0
    for i in range (n):
        if roll() == "2":
            twoCount += 1
        if roll() == "2":
            twoCount +=1
    print ("In", n,"rolls of a pair of dice, there were",twoCount,"twos.")

rollManyCountTwo(6000)
2

There are 2 answers

1
Cory Kramer On

You shouldn't have to deal with strings at all, this could be done entirely using int values

from random import randint

def roll():
    return randint(1,6)

def roll_twice():
    total = 0
    for turn in range(2):
        total += roll()
    return total

For example

>>> roll_twice()
10
>>> roll_twice()
7
>>> roll_twice()
8

And for your function that is supposed to count the number of 2s that were rolled, again you can do integer comparison

def rollManyCountTwo(n):
    twos = 0
    for turn in range(n):
        if roll() == 2:
            twos += 1
    print('In {} rolls of a pair of dice there were {} twos'.format(n, twos))
    return twos

>>> rollManyCountTwo(600)
In 600 rolls of a pair of dice there were 85 twos
85
0
Mp0int On
from random import randint

def roll():
    return randint(1,6)

def rollManyCountTwo(n):
    twoCount = 0
    for _n in xrange(n*2):
        if roll() == 2:
            twoCount += 1
    print "In {n} rolls of a pair of dice, there were {cnt} twos.".format(n=n, cnt=twoCount)

Since you roll two dices for n times and count every single two rolled, just loop for n*2 and check if the dice result is two.