[Solved] how to format numbers with commas in python


You can use a dict to store the results of your die rolls in a much simpler fashion. This will allow you to loop over all the results instead of writing a separate print statement for each. It also simplifies your code a lot!

For example:

import random
results = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
for count in range(6000000):
    die = random.randint(1, 6)
    results[die] += 1

print('Here are the results:')
# Loop over the *keys* of the dictionary, which are the die numbers
for die in results:
    # The format(..., ',d') function formats a number with thousands separators
    print(die, '=', format(results[die], ',d'))
# Sum up all the die results and print them out
print('Total rolls equal:', sum(results.values()))

Here’s some sample output:

Here are the results:
1 = 1,000,344
2 = 1,000,381
3 = 999,903
4 = 999,849
5 = 1,000,494
6 = 999,029
Total rolls equal: 6000000

Note that for this simple example, we could also use a list to store the results. However, because of the index translation between zero-indexing and one-indexing, the code would be less clear.

solved how to format numbers with commas in python