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
JavaScript
x
31
31
1
import json
2
3
class Kasa:
4
def __init__(self):
5
6
self._running = True
7
8
while self._running:
9
print(self._running)
10
try:
11
with open('save.json') as json_file:
12
DATA = json.load(json_file)
13
CHOICE = input()
14
self._running = self.handleEvent(CHOICE)
15
except IOError:
16
CHOICE = input()
17
self._running = self.handleEvent(CHOICE)
18
19
20
def handleEvent(self, event):
21
if event == 'C':
22
pass
23
elif event == 'Q':
24
return False
25
else:
26
return True
27
28
29
if __name__ == "__main__":
30
Kasa().__init__()
31
exec output
JavaScript
1
19
19
1
>>>python file.py
2
True
3
4
True
5
6
True
7
8
True
9
10
True
11
Q
12
True
13
14
True
15
16
True
17
Q
18
#script stopped executing here
19
Advertisement
Answer
No need to explicitly call init, calling Kasa() class will automatically call init
JavaScript
1
3
1
if __name__ == "__main__":
2
Kasa()
3
I would rather suggest to write the logic outside init in a seperate method