Skip to content
Advertisement

Why my loop stops executing only if I input false 2 times?

Why does my code execute like this? I want to break loop when user inputs “Q”, but it stops only when I input “Q” 2 times. Sometimes it doesn’t even stop after 2 “Q”s. It’s purely random.

code

import json
    
    class Kasa:
        def __init__(self):
    
            self._running = True
    
            while self._running:
                print(self._running)
                try:
                    with open('save.json') as json_file: 
                        DATA = json.load(json_file)
                        CHOICE = input()
                        self._running = self.handleEvent(CHOICE)
                except IOError:
                    CHOICE = input()
                    self._running = self.handleEvent(CHOICE)
    
    
        def handleEvent(self, event):
            if event == 'C':
                pass
            elif event == 'Q':
                return False
            else:
                return True
                
            
    if __name__ == "__main__":
        Kasa().__init__()

exec output

>>>python file.py
True

True

True

True

True
Q
True

True

True
Q
#script stopped executing here

Advertisement

Answer

No need to explicitly call init, calling Kasa() class will automatically call init

if __name__ == "__main__":
        Kasa()

I would rather suggest to write the logic outside init in a seperate method

Advertisement