【问题标题】:Inputing floats, integers, or equations in raw_input to define a variable在 raw_input 中输入浮点数、整数或方程来定义变量
【发布时间】:2016-10-26 19:59:26
【问题描述】:

我已经编写了这个程序,所以根据用户定义的值求解两个方程。常量 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()

【问题讨论】:

    标签: python python-2.7 raw-input


    【解决方案1】:

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

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

    请注意,用户可以使用eval 执行一些nasty things。我的解决方案可以保护您免受大多数的影响,但不是全部 - 预先检查字符串以确保没有任何 __ 会使其更加安全(消除所有漏洞我知道,但可能还有其他人)

    【讨论】:

      【解决方案2】:

      我希望用户输入一个数字,或者类似 6 * np.pi (6Pi)。

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

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

        这很简单。您可以通过多个isinstance 检查来检查这一点

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

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

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

      【讨论】:

        【解决方案3】:


        我正在使用 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
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-12-03
          • 1970-01-01
          • 1970-01-01
          • 2021-05-14
          • 2021-12-06
          • 2020-04-18
          • 2019-01-23
          • 2018-06-26
          相关资源
          最近更新 更多