Dictionary running all keys instead of just one

Asked

Viewed 33 times

1

I have in the following code I have a function that performs certain operation according to the parameters passed. Then I have a dictionary serving as 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 running the program and choosing the entries the program performs all operations within the dictionary and not just the one selected by the user. For example, if the inputs are 5 and 1, instead of just performing 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 someone explain to me why this and how to fix the problem?

  • 5 1, this way

1 answer

1


The construction in switch It calls the functions as it defines the various possible values, which makes it execute the 4 existing operations.

Can fix this easily by making the switch just construct the value you want to use in the function, and call the function with that 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

Exit:

6
7
8
9
10
11
12
13
14
15

Example in Ideone

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.