Issue
I'm writing a program for A teacher. The teacher is suppose to ask the name of the student and then the grade of the student. And this for as many that is needed and then once the teacher enters 'q' the program is suppose to print out all the names and grades of the students in one on top of the other order. Here is what I have so far. the problem is Its not printing all the names and grades I'm trying to see how to store the names and grades together in a list of some sort. But I don,t know how.
while True:
students = raw_input("Please give me the name of the student (q to quit): ")
if students == 'q':
break
grade = raw_input("Please give me their grade: ")
print "Okay, printing grades!"
print "Student Grade"
print students, grade
Solution
Use a list of dictionaries. This will allow you to preserve the order in which they were entered.
students_grades = []
while True:
data = {}
data["student_name"] = raw_input("Please give me the name of the student (q to quit): ")
if data["student_name"] == 'q':
break
data["grade"] = raw_input("Please give me their grade: ").capitalize()
students_grades.append(data)
print "Okay, printing grades!"
for data in students_grades:
print "{student_name}: {grade}".format(**data)
The format
method on strings allows you to replace brackets in strings in various ways, one of which allows you to pass in kwargs that replace the corresponding named brackets. The splat operator **
basically takes a dictionary and turns it into function kwargs, so it's the equivalent of passing in .format(student_name="...", grade="...")
in this case.
Answered By - Julien
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.