【发布时间】:2017-03-19 20:32:00
【问题描述】:
我要做的是根据用户输入制作一个姓名和成绩列表,然后显示该列表并在表格中组织该列表,最后计算平均成绩。
所以我希望我的脚本提示用户输入姓名和成绩,然后将它们存储在一个列表中。此提示将一直重复,直到用户输入一个空字符串(在提示输入名称时按回车键)。
我在存储列表时遇到问题,输入空字符串时开始打印和计算。
这是我目前得到的:
# Importing Python tabulate package
from tabulate import tabulate
# Defining functions
def getRec():
# Get a record from user input, return an empty of the user entered an empty string as input
name = str(input("Enter a name: "))
if name != "":
score = int(input("Enter the grade of " + name +": "))
return name,score
else:
return None
def addList(List,rec):
# Add a rec into the list
List = tuple(rec)
return List,rec
def putRec(List):
# Print a record in a specific format
print(List)
def printTable(List):
# Print a table with a heading
print(tabulate(List,showindex="always",headers=["Index","Name","Grade"]))
def average(List):
# Computes the average score and return the value
total = List[0][1]
avg = total/len(List)
print("Average Grade: ",avg)
# Main function
List = []
rec = []
while True:
rec = list(getRec())
List = addList(List,rec)
if rec == None:
for index in range(len(List)):
print()
putRec(List)
print()
printTable(List)
print()
average(List)
break
当我尝试启动打印和计算时,出现错误,因为我在第一个函数中返回了“无”。但是如果我返回零,列表就变成了零。我需要帮助来尝试启动我的其他功能,并可能修复我如何根据输入创建列表。
感谢任何帮助。提前致谢。
【问题讨论】:
标签: python python-3.x