Skip to content
Advertisement

want to make python function a tv_turn_on_or_Off() to print on for first time then off if called again

make a function named tv_turn_on_or_Off() ,it will take no parameter. if called for the first time it will print tv is on. if called again it will print tv is off. Then,if called again will print tv is on

class abcTv:
    def __init__(self):
        pass
    def tv_turn_on_or_of(self):
        pass





a=abcTv()
a.tv_turn_on_or_of()
a.tv_turn_on_or_of()


#Output
#tv is on
#tv is off

Advertisement

Answer

Just have a simple flag as your instance variable. By each call you should toggle it:

class abcTv:
    def __init__(self):
        self._is_on = False

    def tv_turn_on_or_of(self):
        if not self._is_on:
            print("tv is on")
            self._is_on = True
        else:
            print("tv is off")
            self._is_on = False
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement