【问题标题】:Display the courses whose value is not 0.0显示值不为 0.0 的课程
【发布时间】:2017-12-18 22:28:39
【问题描述】:

我使用获取学生姓名、学号、学生课程及其成绩的类制作了这个 python 脚本。

#!/usr/bin/env python3

class Student:
    def __init__(self, name, number):
        self.name = name
        self.number = number
        self.courses = {}

    def displayStudent(self):
        return 'Student Name: ' + self.name + '\n' + 'Student Number: ' + str(self.number)

    def addGrade(self, course, grade):
        self.courses[course] = grade

    def displayGPA(self):
        if len(self.courses) == 0:
            errormsg  = print('oops')
            return errormsg

        else:
            gpa = 0.0
            for course in self.courses.keys():
                gpa = gpa + self.courses[course]
            return 'GPA of student ' + self.name + ' is ' + str(gpa / len(self.courses))


    def displayCourses(self):
        return list(self.courses.keys())


if __name__ == '__main__':
    # Create first student object and add grades for each class
    student1 = Student('John', '013454900')
    student1.addGrade('uli101', 1.0)
    student1.addGrade('ops235', 2.0)
    student1.addGrade('ops435', 3.0)

    # Create second student object and add grades for each class
    student2 = Student('Jessica', '123456')
    student2.addGrade('ipc144', 4.0)
    student2.addGrade('cpp244', 3.5)
    student2.addGrade('cpp344', 0.0)

    # Display information for student1 object
    print(student1.displayStudent())
    print(student1.displayGPA())
    print(student1.displayCourses())

    # Display information for student2 object
    print(student2.displayStudent())
    print(student2.displayGPA())
    print(student2.displayCourses())

执行后,成功显示如下输出:

Student Name: John
Student Number: 013454900
GPA of student John is 2.0
['ops235', 'ops435', 'uli101']
Student Name: Jessica
Student Number: 123456
GPA of student Jessica is 2.5
['ipc144', 'cpp344', 'cpp244']

我的问题是,在displayCourses(self):函数下,我只想显示GPA不是0.0的课程。像这样...没有课程cpp344

python3 lab6a.py
Student Name: John
Student Number: 013454900
GPA of student John is 2.0
['ops435', 'ops235', 'uli101']
Student Name: Jessica
Student Number: 123456
GPA of student Jessica is 2.5
['cpp244', 'ipc144']

【问题讨论】:

  • 如果你理解你刚刚发布的代码,你可以在displayCourses函数中返回之前检查每个键的值

标签: python python-3.x


【解决方案1】:

您应该更新您的displayCourses() 方法。像

return [k for k in self.courses.keys() if self.courses[k] > 0]

这会检查每个课程的self.courses[k] 的值,并且仅当该键的值大于零时才将课程包含在返回的列表中。

【讨论】:

    猜你喜欢
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 2016-10-20
    • 2013-10-03
    • 1970-01-01
    相关资源
    最近更新 更多