Christian Singer - 1 year ago 85

Python Question

How can you make Python take a polynomial as an input while maintaining the ability to substitute x for a real value?

Here is what I tried:

`fx=input("Enter a Polynomial: ")`

x=float(input("At wich position should the polynomial be evaluated: "))

while True:

print(eval("fx"))

continue

The problem that arises is that Python will just evaluate fx as x and not as the value that I gave to x via my second input.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

This should help:

```
def eval_polynomial(poly, val):
xs = [ x.strip().replace('^','**') for x in poly.split('+') ]
return sum( [eval(n.replace('x', str(val))) for n in xs] )
```

Please keep in mind that you earlier have to make sure val is a number for safety reasons.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**