Python Forum
Please help me add all the results - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Please help me add all the results (/thread-31437.html)



Please help me add all the results - mr_kungfu - Dec-10-2020

Hey all, Im trying to code dice rolls that all get added together

Two pieces of code here, first bit generates all the numbers and prints then out, the second set of code is me try to get it added all together

please help

#working code
import random


def D4(x):
    
    for d4 in range(x):
        d4 = (random.randint)(1,4)  
        
        print(d4)
#eg
D4(10)
################################################


#my best attempt
import random

def D4(x):

    rolls = 0
    for d4 in range(x):
        d4 = (random.randint)(1,4)  
        rolls = rolls + d4
        
        return rolls
                            
def dicetotals(x):
    print(D4(x))

dicetotals(2)



RE: Please help me add all the results - michael1789 - Dec-10-2020

import random

def D4(x):

    rolls = 0
    for d4 in range(x):
        d4 = (random.randint)(1,5)
        rolls +=  d4

    return rolls

dicetotals = D4(4) 

print(dicetotals)



RE: Please help me add all the results - deanhystad - Dec-12-2020

You had an indentation problem. And stop wrapping things in parenthesis that don't need parenthesis.
import random
 
def D4(count):
    total = 0
    for _ in range(count):
        total += random.randint(1,4)  
    return total
                             
print(D4(2))
You could make a generic die roller that works for any sided dice. This one returns the total and the individual die. If you call it without any arguments it rolls a single six sided die.
import random
 
def roll(sides=6, count=1):
    die = random.choices(range(1, sides+1), k=count)
    return sum(die), die

print(*roll(4, 2))