Python Program help with IF Else

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ilikepython
    Recognized Expert Contributor
    • Feb 2007
    • 844

    #16
    Originally posted by bartonc
    I also like the tuple (humble beginnings of a true object) to define a "course".
    I do not, however, find any redeeming qualities in this usage:
    Code:
    grades[string.lowercase.index(grade.lower())]
    Sorry, my friend:
    • too many functions squished into one line (there is no advantage in doing so)
    I'm not entirely convinced. I know its messy, but I think it could be made easier:
    [code=python]
    grade_names = ["a", "b", "c", "d", "f"]
    grade_values = [4.0, 3.0, 2.0, 1.0, 0.0]

    ...

    grade = grade.lower()
    if grade not in grade_names:
    print "Invalid Grade"
    else:
    value_index = grade_names.ind ex(grade)
    totalpoints += grade_values[value_index] * credit
    [/code]
    The reason I used it was because it aviods writing the if statements. Also, it might be easier implementing it with classes:
    [code=python]
    grade_names = ["a", "b", "c", "d", "f"]
    grade_values = [4.0, 3.0, 2.0, 1.0, 0.0]

    class Grade:
    value = 0.0
    name = "f"

    def setGrade(self, gr):
    if type(gr) == type(0.0):
    if gr in grade_values:
    self.name = grade_names[grade_values.in dex(gr)]
    self.value = gr

    else:
    print "Bad Grade"

    elif type(gr) == type(''):
    if gr in grade_names:
    self.name = gr
    self.value = grade_values[grade_names.ind ex(gr)]

    else:
    print "Bad Grade"
    else:
    print "Bad grade format"

    def getGrade(self):
    return self.name

    def getValue(self):
    return self.value

    gr = Grade()
    gr.setGrade(use r_input)

    totalpoints += gr.getValue() * credit
    [/code]
    The class might not be the best, but it works as an example. Is this ok to do it like that?

    Comment

    Working...