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

Question:

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
Asked By: RaFii

||

Answers:

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
Answered By: S.B
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.