python中的表 - 不确定它为什么不起作用

时间:2015-08-31 11:37:41

标签: python python-3.x

students = []
scores = []
name = input("Please enter the student's name: ")
while name != "":
    scores.append([0,0,0,0])
    students.append(name)
    test1 = int(input("What was the score of the first test?: "))
    test2 = int(input("What was the score of the second test?: "))
    total = test1 + test2
    percentage = (total / 80) * 100
    scores.append([test1,test2,total,percentage])
    name = input("Please enter the student's name or press enter: ")
print("+----------+----------+----------+----------+----------+")
print("|Name       |Score 1   |Score 2   |Total     |Percent  |")
print("+----------+----------+----------+----------+----------+")
length = len(students)
for count in range(0,length):
    print("|%-10s|%10i|%10i|%10i|%10f|" %(students[count],scores[count][0],scores[count][1],scores[count][2],scores[count][3]))
    print("+----------+----------+----------+----------+----------+")

该代码应该允许用户输入学生及其考试成绩,然后计算总分和百分比。当他们在询问学生姓名时按回车键,应该打印一张表格,上面写着姓名和分数等。

唯一的问题是,当打印出桌子时,它打印出第一个学生的名字,但第一个学生的分数,总数和百分比将为0.然后对于第二个学生,分数,总数和百分比将是实际上第一个学生的。

这是我的代码的结果:

Please enter the student's name: tk
What was the score of the first test?: 33
What was the score of the second test?: 32
Please enter the student's name or press enter: kk
What was the score of the first test?: 34
What was the score of the second test?: 35
Please enter the student's name or press enter: 
+----------+----------+----------+----------+----------+
|Name       |Score 1   |Score 2   |Total     |Percent  |
+----------+----------+----------+----------+----------+
|tk        |         0|         0|         0|  0.000000|
+----------+----------+----------+----------+----------+
|kk        |        33|        32|        65| 81.250000|
+----------+----------+----------+----------+----------+

1 个答案:

答案 0 :(得分:0)

正如余浩在评论中所述,问题就在于

scores.append([0,0,0,0])

在第一个循环开始时向表中添加一行零。如果您要测试两个以上的学生,您会发现每个奇怪的学生都被列为全零:对于您所做的每个“学生”条目,您创建两个“分数”条目 - 一个是“0,0,0, 0“和一个与实际分数。

如果删除该语句,则代码应按预期运行。

顺便说一下 - 第二个循环是内置“zip”的一个很好的例子。 https://docs.python.org/3/library/functions.html#zip

而不是:

for count in range(0,length):
    print("|%-10s|%10i|%10i|%10i|%10f|" %(students[count],scores[count][0],scores[count][1],scores[count][2],scores[count][3]))

尝试:

for student,score in zip(students,scores):
    print("|%-10s|%10i|%10i|%10i|%10f|" %(student,score[0],score[1],score[2],score[3]))

使用zip阅读可能更容易,这使您以后更容易编辑。 (因此更“Pythonic”)