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

Viewed 201

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

2 Answers

I think you are over-complicating things.

Once you get the number of dice to roll as well as the sides, simply using a for loop is enough.

import random

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

total = 0
for num in range(r):
    die = random.randint(1, s)
    print(f"Die {num + 1}: {die}")
    total += die

print(f"Total of all dice: {total}")

Outputs

Enter the number of dice to roll: 2
Enter the number of sides per die: 20
Die 1: 7
Die 2: 2
Total of all dice: 9

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
Related