Using functions, how would I print the lowest, highest, and average of my PAY list?

try:
text_file = open ("Pay.txt", "w")
text_file.writelines(Pay)
text_file.close()
except (IOError):
print 'Error opening/writing Pay.txt'

try:
text_file= open("Pay.txt","r")
PAY= text_file.readlines()
text_file.close()
PAY.sort()

I modified this one a bit from a post I made a few days ago so you will need to clean it up but it does what you want.

from random import randrange


def initialize():
    """ create a list of random numbers and sort them and print them out"""
    #creates the list
    tmp = []
    mylist = []
    for num in range(0,15):
        mylist.append(randrange(1,1000))

    #keep sending the list to the sorter always returning the
    #highest number back until initial list is empty
    while mylist != []:
        highest = sorter(mylist)
        tmp.append(highest)
        mylist.remove(highest)
    #print to screen
    #print "high to low\n" , tmp
    print "high", tmp[0]
    tmp.reverse()
    #print "low to high\n" , tmp
    print "low", tmp[0]
    length = len(tmp)
    average = 0
    for item in tmp:
        average += item
    average = average / length
    print "average", average


def sorter(mylist):
    """ find the highest number and return it"""
    highest = 0
    for item in mylist:
        if item > highest:
            highest = item
    return highest

initialize()

Generally, it pays (no pun intended) to keep your pay list object intact. Save and load it with module pickle. A purely numeric list like that makes the rest of the calculations easy ...

# sample list of annual salaries
pay_list = [
35500,
49600,
28450,
75234,
51230
]

# get lowest pay
print(min(pay_list))  # 28450 

# get highest pay
print(max(pay_list))  # 75234 

# get average pay
print(float(sum(pay_list))/len(pay_list))  # 48002.8
This article has been dead for over six months. Start a new discussion instead.