问题
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 "lab1_2.py", 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/function_base.py", 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)
grid(True)
show()
回答1:
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})
18.84955592153876
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)
回答2:
I would like the user to either enter a number, or something like 6 * np.pi (6Pi).
To implement this you need to do two things :
First,check whether your input is an int or float
This is simple. You can check for this by multiple
isinstance
checksIf not, then you need to execute the input as a command and save the output in a variable
Once you are sure it is a command, then you can use the
exec
oreval
command to execute the input and store the output in a variable.Example :
exec("""v = 6*2""")
orv = eval("6*2")
both of which assign 12 tov
回答3:
I'm using Python 2.7 and Ecplise workspace.
This source code is working fine for me, by-using raw_input.
import time
startTime = time.clock()
print "{0:*^80}".format(" Begins ")
name = raw_input('Please give the name : ')
print "Name is : ".ljust(40, '.'), name
print "Length of name : ".ljust(40, '.'), len(name)
print
radius = float(raw_input('Please enter the radius of circle : '))
print "Radius is : ".ljust(40, '.'),radius
diameter = float(2 * radius)
print "Diameter of circle is : ".ljust(40, '.'), diameter
print "\n{0:*^80}".format(" End ")
print "\nElapsed time : ", (time.clock() - startTime)*1000000, "microseconds"
Here, input :
name : "Sir! Guido von Rossum" and
radius : 1.1
Output :
************************************ Begins ************************************
Please give the name : Sir! Guido von Rossum
Name is : .............................. Sir! Guido von Rossum
Length of name : ....................... 21
Please enter the radius of circle : 1.1
Radius is : ............................ 1.1
Diameter of circle is : ................ 2.2
************************************* End **************************************
Elapsed time : 3593748.49903 microseconds
Thought, might be it helps you or someone else.
Thanks
来源:https://stackoverflow.com/questions/14566260/inputing-floats-integers-or-equations-in-raw-input-to-define-a-variable