Home > Blockchain >  Is there any way to set an elif statement inside the init() function in the class?
Is there any way to set an elif statement inside the init() function in the class?

Time:11-06

I have code which targets to use if-elif-else functions to filter inputs.

So the target is to make a filtering code that filters three integer input to get a value from 0 to 90. The number exceeding 90 should be valued as 90 and negative numbers should be valued as 0. The inputs however, are linked into mother class 'self'.

So I picked the if-elif-else since it was the most preferable choice, but I couldn't find the right way.

Code is

class student_scores(object):
    def __init__(self, name, id, math_score, english_score, science_score):
        self.name = name
        self.id = id
        self.math_score = math_score
        self.english_score = english_score
        self.science_score = science_score
        # We need some codes here to match the conditions.
    def print_scores(self):
        print("%s 's math, english, science score is %d, %d, %d respectively."%(self.name, self.math_score, self.english_score, self.science_score))

student1 = student_scores("Kay", 20141, 50, 110, -10)
student2 = student_scores("Lisa", 20304, 55, 70, 65)
student3 = student_scores("Rin", 29850, 100, 11, 4)
 

And the result should be printed as

Kay's math, english, science score is 50, 90, 0 respectively.
Lisa's math, english, science score is 55, 70, 65 respectively.
Rin's math, english, science score is 90, 11, 4 respectively.

CodePudding user response:

Yes, you can use conditionals fine within a constructor, but you don't need them. You can cap values using min/max functions, for example

    self.math_score = min(max(0, math_score), 90)
    self.english_score = min(max(0, english_score), 90)
    self.science_score = min(max(0, science_score), 90)

If the input is negative, max(0, value) returns 0. If the input is above 90, then min(value, 90) returns 90.

  • Related