working out the mean from a csvfile already containing names - python

import operator
import csv
question= input("Are you a student or teacher: ")
if question=="student" or "s" or "Student":
print("You are using the wrong program. Please use the arithmetic quiz")
elif question=="teacher" or "t" or "Teacher":
print("Hello and welcome to the program which lets you see your students' scores in the arithmetic quizes")
form=input("What form do you want to view the results of? 1,2 or 3?")
if form=="1":
print("if you want the data sorted by names in alphabetical order")
print("enter 1, if you want the data sorted by scores highest to")
print("lowest enter 2, if you want the data sorted by average score")
teachermenu=input("highest to lowest enter 3:")
if teachermenu=="1":
start=csv.reader(open("form1.csv"), delimiter=";")
datasorted= sorted(start, key=operator.itemgetter(0))
data= open("form1.csv","r")
for eachline in datasorted:
eachline.sort()
print(eachline)
data.close()
elif teachermenu=="2":
data= open("form1.csv")
start=csv.reader(data)
for line in start:
scores = (line[1:5])
scores.sort(reverse = True)
print(scores)
elif teachermenu=="3":
studentsaverages=[]
data= open("form1.csv")
start=csv.reader(data)
for line in data:
numbers=(line[2:4])
numbers=list(map(int, numbers))
mean= round(sum(numbers)/len(numbers))
data.append(mean)
data.sort(reverse=True)
print(studentsaverages)
in this code the working out of the mean doesnt work and i dont know why
i have tried several times
but it doesnt seem to work
also the other parts of the code work
but the working out of the mean doesnt
e.g. putting it highest to lowest works
and so does putting the names in alphabetical order

If I understand correct what you are trying to do, you need to append and then sort the mean to the studentsaverages variable(after the for loop) instead of data.
for example:
elif teachermenu=="3":
studentsaverages=[]
data = open("form1.csv")
start=csv.reader(data)
for line in data:
numbers=(line[2:4])
numbers=list(map(int, numbers))
mean = round(sum(numbers)/len(numbers))
studentsaverages.append(mean)
studentsaverages.sort(reverse=True)
print(studentsaverages)

Related

How do I add numbers I've iterated into a list to a string?

I've got a tiny project I'm working on: I'm trying to make a "grading" program that lets you enter the number of exams, the scores for each exam, and then prints the results.
What I'm looking to do:
Enter the number of tests:
use that number with the string "Exam #: " to number each test.
I've gotten as far as sticking the input from "Enter the number of tests:" into a list..(looks like [0,1,2,3,4.. etc] now I'm trying to combine each of those list numbers with the above string and nothing I'm trying is working.. suggestions?
This is what I came up with, and its output:
test1 = int(input('How many tests are there? '))
test2 = []
for number in range(test1):
test2.append(number)
for number2 in test2:
print('Exam #:' + str(number2))
(inputting "5" here)
Exam #:0
Exam #:1
Exam #:2
Exam #:3
Exam #:4
exactly what I needed!
Try something link this
num_exams = int(input('Enter the number of exams: '))
exam_scores = [int(input(f'Enter score for exam #{n+1}: ')) for n in range(num_exams)]
print(f'Average score: {sum(exam_scores) / num_exams:0.2f}')
Seems like you'd want to collect inputs for the number of tests and then all the test scores. Then to print the test scores you could do something like
for test in range(numTests):
print('Exam #' + (test+1) + ': ' + testScores[test])
The (test+1) is so that you could have the same variable manage the test number as well as the index in the test array. For example, it could print
Exam #1: 82
Exam #2: 93
Exam #3: 87
Not sure if this is needed for your program, but you can iterate through all your values in a list with a for loop. This allows you you to access each value and perform some set of commands on that value. So in this example, we will access each value and then print it. Print can take multiple arguments. It will print out each argument with a space in between.
for examNumber in myList:
print ('Exam', examNumber)

Why will no more code run after using a while loop?

