0

I am currently taking a course to learn Python and I am currently stuck. The task I am trying to accomplish is to be able to have the user input 2 numbers and an operator and to have the program make the appropriate calculation. for example:

if the user inputs: "2,3,+" the output should be: 5

Instead, I am getting the output of: "['2', '3', '+']

Here is the code that I am currently using:

def Add(num1, num2):
    return num1 + num2

def Subtract(num1, num2):
    return num1 - num2

def Multiply(num1, num2):
    return num1 * num2

def Divide(num1, num2):
    try:
        return num1 / num2
    except ZeroDivisionError:
        print("Sorry, A number can't be divided by 0")
      
def scalc(p1):
    astring = p1.split(",")
    print(astring)
    num1 = float(astring[0])
    num2 = float(astring[1])
    if astring[2] == "+":
        Add(num1, num2)
    elif astring[2] == "-":
        Subtract(num1, num2)
    elif astring[2] == "*":
        Multiply(num1, num2)
    elif astring[2] == "/":
        Divide(num1, num2) 
p1 = input("Enter two numbers and an operator with each separated by a comma: ")
scalc(p1)       

I am very new to programming and taking this course online has been challenging since I cant have an instructor present to look over my shoulder as I am trying to work through a problem. This is also my first time posting on this website so I hope I got the formatting correct and that this isn't too difficult to read. Any help here would be greatly appreciated.

  • Try `return Add(num1, num2)` `return Subtract(num1, num2)` etc. You just need `scalc` to return what you want =) – ssp Jan 15 '21 at 18:07
  • Does this answer your question? [Evaluating a mathematical expression in a string](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) – Chris_Rands Jan 15 '21 at 18:36

2 Answers2

0

Your code works perfectly. You've received your results after calling the functions but have never printed them.

if astring[2] == "+":
    print(Add(num1, num2))
elif astring[2] == "-":
    print(Subtract(num1, num2))

You could also return those values, and print(scale(p1)).

Ori David
  • 332
  • 3
  • 13
0

I tried doing this:

def scalc(p1):
    astring = p1.split(",")
    print(astring)
    num1 = float(astring[0])
    num2 = float(astring[1])
    if astring[2] == "+":
        return Add(num1, num2)
    elif astring[2] == "-":
        return Subtract(num1, num2)
    elif astring[2] == "*":
        return Multiply(num1, num2)
    elif astring[2] == "/":
        return Divide(num1, num2)
    
p1 = input("Enter two numbers and an operator with each separated by a comma: ")
scalc(p1)

but the result is still the same, where the output is a list instead of the desired function being run.