(Nov-08-2019, 06:36 AM)ndc85430 Wrote: Do you understand that the values in the dictionary are functions?actually in the current implementation they call/execute all functions in the dict at the time when it is defined i.e. at the moment it's a dict of calculated results using global variables, not functions. And that is bad
Also functions should take operands as arguments (like in OP original code), not use global variables.
def add (a, b): return a + b def substract(a, b): return a - b math_functions = {'1':add, '2':substract} user_func = input('What math operation (1 for add, 2 for substract): ') num1 = int(input('Enter first integer number: ')) num2 = int(input('Enter second integer number: ')) print(math_functions[user_func](num1, num2))
Output:What math operation (1 for add, 2 for substract): 1
Enter first integer number: 10
Enter second integer number: 3
13
the code is bare-bone, i.e. no checks for invalid input, etc. Also as ndc85430 wrote - one can use operator module from standard libraryAlso check our tutorial: https://python-forum.io/Thread-if-struct...dictionary
it's a perfect fit for your case
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs