Simple Python Calculator


#1



I am attempting to program a simple Python calculator for experience. However, I am having a syntax issue with the elif statement and an error with the operations (for example, 12 + 13 gives me 1213).


def add(a,b):
    return a + b
    
def subtract(a,b):
    return a - b
    
def multiply(a,b):
    return a * b

def divide(a,b):
    return a/b

print "Enter 1 for addition"
print "Enter 2 for subtraction"
print "Enter 3 for multiplication"
print "Enter 4 for division"

operation = raw_input()

num1 = raw_input("Enter first number")
num2 = raw_input("Enter second number")

if operation == "1":
    print num1 + "+" + num2 + "=" + add(num1,num2)

    elif operation == "2":
        print num1 + "-" + num2 + "=" + subtract(num1,num2)
    
    elif operation == "3":
        print (num1) + "*" + (num2) + "=" + (multiply(num1,num2)
    
    elif operation == "4":
        print num1 + "/" + num2 + "=" + divide(num1,num2)


#2

A little prompting goes a long way.

The indentation on your if..elif statement looks a little off.

Remember that raw_input() returns a string. To do math, convert to a float.


#3

Thanks for the response!

I edited the formatting, but there still seems to be an issue:

def add(a,b):
    return a + b
    
def subtract(a,b):
    return a - b
    
def multiply(a,b):
    return a * b

def divide(a,b):
    return a/b

print "Enter 1 for addition"
print "Enter 2 for subtraction"
print "Enter 3 for multiplication"
print "Enter 4 for division"

operation = raw_input()

num1 = raw_input("Enter first number")
num2 = raw_input("Enter second number")

if operation == "1":
    print num1 + "+" + num2 + "=" + add(num1,num2)

elif operation == "2":
    print num1 + "-" + num2 + "=" + subtract(num1,num2)
    
elif operation == "3":
    print (num1) + "*" + (num2) + "=" + (multiply(num1,num2)
    
elif operation == "4":
    print num1 + "/" + num2 + "=" + divide(num1,num2)

Also, I know the str() function, but I'm not sure how to convert a string to an integer. I would appreciate it if you could edit my code.

Thanks!


#4

We convert using the built in function, int(), or in this case I would recommend float() so your math works as expected.

num1 = float(raw_input("Enter first number"))

When dividing we need to consider division by zero.

def divide(a,b):
    try:
        return a / b
    except ZeroDivisionError:
        return "Division by zero error"

Eg.

>>> def divide(a,b):
    try:
        return a / b
    except ZeroDivisionError:
        return "Division by zero error"

>>> divide(12, 0)
'Division by zero error'
>>>

#5

I had tried to use the int() function, but division results left out decimals. float() works perfectly. Thanks!


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.