Home > Mobile >  my code do my print statement for many times ,I want to do it just for one time
my code do my print statement for many times ,I want to do it just for one time

Time:06-19

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)

CodePudding user response:

I think you mean something like this:

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

Or following your original idea:

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

CodePudding user response:

You can store the str in a variable and print it in the end.

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)

Thus it will print only once.

CodePudding user response:

it will print 'leap year declined' twice and when the condition is true when it's equal to 9 it will print 'leap year confirmed.' so you need to move else statement out from for loop

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