Python Forum

Full Version: Please help me add all the results
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
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)
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))