我是Python初学者。我用python为学生创建了一个数据库。我无法在dict中获得所有迭代的输出
我的源代码:
n = int(raw_input("Please enter number of students:"))
student_data = ['stud_name', 'stud_rollno', 'mark1', 'mark2','mark3','total', 'average'] for i in range(0,n):
stud_name=raw_input('Enter the name of student: ')
print stud_name
stud_rollno=input('Enter the roll number of student: ')
print stud_rollno
mark1=input('Enter the marks in subject 1: ')
print mark1
mark2=input('Enter the marks in subject 2: ')
print mark2
mark3=input('Enter the marks in subject 3: ')
print mark3
total=(mark1+mark2+mark3)
print"Total is: ", total
average=total/3
print "Average is :", average
dict = {'Name': stud_name, 'Rollno':stud_rollno, 'Mark1':mark1, 'Mark2':mark2,'Mark3':mark3, 'Total':total, 'Average':average} print "dict['Name']: ", dict['Name'] print "dict['Rollno']: ", dict['Rollno'] print "dict['Mark1']: ", dict['Mark1'] print "dict['Mark2']: ", dict['Mark2'] print "dict['Mark3']: ", dict['Mark3'] print "dict['Total']: ", dict['Total'] print "dict['Average']: ", dict['Average']
如果我不给任何一个学生2,我得到的dict只为第二个数据库,而不是第一个。
我得到的输出
Please enter number of students:2
Enter the name of student: a
a
Enter the roll number of student:1
1
Enter the marks in subject 1:1
1
Enter the marks in subject 2:1
1
Enter the marks in subject 3:1
1
Total is:3
Average is :1
Enter the name of student:b
b
Enter the roll number of student:2
2
Enter the marks in subject 1:2
2
Enter the marks in subject 2:2
2
Enter the marks in subject 3:2
2
Total is:6
Average is :2
dict['Name']:b
dict['Rollno']:2
dict['Mark1']:2
dict['Mark2']:2
dict['Mark3']:2
dict['Total']:6
dict['Average']:2
当前代码每
i
覆盖dict
。此外,不应该使用名称dict
,因为这会导致与Python中的数据类型dict
混淆。一个解决方案是使用字典列表,如下所示:
通过将每个新学生的回答添加到列表的末尾,我们依次跟踪所有的回答。最后,我们使用字典中存储的
keys
和values
将它们打印出来。这将打印出您的输入:相关问题 更多 >
编程相关推荐