def AddStudent():
#Variable to control the loop
again = 'y'
#While loop that gets user input to be added to dictionary
while again.lower() == 'y':
student_key = input("What's the name of the student? ")
#Ask user for number of grades
n = int(input('How many grades do you wish to input? '))
#Empty list where grades will be saved
grades = []
#for loop to add as many grades as user wishes
for i in range(0 ,n):
grade = int(input(f'Grade {i + 1}: '))
grades.append(grade)
#Call StudentGradeBook and send values as parameters
StudentGradeBook(student_key, grades)
again = input('Do you wish to add another student? (y) ')
def StudentGradeBook(name, grade_value):
#Dictionary of the grades
grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}
#Add the key and value to the dict
grade_book[name] = grade_value
print(grade_book)
When I add more than one name and grade list to the dict, it just replaces the third one instead of adding a 4th, 5th, etc.
This is the output:
What's the name of the student? Bill
How many grades do you wish to input? 3
Grade 1: 88
Grade 2: 88
Grade 3: 88
{'Tom': [90, 85, 82], 'Bob': [92, 79, 85], 'Bill': [88, 88, 88]}
Do you wish to add another student? (y) y
What's the name of the student? Thomas
How many grades do you wish to input? 3
Grade 1: 87
Grade 2: 88
Grade 3: 88
{'Tom': [90, 85, 82], 'Bob': [92, 79, 85], 'Thomas': [87, 88, 88]}
Do you wish to add another student? (y) n
I suggest that you save all the inputs in a list, then you pass the list to StudentGradeBook() :
def AddStudent():
# Variable to control the loop
again = 'y'
# Keep track of your inputs
inputs_list = []
# While loop that gets user input to be added to dictionary
while again.lower() == 'y':
student_key = input("What's the name of the student? ")
# Ask user for number of grades
n = int(input('How many grades do you wish to input? '))
# Empty list where grades will be saved
grades = []
# for loop to add as many grades as user wishes
for i in range(0, n):
grade = int(input(f'Grade {i + 1}: '))
grades.append(grade)
# Save the inputs before calling StudentGradeBook
inputs_list.append([student_key, grades])
again = input('Do you wish to add another student? (y) ')
# Call StudentGradeBook and pass the inputs as a list
StudentGradeBook(inputs_list)
def StudentGradeBook(grades):
grade_book = {'Tom': [90, 85, 82], 'Bob': [92, 79, 85]}
grade_book.update(grades)
print(grade_book)
Your StudentGradebook function is always beginning with:
grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}
and since it neither returns the resulting modified dict nor stores it elsewhere, it's always restarting from scratch. If you want to preserve a single student gradebook across calls, I'd recommend making it a class, and reusing an instance of said class to add new student info to, e.g. defining it like so:
class StudentGradeBook:
def __init__(self):
# Initial dictionary on creation
self.grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}
def add_grades(self, name, grades):
# Update with additional data
self.grade_book[name] = list(grades) # Shallow copy to avoid being tied to caller list
# Optionally, if new grades for an existing student should be allowed,
# replace the line above with:
self.grade_book.setdefault(name, []).extend(grades)
# which will concatenate on new grades for the name rather than replacing all grades
and using it like so:
def AddStudent(gradebook=None): # Allow passing in an existing gradebook
if gradebook is None:
gradebook = StudentGradebook() # Make a new one if it one wasn't provided
#Variable to control the loop
again = 'y'
#While loop that gets user input to be added to dictionary
while again.lower() == 'y':
student_key = input("What's the name of the student? ")
#Ask user for number of grades
n = int(input('How many grades do you wish to input? '))
#Empty list where grades will be saved
grades = []
#for loop to add as many grades as user wishes
for i in range(0 ,n):
grade = int(input(f'Grade {i + 1}: '))
grades.append(grade)
#Call StudentGradeBook and send values as parameters
gradebook.add_grades(student_key, grades)
print(gradebook.grade_book) # Print the state so far
again = input('Do you wish to add another student? (y) ')
return gradebook # So caller can use it if they didn't already provide one
Every time you call StudentGradeBook you are redefining grade_book from scratch as
grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}
Just move it outside of both function body and it will work.
def AddStudent():
...
#Dictionary of the grades
grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}
def StudentGradeBook(name, grade_value):
#Add the key and value to the dict
grade_book[name] = grade_value
print(grade_book)
You can also pass grade_book to keyword arguments in function as default value:
def StudentGradeBook(name, grade_value, grade_book={'Tom': [90, 85, 82], 'Bob': [92, 79, 85]}):
Full code:
def AddStudent():
again = 'y'
while again.lower() == 'y':
StudentGradeBook(input("What's the name of the student? "), [int(input(f'Grade {i + 1}: '))
for i in range(int(input('How many grades do you wish to input? ')))])
again = input('Do you wish to add another student? (y) ')
def StudentGradeBook(name, grade_value, grade_book={'Tom': [90, 85, 82], 'Bob': [92, 79, 85]}):
grade_book[name] = grade_value
print(grade_book)
Output:
What's the name of the student? Bill
How many grades do you wish to input? 3
Grade 1: 88
Grade 2: 88
Grade 3: 88
{'Tom': [90, 85, 82], 'Bob': [92, 79, 85], 'Bill': [88, 88, 88]}
Do you wish to add another student? (y) y
What's the name of the student? Thomas
How many grades do you wish to input? 3
Grade 1: 87
Grade 2: 88
Grade 3: 88
{'Tom': [90, 85, 82], 'Bob': [92, 79, 85], 'Bill': [88, 88, 88], 'Thomas': [87, 88, 88]}
Do you wish to add another student? (y) n
Related
I want to make two lists, the first containing three names and the second containing three lists of scores:
name_list = [[name1][name2][name3]]
score_list = [[22,33,35][32,22,34][32,44,50]]
My current code is this:
name = []
name.append(input('input students name: '))
score = []
for i in range(3):
score.append(int(input('input students scores: ')))
I want to save three names and three lists of scores, but it only saves the last input name and values.
Here is the program I am trying to make:
enter image description here
If you want 3 names and 3 sets of scores, you need another for loop:
names = []
scores = []
for _ in range(3):
names.append(input('input students name: '))
scores.append([])
for _ in range(3):
scores[-1].append(int(input('input students score: ')))
print(f"names: {names}")
print(f"scores: {scores}")
input students name: name1
input students score: 22
input students score: 33
input students score: 35
input students name: name2
input students score: 32
input students score: 22
input students score: 34
input students name: name3
input students score: 32
input students score: 44
input students score: 50
names: ['name1', 'name2', 'name3']
scores: [[22, 33, 35], [32, 22, 34], [32, 44, 50]]
Do you mean that every time you run the script, it asks for the score value again? I.e., it doesn't save between sessions?
If so, you could save each var's value inside a text file that's stored in your script's folder.
One way you could go about this is:
def get_vars():
try:
fil = open("var-storage.txt", "r") # open file
fil_content = str(fil.read()) # get the content and save as var
# you could add some string splitting right here to get the
# individual vars from the text file, rather than the entire
# file
fil.close() # close file
return fil_content
except:
return "There was an error and the variable read couldn't be completed."
def store_vars(var1, var2):
try:
with open('var-storage.txt', 'w') as f:
f.write(f"{var1}, {var2}")
return True
except:
return "There was an error and the variable write couldn't be completed."
# ofc, you would run write THEN read, but you get the idea
I designed a python program
After entering the grades of all students,
Minimum to maximum
I hope to rewrite the program as
When if the input value (score variable) is empty (when nothing is entered)
The program execution ends and the result of print is displayed.
My problem is that I don't know how to write judgment grammar?
When if input input (score variable)
The value is a null value, the program execution ends, and the result of print is displayed.
Program execution effect:
When judging the input (score variable), it is a null value
End the program execution and display the result of print
Please enter the student's grade: 89
Please enter the student's grade: 38
Please enter the student's grade: 49
Please enter the student's grade: 77
Please enter the student's grade: 448
Please enter the student's grade: 38
Please enter the student's grade: 39
Please enter the student's grade:
Grades are sorted from smallest to largest: [448 44, 55, 66, 88, 97, 22]
My code
score=int(input("Please enter the student's score:"))
mes = list()
for i in range(1,8):
score=int(input("Please enter the student's score:"))
mes.sort()
mes.append(score)
print("Grades are sorted from smallest to largest", str(mes))
Hope can ask for help, thank you all
I think this is what your are looking for.
score = 0
grades = []
while score != "":
score = input("Please enter the student's score:")
if score != "":
grades.append(score)
grades = sorted(grades)
print(f"Grades are sorted from smallest to largest: {grades}")
I have designed a code which functions as I wish to do, by asking the administrator at my private school the number of students, how many grades to input per each student and lastly the course code for the courses that they are taking.
COLS= int(input("number of students to enter: "))
ROWS= int(input("number of grades per student: "))
def main(COLS,ROWS):
number =[]
for c in range(COLS):
student =(input("enter student Name: "))
number.append(student)
for r in range (ROWS):
course=input("Enter course Code: ")
number.append(course)
grades =(input("Enter grade for module: "))
number.append(grades)
print(number)
main(COLS,ROWS)
An example of the output is:
number of students to enter: 3
number of grades per student: 2
enter student Name: LarryH
Enter course Code: Math202
Enter grade for module: 80
Enter course Code: Sci101
Enter grade for module: 90
enter student Name: JeromeK
Enter course Code: TT101
Enter grade for module: 60
Enter course Code: PSY205
Enter grade for module: 50
enter student Name: CheungL
Enter course Code: PS100
Enter grade for module: 80
Enter course Code: Math300
Enter grade for module: 50
['LarryH', 'Math202', '80', 'Sci101', '90', 'JeromeK', 'TT101', '60', 'PSY205', '50', 'CheungL', 'PS100', '80', 'Math300', '50']
Now the code works except for the last line of my output where the list is given with the students and their respective grades and course code.
I am trying to instead of my output producing that 1d list, produce a 2d list, for example:
[
["Andre", "MA22", 79, "MA300", 88, "CM202", 69],
["Larry", "PS44", 67, "MA555", 80, "ACC200", 67],
...
]
Does anyone have any suggestions as to what I may alter in my code to produce a desired output like that above,
Thank you
Within the first loop, you can create a new temporary array to store the data for that particular student, e.g.:
for c in range(COLS):
studentInfo = [] # Info per-student
student =(input("enter student Name: "))
studentInfo.append(student)
for r in range (ROWS):
course=input("Enter course Code: ")
studentInfo.append(course)
# ...
# ...
number.append(studentInfo)
You could also look into storing student info in dictionaries, rather than lists so that the order is not as important. So instead of:
singleStudentInfo = ["Andre", "MA22", 79, "MA300", 88, "CM202", 69]
You would have:
singleStudentInfo = {"name": "Andre", "MA22": 79, "MA300": 88, "CM202": 69}
So far I have...
def main():
list = [8, 25, 10, 99, 54, 3, 61, 24]
print("Your list is: ",list)
new = input("Please choose a number from the list:")
print("Your numbers index is:", list.index(new))
input("Press enter to close program")
So my issue is that I can't figure out how to take the user input and get the index of the users choice. For example, if the user entered 99, my program will return "Your numbers index is:3"
Please help.
The input function returns a string, while your list contains ints. You need to convert the string to int:
new = int(input("Please choose a number from the list: "))
I double checked the following code. Can you try running it?
def main():
list = [8, 25, 10, 99, 54, 3, 61, 24]
print("Your list is: ", list)
new = int(input("Please choose a number from the list:"))
print("Your numbers index is:", list.index(new))
input("Press enter to close program")
main()
I need a two dimensional list to store information about students and their grades.
When I run my program I just get one list of the numbers but I need separate lists for each student. Can anyone help me?
This is what I've done so far:
COLS= int(input("number of students to enter "))
ROWS= int(input("number of grades per student "))
def main():
number =[]
for c in range(COLS):
student =(input("enter student ID number "))
number.append(student)
for r in range (ROWS):
grades =(input("Enter grade for module: "))
number.append(grades)
print(number)
my result is
number of students to enter 2
number of grades per student 4
enter student ID number 1234
Enter grade for module: 55
Enter grade for module: 66
Enter grade for module: 43
Enter grade for module: 33
enter student ID number 2345
Enter grade for module: 34
Enter grade for module: 56
Enter grade for module: 78
Enter grade for module: 99
['1234', '55', '66', '43', '33', '2345', '34', '56', '78', '99']
>>>
You need to create a new list for each row:
for c in range(COLS):
grades = []
student =(input("enter student ID number "))
number.append(student)
number.append(grades)
for r in range (ROWS):
grade =(input("Enter grade for module: "))
grades.append(grade)
I would use a dictionary indexed by student id:
COLS= int(input("number of students to enter "))
ROWS= int(input("number of grades per student "))
def main():
student_grades = {}
for c in range(COLS):
student =(input("enter student ID number "))
grades = []
for r in range (ROWS):
grade =(input("Enter grade for module: "))
grades.append(grade)
student_grades[student] = grades
As per my comment, an example of doing this with list & dict comprehensions:
cols = int(input("Number of students: "))
rows = int(input("Number of grades per student: "))
grades = {input("Enter student ID number: "):
[input("Enter grade for module: ") for _ in range(rows)]
for _ in range(cols)}
Note this is a dictionary as in Kyle Strand's answer, rather than a list. This suits the data better, and will make working with it later easier.
As another note, a better interface could be achieved by repeating this until the user decides not to enter more students, rather than asking up-front how many students will be entered:
rows = int(input("Number of grades per student: "))
def get_students():
while True:
value = input("Enter student ID number, or nothing to finish: ")
if not vale:
return
else:
yield value
grades = {student: [input("Enter grade for module: ") for _ in range(rows)]
for student in get_students()}
Here this is achieved with a generator, which yields new student numbers obtained from the user until the user enters nothing.
Just build a list before you insert it into the number list:
for c in range(COLS):
student =(input("enter student ID number "))
temp_arr = [student] # make a temporary array for the student id and their grades
for r in range (ROWS):
grades =(input("Enter grade for module: "))
temp.append(grades) # append to the temp array here
# after you are done getting the grades
# insert the entire temp array into the number array
number.append(temp)
Also, this data would probably be stored in a better fashion if you made a class Student, which could have an id and a list of grades.
I think it would better to use a dictionary of lists instead of a two dimensional list -- a list of lists -- because it makes access to data for both input and access later easier and readable. For those same reasons I also changed its name from number in your code to grades in the code below to better reflect what is being put into it.
COLS = int(input("number of students: "))
ROWS = int(input("number of grades per student: "))
grades = {}
def main():
for c in range(COLS):
student = int(input("enter student ID: "))
grades[student] = [] # initialize to empty row of grades
for r in range(ROWS):
grade = int(input("Enter grade for module: "))
grades[student].append(grade)
for student in grades.keys():
print 'student:{}, grades:{}'.format(student, grades[student])
Output after inputting your sample data:
student:2345, grades:[34, 56, 78, 99]
student:1234, grades:[55, 66, 43, 33]