class LunarYear:
def leap_year(self):
for remaining in [1, 5, 9, 13, 17, 22, 26, 30]:
if self % 33 == remaining:
print("leap year confirmed.")
break
else:
print("leap year declined.")
LunarYear.leap_year(self=1395)
我想你的意思是这样的:
class LunarYear:
def leap_year(self):
leap_year_remainders = [1, 5, 9, 13, 17, 22, 26, 30]
return self % 33 in leap_year_remainders # Returns True or False
outputs = {True: 'leap year confirmed', False: 'leap year declined'}
print(outputs[LunarYear.leap_year(self=1395)]) # Output: leap year confirmed
或者遵循你最初的想法:
class LunarYear:
def leap_year(self):
for remaining in [1, 5, 9, 13, 17, 22, 26, 30]:
if self % 33 == remaining:
print("leap year confirmed")
break
else:
print("leap year declined")
LunarYear.leap_year(self=1395) # Output: leap year confirmed
可以将字符串存储在一个变量中,并在最后打印出来。
class LunarYear:
def leap_year(self):
msg = ""
for remaining in [1, 5, 9, 13, 17, 22, 26, 30]:
if self % 33 == remaining:
msg = "leap year confirmed."
break
else:
msg = "leap year declined."
print(msg)
因此它将只打印一次。
它将打印'闰年已拒绝'两次,当条件为真时,当它等于9时,它将打印'闰年已确认'。所以你需要把else语句从for循环
中移出for remaining in [1, 5, 9, 13, 17, 22, 26, 30]:
if self % 33 == remaining:
print("leap year confirmed.")
break
else:
print("leap year declined.")