mercredi 31 octobre 2018

Python; If statements, For Loops, File Reading

To be clear, I am not asking anyone to do this for me. I am simply asking a question seeking guidance so I can continue working on this.

We are given a file that gives various weights of packages;

11
25
12
82
20
25
32
35
40
28
50
51
18
48
90

I have to create a program that will count the amount of packages, Categorize them into Small, Medium, and Large, and find the average of the weights. I know I have to use If statements, and for loops to accumulate the weight count and categorize them among each category.

The terms for what is small, med, and large is as follows;

Small < 10 lbs

Medium >= 10 lbs. and < 30 lbs

Large >= 30 lbs.

If no packages of a weight class are entered, report the message “N/A” instead of an average (if you try to divide by 0 you will get an exception).

This is the code I have so far, I cant figure out if I have to include a for loop after the if, elif, and else. Or if what I have is on track.

infile = open("packages.txt", 'r')
count = 0
line = infile.readline()
weight = int(line)
for line in infile:
    if weight < 10:
        count = count + 1
        weight = weight + int(line)
        while weight < 10:
            try:
                avg = weight / count
            except ValueError:
                print("N/A")
    elif weight >= 10:
        if weight < 30:
            weight = weight + int(line)
            count = count + 1
            avg = weight/count
    else:
        weight = weight + int(line)
        count = count + 1
        avg = weight/count

The output has to look something like this

Category    Count    Average
Small       0        N/A
Medium      7        19.9
Large       8        53.5

Again, I am not looking for someone to do this for me. I am looking for the next step and/or tweaks to what I currently have to be able to continue forward. Thank you!

Aucun commentaire:

Enregistrer un commentaire