I need to ask the final grade of 10 students (while) incrementing their values:
So something like:
Please enter final grade for student 1
Please enter final grade for student 2
and so on... till 10
Then I need to get the grades they entered, and find average.
This is what I have so far:
def main():
x = []
for i in range(10):
final_grades = x.append(int(input('Please enter final grade for student: ')))
##average_final_grade = final_grades / 10
##print(average_final_grade)
main()
# list of grades
x = []
# count of students
n = 10
# fill list with grades from console input
# using pythonic generator
x = [int(input('Please enter final grade for student {}: '.format(i+1))) for i in range(n)]
# count average,
# sum is builtin way to sum values in list
# float required for python 2.x to make avg float, not int
average_final_grade = sum(x) / float(n)
print('Avg grade is {}'.format(average_final_grade))
Online demo.
First, you need to get the values, as you have already done:
x = []
for i in range(10):
x.append(int(input('Please enter final grade for student: ')))
Now you need to sum the values of x:
total_sum = sum(x)
Then, you get the average:
average_final_grade = total_sum/len(sum)
total=sum(x)
average=total/10
print(average)
tack this at the bottom and it should work
Related
Alright so this problem has been grinding me for a good hour. I am taking a zybooks course and I'm presented with the prompt,
Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max.
Ex: If the input is:
15 20 0 5
the output is:
10 20
currently I have it 'working' with my code but the issue is I cannot figure out how to keep the input open for more or less inputs as zybooks runs through multiple different tests. i'm sure its something simple im overlooking. anything helps!
nums = []
for i in range(0, 4):
number = int(input('Enter number'))
nums.append(number)
avg = sum(nums) / len(nums)
print(max(nums), avg)
This code continually asks the user to enter values until they enter a blank (just press enter without typing).
This is the code:
nums = []
# initialse
number = 0
# loop until there isn't an input
while number != "":
# ask for user input
number = input('Enter number:')
# validate the input isn't blank
# prevents errors
if number != "":
# make input integer and add it to list
nums.append(int(number))
avg = sum(nums) / len(nums)
print(max(nums), avg)
Alternatively, if you have the list of numbers:
def maxAndAvg(nums):
avg = sum(nums) / len(nums)
return max(nums), avg
One solution is to have the user specify how many numbers they want to take the average of. For instance:
nums = []
n = int(input('How many numbers: '))
for i in range(n):
number = int(input('Enter number: '))
nums.append(number)
avg = sum(nums) / n
print(max(nums), avg)
Alternatively, if you want a function that itself takes a variable number of arguments, you'll need to use the "*args" operator. For instance,
def my_average(*args):
return sum(args)/len(args)
An example usage:
print(my_average(1),my_average(1,2),my_average(1,2,3))
Result:
1.0 1.5 2.0
Ok, guys this is the correct code to figure this lab out. Did some data mining and some line manipulation to pass all ten tests:
nums = []
while not nums:
number = input()
nums = [int(x) for x in number.split() if x]
avg = int(sum(nums) / len(nums))
print(avg, max(nums))
I have my code set to allow the user to make a list of names for students and another list for their corresponding grades. What I cant seem to figure out is how to take the highest grade, the lowest grade, and the closest to the average then state it with the student it belongs to.
This is what I have so far
# creating statements
students = []
grades = []
print('students:',students)
print('grades:',grades)
looper1 = 0
looper2 = 0
studentappend = 0
gradeappend = 0
# list creation
while looper1 != 2:
print('please choose an option:')
print('1: add student and grade')
print('2: Finish step')
looper1 = int(input())
if looper1 ==1:
students.append(input('enter student name: '))
grades.append(int(input('enter grade:')))
print('students:',students)
print('grades:',grades)
if looper1 ==2:
break
if looper1 !=1 and looper1 !=2:
print('Invalid. enter 1 or 2')
print('students:',students)
print('grades:',grades)
print("Largest element is:", max(grades))
On the last line I have it set to say "Largest grade is: 55" for example, but I want to make it say the name the grade belongs to as well. For example "Bill has the largest grade of 55" This will apply to the lowest grade and the grade that is the closest to the average. I was hoping the max() function would print the number that would tell me where the grade I was looking for was located rather then simply stating it.
Here is a solution with modifications to make your code more streamlined:
students = []
grades = []
#gather input
looper = 1
while looper == 1:
students.append(input('enter student name: '))
grades.append(int(input('enter grade: ')))
looper = int(input('Enter 1 to add more data or another number to exit: '))
#calculate closest to mean
true_mean = sum(grades)/len(grades)
close_to_mean = 0
for i, grade in enumerate(sorted(grades)):
if grade < true_mean < sorted(grades)[i+1]:
close_to_mean = grade
print('students:',students)
print('grades:',grades)
print(f"Highest grade is: {max(grades)} and belongs to {students[grades.index(max(grades))]}.")
print(f"Lowest grade is: {min(grades)} and belongs to {students[grades.index(min(grades))]}.")
print(f"Closest to mean grade is: {close_to_mean} and belongs to {students[grades.index(close_to_mean)]}.")
You can reference the index location for the highest value in the grades list and use that index to return the corresponding student in the students list.
print(students[grades.index(max(grades))]+" has the larges grade of "+str(max(grades)))
Note that the index method returns the index of the first matching item in the list. So if two students are tied with the highest score, it will only return the one listed first.
If you aren't opposed, another approach is to use NumPy functions.
np.argmax and np.argmin give the indices of the (first occurrence of) the maximum and minimum value in an array or list.
To get the name of the student with the highest grade: students[np.argmax(grades)]
To get the name of the student with the lowest grade: students[np.argmin(grades)]
To get the name of the student with the grade closest to the average, you may need list comprehension to calculate the absolute difference between the average grade and each student's grade:
students[np.argmin(np.abs([x - np.mean(grades) for x in grades]))]
Alternatively, instead of list comprehension, you can directly cast it to a numpy array:
students[np.argmin(np.abs(np.array(grades) - np.mean(grades)))]
I've been struggling with this problem for a while now since loops are a bit confusing to me. Essentially, I think I got some of the more difficult stuff (for me at least) out of the way. The issue is that I need the average of 3 students per exam not 6 students per exam, which is what my current code gives.
If what I am asking isn't clear let me know and I will clear it up.
My inputs are n = 3 and m = 2.
def readGrade():
grade = int(input("Enter the grade: "))
while grade > 100 or grade < 0:
print("Invalid Grade")
grade = int(input("Enter the grade: "))
return grade
def examAverage(m):
average = 0
for i in range(n):
readGrade()
average = average + readGrade()
return (average / n)
n = int(input("Enter the number of students: "))
m = int(input("Enter the number of exams: "))
for i in range(m):
print("The average of exam", i + 1, "is:", examAverage(m))
You are calling readGrade() two times within examAverage()
I think this is what examAverage() should be:
def examAverage(m):
average = 0
for i in range(n):
this_grade = readGrade()
average = average + this_grade
return (average / n)
The program is supposed to calculate and print out a given student's average percentage.
Unfortunately I am only able to print out the average percentage of the last student name in the array.
I want to know where exacltly I am going wrong with my coding.
Thanks. Heres my code below.
def averagepercentage():
scores = int(name_marks[1]),int(name_marks[2]),int(name_marks[3])
ap = sum(scores)/3
return ap
N = int(input('Number of students: ')) # total number of students
marks = int()
arr = []
for i in range(N):
name_marks = input('name & marks').split() #enter name & three different scores
name = str(name_marks[0])
arr.append(name)
print(arr)
student_name = str(input('student_name'))
for x in arr:
if student_name in x:
print (x)
print("%.2f" %averagepercentage())
In your first loop:
for i in range(N):
name_marks = input('name & marks').split() #enter name & three different scores
name = str(name_marks[0])
arr.append(name)
print(arr)
you don't store the marks of the previous students, you replace your variable name_marks by the last marks from your input
the if student_name in x: looks if student_name is included in x, which is not exactly what you want to do, consider doing if student_name == x: instead.
Then:
def averagepercentage():
scores = int(name_marks[1]),int(name_marks[2]),int(name_marks[3])
ap = sum(scores)/3
return ap
looks at the global variable name_marks to compute the average, but this variables only contains the value of the last student (because of my first remark)
what you can do, to keep most of your code structure is:
for i in range(N):
name_marks = input('name & marks').split() #enter name & three different scores
name = str(name_marks[0])
arr.append((name,averagepercentage()))
print(arr)
student_name = str(input('student_name'))
for x in arr:
if student_name in x:
print ("student :" + x[0])
print("average :" + x[1])
For my computer science class I have to make a program that will calculate grades.
This is my first computer science class (no prior experience) so I am struggling through it.
These are the directions:
Ask the user for the number of tests, assignments, quizzes, and labs in their course.
Ask the user if there is a final with a separate weight from the tests above, e.g. a course has 2 tests, each weighing 12.5%, and 1 final weighing 15%.
For each category having a number > 0
a. Prompt the user for the weighted percent, out of 100%, which should total
100% for all categories!!!
b. Get the score(s) for the category.
c. If the category is labs, then sum all the scores.
d. Else, average the scores.
e. Calculate the weighted average for the category.
Using the weighted average of each category, calculate the grade in the course.
Ask the user if he/she wants to calculate a grade for another class.
If the user responds yes, then go back to step 1.
Else, end the program.
My code so far:
def main():
lists = get_user_input()
get_scores(lists);
get_weighted_average(lists)
def get_user_input():
# How many?
t = int(input("How many tests?: "))
a = int(input("How many assignments?: "))
q = int(input("How many quizzes?: "))
l = int(input("How many labs?: "))
# How much weight on grade?
tw = float(input("Enter weight of tests: "))
aw = float(input("Enter weight of assignments: "))
qw = float(input("Enter weight of quizzes: "))
lw = float(input("Enter weight of labs: "))
lists = [t, a, q, l, tw, aw, qw, lw]
return lists
def get_scores(lists):
# What are the scores?
scores = [0] * 5
for(x in range(lists[0]):
test_scores = float(input("enter your test scores: "))
scores[x] = test_scores
for(x in range(lists[1]):
test_scores = float(input("enter your assignment scores: "))
scores[x] = assignment_scores
for(x in range(lists[2]):
test_scores = float(input("enter your quiz scores: "))
scores[x] = quiz_scores
for(x in range(lists[3]):
test_scores = float(input("enter your lab scores: "))
scores[x] = lab_scores
sumlabs = 0
for(x in range(lists[3]):
sumlabs = sumlabs + scores[x]
print(sumlabs)
def get_weighted_average(lists):
main()
I am not sure how to proceed so any help is much appreciated.
Averaging a score means adding them up and dividing by the number of them. You can use the fact that a list has a way to tell you how many elements it has. For example if x is a list then len(x) is the number of things in the list. You should be careful about not trying to calculate the score of an empty list, because that would mean dividing by zero. In the following function the 'if score_list:' will be true if there is something in the list. Otherwise it returns None (since the average is not defined).
def average_score(score_list):
if score_list: # makes sure list is not empty
total = 0 # our total starts off as zero
for score in score_list: # starts a loop over each score
total += score # increases the total by the score
return total / len(score_list) # returns aveage
To form a list of scores from user input, presuming the user will put them all on the same line when you prompt them, you can get a string from the user (presumably like: "13.4 12.9 13.2" And then use the string's split method to convert this to a list of strings like ["13.4", "12.9", "13.2"], and then convert this list of strings to a list of floats. Finally using the average function above you can get an average:
test_score_entry = raw_input("Enter your test scores separated by spaces: ")
test_sore_strings = test_score_entry.split()
test_scores = [float(_) for _ in test_score_strings]
average_score = average(test_scores)