将字符串转换为一种命令 - Python

时间:2017-06-28 12:56:22

标签: python string variables math trigonometry

我正在制作一个给我三角函数值的程序。

import math

function = str(input("Enter the function: "))
angle = float(input("Enter the angle: "))
print(math.function(angle))

我们必须输入sin(x)到函数中。所以我们在变量“function”中输入“sin”,让“angle”为“x”。

数学语法是:

math.sin(x)

但我希望它发生的方式是:

  1. 将函数值指定为“sin”
  2. 将角度值指定为“x”
  3. 计算值。
  4. 我知道它不起作用,因为我们使用变量代替关键字。所以我正在寻找可以使用变量并将其分配给关键字的代码。

3 个答案:

答案 0 :(得分:2)

也许这可能对您有用,使用内省,特别是getattrinfo on gettattr):

import math

function = str(input("Enter the function: "))

angle = float(input("Enter the angle: "))

# if the math module has the function, go ahead
if hasattr(math, function):
    result = getattr(math, function)(angle)

然后打印结果以查看答案

答案 1 :(得分:2)

一个选项是制作所需功能的字典,如下所示:

import math

functions = {
    'sin': math.sin,
    'cos': math.cos
}

function = functions[input('Enter the function: ')]
angle = float(input('Enter the angle: '))
print(function(angle))

此外,您可以使用try-catch块来围绕功能分配,以处理错误的输入。

答案 2 :(得分:0)

执行此操作的最简单方法可能是使用已知语句:

import math

function = str(input("Enter the function: "))
angle = float(input("Enter the angle: "))

output = "Function not identified"  # Default output value

if function == "sin":
    output = math.sin(angle)
if function == "tan":
    output = math.tan(angle)
# Repeat with as many functions as you want to support

print output

缺点是你必须为你想要允许的任何输入做好准备。

相关问题