Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading