Search code examples
pythonevalcommand-line-arguments

Must eval be a string or code object?


When I run the code below, I get the following error: eval() arg 1 must be a string or code object

Anyone know why? This is code i'm learning from a book, so I assumed that it would be correct.

 # Prompt the user to enter three numbers
number1 = eval(input("Enter the first number: "))
number2 = eval(input("Enter the second number: "))
number3 = eval(input("Enter the third number: "))

 # Compute average
average = (number1 + number2 + number3) / 3

print("The average of", number1, number2, number3, "is", average)

Solution

  • You are using input() on Python 2, which already runs eval() on the input. Just remove the eval() call, or replace input() with raw_input().

    Alternatively, use Python 3 to run this code, it is clearly aimed at that version. If your book uses this syntax, then you want to use the right version to run the code samples.

    Most of all, don't use input() on Python 2 or eval() on Python 3. If you want integer numbers, use int() instead.

    Python 2 example:

    # Prompt the user to enter three numbers
    number1 = int(raw_input("Enter the first number: "))
    number2 = int(raw_input("Enter the second number: "))
    number3 = int(raw_input("Enter the third number: "))
    
    # Compute average
    average = (number1 + number2 + number3) / 3
    
    print "The average of", number1, number2, number3, "is", average
    

    Python 3 version:

    # Prompt the user to enter three numbers
    number1 = int(input("Enter the first number: "))
    number2 = int(input("Enter the second number: "))
    number3 = int(input("Enter the third number: "))
    
    # Compute average
    average = (number1 + number2 + number3) / 3
    
    print("The average of", number1, number2, number3, "is", average)