简体   繁体   English

如何在 Python 中获取数学函数作为用户的输入并在循环中使用它

[英]How to get a mathematical function as user's input in Python and use it in a loop

I used f = lambda x: input() to get a mathematical function as the user's input.我使用f = lambda x: input()来获得一个数学函数作为用户的输入。 I put this in a for loop, but input is requested in every iteration.我把它放在一个 for 循环中,但在每次迭代中都需要输入。 How do I store the function in a variable only once and use it in the loop?如何仅将函数存储在变量中一次并在循环中使用它?

Here's my code:这是我的代码:

from math import cos, sin, pow, e

n = int(input('Number of elements in partition: '))
print('The range is set at ...... ')
minimum = int(input('Minimum: '))
maximum = int(input('Maximum: '))
f = lambda x: eval(input('Enter a funtion: '))

fraction = (maximum - minimum) / (n-1)

UpperSum = 0
LowerSum = 0

for i in range(1, n):
    UpperSum = UpperSum + fraction * f(fraction * i)
    LowerSum = LowerSum + fraction * f(fraction * (i - 1))

You've specifically made function input part of the function itself:您专门将函数输入作为函数本身的一部分:

f = lambda x: eval(input('Enter a funtion: '))

As the old line goes, "If it hurts when you do that, then don't do that!"正如那句老话所说,“如果你这样做会痛,那就不要那样做!” Input the function only once:只输入一次函数:

func_text = input('Enter a function: ')
func_eval = eval(func_text)
f = lambda x: func_eval

I broke it down one extra step.我把它分解了一个额外的步骤。 The point, though, is to read the input, evaluate it, and then make only that evaluation the function you call.不过,重点是读取输入,对其进行评估,然后仅对您调用的函数进行评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM