0

How do I take randomly generated numbers and print the average of the numbers? And how do should I go about printing how many even and odd numbers that were generated?

Thanks

3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by Paul Thompson
0

This is rather crude, but it works:

import random

y = 0
count = 0
even_count = 0
odd_count = 0
while count < 100:
    x = random.randint(1,101)
    print x
    y += x
    count += 1
    avg = y / count
    if y %2 == 0:
        even_count += 1
        print " the average is ", avg
    else:
        odd_count += 1
        print "The average is", avg

print "Out of 100 tries, %d was odd and %d was even" %(odd_count, even_count)
0

To get the average i usually make a function

import random

def averageList(l):
    total = 0 
    for item in l:
        total += item
    return total/len(l)

#then i make my list
l = [random.rangrange(0,100) for f in range(100)]
print averageList(l)

Functions are a great way to reuse your code if you ever need to.

Hope that helps :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.