print("please enter your 5 marks below")
#read 5 inputs
mark1 = int(input("enter mark 1: "))
mark2 = int(input("enter mark 2: "))
mark3 = int(input("enter mark 3: "))
mark4 = int(input("enter mark 4: "))
mark5 = int(input("enter mark 5: "))
#create array/list with five marks
marksList = [mark1, mark2, mark3, mark4, mark5]
#print the array/list
print(marksList)
#calculate the sum and average
sumOfMarks = sum(marksList)
averageOfMarks = sum(marksList)/5
#display results
print("The sum of your marks is: "+str(sumOfMarks))
print("The average of your marks is: "+str(averageOfMarks))
Couldn't really come up with anything
The assessment has the following guidelines.
Ask the user to input the marks for the five subjects in a list/array.
The program must ensure that the marks are between 0 and 100
Display the list/array of marks entered.
Find the sum of all the marks in the list (all five subjects) and display the output as:
The sum of your marks is: [sum]
Find the average of all the marks in the list (all five subjects) and display the output as:
The average of your marks is: [average mark]
If when you said "debug", you are referring to inspect the values and validate it, then you can write some unit tests
another way is to install ipdb and set a ipdb.set_trace()
How about this:
N = 5
print(f"please enter your {N} marks below")
# read inputs
def checked_input(tip: str) -> int:
try:
num = int(input(tip))
assert 0 <= num <= 100
except (ValueError, TypeError, AssertionError):
print('mark must between 0 and 100!')
return checked_input(tip)
else:
return num
marks = [checked_input(f'enter mark {i}: ') for i in range(1, N+1)]
# print the array/list
print(marks)
# calculate the sum and average
total = sum(marks)
average = total / N
# display results
print(f"The sum of your marks is: {total}")
print(f"The average of your marks is: {average}")
I am creating a program that takes users and stores them in list and takes their marks and afterwards it grades them. I've done the user input part and the marks as well along with the average of them but I am struggling to give them grade and print it along with their name so it will be like Name marks Grade. If anyone can help me with this I'll be thankful greatly here is my code
students=[]
for i in range (2):
x=(input("Enter Student Name. \n"))
students.insert(i,x)
i+=1
print(students)
grades = []
for student in students:
grade = eval(input(f"Enter the grade for {student}: "))
grades.append(grade)
result = list(zip(students, grades))
print(result)
average = sum(grades) / len(grades)
print ( "Average is: " + str(average))
total = sum(grades)
# print ("Total is: " + str(total))
print("Highest marks", max(list(zip(grades, students))))
print("Lowest marks", min(list(zip(grades, students))))
## To do assign grades to each according to their marks
I am struggling to give them grade and print it along with their name so it will be like Name marks Grade.
Look at the below - it uses zip and loop
names = ['Jack','Dan']
grades = [67,86]
def _get_grade(grade):
if grade < 50:
return 'C'
elif grade >= 50 and grade <= 75:
return 'B'
else:
return 'A'
for name,grade in zip(names,grades):
print(f'Name: {name} - Grade: {_get_grade(grade)}')
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'])
Create a program that will calculate a student’s grade in a class that uses a weighted gradebook.
A weighted system uses percentages to determine how much each assignment category is worth. For this project, use the following percentages:
Project Grades = 30% (weight = .30)
Participation Grades = 20% (weight = .20)
Quizzes = 10% (weight = .10)
Exams = 40% (weight = .40)
Grading scale:
A - 90-100
B - 80-89
C - 70-79
D - 60-69
F - Below 60
Note: You will multiply the average for each of the categories by its weight. The final grade is the sum of the calculated weights.
Can't get the code to the allow the user to enter grades in all 4 categories, because it gets stuck on the first category chosen and the loop just goes on and on without stopping asking for a list of scores. I attempted a loop inside a loop, but it only continued on the first one chosen as well. Need multiple grades entered into all 4 categories which is why I need the program to allow the user to enter grades to the other categories not just the one that is chosen first.
print ("Weighted Grade Calculator ")
name = input("Enter the Student's Name ")
number = input("Enter the Student's Number ")
x = input("Enter Assignment type: ")
c = 'y'
#Loop is in case user wants to calculate another students grade
while c=='y' or c=='Y':
if x >= "quiz" or x >= "Quiz":
input_string = input("Enter a list of scores separated by space ")
#Read ints separated by spaces
lst = input_string.split()
print("Calculating sum of element of input list")
#convert strings to ints and convert map to list
lst = list(map(int, lst))
#Find total and avg
total = sum(lst)
avg_1 = total/len(lst)
elif x >= "project" or x >= "Project":
input_string = input("Enter a list of scores separated by space ")
lst = input_string.split()
print("Calculating sum of element of input list")
lst = list(map(int, lst))
total = sum(lst)
avg_2 = total/len(lst)
elif x >= "participation" or x >= "Participation":
input_string = input("Enter a list of scores separated by space ")
lst = input_string.split()
lst = list(map(int, lst))
total = sum(lst)
avg_3 = total/len(lst)
elif x >= "exam" or x >= "Exam":
input_string = input("Enter a list of scores separated by space ")
lst = input_string.split()
print("Calculating sum of element of input list")
lst = list(map(int, lst))
total = sum(lst)
avg_4 = total/len(lst)
else:
print("error, please try again")
#Finds percentage earned from each category
w_quiz = avg_1 * 0.1
w_project = avg_2 * 0.3
w_participation = avg_3 * 0.2
w_exams = avg_4 * 0.4
total = w_project + w_quiz + w_participation + w_exams
if(total >= 90 and total <=100):
grade = 'A'
elif(total >= 80 and total < 90):
grade = 'B'
elif(total >= 70 and total < 80):
grade = 'C'
elif(total >= 60 and total < 70):
grade = 'D'
elif(total >= 0 and total < 60):
grade = 'F'
print ("Student Name: " + str(name))
print ("Student ID: " + str(number))
print ("Total Weighted Score: " + str(total) + "%")
print ("Letter Grade: " + grade)
c = input("Would you like to calculate another grade? (Y or N): ")
Not sure exactly what you are looking for, but this code will take as much input as you give it and at the end will calculate the average of all totals and its respective letter grade:
def calculate_letter(total):
#function calculates letter grade
if(total >= 90 and total <=100):
grade = 'A'
elif(total >= 80 and total < 90):
grade = 'B'
elif(total >= 70 and total < 80):
grade = 'C'
elif(total >= 60 and total < 70):
grade = 'D'
elif(total >= 0 and total < 60):
grade = 'F'
return grade
print ("Weighted Grade Calculator ")
name = input("Enter the Student's Name ")
number = input("Enter the Student's Number ")
totals = [] #initialize list to append scores to
while True:
project = float(input("Enter the percentage for Projects (numbers only): "))
participation = float(input("Enter the percentage for the Participation (numbers only): "))
quizzes = float(input("Enter the percentage for Quizzes (numbers only): "))
exams = float(input("Enter the percentage for the Final Exam (numbers only): "))
w_project = project * 0.3
w_participation = participation * 0.2
w_quiz = quizzes * 0.1
w_exams = exams * 0.4
total = w_project + w_quiz + w_participation + w_exams
grade = calculate_letter(total) #running the function defined above to evaluate letter grade from total
print ("Total Weighted Score: " + str(total) + "%")
print ("Letter Grade: " + grade)
c = input("Would you like to calculate another grade? (Y or N): ").lower()
totals.append(total)
if c == 'y':
#restarts the loop
continue
else:
#exits the loop
break
print(totals)
final_averaged_score = sum(totals) / len(totals) #finding the average of the list
final_grade = calculate_letter(final_averaged_score)
print ("Student Name: " + str(name))
print ("Student ID: " + str(number))
print ("Final Averaged score: " + str(final_averaged_score))
print ("Final letter grade: " + str(final_grade))
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.