The program is executing all the functions and I only want it to execute the one that is called in the function_call[operation] dictionary key.
# Define functions for addition, subtraction, division, and multiplication
# Write the equation and its output to a file
def add(num1, num2):
answer = num1 num2
with open("equation.txt", "w") as equation:
return equation.write(f" {num1} {num2} = {answer}")
def subtract(num1, num2):
answer = num1 - num2
with open("equation.txt", "w") as equation:
return equation.write(f" {num1} - {num2} = {answer}")
def multiply(num1, num2):
answer = num1 * num2
with open("equation.txt", "w") as equation:
return equation.write(f" {num1} * {num2} = {answer}")
def divide(num1, num2):
answer = num1/num2
with open("equation.txt", "w") as equation:
return equation.write(f" {num1} / {num2} = {answer}")
# input first number
# input operation
# input second number
num1 = int(input("Please enter a valid first number: "))
operation = input(''' Choose between:
: addition operation
- : subtract operation
* : multiply operation
/ : divide operation
: ''')
num2 = int(input("Please enter a valid second number: "))
# create dictionary with operation input as key and corresponding value as function
# call diction value with operation variable as key to call the desired function or operation to be executed
function_call = {
" " : add(num1, num2),
"-" : subtract(num1, num2),
"*" : multiply(num1, num2),
"/" : divide(num1, num2),
}
print(function_call[operation])
CodePudding user response:
func = function_call[operation]
print(func(num1, num2))
Functions in Python are objects. So you could handle them as objects and interoperate between other objects. All you need is just provide arguments to run it (call
)
CodePudding user response:
The problem is that when you define the function_call
dictionary, you're calling all of the functions and storing the results of those calls in the dictionary:
function_call = {
" " : add(num1, num2),
"-" : subtract(num1, num2),
"*" : multiply(num1, num2),
"/" : divide(num1, num2),
}
Instead, put the functions themselves in the dictionary without calling them yet:
function_call = {
" " : add,
"-" : subtract,
"*" : multiply,
"/" : divide,
}
and then call the appropriate function after you fetch it from the dictionary:
print(function_call[operation](num1, num2))
CodePudding user response:
function_call = {
" " : add(num1, num2),
"-" : subtract(num1, num2),
"*" : multiply(num1, num2),
"/" : divide(num1, num2),
}
Because there are parentheses after the function names, they are called during the definition of the dictionary.
If you don't want that, then don't put the parentheses:
function_call = {
" " : add,
"-" : subtract,
"*" : multiply,
"/" : divide,
}