I'm getting this error from the code, "UnboundLocalError: local variable 'lowest' referenced before assignment". Why am I getting this? What does 'referenced before assignment' in this case really mean? Because I think that I assign the variable 'lowest' only after 'scores' variable is defined. Any help would be appreciated.
def main():
scores = get_score()
total = get_total(scores)
lowest -= min(scores)
average = total / (len(scores) - 1)
print('The average, with the lowest score dropped is:', average)
def get_score():
test_scores = []
again = 'y'
while again == 'y':
value = float(input('Enter a test score: '))
test_scores.append(value)
print('Do you want to add another score? ')
again = input('y = yes, anything else = no: ')
print()
return test_scores
def get_total(value_list):
total = 0.0
for num in value_list:
total += num
return total
main()
You're using -=, which requires a starting value. But you don't provide a starting value. In context it looks like you meant to use = instead.
That's because in main() you are saying
lowest -= min(scores)
which is essentially lowest = lowest - min(scores). Since you don't have lowest set previously, you'll get that error
Your lowest variable is not defined. You use "lowest -= min(scores)" which means subtract min(scores) from lowest, but lowest doesn't exist yet. Based on the name of the variable I'm guessing you want to do:
def main():
scores = get_score()
total = get_total(scores)
lowest = min(scores)
average = total / (len(scores) - 1)
print('The average, with the lowest score dropped is:', average)
Related
I'm a newbie of python and I'm trying to practice some exercises, however I'm stuck with the line "total = 0" in this code. Actually I don't really understand why this value is initialized to 0.
Could anyone please explain it for me ?
def main():
print("This program allows you to total up some numbers")
print()
n = int(input("How many numbers do you have? "))
total = 0
for i in range(n):
num = float(input("Enter a number: "))
total = total + num
print()
print("The sum of the numbers is:", total)
main()
Remove that line and you see you will get an error:
NameError: name 'total' is not defined
This is because both total and num must be initialised before you can use them in total = total + num
You initialise it before the for loop otherwise it would be reset to 0 each time.
Whenever I run the function to calculate the percentage of scores above the average I get the output 56.301. The correct answer should be 34. The average is 54.8415588235294.
#This function calls on the data file
def get_meet_scores_from_file():
input_file = open('state_meet.txt','r')
all_around_points = []
aline = input_file.readline()
while aline:
values = aline.split(',')
all_around_points.append(float(values[2]))
aline = input_file.readline()
input_file.close()
return all_around_points
#This function calculates the average.
def average_scores(score_list):
average_of_scores = 0
list_length = len(score_list)
for index in range (list_length):
list_item = score_list[index]
average_of_scores = average_of_scores + (list_item / list_length)
return average_of_scores
# This is the function that is causing the problem.
#I am trying to get the code to count the number of scores above the average [enter link description here][1]so I can continue and with the code to determine the percentage.
def percentage_above_average(score_list,average):
above_average = score_list[0]
for i in range(int(above_average)):
if above_average > average:
above_average = above_average + 1
return above_average
Your logic in percentage_above_average makes no sense. All you're doing is taking the first score in score_list, adding 1 if it's above the average score, and returning that number. That just gives you a particular score, incremented by 1 in this instance; it's not a percentage or count of anything.
What you need to do is loop through score_list, count scores higher than the average, and divide that count by len(score_list). The code would look something like this:
def percentage_above_average(score_list,average):
above_average = 0
list_length = len(score_list)
for index in range (list_length):
if score_list[index] > average:
above_average = above_average + 1
return above_average / list_length
The percentage of scores above the average will be the number of scores above the average divided by the total number of scores.
Here's a nice little way to count the number of something in an iterable that meets some condition
sum(1 for i in iterable if some_condition(i))
And of course we can get the total number of scores by getting the length of the list containing them
len(score_list)
So we can put those together to make our function
def percentage_above_average(score_list,average):
above_count = sum(1 for score in score_list if score > average)
return above_count/len(score_list)
Im trying to write a program that will determine the average of a number tests. The number of tests will vary, but I do not want it to be initially set by user input. I'm want to use a while loop and a sentinel value of zero to stop the input. I would like the average to display to three decimal places, with the % symbol immediately following the final digit as shown below...
SAMPLE RUN:
Enter test score 80
Enter test score 70
Enter test score 90
Enter test score 88
Enter test score 0
The average is 82.000%
total =0
counter = 0
while True:
entry = int(input('Enter test score:'))
if entry ==0:
break
total += entry
counter += 1
average = (total/counter)
print("The average score:",format(average, '.3f'),'%',sep='')
While needs to be all lowercase.
if entry == 0 is missing a colon.
total += entry and counter += 1 need to be inside the loop since they must happen with every iteration.
Did you try running the code you had before posting here?
total = 0
counter = 0
while True:
entry = int(input("Enter Test score: "))
if entry == 0: break
total += entry # this should be in while loop
counter += 1
total = total * 1.0
if counter == 0: exit(1)
avg = total / counter
print("Average is: %3.f" % avg + '%')
total += entry should be inside while loop, because you want to add it for every entry received.
hope that helped :)
It doesn't look like you even tried, because your code as is in not able to run at all. However, here is the answer. You'll want to store the results in a list, then get the average by the sum of the list over the length of the list (number of scores). the .format method allows you to specify 3 decimal places.
scores = []
while True:
entry = int(input('Enter test score: '))
if entry == 0:
break
scores.append(entry)
print('The average is', "{0:.3f}".format(float(sum(scores) / len(scores))))
The following should work.
scores = []
while True:
entry = input("Enter test score: ")
if entry == '':
break
elif not entry.isnumeric():
print("Scores must be numeric.")
else:
scores.append(int(entry))
average = sum(scores)/len(scores)
print("The average score is {:.03f}.".format(average))
The average is computed by taking the sum of the list of scores and dividing it by the total number of elements in scores. The rest is just logic to ensure that the user inputs numeric scores and exit when the user enters nothing (just presses Return with no text).
total =0
counter = 0
while True:
entry = int(input('Enter test score:'))
if entry ==0:
break
total += entry
counter += 1
average = (total/counter)
print("The average score:",format(average, '.3f'),'%',sep='')
here is my code so far. I'm not sure whether I do something wrong on the code because the average seems to be wrong. please help me. Thank you
def enter_score ():
results = []
scores = int(input("How many results to enter? : "))
for i in range(scores):
student_name = input("enter student name: ")
student_score = int(input("Please enter score for student " + student_name + " : " ))
results.append(student_score)
results.append(student_name)
print(results)
return results
def calc_average():
total=0
total=total+student_score
average= total/scores
print("the average is ", average)
return
def above_average():
above_average=0
for i in range (scores):
if results [i] > average:
above_average = above_average + 1
print(" the above average score is ", above_average)
return above_average
enter_score()
calc_average()
above_average()
You're making a list results that contains scores and names alternating -- very hard to use. You return that list from enter_score, then completely ignore -- you throw it away! So the other two functions are supposed to work on some magic, or thin air...?
Clearly, the overall flow at the end must instead be:
results = enter_score()
average = calc_average(results)
above_average(results_average)
and calc_average must end with return average.
results is better arranged by replacing the two results.append calls with a single one:
results.append((student_score, student_name))
i.e, make it a list of tuple, not a weird mix of numbers and names.
The other two functions clearly must loop on that list (which they now receive as an argument) to do their respective jobs.
So:
def calc_average(results):
total = 0
for student_score, student_name in results:
total=total+student_score
average= total/float(len(results))
print(average)
return average
and:
def above_average(average, results):
above_average = 0
for student_score, student_name in results:
if student_score > average:
above_average += 1
print(" the number of above average scores is ", above_average)
return above_average
I fixed/ammended your code so that it works:
def enter_score ():
results = []
scores = int(input("How many results to enter? : "))
for i in range(scores):
student_name = input("enter student name: ")
student_score = int(input("Please enter score for student " + student_name + " : " ))
results.append((student_name, student_score))
print(results)
return results
def calc_average(results):
total=0
for student_name, student_score in results:
total=total+student_score
average= total/len(results)
print("the average is ", average)
return average
def above_average(results, average_score):
above_average_no=0
for student_name, student_score in results:
if student_score > average_score:
above_average_no = above_average_no + 1
print(" the above average score is ", above_average_no)
return above_average_no
results = enter_score()
average_score = calc_average(results)
above_average_no = above_average(results, average_score)
I wont provide detailed explanation on what and why things changes. Leave it to you to figure it out. Please note that I tried to make minimal changes to your code. Many things could be improved, such as calculating sum, etc. Hope this helps.
I'm having trouble with this python code that is supposed to ask for five values, find the minimum value and subtract it and find the average of the remaining four numbers. I want to use a for loop and if anyone can help me also create a list, i can't seem to get that to work either so I'm doing it as you see below
def get_data():
name = raw_input("What is your name: ")
for i in range(5):
scores = int(input("what are your test scores? ")
return name, scores
def low_score(scores):
low = min(scores)
print low
return low, scores
def find_avg(scores, low):
avg = sum(scores)
print name, "your average = ", avg
return avg
name, scores = get_data()
low, scores = low_score(scores)
avg = find_avg(scores, low)
There are a few problems with your approach. Take a look at this while I write some comments:
def get_data():
name = raw_input("What is your name: ")
scores = []
for i in range(5):
scores.append(int(input("what are your test scores? ")))
return name, scores
def drop_low_score(scores):
sorted_scores = sorted(scores)
print "Dropping", sorted_scores[0]
highest_four_scores = sorted_scores[1:]
return scores
def find_avg(scores):
avg = sum(scores) / float(len(scores))
print name, "your average = ", avg
return avg
name, scores = get_data()
scores = drop_low_score(scores)
avg = find_avg(scores)
When you assign the value from input to score, you are overwriting it each time. Here I am appending it to a list I create before the loop.
Think of it like this:
scores = []
for i in range(5):
new_score = int(input("test score?"))
scores.append(new_score)
Each time through the loop you are appending a new value to the list of scores. At the end of the loop you have 5 scores in your list.
The next problem is you are getting the low_score, but you are doing nothing with it. There are a few ways to deal with that. Read about list to find ways to do it. In my code (since the list is so small) I simply sort it and slice the list, cutting off the first one after it is sorted (default sorting is small to large), so it removes the smallest value. You can read up on list slicing too, but this is an example,
>>> my_list = [1, 2, 3, 4]
>>> print my_list[2:]
[3, 4]
>>> print my_list[3:]
[4]
>>> print my_list[:2]
[1, 2]
The last problem is your find_avg which doesn't find an average at all, it is just summing the scores. You need to sum and divide by the number of elements in the list.
You have a missing bracket in the line -
scores = int(input("what are your test scores? ")
I'm guessing that's the source of your problem because you haven't provided any traceback.
In your loop
for i in range(5):
scores = int(input("what are your test scores? ")
you are overwriting scores five times, without saving the previous values.
Maybe you want something like this:
scores = [int(input("what are your test scores? ") for _ in range(5)]
So the whole assignment would boil down to:
scores = [int(input("what are your test scores? ") for _ in range(5)]
print('Your top four average is', (sum(scores)-min(scores))/4.0)
def get_data():
name = raw_input("What is your name: ")
scores = []
for i in range(5):
scores.append(int(input("what are your test scores? ")))
return name, scores
def low_score(scores):
low = min(scores)
print low
return low, scores
def find_avg(scores, low):
indvalue = scores.index(low)
scores.pop(indvalue)
avg = sum(scores)/len(scores)
print name, "your average = ", avg
return avg
name, scores = get_data()
low, scores = low_score(scores)
avg = find_avg(scores, low)
the above code should wrk fine... with minor modifications in your logic