How do I get data from dictionary in python? - python

a= int(input("Enter number of students:"))
i=1
n = []
t = []
p = []
avg = []
while i<=a:
total=0
name = input("Enter name of student:")
n.append(name)
subjects = int(input("Enter count of subjects:"))
i=i+1
j=1
while j<=subjects:
s = int(input("Enter marks:"))
total = total + s
j=j+1
percentage = (total/(subjects*100))*100
average = total/subjects
t.append(total)
p.append(percentage)
avg.append(avg)
result = dict(zip(n,p))
print("Total marks of", name, "is", total)
print("The students:",n)
print("The total of students:",total)
print("The average of students:",avg)
print("The percentage of students:", percentage)
print("The result of students:", result)
i want to store the data which I get from this code and later on display specific data like if I search for student's name, I'll get his marks and average. how do I do this?

First get the name. Then find the index of that. Now search for the marks, average etc in the arrays. Keep in mind that this will only work when the indices are same for each student data. Imagine that the arrays are stacked on top of each other, the data for each student should be in a straight line(You have done that only here).Oh, and one more thing, they are called arrays, not dictionaries. Dictionaries are initialized with {}(curly brackets).
Here is a sample code:
n=["S1","S2"]
t=[100,70]
avg=[30,20]
#say you want to get the data of S2
i=n.index("S2")
print("Student name: "+str(n[i])+" Student total marks:"+str(t[i])+" Student average: "+str(avg[i]))

Related

Python code that printing an avarage number from the dictionary

I have been working on a code that collecting students name and their score. Then printing their name, their score, their highest score, lowest score, and average score. I have completed to write a code that printing name,score, highest and lowest score.I have not completed average one. I have tried some codes but all of them have not worked so far. could you give me some advice or some code that I can use for the code, please? I visited some website to find some code that I can use for my code.
In the code below I have tried with importing module, but it does not work.
I look forward to hearing some great advice from you guys.
from statistics import median
from math import isnan
from itertools import filterfalse
def ScoreList():
scores = {'name': [], 'score': []}
while True:
name = input("Enter a name or enter 'done' when finished ")
if name == 'done': break
scores['name'] += [name]
score = input('Enter score ')
scores['score'] += [int(score)]
return scores
if __name__ == '__main__':
scores = ScoreList()
print(scores)
maxScore = max(scores['score'])
print("max score is:", maxScore)
minScore = min(scores['score'])
print("min score is:", minScore)
midScore = mid(scores['score'])
print("average score is", midScore)
I have visited some website to find some codes example that I can use for my code and all of them did not work so far.
Currently your dictionary only stores a list of names and a list of scores. This is probably not the best way because there will be multiple scores associated with one name. You could instead use the name as the key in the dictionary, and a list of scores as the value. Define scores = {} in your main function. In the input loop you have to ask, if a name is already present in the dict, if so, append the score, otherwise make a new name entry
name = input("Enter a name or enter 'done' when finished ")
score = int(input('Enter score '))
if name in scores:
scores[name].append(score)
else:
scores[name] = [score]
Now you can ask for min, max and average score of a student by
for student_name in scores:
student_min = min(scores[student_name])
student_max = max(scores[student_name])
student_avg = sum(scores[student_name]) / len(scores[student_name])
print(student_name, student_min, student_max, student_avg)
If your intent is to allow the user to enter one or more scores for one or more students and then calculate the max, min, and average across all students then something like this will work. score_dict uses student name for its keys and one or more scores per student for its values. chain is an easy way to extract those values into a list which makes calculating the results straightforward.
from collections import defaultdict
from itertools import chain
from statistics import mean
def get_score_dict():
scores = defaultdict(list)
while (name := input("Enter a name or enter 'done' when finished: ")) != "done":
score = input("Enter score: ")
scores[name].append(int(score))
return scores
if __name__ == '__main__':
score_dict = get_score_dict()
score_list = list(chain.from_iterable(score_dict.values()))
print(score_list)
print(f"Max score: {max(score_list)}")
print(f"Min score: {min(score_list)}")
print(f"Avg score: {mean(score_list)}")

How to find the average of an array and pin it with its corresponding name with another array

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)))]

print average percentage of a student from an array

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])

I need help finishing a grade calculator program in python

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)

python 3: im a beginner and i need to know what im missing. how do i make it state each childs name individually?

The program will allow the teacher to enter the number of students in her class, and enter the names of each student. Then she will be able to enter the results for one test and find out the percentage scores and a mean average for the class.
This is what I've got so far:
how=int(input("how many students in your class?"))
for i in range (how):
student=str(input("Enter name of student " +str(i+1)+":"))
for n in range (how):
score=int(input("Enter the score of child " +str(n+1)+":"))
outof=int(input("what was the exam out of?"))
print ("The percentage scores are:")
for p in range (how):
print (student,":",(score/outof)*100,"%")
I want it to say each child and each percentage individually. I'd also like to work out the mean of the data.
An example
list_students = []
list_score = []
list_outof = []
how=int(input("how many students in your class?"))
for i in range(how):
student=str(input("Enter name of student " +str(i+1)+":"))
list_students.append(student)
for student in list_students:
score=int(input(" " + student +":"))
list_score.append(score)
outof=int(input("what was the exam out of?"))
list_outof.append(outof)
print("The percentage scores are:")
for index, student in enumerate(list_students):
print (student,":",(list_score[index]/list_outof[index])*100.0,"%")
This is rather simplistic but it should give you enough of a basis to build on for your project.
how = raw_input("how many students in your class?\n")#raw_input() always returns a string
how = int(how)
student_list = []
for student in range(how):
x = raw_input("please input the student's name\n")
y = raw_input("Type the student's score\n")
y = int(y)
student_list.append((x,y))#simple tuple with student's name and score
total =0
for each in student_list:
total+= each[1]
print "The average was " +str(total/float(how))

Categories

Resources