I have an assignment
(Find the highest score) Write a program that prompts the user to enter the number
of students and each student’s score, and displays the highest score. Assume that
the input is stored in a file named score.txt, and the program obtains the input from
the file.
However we haven't learned how to store data in a .txt file yet so the teacher told us to just treat it as inputs.
What I have so far:
grade = 0
students = eval(input("enter number of students: "))
for i in range(1, students + 1):
grade = eval(input("enter student score: "))
I understand how to input number of students and store it in to a variable (students).
And I know how to write a loop to repeatedly ask for the input (student score) equal to the number of students
but I don't know how to store each students score separately other than doing it once under the for loop (grade).
students = int(input("enter number of students: "))
highest_grade = 0
for i in range(1, students + 1):
grade = int(input("enter student score: "))
if grade > highest_grade:
highest_grade = grade
print("Highest score is {}".format(highest_grade))
I just run and tested. Its working fine
Well you can also try using dictionary. Store student names as well as their scores. Then check for the highest score. You code:
students=int(input ("Enter no of students: "))
scores={}
hg=0
for i in range(students):
name=input("Enter name of student= ")
score=int(input ("Enter score: "))
scores[name]=score
if score>hg:
hg=score
print("Highest score is ",hg)
Explaination: we'll take input for both name as well as score from user and store it in dictionary. By default, we'll save hg(highest score) as 0. Then while taking user input for score, we'll check whether it greater than hg, if yes, update hg to new score and keep checking it until the loop terminates and finally print it
You do this stuff without dictionary and list, I just suggested dictionary because it can save data in more systematic way showing both name as well as score
Related
The prompt for the problem goes as follows:
Create an interactive student records system.
Prompt the user for a student name.
Then prompt the user for a numeric grade
Repeat this until the user enters 'done' in place of a name.
Then print each student and the average of their grades
I have come up with the following code (I'm a beginner guys, sorry if this is obvious)
# I am creating a dictionary so I can store multiple values that are associated with one name
lst = []
dict = {}
while True:
try:
name = str(input("Please enter student's name."))
grade = int(input("Please enter grade student recieved."))
if (name not in list(dict.keys()) and name != "done"):
lsst = []
lsst.append(grade)
dict[name] = lsst
print(lsst)
continue
elif name in list(dict.keys()):
lsst.append(grade)
print(lsst)
continue
elif name == "done":
break
except ValueError:
print("Try Again")
pass
for i in range(list(dict.keys())):
print(f"{name}: {grade}")
I am trying to print the averages after I type 'done' for the name input, but it just moves on to the next input inquiry. Why is this, and how do I fix it?
There are many mistakes in the code but I will break them down in my corrected version.
names_and_grades = {} # I renamed this variable because there is a built in type called dict in Python.
while True: # Using while True is usually discouraged but in this case, it's hard to avoid that.
try:
name = input("Please enter student's name.") # No need to convert to string as it takes the input as a string by default.
if name == "done": # After you prompted for a name immediately check whether the user entered done. This way, you can break right after that.
break
grade = int(input("Please enter grade student recieved."))
if name not in names_and_grades.keys():
names_and_grades[name] = [grade] # We don't actually need a separate list as the entry in the dictionary will be the list itself (that's why it's put between brackets).
elif name in names_and_grades.keys():
names_and_grades[name].append(grade) # Once the list was declared, you can simply append it.
print(names_and_grades[name]) # No need to repeat this twice in the if-else statements, you can just write it after them. And a very important thing, there is no need to use continue, since you are using if-elfe. When you are using if-else, only one of the blocks will be used, the first block where the condition evaluates as true.
except ValueError:
print("Try Again")
for k in names_and_grades.keys():
print(f"{k}: {names_and_grades[k]}") # This is the simplest way to iterate through a dictionary (if you want to format the entries), by iterating through the keys of the dictionary and with the help of the keys, calling the appropriate values.
I hope this helps, let me know if something is unclear.
#I8ACooky - there are some logic and syntax errors, so I will suggest you to run this and see if you can get some ideas to work out your own later:
from collections import defaultdict
grades = defaultdict(list) # in case for multiple scores for a student
print('Welcome to the simple Scoring program. ')
while True:
try:
name = input("Please enter student's name.")
score = int(input("Please enter grade student recieved: "))
if name == 'done' and score == 0:
break
grades[name].append(score)
except ValueError:
print('Try Again....?')
print(dict(grades))
#------------------------
# average scores leave as an exercise...
Outputs:
Welcome to the simple Scoring program.
Please enter student's name.Adam
Please enter grade student recieved: 100
Please enter student's name.Bob
Please enter grade student recieved: 60
Please enter student's name.Cindy
Please enter grade student recieved: 80
Please enter student's name.Adam
Please enter grade student recieved: 80
Please enter student's name.Bob
Please enter grade student recieved: 100
Please enter student's name.Cindy
Please enter grade student recieved: 90
Please enter student's name.done
Please enter grade student recieved: 0
{'Adam': [100, 80], 'Bob': [60, 100], 'Cindy': [80, 90]}
I have to make this program:
Write a program that allows a teacher to input how many students are in his/ her class, then allow them to enter in a name and mark for each student in the class using a for loop. Please note you do not need to record all of the names for later use, this is beyond the scope of the course * so just ask them each name, have it save the names over top of each other in ONE name variable.
i.e.)
INSIDE OF A LOOP
name = input (“Please enter student name: “)
Calculate the average mark for the entire class – this will require you to use totaling.
Output the class average at the end of the program, and ask if they would like to enter marks for another class. If they say yes, re-loop the program, if no, stop the program there.
So I started writing the program and it looks like this
studentamount = int(input("Please enter how many students are in your class: "))
for count in range():
name = input ("Please enter student name: ")
mark = int(input("Please enter the student's mark"))
I ran into the following problem: how would I allow the set of code under the for loop to loop for each student? I was thinking I could just enter in the studentamount variable as the range but I can't since python does not allow you to enter in a variable as a range.
How would I get the for loop to loop for the amount of students typed in? e.g. if 20 students for student amount was typed in, I would want the for loop to loop 20 times. Your help and knowledge is much appreciated.
Read the user input, convert it to int and pass it as a parameter to range:
studentamount = input("Please enter how many students ...: ") # this is a str
studentamount = int(studentamount) # cast to int ...
for count in range(studentamount): # ... because that's what range expects
# ...
Python does not allow you to enter in a variable as a range.
Python does allow you to enter variables as a range, but they must be numbers. Input () reads input in as string, so you need to cast it.
So, this is correct:
```Python
studentamount = int(input("Please enter how many students are in your class: "))
for count in range(studentamount):
name = input ("Please enter student name: ")
mark = int(input("Please enter the student's mark)
```
P.S a try - except clause would be useful here to catch people entering a non-integer data in [TypeError]
P.S.P.S #schwobaseggl 's example is good too, it is possibly more pythonistic to use the nested function studentamount = int(input("Text") than
studentamount = input("Text")
studentamount = int(studentamount)
You can store each student name and mark in a dictionary or tuple and store each dictionary (or tuple) into a list, see code sample (at the end enter "no" to exit or any other value to re-loop the program):
response = None
while response != 'no':
student_count = int(input('Please enter the number of students: '))
students = []
mark_sum = 0
print('There are {} student(s).'.format(student_count))
for student_index in range(student_count):
student_order = student_index + 1
student_name = input('Please enter the name of student number {}: '.format(student_order))
student_mark = float(input('Please enter the mark of student number {}: '.format(student_order)))
students.append({'name': student_name, 'mark': student_mark})
mark_sum += student_mark
print('The average mark for {} student(s) is: {}'.format(student_count, mark_sum / student_count))
response = input('Do you want to enter marks for another class [yes][no]: ')
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."
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])
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))