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

Recommended Answers

All 2 Replies

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)

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 :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.