Q:

Convert a string into a kind of command - Python

I am making a program that gives me trigonometric function's value.
import math

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

We have to input, say, sin(x) into  the function. So we input "sin" in the variable "function" and let "angle" be "x".
Syntax of math is:
math.sin(x)
But the way I want it to happen is:

Assign the value of function as "sin"
Assign the value of angle as "x"
Calculate the value.

I know it won't work as we are using a variable in place of a keyword. So I am looking for such a code that can use a variable and assign it to the keyword.

A:

Perhaps this could work for you, using introspection, and in particular 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)

Then print result to see your answer

