pythoncalc

trying to make a calculator but my first function(addition) isnt working as intended


This is my first time messing around with functions and I'm trying to make a calculator.

I have made 4 functions - each set for add, subtract, multiply and divide.

I have 2 inputs for x and y and an operations variable for the calculator to take in.

you can see the code I got so far below.

when I enter the two numbers let's say 5 and 5 for now choose "add". it will spit out 55. can anyone enlighten me on why and how I counter this as well as any tips for refining/improving the current code.

any help is appreciated, please be nice :)

def add(x, y):
    print(x+y)
    return
def subtract(x, y):
    print(x-y)
    return
def multiply(x, y):
    print(x*y)
    return
def divide(x, y):
    print(x/y)
    return

x = input("Enter number:")
y = input("Enter number:")
operation = input("Enter operation: ")

if operation == "add":
    add(x,y)

Solution

  • The input you receive from the user is in the form of a string - '5'. When you add two strings together, they simply concatenate - '5' + '5' results in '55.

    If you want the inputs to be converted to numbers, you need to make that conversion explicit using int or float. You can then add them up and have it behave the way you want. Like so:

    x = int(input("Enter number:"))
    y = int(input("Enter number:"))