Why cant I get my "+" to do actual addition?

Question:

I am about 4 hours into some self teaching of python 3.5 using notepad++ and have hit a road block. The main problem is that where I am stuck is so simple, I cant find a single way to fix it on google! I am trying to make a calculator work, and will show the code I have used to do so. But first…

def add(x, y):
 return x * y
myValue=add(3,3)
print (myValue)

This returns correct results. This case being 6. When I try to use this in my larger calculator string, the result would be 33 instead. It does not add them, it simply prints the numbers side by side.

Complete code:

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


#A calculator that does +,-,*,/
def main():
  operation = input('What may I calculate? (+,-,*,/)')
  if (operation != '+' and operation != '-' and operation != '*' and operation != '/'):
      #invalid operation text
      print('Please try again. Select + for addition, - for subtraction, * for multiplication, / for division')

  else:
      x=input('Enter Number 1:')
      y=input('Enter Number 2:')
      if(operation=='+'):
        print (add(x, y))


main()
Asked By: Mike B

||

Answers:

The problem is that you are passing strings to the function and not ints/floats. The result is that it concatenates the strings. You need to convert the input from string to float (unless you’re comfortable with just int)

else:
    x = float(input('Enter Number 1:'))
    y = float(input('Enter Number 2:'))
Answered By: nbryans
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.