0

What happens is that when I use the functions like sum() Python says me that it doesn't exist. Because it's trying to send a numeric result instead of the formula, as I want. Somebody knows any way to make it work??

def calculator(action, formula):
    print('I need two numberst to {} them'.format(accion))
    a = int( input('Enter the first term'))
    b = int( input('Enter the second term'))

def sum():
    calculator('add', a+b)

def substraccion():
    calculator('substract', a-b)

def multimplication():
    calculator('multiply', a*b)

def division():
    calculator('divide', a/b)

# --- MAIN --- #

sum()
ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57

3 Answers3

1

There is no thing called "formula" in Python. a + b is an expression and it does not do what you think it does.

When encountered, a + b is evaluated by examining types of a and b to determine how to calculate + operation. At that point, both a and b variables must exist and be initialised to something that can be summed.

What you call a "formula" is most similar to a function. So, you can create a function:

def plus(x, y):
    return x + y

This function does what you want, e.g.

>>> plus(5, 6)
11
>>> plus(2, -5)
-3

Now, you can send that function to the calculator:

def calculator(action_name, function):
    print('I need two numbers to {} them'.format(action_name))
    a = int( input('Enter the first term: '))
    b = int( input('Enter the second term: '))
    result = function(a, b)
    print('The result is {}'.format(result))

def sum():
    calculator('add', plus)

BTW, I would not call my function sum, because there is a built-in function named sum, which you hide when you create your own. Choose a different name.

zvone
  • 18,045
  • 3
  • 49
  • 77
0

Have a look here: How to pass an operator to a python function?

You can't just type a+b as parameter and think that python is gonna understand that you want to pass an operator

Cemal K
  • 96
  • 8
0

You could pass a lambda function Ex: Calculator ('add', lambda x,y:x+y)

aivision2020
  • 619
  • 6
  • 14