Support Forums

Full Version: Calculator Using Object Oriented Programming
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Code:
while True:
    class math():
        def math_add(self, add):
            self.add = add
        def math_sub(self, sub):
            self.sub = sub
        def math_mul(self, mul):
            self.mul = mul
        def math_div(self, div):
            self.div = div
    a=int(raw_input("First Number: "))
    b=int(raw_input("Second Number: "))
    c=raw_input("Operation: ")
    math = math()
    math.math_add(a+b)
    math.math_sub(a-b)
    math.math_mul(a*b)
    math.math_div(a/b)
    if c=='+': print math.add
    elif c=='-': print math.sub
    elif c =='*': print math.mul
    elif c =='/': print math.div
    else: print "Please use +, -, *, or /"

Edit: A simpler way to this may actually be something like this:

Code:
class math():
    def math_add(self,a,b):
        self.add = a + b    
math = math()
math.math_add(1,2)
print math.add
That cant be efficent lol
This may help you a bit, I threw it together real quick

Code:
#!/usr/bin/env python

class Calculations( object ):
    def Addition( self, Numbers ):
        return sum( Numbers )
    def Subtract( self, Numbers ):
        Total = Numbers[ 0 ]
        for Index, Num in enumerate( Numbers ):
            try: Total -= Numbers[ Index + 1 ]
            except IndexError: return Total
    def Multiply( self, Numbers ):
        Total = 1.0
        for Num in Numbers: Total *= Num
        return Total
    def Divide( self, Numbers ):
        Total = Numbers[ 0 ]
        for Index, Num in enumerate( Numbers ):
            try: Total /= Numbers[ Index + 1 ]
            except IndexError: return Total
Numbers, Counter, Answer = [], 0, True
while Answer:
    Counter += 1
    try:
        Answer = int( raw_input( "Number %i: " % ( Counter ) ) )
        Numbers.append( Answer )
    except ValueError: Answer = False
if len( Numbers ) < 2: print "Error: You need atleast two numbers..."
else:
    Methods, Method = ["add", "subtract", "divide", "multiply"], False
    while not Method in Methods: Method = raw_input( "Add/Subtract/Divide/Multiply? : ").lower()
    Math = Calculations( )
    if Method == Methods[ 0 ]: print Math.Addition( Numbers )
    if Method == Methods[ 1 ]: print Math.Subtract( Numbers )
    if Method == Methods[ 2 ]: print Math.Divide( Numbers )
    if Method == Methods[ 3 ]: print Math.Multiply( Numbers )