Dictionary running all keys instead of just one

1

I have in the following code I have a function that performs certain operation according to the passed parameters. Then I have a dictionary serving as a switch case, which will serve to define which parameters will be passed to the function.

def calculate(number, operator):
    for i in range(1, 11): print(eval(number + operator + str(i)))


inputs = list(input().split())

switch = {
    '1': calculate(inputs[0], '+'),
    '2': calculate(inputs[0], '*'),
    '3': calculate(inputs[0], '/'),
    '4': calculate(inputs[0], '-'),
}

switch[inputs[1]]

But when you run the program and choose the entries, the program executes all operations within the dictionary, not just the one selected by the user. For example, if the inputs are 5 and 1, instead of just doing the addition operation, we have the following output:

6
7
8
9
10
11
12
13
14
15
5
10
15
20
25
30
35
40
45
50
5.0
2.5
1.6666666666666667
1.25
1.0
0.8333333333333334
0.7142857142857143
0.625
0.5555555555555556
0.5
4
3
2
1
0
-1
-2
-3
-4
-5

Could anyone explain why and how to fix the problem?

    
asked by anonymous 03.11.2017 / 16:53

1 answer

1

The construction on the% w / w you have calls the functions as you define the various possible values, which makes you execute the 4 existing operations right away.

You can fix this easily by having switch only construct the value you want to use in the function, and call the function with this new value:

import ast

def calculate(number, operator):
    for i in range(1, 11): print(ast.literal_eval(number + operator + str(i)))


inputs = list(input().split())

switch = { #apenas constroi os valores de correspondencia
    '1': '+',
    '2': '*',
    '3': '/',
    '4': '-',
}

calculate(inputs[0], switch[inputs[1]]) #chama com o valor que vem do switch

Output:

6
7
8
9
10
11
12
13
14
15

Example on Ideone

Note : You should use switch instead of ast.literal_eval for security reasons, since it will give you error in various types of calls, such as commands in the operating system, which can be devastating.

    
03.11.2017 / 18:08