Jul-31-2019, 12:36 AM

I made a program that randomly adds numbers between 1 and 10 to a list 1,000 times and then counts the number of times each number occurs in that list. The results are given as percentages.

import random # Declaring the variables I'm going to use list_of_numbers = [] list_length = 0 ones = 0 twos = 0 threes = 0 fours = 0 fives = 0 sixes = 0 sevens = 0 eights = 0 nines = 0 tens = 0 # Adding a random number between 1 and 10 to my list_of_numbers 1,000 times while list_length < 1000: list_of_numbers.append(random.randint(1, 10)) list_length += 1 # Counting the number of times each number between 1 and 10 appears in the list for each in list_of_numbers: if each == 1: ones += 1 elif each == 2: twos += 1 elif each == 3: threes += 1 elif each == 4: fours += 1 elif each == 5: fives += 1 elif each == 6: sixes += 1 elif each == 7: sevens += 1 elif each == 8: eights += 1 elif each == 9: nines += 1 else: tens += 1 # Printing the results as percentages def print_percents(num_count, num_title): percent = 100 * (num_count / list_length) # <--- Notice that, inexplicably, I'm able to use a variable from the script's namespace in a function and without error. print(str(num_title).capitalize() + ": " + str(percent) + "%") print_percents(ones, "ones") print_percents(twos, "twos") print_percents(threes, "threes") print_percents(fours, "fours") print_percents(fives, "fives") print_percents(sixes, "sixes") print_percents(sevens, "sevens") print_percents(eights, "eights") print_percents(nines, "nines") print_percents(tens, "tens")It works. But now suppose I wanted to add all the percentages together to make sure they add up to 100%. How would I do that (most easily and with as little code as possible) without using global variables?