【问题标题】:Convert a string into a kind of command - Python将字符串转换为一种命令 - Python
【发布时间】:2024-05-15 21:30:02
【问题描述】:

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

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. 计算值。

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

【问题讨论】:

标签: python string variables math trigonometry


【解决方案1】:

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

然后打印结果看看你的答案

【讨论】:

  • 您可能必须小心这一点,尤其是当用户指定的函数不遵循需要单个参数的典型格式 sin/tan/etc 时。诸如hypot()pow() 之类的函数需要两个参数,但仍然是math 的属性,因此根据您希望使程序有多健壮,在使用attr() 时可能必须考虑到这一点。只是一个想法。
  • @ISOmetric 这是真的。 OP,您当然希望确保用户不能通过输入意外的内容来“破坏”程序......如果您真的只想说两个不同的功能之一,比如“sin”和“cos”,那么也许一个其他答案中的一个会更合适..但如果你小心的话,这也很好
【解决方案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 块围绕函数分配来处理错误输入。

【讨论】:

    【解决方案3】:

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

    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
    

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

    【讨论】:

    • 你打败了我 :)
    • "# 重复使用尽可能多的功能,您想支持多少功能" 我不敢苟同。而不是支持 20 个函数所需的 20 个 if/elif 条件,而是创建一个从字符串到函数的字典:functions_dict = {'sin': math.sin, 'tan': math.tan, ...} 然后你可以简单地做 functions_dict[function](angle) 这当然要求所有函数接受相同的参数。
    • 我已经有了那个。我只是想让我的代码更短。所以,getattr 就是答案。
    最近更新 更多