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)}")
Related
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]))
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)))]
This is the output of the code I am trying to write. I have seen this done for C++, but not python with a dictionary. The key here is the dictionary is not optional. I need to use it to fulfill the assignment.
ID Candidate Votes Received % of Total Vote
1 Johnson 5000 55.55
2 Miller 4000 44.44
Total 9000
and the winner is Johnson!
I need to use a dictionary and a loop to create this. However, I am stuck on 3 points.
1.The percent- current code returns the percent before it has the whole total ex: first candidate always has 100%.
2. Declare a winner- code finds the max votes and returns the number value but I need it to return the name.
3. How to format the dictionary values so it lines up under the header. I don't think is possible, but it must be a requirement to use a dictionary for a reason. I am thinking I need to make a copy of the dictionary and format that?
Here is what I have so far:
totalVotes=[]
dct = {}
i = 1
while(True):
name = input('Please enter a name: ')
if name == '':
break
votes = input('Please enter vote total for canidate: ')
totalVotes.append(votes)
totalVotesInt= map(int, totalVotes)
total = sum(totalVotesInt)
dct[i] = {name,votes,int(votes)/total*100}
i += 1
header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print(header)
print("\n".join("{}\t{}".format(key, value) for key, value in dct.items()))
print('Total '+str(total))
print('The Winner of the Election is '+max(totalVotes))
Which returns:
Please enter a name: Smith
Please enter vote total for canidate: 100
Please enter a name: Frieda
Please enter vote total for canidate: 200
Please enter a name: West
Please enter vote total for canidate: 10
Please enter a name:
ID Name Votes % of Total Vote
1 {'Smith', '100', 100.0}
2 {'Frieda', 66.66666666666666, '200'}
3 {3.225806451612903, '10', 'West'}
Total 310
The Winner of the Election is 200
You add the number of each candidates votes at the same time you calculate the percent vote for each candidate. You need to find the total votes first, then divide each candidates votes by the total
You are returning the max of a list of integers. Obviously you aren't going to get a string. You need some way to connect the number votes with the candidate.
Don't bother. You can try to figure out how many tabs you need to get the whole thing lined up, but from experience, it is basically impossible. You could separate them with commas and open it in excel as a csv, or you could just make the user figure out what number goes with what.
The other answer uses data tables, so I will take another, more vanilla and cool approach to getting what you want.
class candidate():
def __init__(self, name, votes):
self.name = name
self.votes = int(votes)
def percentvotes(self, total):
self.percent = self.votes/total
def printself(self, i):
print('{}\t{}\t\t{}\t\t{}'.format(i, self.name, self.votes, self.percent))
def getinput():
inp = input('Please enter your candidates name and votes')
return inp
candidates = []
inp = getinput()
s = 0
while inp != '':
s+=1
candidates.append(candidate(*inp.split(" ")))
inp = getinput()
for c in candidates:
c.percentvotes(s)
candidates.sort(key = lambda x:-x.percent)
print('ID\tname\t\tvotes\t\tpercentage')
for i, c in enumerate(candidates):
c.printself(i+1)
I have added very little changes to your code to make it work:
I have mentioned the changes as comments in the code.
Edit: It's more efficient to use objects for each candidate if you require scaling in the future.
totalVotes=[]
dct = {}
i = 1
while(True):
name = input('Please enter a name: ')
if name == '':
break
votes = input('Please enter vote total for canidate: ')
totalVotes.append(votes)
totalVotesInt= map(int, totalVotes)
total = sum(totalVotesInt)
# I change it to a list so it's much easier to append to it later
dct[i] = list((name,int(votes)))
i += 1
# I calculate the total percent of votes in the end and append to the candidate
maxVal = 0
for i in range(1, len(dct) + 1):
if dct[i][1] > maxVal:
maxInd = i
dct[i].append(int((dct[i][len(dct[i]) - 1]) / total * 100))
header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print(dct)
print(header)
print("\n".join("{}\t{}".format(key, value) for key, value in dct.items()))
print('Total '+str(total))
print('The Winner of the Election is '+ dct[maxInd][0]))
I believe that this is the solution you are looking for. Just change the input statements in case you are using Python 2.x. Using Dataframe, the output will be exactly how you wanted.
import pandas as pd
import numpy as np
df = pd.DataFrame(columns=["Candidate", "Votes Received","Percentage of total votes"])
names=list()
votes=list()
while True:
name = str(input("Enter Name of Candidate."))
if name=='':
break
else:
vote = int(input("Enter the number of votes obtained."))
names.append(name)
votes.append(vote)
s=sum(votes)
xx=(votes.index(max(votes)))
myArray = np.array(votes)
percent = myArray/s*100
for i in range(len(names)):
df1 = pd.DataFrame(data=[[names[i],votes[i],percent[i]]],columns=["Candidate", "Votes Received","Percentage of total votes"])
df = pd.concat([df,df1], axis=0)
df.index = range(len(df.index))
print (df)
print ("Total votes = ",s)
print ("The man who won is ",names[xx])
Im really struggling with this question, can anyone help me write a code for this program? or at least say where am I going wrong? Ive tried a lot but can't seem to get the desired output.
This is the program description: Python 3 program that contains a function that receives three quiz scores and returns the average of these three scores to the main part of the Python program, where the average score is printed.
The code I've been trying:
def quizscores():
quiz1 = int(input("Enter quiz 1 score: "))
quiz2 = int(input("Enter quiz 2 score: "))
quiz3 = int(input("Enter quiz 3 score: "))
average = (quiz1 + quiz2 + quiz3) / 3
print (average)
return "average"
quizscores(quiz1,quiz2,quiz3)
One, you are returning a string, not the variable. Use return average instead of return "average". You also don't need the print() statement in the function... actually print() the function.
If you call a function the way you are doing it, you need to accept parameters and ask for input outside the function to prevent confusion. Use a loop as needed to repeatedly use the function without having to rerun it every time. So the final code would be:
def quiz_average(quiz1, quiz2, quiz3):
average = (quiz1 + quiz2 + quiz3) / 3
return average
quiz1 = int(input("Enter Quiz 1 score: "))
quiz2 = int(input("Enter Quiz 2 score: "))
quiz3 = int(input("Enter Quiz 3 score: "))
print(quiz_average(quiz1, quiz2, quiz3)) #Yes, variables can match the parameters
You are returning a string instead of the value. Try return average instead of return "average".
There are a few problems with your code:
your function has to accept parameters
you have to return the actual variable, not the name of the variable
you should ask those parameters and print the result outside of the function
Try something like this:
def quizscores(score1, score2, score3): # added parameters
average = (score1 + score2 + score3) / 3
return average # removed "quotes"
quiz1 = int(input("Enter quiz 1 score: ")) # moved to outside of function
quiz2 = int(input("Enter quiz 2 score: "))
quiz3 = int(input("Enter quiz 3 score: "))
print(quizscores(quiz1,quiz2,quiz3)) # print the result
An alternative answer to the already posted solutions could be to have the user input all of their test scores (separated by a comma) and then gets added up and divided by three using the sum method and division sign to get the average.
def main():
quizScores()
'''Method creates a scores array with all three scores separated
by a comma and them uses the sum method to add all them up to get
the total and then divides by 3 to get the average.
The statement is printed (to see the average) and also returned
to prevent a NoneType from occurring'''
def quizScores():
scores = map(int, input("Enter your three quiz scores: ").split(","))
answer = sum(scores) / 3
print (answer)
return answer
if __name__ == "__main__":
main()
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))