我的代碼旨在使用 if-elif-else 函式來過濾輸入。
所以目標是制作一個過濾代碼,過濾三個整數輸入以獲得從0到90的值。超過90的數字應該被賦值為90,負數應該被賦值為0。但是輸入鏈接到母類'自己'。
所以我選擇了 if-elif-else 因為它是最可取的選擇,但我找不到正確的方法。
代碼是
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)
結果應列印為
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.
uj5u.com熱心網友回復:
是的,您可以在建構式中很好地使用條件,但您不需要它們。例如,您可以使用min/max函式限制值
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)
如果輸入為負,則max(0, value)回傳0。如果輸入大于 90,則min(value, 90)回傳90。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/351215.html
上一篇:統計個人獲得排行榜的次數
