1+ class Calculator :
2+ def __init__ (self ):
3+ self .equation_first = ""
4+ self .equation_last = ""
5+ self .equation_type = ""
6+ self .current_part = "first"
7+
8+ def input_button (self , button : str ):
9+ if button .isdigit ():
10+ self .add_digit (button )
11+ elif button in ["+" , "-" , "/" , "x" ]:
12+ self .set_operator (button )
13+ elif button == "=" :
14+ if self .current_part == "last" :
15+ self .solve ()
16+ elif button == "." :
17+ self .add_decimal ()
18+ elif button == "+/-" :
19+ self .flip_sign ()
20+
21+ def add_digit (self , digit ):
22+ if self .current_part == "first" :
23+ self .equation_first += digit
24+ elif self .current_part == "last" :
25+ self .equation_last += digit
26+
27+ def set_operator (self , operator ):
28+ self .equation_type = operator
29+ if self .current_part == "first" :
30+ self .current_part = "last"
31+
32+ def flip_sign (self ):
33+ if self .current_part == "first" :
34+ if self .equation_first .startswith ("-" ):
35+ self .equation_first = self .equation_first .removeprefix ("-" )
36+ else :
37+ self .equation_first = "-" + self .equation_first
38+ elif self .current_part == "last" :
39+ if self .equation_last .startswith ("-" ):
40+ self .equation_last = self .equation_last .removeprefix ("-" )
41+ else :
42+ self .equation_last = "-" + self .equation_last
43+
44+ def add_decimal (self ):
45+ if self .current_part == "first" :
46+ if not "." in self .equation_first :
47+ self .equation_first += "."
48+ if self .current_part == "last" :
49+ if not "." in self .equation_last :
50+ self .equation_last += "."
51+
52+ def solve (self ):
53+ result = float (self .equation_first )
54+
55+ if self .equation_type == "+" :
56+ result += float (self .equation_last )
57+ elif self .equation_type == "-" :
58+ result -= float (self .equation_last )
59+ elif self .equation_type == "/" :
60+ result /= float (self .equation_last )
61+ elif self .equation_type == "x" :
62+ result *= float (self .equation_last )
63+
64+ if result == int (result ):
65+ self .equation_first = str (int (result ))
66+ else :
67+ self .equation_first = str (result )
68+
69+ self .equation_last = ""
70+ self .equation_type = ""
71+ self .current_part = "first"
0 commit comments