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.
5 Answers
+ 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
+ 1
or better said: it sees the thing in a string as a mathematical calculation/formula if it is indeed formed that way
+ 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.
+ 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 :)
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")