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!
To begin with you need three weight
and count
variables: One for each category.
Then your reading for the file is a little flawed. Don't start by reading a line, instead just have the loop and assign to weight
inside the loop the first thing you do.
Perhaps something like this:
total_small = 0
total_medium = 0
total_large = 0
count_small = 0
count_medium = 0
count_large = 0
for line in infile:
weight = int(line)
if weight < 10:
total_small += weight
count_small += 1
# And the same for medium and large as well...
Then after the loop you can easily calculate the average of each category as you print it.
Oh, and you don't check for the upper limit of medium packages, which you need to do.