0

how eval() function is working here?

print(eval("1*2*3*4")) output :: 24 how the answer is 24? please can anyone explain? Thanks in advance.

12th Jul 2020, 2:15 PM
Ifthekher
Ifthekher - avatar
5 Réponses
+ 1
eval() doesn’t change anything about the calculation. what it does is see everything in it not as a string but as a “formula” so it simply does math now. 1*2 = 2 2*3 = 6 6*4 = 24 that’s it
12th Jul 2020, 2:18 PM
Brave Tea
Brave Tea - avatar
+ 1
or better said: it sees the thing in a string as a mathematical calculation/formula if it is indeed formed that way
12th Jul 2020, 2:19 PM
Brave Tea
Brave Tea - avatar
+ 1
Brave Tea not actually. You can do things other than calculations. Like eval("[i for i in range({})]".format(int(input()))) will work fine. Ifthekher also, the string is actually converted to bytecode and then executed by the interpreter, so it slows the code down. That is why use of eval() is avoided.
12th Jul 2020, 2:23 PM
XXX
XXX - avatar
+ 1
well, yeah, sure. I know, but OP asked how it worked here :) another reason it is avoided is because it is often used on inputs which makes the programme incredibly liable to outside influence :)
12th Jul 2020, 8:37 PM
Brave Tea
Brave Tea - avatar
0
eval() takes a string as argument and returns the executed code. Note that it takes an expression and not a statement. So you can pass "1 + 37 * 18" or "sum([1, 2])" but you cannot pass ("x = 18")
12th Jul 2020, 2:17 PM
XXX
XXX - avatar