Skip to content
Advertisement

How do I print the result of the individual die in the dice roll program in python?

This is what I have so far:

import random
r = int(input("Enter the number of dice to roll: "))
s = int(input("Enter the number of sides per die: "))

def Rolldice(s,r):
    for i in range(0,r):
        die = random.randint(1, s)
    
        yield die
for num in range(1):
    print("Rolling",r,'d',s,':')
    print(f"Total: ")
    generator = Rolldice(s,r)
    print(sum(generator))

I want to print the individual die as I already get the result.

Rolling 2d20…

Die 1: 1

Die 2: 15

Total: 16

Advertisement

Answer

You can add a print() statement inside the RollDice() function (though this will cause the generator to have the side effect of printing to the console, which may or may not be desirable depending on if you’re using this function elsewhere):

def Rolldice(s,r):
    for i in range(0,r):
        die = random.randint(1, s)
        print(f"Die {i}: {die}")
        yield die
Advertisement