what is the difference between “eval” and “int”

后端 未结 2 415
谎友^
谎友^ 2021-01-18 11:20

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

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

相关标签:
2条回答
  • 2021-01-18 11:33

    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.

    0 讨论(0)
  • 2021-01-18 11:52

    eval() is used to verify an expression. On number is considered an expression, except octal numbers (numbers that start with 0). int() handles string to integer conversion. There are many reasons why you should avoid using eval(). Just keep in mind:

    • Python 2.x

      x = raw_input('Enter number here: ') 
      
    • Python 3.x

      x = input('Enter number here: ') 
      
    • Python 2.x
      Security risk:

      x = input('Enter number here: ') 
      
    • Python 3.x
      Security risk:

      x = eval(input('Enter number here: ')) 
      

    Also, keep in mind that eval() has the potential to run code, which could cause a huge security risk. I suggest not using it unless you clearly know what you're doing or it could compromise your application.

    0 讨论(0)
提交回复
热议问题