Search code examples
pythoneval

Trouble with the eval function in python


I am trying to evaluate an equation that the user has inputted. I put all of the numbers into a list in string form then use the join function to put it into one large string and feed that into an eval function. The problem is I keep getting the error:

Use input:

Please enter the function: 8x-3
Please enter the smaller x: -6Please enter the larger x: 4
8*x-3

Error message:

Traceback (most recent call last):
  File "main.py", line 27, in <module>    slope(input("Please enter the function: "), input("Please enter the smaller x: "), input("Please enter the larger x: "))  File "main.py", line 21, in slope
    y1 = eval("".join(f_list))
  File "<string>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'int'

I make sure that I have x specified and that everything is a string.

Here is the program where "function" is the user inputted equation:

f_list = []
    for ind, character in enumerate(function):
        f_list.append(character)
        if ind > 0 and character == "x" and is_number(function[ind-1]):
          f_list.insert(ind, "*")

    if not idx:
      print("".join(f_list))
      y1 = eval("".join(f_list))
    else:
      y2 = eval("".join(f_list))

Also:

"".join(f_list)

returns:

8*x-3

Solution

  • When your eval() function is running it is attempting to use the variable x, which you have the user provide as a string, thus when eval() tries to solve your equation it is using the string of x: i.e "-6" not -6.

    To fix this problem you must cast x to an integer: x = int(x) before calling the eval() function.