Question: Write a program to continuously asks the user an exam score given as integer percentages in the range 0 to 100. If a value not in the range is input except for -1, print out an error and prompt the user to try again. Calculate the average of all valid grades input along with the total number of grades in each letter-grade category as follows: 90 to 100 is an A, 80 to 89 is a B, 70 to 79 is a C, 60 to 69 is a D, and 0 to 59 is an F. Use a negative score as a sentinel value to indicate the end of the input. (The negative value is used only to end the loop, so do not use it in the calculations.) For example, if the input is.
#Enter in the 4 exam scores
g1=int(input("Enter an exam score between 0 and 100 or -1 to end: "))
g2=int(input("Enter an exam score between 0 and 100 or -1 to end: "))
g3=int(input("Enter an exam score between 0 and 100 or -1 to end: "))
g4=int(input("Enter an exam score between 0 and 100 or -1 to end: "))
total =(g1 + g2 + g3 + g4)
while g1 is range(0,100):
continue
else:
print("Sorry",g1,"is not in the range of 0 and 100 or -1. Try again!")
while g2 is range(0,100):
continue
else:
print("Sorry",g2,"is not in the range of 0 and 100 or -1. Try again!")
while g3 is range(0,100):
continue
else:
print("Sorry",g3,"is not in the range of 0 and 100 or -1. Try again!")
while g4 is range(0,100):
continue
else:
print("Sorry",g4,"is not in the range of 0 and 100 or -1. Try again!")
#calculating Average
def calc_average(total):
return total/4
def determine_letter_grade(grade):
if 90 <= grade <= 100:
1 + TotalA
elif 80 <= grade <= 89:
1 + TotalB
elif 70 <= grade <= 79:
1 + TotalC
elif 60 <= grade <= 69:
1 + TotalD
else:
1 + TotalF
grade=total
average=calc_average
#printing the average of the 4 scores
print("You entered four valid exam scores with an average of: " + str(average))
print("------------------------------------------------------------------------")
print("Grade Distribution:")
print("Number of A's: ",TotalA)
print("Number of B's: ",TotalB)
print("Number of C's: ",TotalC)
print("Number of D's: ",TotalD)
print("Number of F's: ",TotalF)
Sample output that I was given:
Enter an exam score between 0 and 100 or -1 to end: 88.64
Enter an exam score between 0 and 100 or -1 to end: 103
Sorry, 103 is not in the range of 0 and 100 or -1. Try Again!
Enter an exam score between 0 and 100 or -1 to end: 99.10
Enter an exam score between 0 and 100 or -1 to end: 71.52
Enter an exam score between 0 and 100 or -1 to end: 73
Enter an exam score between 0 and 100 or -1 to end: -1
You entered 4 valid exam scores with an average of 83.07.
Grade Distribution
Number of A’s = 1
Number of B’s = 1
Number of C’s = 2
Number of D’s = 0
Number of F’s = 0
Note: This is my first computer science class so I'm sure there is an obvious work around that I am missing but id appreciate any help I can get
Here is my walk-through explanation:
So, the program is supposed to ask the user what score they got until they say they got a score of -1, in which after you give them their results. To loop until they give -1, we can use a while loop:
inp = float(input("Enter an exam score between 0 and 100 or -1 to end: ")) # Get input
grades = []
while inp > -1: # Loop until user gives a score of -1
if inp >= 0 and inp <= 100: # Check if valid grade
grades.append(inp) # Add grade to grades list
inp = float(input("Enter an exam score between 0 and 100 or -1 to end: ")) # Ask again
else:
print("Sorry", inp, "is not in the range of 0 and 100 or -1. Try again!") # Invalid grade
# ANALYSIS OF GRADES
# Format first line of output - the first str(len(grades)) give the amount of grades they entered,
# and the str(sum(grades) / len(grades)) gives the average of the grades list.
print("You entered", str(len(grades)), "valid exam scores with an average of", str(sum(grades) / len(grades)))
print("Grade Distribution:")
print("Number of A's =", str(sum(90 <= g <= 100 for g in grades)) # I am using a very short notation
print("Number of B's =", str(sum(80 <= g <= 89 for g in grades)) # here - this is basically counting
print("Number of C's =", str(sum(70 <= g <= 79 for g in grades)) # the number of grades that are
print("Number of D's =", str(sum(60 <= g <= 69 for g in grades)) # a valid value based on the checks
print("Number of F's =", str(sum(0 <= g <= 59 for g in grades)) # I am making.
Hopefully my comments help you figure out what is happening in my code!
here your problem can be devided into few parts,
get number of exam from user
get the valid input from user for those exam
calculate the average of all exam
calculate the grade distribution
exit if user input is -1
below code is following all these steps
#calculating Average
def calc_average(scores):
return sum(scores)/len(scores)
grade_dist = {
(90, 101):'A',
(80,90):'B',
(70, 80):'C',
(59, 70):'D',
(0,59):'F'
}
def get_grade_freq(scores):
grades = {'A':0, 'B':0, 'C':0, 'D':0, 'F':0}
for score in scores:
for k, v in grade_dist.items():
if score in range(k[0], k[1]):
grades[v]+=1
print("Grade distributions")
for grade, number in grades.items():
print("Number of {}’s = {}".format(grade, number))
def get_scores(n):
scores = []
cond = True
while cond and n>0:
score = int(input("Enter an exam score between 0 and 100 or -1 to end : "))
if score==-1:
cond=False
return -1
if score not in range(0,101):
print("Sorry, {} is not in the range of 0 and 100 or -1. Try Again!".format(score))
if score in range(0,101):
scores.append(score)
n-=1
return scores
def main():
n = int(input('total number of exams ' ))
scores = get_scores(n)
if scores == -1:
exit(-1)
average = calc_average(scores)
print("You entered {} valid exam scores with an average of {}.".format(n, average))
get_grade_freq(scores)
if __name__=='__main__':
main()
Whenever you have multiple instances of similar things to manipulate (scoring ranges, total counts) you must try to use multi-value structures rather than individual variables. Python's lists and dictionaries are designed for collecting multiple entries either as a positional list or as a keyed index (dictionary).
This will make your code more generalized. You'll know you're on the right track when you manipulate concepts rather than instances.
For example:
grading = [(None,101),("A",90),("B",80),("C",70),("D",60),("F",0)]
scores = {"A":0, "B":0, "C":0, "D":0, "F":0}
counts = {"A":0, "B":0, "C":0, "D":0, "F":0}
while True:
input_value = input("Enter an exam score between 0 and 100 or -1 to end: ")
value = int(input_value)
if value == -1: break
score = next((s for s,g in grading if value >= g),None)
if score is None:
print("sorry ",input_value," is not -1 or in range of 0...100")
continue
scores[score] += value
counts[score] += 1
inputCount = sum(counts.values())
average = sum(scores.values())//max(1,inputCount)
print("")
print("You entered", inputCount, "valid exam scores with an average of: ", average)
print("------------------------------------------------------------------------")
print("Grade Distribution:")
for grade,total in counts.items():
print(f"Number of {grade}'s: ",total)
The grading list contains pairs of score letter and minimum value (in tuples). such a structure will allow you to convert the grade values in to score letters by finding the first entry that has a value lower or equal to the input value and use the corresponding letter.
The same list is used to validate the input value by strategically placing a None value after 100 and no value below zero. The next() function will perform the search for you and return None when no valid entry is present.
Your main program loop needs to continue until the input value is -1 but it needs to go through the input at least onces (typical of a repeat-until structure but there is only a while in Python). So the while statement will loop forever (i.e. while True) and will need to be arbitrarily broken when the exit condition is met.
To accumulate the scores, a dictionary (scores) is better suited than a list because a dictionary will allow you to access instances using a key (the score letter). This allows you to keep track of multiple scores in a single variable. The same goes for counting how many of each score were entered.
To get the average at the end, you simply need to sum up the values scores of the scores dictionary and divide by the count of of scores you added to the counts dictionary.
Finally to print the summary of score counts, you can leverage the dictionary structure again and only write one generalized printing line for all the score letters and totals.
This may work for you:
scores = {
"A": 0,
"B": 0,
"C": 0,
"D": 0,
"F": 0,
}
total = 0
count = 0
input_value = 0
while (input_value != -1) and (count < 4):
input_value = int(input("Enter an exam score between 0 and 100 or -1 to end: "))
if 0 <= input_value <= 100:
total += input_value
count += 1
if input_value >= 90:
scores["A"] += 1
elif input_value >= 80:
scores["B"] += 1
elif input_value >= 70:
scores["C"] += 1
elif input_value >= 60:
scores["D"] += 1
else:
scores["F"] += 1
else:
print("Sorry", input_value, "is not in the range of 0 and 100 or -1. Try again!")
print("You entered {} valid exam scores with an average of: {}".format(count, total / count))
print("------------------------------------------------------------------------")
print("Grade Distribution:")
print("Number of A's: ", scores['A'])
print("Number of B's: ", scores['B'])
print("Number of C's: ", scores['C'])
print("Number of D's: ", scores['D'])
print("Number of F's: ", scores['F'])
I try to calculate several properties of students:
the amount of students
the sum of the marks of the students
the lowest, the average and the highest mark they received.
Yet, the variable mark only shows 0.
How can I solve this problem using function but not max() and min()?
mark = 0
a = 0
student = 0
a = int(input("Enter Marks :"))
def maxx():
maxx = 0
for i in range(1, a):
if a> maxx :
maxx = a
return maxx
def minn():
minn = 0
for i in range(1, a):
if a < minn :
minn = a
return minn
while (a >= 0):
mark = mark + a
student = student + 1
a = int(input("Enter Marks :"))
print("Exit")
print("Total students :", student)
print ("The total marks is:", mark)
average = mark/student
print ("The average marks is:", average)
print("The max marks is :", maxx())
print("The min marks is :", minn())
Your code has a lot of problems. One of them is
for i in range(1, a):
This part makes no sense if you want a min or max value. You need to iterate over a list of grades instead.
mark and student are also unnecessary considering they can be replaced by sum and len respectively.
The entire code seems to lack a proper structure. Here's an example implementation. If you are not allowed to use sum or len, you may bring your own mark and student method back, but try not to make a mess and keep it readable:
def maxx(grades):
if (not grades): # if empty, we let the caller know
return None
res = grades[0] # we know the list is not empty
for i in grades:
if i > res:
res = i
return res
def minn(grades):
if (not grades):
return None
res = grades[0]
for i in grades:
if i < res:
res = i
return res
def main():
grades = [] # list of grades
while (True):
grade = int(input("Enter Mark: "))
if (grade < 0): break
grades.append(grade)
student_cnt = len(grades)
total = sum(grades)
print("Exit")
print("Total students :", student_cnt)
print("The total marks is:", total)
print ("The average marks is:", total / student_cnt)
print("The max marks is :", maxx(grades))
print("The min marks is :", minn(grades))
if __name__ == "__main__":
main()
Input/Output:
Enter Mark: 30
Enter Mark: 20
Enter Mark: 10
Enter Mark: 40
Enter Mark: -1
Exit
Total students : 4
The total marks is: 100
The average marks is: 25.0
The max marks is : 40
The min marks is : 10
This is my Task:
Require the user to enter their name, with only a certain name being able to trigger the loop.
Print out the number of tries it took the user before inputting the correct number.
Add a conditional statement that will cause the user to exit the program without giving the average of the numbers entered if they enter a certain input
numbers = []
number = 0
count = 0
total = 0
name = 0
while number >= 0:
number = int(raw_input("Please enter any number: \n"))
if number == -1:
break
numbers.append(number)
avg = float(sum(numbers)) / len(numbers)
print "The average of the numbers you entered is " + str(avg) + "!"
while name >= 0:
name = int(raw_input("Please enter the number of characters your name contains: \n"))
count += 1
total += count
if name == 6:
break
tries = sum(total)
print tries
tries = sum(total)... sum takes an iterable whereas total is an int hence the error.
If total = [ ]
and you can append count values in total that would be fine.
so total.append(count)
would create list then you can use sum(total) on it
but here you can simply use print total or count both are same.
numbers = []
number = 0
count = 0
total = 0
name = 0
while number >= 0:
number = int(raw_input("Please enter any number: \n"))
if number == -1:
break
numbers.append(number)
avg = float(sum(numbers)) / len(numbers)
print "The average of the numbers you entered is " + str(avg) + "!"
while name >= 0:
name = int(raw_input("Please enter the number of characters your name contains: \n"))
count += 1
total += count
if name == 6:
break
tries = total
print tries
and you try to reduce your code.
Hello i was wondering why this code will not run,thanks.
count = 0
finished = False
total = 0
while not finished:
number = int(input("Enter a number(0 to finish)"))
if number == 0:
finished = True
else:
total = total + number
count = count + 1
print("the average is", total/ count)
count = 0
Your script is alright, you haven't indented properly the elseclause, here's a working example, also, you should cast to float your average:
count = 0
finished = False
total = 0
while not finished:
number = int(input("Enter a number(0 to finish)"))
if number == 0:
finished = True
else:
total = total + number
count = count + 1
print("the average is", float(total) / float(count))
count = 0
Another possible way to do the same with few lines would be this:
values = []
while True:
number = int(input("Enter a number(0 to finish)"))
if number == 0:
break
values.append(number)
print("the average is", float(sum(values)) / float(len(values)))
It does run, the only issue I can see is that your else is indented inside your if block. In Python, indentation is important in a way that curled brackets or keywords are important in other programming languages.
count = 0
finished = False
total = 0
while not finished:
number = int(input("Enter a number(0 to finish)"))
if number == 0:
finished = True
else:
total = total + number
count = count + 1
print("the average is", total/ count)
count = 0
How to complete my program which repeatedly reads numbers until the user enters
“done”. Once “done” is entered, print out the total, count, and average of
the numbers. If the user enters anything other than a number, detect their mistake
using try and except and print an error message and skip to the next number.
count = 0
total = 0
while True:
x = raw_input('Enter number')
x=int(x)
total = total + x
count = count + 1
average = total / count
print total, count, average
The following code should be what you want.
count = 0
total = 0
while True:
x = raw_input('Enter number: ')
if(x.lower() == "done"):
break
else:
try:
x=int(x)
total = total + x
count = count + 1
average = total / count
except:
print("That is not an integer. Please try again.")
print total, count, average
or in Python 3
count = 0
total = 0
while True:
x = input('Enter number: ')
if(x.lower() == "done"):
break
else:
try:
x=int(x)
total = total + x
count = count + 1
average = total / count
except:
print("That is not an integer. Please try again.")
print(total, count, average)