Jonathan Fry Jonathan Fry - 1 year ago 113
Python Question

Inputing floats, integers, or equations in raw_input to define a variable

I've written this program so solve two equations based on values defined by the user. The constants kx and ky, I've defined as floats. For the range - variables start and end - I would like the user to either enter a number, or something like 6 * np.pi (6Pi). As it is now, I get the following error. How can I define this variable to allow users to enter multiple types of inputs? Thanks!

Traceback (most recent call last):
File "", line 11, in <module>
x = np.linspace(start, end, 256, endpoint=True)
File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/site- packages/numpy/core/", line 80, in linspace
step = (stop-start)/float((num-1))
TypeError: unsupported operand type(s) for -: 'str' and 'float'

Here's the code:

from pylab import *
import numpy as np

kx = float(raw_input("kx: "))
ky = float(raw_input("ky: "))

print "Define the range of the output:"
start = float(raw_input("From: "))
end = float((raw_input("To: "))

x = np.linspace(start, end, 256, endpoint=True)
y = np.linspace(start, end, 256, endpoint=True)

dz_dx = ((1 / 2.0) * kx * np.exp((-kx * x) / 2)) * ((2 * np.cos(kx *x)) - (np.sin(kx * x)))
dz_dy = ((1 / 2.0) * ky * np.exp((-ky * y) / 2)) * ((2 * np.cos(ky *y)) - (np.sin(ky * y)))

plot(x, dz_dx, linewidth = 1.0)
plot(y, dz_dy, linewidth = 1.0)


Answer Source

You'll need to either parse the string yourself (the ast module would probably be useful), or use eval:

>>> s = '6*pi'
>>> eval(s,{'__builtins__': None, 'pi': np.pi})

Note that there are some nasty things that users can do with eval. My solution protects you from most of them, but not all -- pre-checking the string to make sure that there aren't any __ will make it even safer (that eliminates all of the vulnerabilities that I know of, but there could be others)

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