I am new to Python.
I am creating a GPA calculator. The first part is taking a student number and checking if it is valid. It is valid if the sum of the numbers are divisible by seven (that part works).
If the number is valid, then the user must enter their letter grades for all their classes. The code must keep accepting input until a blank line is submitted. I am using a while loop for this part.
But once all their grades are submitted, and they enter a blank line, I need to take the raw input and use it to calculate their GPA. My problem is that no other code seems to run after the while loop ends. I want to run a for loop to check the input and translate them into GPA scores, but no matter where I put it/what I put in it, the code will just end after the input is submitted.
Here is what I've done:
student_number=raw_input("What is your 5-digit student number?")
added_digits=sum(int(x) for x in student_number)
div_7=added_digits%7
if div_7==0 and len(str(student_number))==5:
print "Your student number is valid."
grades=raw_input("To find out your average GPA, please list your letter
grades for each class.\n")
while grades!="":
grades=raw_input()
grade_value=0
for x in grades:
if x=="A":
grade_value+=4.0
print grade_value
if x=="B":
grade_value+=3.0
print grade_value
else:
print "That is not a valid student number."`enter code here`
No matter what input I put in, the for loop after the while loop never seems to run. I can't seem to make the code do anything else after the while loop.
Thanks!
Your while-loop ensures that grades ends up empty (it throws anything non-empty away), and your for-loop then goes over that empty grades. So of course it has nothing to do.
the problem is that your for-loop use grades while grades is not a list, in my opinion, you should use one more list to store you grades:
student_number=raw_input("What is your 5-digit student number?")
added_digits=sum(int(x) for x in student_number)
div_7=added_digits%7
if div_7==0 and len(str(student_number))==5:
print "Your student number is valid."
grades=raw_input("To find out your average GPA, please list your letter grades for each class.\n")
grade_list = [grades] #use a list to store your grades
while grades!="":
grades=raw_input()
grade_list.append(grades) #store every input in grade_list
grade_value=0
for x in grade_list: #use grade_list, not grades
if x=="A":
grade_value+=4.0
print grade_value
if x=="B":
grade_value+=3.0
print grade_value
else:
print "That is not a valid student number."
raw_input will take the grades as input by itself. You don't need to take them again using a loop.
So, this is one way to do what you're trying to do.
student_number=raw_input("What is your 5-digit student number?")
added_digits=sum(int(x) for x in student_number)
div_7=added_digits%7
if div_7==0 and len(str(student_number))==5:
print "Your student number is valid."
grades=raw_input("To find out your average GPA, please list your letter grades for each class.\n")
#while grades!="":
#grades=raw_input()
grade_value=0
for x in grades:
if x=="A":
grade_value+=4.0
print grade_value
if x=="B":
grade_value+=3.0
print grade_value
else:
print "That is not a valid student number."

Prompt to enter a name and then output the name that was entered along a score

I am writing a program for my intro CS class but I am a little stuck.
I have a designated list of names that correspond to a list of scores.
I am supposed to prompt the user to enter a name and then the program is supposed to output the name that was entered along with the corresponding score.
As I have it written now the program is printing the first name and score in the set regardless of the input. I have been stuck on this for a while, any help would be greatly appreciated!
Here is what I have right now:
names=['Jim','Sarah','Jason','Lynne','Ginny','Joe','Susan'];
scores=['88','92','95','84','85','92','89'];
input("Please enter student's name:")
for i in range (0,7):
print (input(names[i] + scores[i]));
the program is supposed to output the name that was entered
That'll be hard considering you aren't capturing the input() return value.
Try this (as an example)
name = input("Please enter student's name:")
print(name)
Then, you next task is to check (in your loop) when name == <a name in the list>
Hint: You can use these for your loop rather than range(0,7)
for student in names:
or, even better, see zip lists in python
for (student, score) in zip(names, scores):
Using the zip function, you can combine the two lists together in an easy to use 1-to-1 group of tuples.
names=['Jim','Sarah','Jason','Lynne','Ginny','Joe','Susan']
scores=['88','92','95','84','85','92','89']
data = zip(names, scores) # <- ('Jim', '88'), ('Sarah', '92'), ...
stud = input('Enter the student's name: ')
for (student, score) in data:
if (stud == student):
print('{} -> {}'.format(student, score))
Better to use Python dictionaries for that:
student_scores = {'Jim': 88, 'Sarah': 92, 'Jason': 95}
and so on...
Then you can call for each of them like so;
name = input("Please enter student's name: ")
print(name + 'has a score of ' + student_scores[name])

Rearranging a file

I have a piece of code (seen below) which enables me to be able to ask pupils a series of random questions and then save their name and scores to a file. I combined the name and score into a single variable called info, with the name coming first then the score. I now need to sort this information in order of score. Is there a way for me to make the score go in front of the name temporarily in the entire file so that I can use the sorted function to get it to go from lowest to highest?
Any help would be greatly appreciated!!! Thank you.
import random
import time
Name=input("What is your name?")
Class=input("Are you in Class A, B or C?")
print("Welcome" ,Name, "to the Maths Quiz!!")
time.sleep(3)
QuestionNumber=0
Operations=["+","-","x"]
answer=0
score=0
while QuestionNumber < 10:
Num1=random.randint(1,12)
Num2=random.randint(1,12)
QuestionNumber=QuestionNumber+1
operation = random.choice(Operations)
print("What is", Num1 ,operation, Num2)
guess=int(input("What is the answer to this question?"))
if operation =="+":
answer=Num1+Num2
elif operation =="-":
answer=Num1-Num2
elif operation =="x":
answer=Num1*Num2
if guess==answer:
score=score+1
print ("Correct")
else:
print("Incorrect")
print("Well done You got", score, "Out of 10!!")
score=str((score))
Info= (Name + (" ") + score)
if Class=="A":
ClassA=open("Class A Results.txt","a")
ClassA.write(Info)
ClassA.write(" \n")
ClassA.close()
elif Class=="B":
ClassB=open("Class B Results.txt","a")
ClassB.write(Info)
ClassB.write(" \n")
ClassB.close()
elif Class=="C":
ClassC=open("Class C Results.txt","a")
ClassC.write(" \n")
ClassC.write(Info)
ClassC.close()
Viewscores=input("Do you want to see previous scores? Y/N")
if Viewscores=="Y":
Classresults=input("Which Class would you like to see the results of?")
else:
print ("Thank you for using the maths quiz, press enter to close the program in 10 seconds")
time.sleep(10)
closeprogram=input("Hit enter")
if Classresults=="A":
ClassA=open("Class A Results.txt","r")
Class=Class
alphabet=ClassA.readlines()
for line in sorted(alphabet):
print(line)
elif Classresults=="B":
ClassB=open("Class B Results.txt","r")
Class=ClassB
alphabet=ClassB.readlines()
for line in sorted(alphabet):
print(line)
elif Classresults=="C":
ClassC=open("Class C Results.txt","r")
Class=ClassC
alphabet=ClassC.readlines()
for line in sorted(alphabet):
print(line)
else:
print ("That is not valid")
sorted's key function can do this for you, but it's much nicer if you haven't combined them into a single string, but store tuples of the pairs instead. Using operator.itemgetter generalizes nicely. Instead of storing:
score = str(score)
Info = Name + " " + score
store:
Info = (Name, score) # Score remains a float
Then when you need to sort, do:
# Imports at top of file, not each sort
from operator import itemgetter
...
for name, score in sorted(myunorderedinfo, key=itemgetter(1, 0)):
In the code you provided, you're writing to a file and reading back (which would require reparsing), so you may want to look at the csv module to store the pairs with proper formatting (simple space separation is easy to mess up); you'd have to convert the inputs back to float in that case though, since csv.reader passes back lists of str, but that's relatively easy to do with a simple generator expression (left as an exercise).
As an aside, you could make your code much neater by removing all that duplicated code:
VALID_CLASS_NAMES = {"A", "B", "C"}
if Classresults not in VALID_CLASS_NAMES:
print("Invalid class results selection")
raise Exception("BOOM")
filename = "Class {} Results.txt".format(Classresults)
with open(filename, "r") as class_results_file:
alphabet=class_results_file.readlines()
for line in sorted(alphabet):
print(line)
Now if you ever add class "D" then you just need to add it to the set of valid class names.

Making a statistics program

I am trying to write a Python program that computes and prints the following :
the average score from a list of scores
the highest score from a list of scores
the name of the student who got the highest score.
The program starts by asking the user to enter the number of cases. For EACH case, the program should ask the user to enter the number of students. For each student the program asks the user to enter the student's name and marks. For EACH case the program reports the average marks, the highest marks and the name of the student who got the highest marks.
Also
If there are more than one person with the highest score in a CASE, the program should report the first occurrence only.
The average score and the highest score should have exactly 2 decimal places.
The output should be as in the sample program output.
What I have been trying so far is the following:
grade=[]
name_list=[]
cases=int(input('Enter number of cases: '))
for case in range(1,cases+1):
print('case',case)
number=int(input('Enter number of students: '))
for number in range (1,number+1):
name=str(input('Enter name of student: '))
name_list.append(name)
mark=float(input('Enter mark of student:'))
grade.append(mark)
highest= max (grade)
average=(sum(grade)/number)
high_name=grade.index(max(grade))
print('average',average)
print('Highest',highest)
print (high_name)
This is what i have deciphered so far. my biggest problem now is getting the name of the individual with the high score. Any thoughts and feedback is much appreciated. As with respect to the answer posted below, i am afraid the only thing i do not understand is the dictionary function but otherwise the rest does make sense to me.
This resembles an assignment, it is too specific on details.
Anyways, the official docs are a great place to get started learning Python.
They are quite legible and there's a whole bunch of helpful information, e.g.
range(start, end): If the start argument is omitted, it defaults to0
The section about lists should give you a head start.
numcases = int(input("How many cases are there? "))
cases = list()
for _ in range(numcases):
# the _ is used to signify we don't care about the number we're on
# and range(3) == [0,1,2] so we'll get the same number of items we put in
case = dict() # instantiate a dict
for _ in range(int(input("How many students in this case? "))):
# same as we did before, but skipping one step
name = input("Student name: ")
score = input("Student score: ")
case[name] = score # tie the score to the name
# at this point in execution, all data for this case should be
# saved as keys in the dictionary `case`, so...
cases.append(case) # we tack that into our list of cases!
# once we get here, we've done that for EVERY case, so now `cases` is
# a list of every case we have.
for case in cases:
max_score = 0
max_score_student = None # we WILL need this later
total_score = 0 # we don't actually need this, but it's easier to explain
num_entries = 0 # we don't actually need this, but it's easier to explain
for student in case:
score = case[student]
if score > max_score:
max_score = score
max_score_student = student
total_score += score
num_entries += 1
# again, we don't need these, but it helps to demonstrate!!
# when we leave this for loop, we'll know the max score and its student
# we'll also have the total saved in `total_score` and the length in `num_entries`
# so now we need to do.....
average = total_score/max_entries
# then to print we use string formatting
print("The highest score was {max_score} recorded by {max_score_student}".format(
max_score=max_score, max_score_student=max_score_student))
print("The average score is: {average}".format(average=average))

Categories

Resources