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

Convert a string into a kind of command - Python

我正在编写一个程序来计算三角函数的值。

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. 将angle的值赋为"x"
  3. 计算值。

我知道它不会起作用,因为我们使用变量代替关键字。所以我正在寻找这样的代码,可以使用变量并将其分配给关键字。

也许这对你有用,使用内省,特别是 getattr(info 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)

然后打印结果以查看您的答案

一个选择是制作一个你想要的函数的字典,像这样:

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 块围绕函数分配来处理错误输入。

可能最简单的方法是使用已知语句:

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

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