Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between "eval" and "int"

Earlier I heard that eval(input(a)) will convert a string automatically to int, but if i code

age = eval(input("enter age"))

during input i type in 01 it is an error, but when i code

age = int(input("enter age"))

01 as input works perfectly. Why is it?

like image 398
Cheang Wai Bin Avatar asked Aug 25 '17 12:08

Cheang Wai Bin


People also ask

What does eval () do in Python?

Python's eval() allows you to evaluate arbitrary Python expressions from a string-based or compiled-code-based input. This function can be handy when you're trying to dynamically evaluate Python expressions from any input that comes as a string or a compiled code object.

What is the difference between the input () and eval ()?

Differentiate between the input() and eval() functions in Python. When taking the user's input, if the user enters an integer input, the input function returns a string. The eval() function, however, evaluates the string as an expression and returns the result of that evaluation.

What is the difference between eval and int function?

eval evaluates any python code. int tries to convert any type to integer (float, bool, string ...). you got it.

When should eval () be used?

Eval function is mostly used in situations or applications which need to evaluate mathematical expressions. Also if the user wants to evaluate the string into code then can use eval function, because eval function evaluates the string expression and returns the integer as a result.


1 Answers

eval evaluates the python expression. In python 3, numbers starting by 0 aren't allowed (except for 0000, see Why does 000 evaluate to 0 in Python 3?). In python 2, those are interpreted as octal (base 8) numbers. Not better... (python 3 base 8 now uses exclusively Oo prefix)

int performs a string to integer conversion, so it cannot evaluate a complex expression (that you don't need), but isn't subjected to this leading zero syntax.

Another nice feature is that you can check if the entered expression is an integer by using a simple and qualified try/except block:

while True:
   try:
       age = int(input("enter age"))
       break
   except ValueError:
       print("Retry!")

(with eval you would have to protect against all exceptions)

Advice: use int, because it's safer, doesn't have security issues (eval can evaluate any expression, including system calls and file deletion), and suits your purpose perfectly.

Note: the above code is still unsafe with python 2: input acts like eval. You could protect your code against this with the simple code at the start of your module:

try:
    input = raw_input
except NameError:
    pass

so python 2 input is not unreachable anymore and calls raw_input instead. Python 3 ignores that code.

like image 73
Jean-François Fabre Avatar answered Sep 27 '22 21:09

Jean-François Fabre