How to take a function as an argument? (Python)

I am writing a program to calculate the volume of a rigid body of revolution. The first step is to calculate the integral. I use for this scipy.integrate, but I can’t find a better way to get the equation (for example, x=x**2input on the command line. I initially planned to add the argument “relative to: x | y ', and then take this function as lambda. Unfortunately, argparseI won’t take lambda as an argument type, and trying to use a string to build a lambda ( f = lambda x: args.equation) just returns a string (understandably, really).

Here is what I have so far:

import sys
import argparse
import math
from scipy import integrate

parser = argparse.ArgumentParser(description='Find the volume of the solid of rotation defined')
parser.add_argument('equation', help='continous function')
parser.add_argument('a', type=float, help='bound \'a\'')
parser.add_argument('b', type=float, help='bound \'b\'')
parser.add_argument('-axis', metavar='x|y', help='axis of revolution')
args = parser.parse_args()

def volume(func, a, b, axis=None):
  integral = integrate.quad(func, a, b)
  return scipy.py * integral

print volume(args.equation, args.a, args.b)

Any advice would be appreciated thanks

+3
2

, Python, eval :

volume(eval('lambda x: %s' % args.equation), args.a, args.b)
+6

eval() , :

>>> f = eval("lambda x: x**2")
>>> f(5)
25
+2

Source: https://habr.com/ru/post/1779234/


All Articles