簡體   English   中英

python中的表-不確定為什么不起作用

[英]Tables in python- not sure why it isn't working

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。然后,對於第二個學生,分數,總分和百分比將為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|
+----------+----------+----------+----------+----------+

正如於浩在評論中所說,問題在於

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”)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM