我的代码多次执行我的print语句,我只想执行一次


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.")

相关内容

  • 没有找到相关文章

最新更新