1

我已经编写了这个程序,所以根据用户定义的值求解两个方程。常量 kx 和 ky,我定义为浮点数。对于范围 - 变量开始和结束 - 我希望用户输入一个数字,或者像 6 * np.pi (6Pi) 这样的东西。就像现在一样,我收到以下错误。如何定义此变量以允许用户输入多种类型的输入?谢谢!

    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'

这是代码:

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()
4

3 回答 3

1

您需要自己解析字符串(该ast模块可能很有用),或者使用eval

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

注意,用户可以使用eval. 我的解决方案可以保护您免受大多数问题的侵害,但不是全部 - 预先检查字符串以确保没有任何__会使其更加安全(这消除了我所知道的所有漏洞,但可能还有其他漏洞)

于 2013-01-28T16:18:26.183 回答
0

我希望用户输入一个数字,或者像 6 * np.pi (6Pi) 这样的东西。

要实现这一点,您需要做两件事:

  • 首先,检查您的输入是 int 还是 float

    这很简单。您可以通过多次检查来isinstance检查

  • 如果没有,那么您需要将输入作为命令执行并将输出保存在变量中

    一旦你确定它是一个命令,你就可以使用execoreval命令来执行输入并将输出存储在一个变量中。

    示例:exec("""v = 6*2""")v = eval("6*2")两者都分配 12v

于 2013-01-28T16:17:45.340 回答
0


我正在使用 Python 2.7 和 Ecpise 工作区。通过使用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"

在这里,输入:
名称:“先生!Guido von Rossum”
半径:1.1

输出 :

************************************ 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

想一想,可能对你或其他人有帮助。
谢谢

于 2016-10-26T11:59:26.017 回答