我正在尝试创建一个考勤记录器,我在其中创建一个字典,我填写学生姓名。名称将是我附加课堂出勤数据的列表(无论他们是否上课)。我到目前为止的代码显示在下面`
#! /bin/python3
#add student to dict
def add_student(_dict):
student=input('Add student :')
_dict[student]=[]
return _dict
#collect outcomes
def collector(student,_dict, outcome):
_dict[student].append(outcome)
return _dict
#counts target
def count(_dict,target):
for i in _dict:
# records total attendance names
attendance_stat = len(_dict[i])
# records total instances absent
freq_of_absence=_dict[i].count(target)
# records percentage of absence
perc_absence = float((freq_of_absence/attendance_stat)*100)
print(i,'DAYS ABSENT =',freq_of_absence)
print('TOTAL DAYS: ', i, attendance_stat)
print('PERCENTAGE OF ABSENCE:', i, str(round(perc_absence, 2))+'%')
#main function
def main():
#date=input('DATE: ')
outcomes=['Y','N']
student_names = {}
try:
totalstudents = int(input('NO. OF STUDENTS: '))
except ValueError:
print('input an integer')
totalstudents = int(input('NO. OF STUDENTS: '))
while len(student_names) < totalstudents:
add_student(student_names)
print(student_names)
i = 0
while i < totalstudents:
i = i + 1
target='Y'
student=str(input('student :'))
outcome=str(input('outcome :'))
collector(student,student_names,outcome)
count(student_names,target)
if __name__=='__main__':
main()
` 到目前为止,该代码运作良好,但问题是当学生人数过多时,投入的时间在课堂上大量减少。由于缺席者的数量通常少于存在的数量,因此可以从词典中选择缺席的学生,其将为每个所选择的缺席附加值Y,同时将N附加到词典中的剩余列表。
答案 0 :(得分:0)
这并不是你要求的,但我认为这会有所帮助。而不是要求用户每次为第二部分输入名称,为什么不自己打印名称,只询问结果?您的上一个while
循环将成为for循环,如下所示:
for student_name in student_names:
outcome = input("Outcome for {}: ".format(sudent_name))
collector(student_name, student_names, outcome)
您还可以添加一些逻辑来检查结果是否为空字符串,如果是,请将其设置为“N&#39; N”。这只是允许你点击大多数名字的输入,只需输入&#39; Y&#39;对于某些缺席的人。这看起来像这样:
for student_name in student_names:
outcome = input("Outcome for {}: ".format(sudent_name))
if outcome = "":
outcome = "N"
collector(student_name, student_names, outcome)