Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

counting - Adding up total times a number was rolled on a dice in python 3

I have made a sided dice random generator , but i need for the programme to at the bottom print out 1 was rolled x amount of times 2 was rolled x amount of times and so on. how can I achieve this.

my code is :

import random
print("Six sided dice programme")
count = 1
while True:
    answer = str(input("would you like to roll, 'y' for yes, 'n' for no:"))
    if answer == 'y':
        roll=random.randint(1,6)
        print("roll number" , str(count) , ":" , roll)
        count = count + 1
    if answer == "n":
        print("Game over")
        break
question from:https://stackoverflow.com/questions/65918535/adding-up-total-times-a-number-was-rolled-on-a-dice-in-python-3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You keep counts in an integer count variable. Change to a list/dict representing the count of each side of the dice.

list:

import random

counts = [0] * 6
for i in range(10):
    roll = random.randint(1,6)
    print("roll number" , i, ":" , roll)
    counts[roll-1] += 1

for side, count in enumerate(counts):
    print(side+1, "was rolled", count, "amount of times")

dict:

import random
from collections import defaultdict

counts = defaultdict(int)
for i in range(10):
    roll = random.randint(1,6)
    print("roll number", i+1, ":", roll)
    counts[roll] += 1

for side, count in counts.items():
    print(side, "was rolled", count, "amount of times")

* this will print the counts in order of the first appearance of each side


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...