在 raw_input 中输入浮点数、整数或方程来定义变量 [英] Inputing floats, integers, or equations in raw_input to define a variable
问题描述
我编写了这个程序,以便根据用户定义的值求解两个方程.常量 kx 和 ky,我定义为浮点数.对于范围 - 变量开始和结束 - 我希望用户输入一个数字,或者类似 6 * np.pi (6Pi) 的东西.就像现在一样,我收到以下错误.如何定义此变量以允许用户输入多种类型的输入?谢谢!
回溯(最近一次调用最后一次):文件lab1_2.py",第 11 行,位于 <module>x = np.linspace(开始,结束,256,端点=真)文件/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/site-packages/numpy/core/function_base.py",第 80 行,在 linspace步骤=(停止-开始)/浮动((数字-1))类型错误:不支持 - 的操作数类型:'str' 和 'float'
代码如下:
from pylab import *将 numpy 导入为 npkx = float(raw_input("kx:"))ky = float(raw_input("ky:"))打印定义输出范围:"start = float(raw_input("来自:"))end = float((raw_input("To:"))x = np.linspace(开始,结束,256,端点=真)y = np.linspace(开始,结束,256,端点=真)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)))绘图(x,dz_dx,线宽 = 1.0)绘图(y,dz_dy,线宽 = 1.0)网格(真)表演()
您需要自己解析字符串(ast
模块可能会很有用),或者使用 eval代码>:
请注意,用户可以使用 eval 执行一些讨厌的事情代码>.我的解决方案可以保护您免受大多数的影响,但不是全部——预先检查字符串以确保没有任何
__
将使其更安全(即消除了我所知道的所有漏洞,但可能还有其他漏洞)
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()
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)
这篇关于在 raw_input 中输入浮点数、整数或方程来定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!