Python:如何创建一个函数?例如f(x)= ax ^ 2 [英] Python: How to create a function? e.g. f(x) = ax^2

查看:513
本文介绍了Python:如何创建一个函数?例如f(x)= ax ^ 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对某个函数有某种引用,但我不知道是否需要使用 def f(x)或者 lambda 某种。



例如,我想要 print f(3)并输出 9a ,或者这不是python的工作方式?

第二个问题:假设我有一个工作函数,我该如何返回它的

解决方案

要创建一个函数,可以定义它。函数可以做任何事情,但他们的主要使用模式是参数和返回值。例如,如果你想要 f(x)返回一个数字,那么 a 也应该是一个全局定义或在函数内定义的数值变量:

  In [1]:def f(x):
...:a = 2.5
...:return a * x ** 2
...:

在[2]中:f(3)
Out [2]:22.5

或者你想让它返回这样的字符串:

  In [3] :def f(x):
...:return str(x ** 2)+'a'
...:

In [4]:f( 3)
Out [4]:'9a'

您需要更多的帮助。






编辑:事实证明,您希望与多项式或代数函数作为对象,并用它们做一些代数性的东西。 Python将允许这样做,但不使用标准数据类型。你可以为一个多项式定义一个类,然后定义任何方法或函数来获得最高的功率或其他任何东西。但 Polynomial 不是内置数据类型。虽然可能有一些很好的库定义这样的类。


I want to have some sort of reference to a function but I do not know if I need to use a def f(x) or a lambda of some kind.

For instance I'd like to print f(3) and have it output 9a, or is this not how python works?

Second question: Assuming I have a working function, how do I return the degree of it?

解决方案

To create a function, you define it. Functions can do anything, but their primary use pattern is taking parameters and returning values. You have to decide how exactly it transforms parameters into the return value.

For instance, if you want f(x) to return a number, then a should also be a numeric variable defined globally or inside the function:

In [1]: def f(x):
   ...:     a = 2.5
   ...:     return a * x**2
   ...: 

In [2]: f(3)
Out[2]: 22.5

Or maybe you want it to return a string like this:

In [3]: def f(x):
   ...:     return str(x**2) + 'a'
   ...: 

In [4]: f(3)
Out[4]: '9a'

You have to specify your needs if you need more help.


EDIT: As it turns out, you want to work with polynomials or algebraic functions as objects and do some algebraic stuff with them. Python will allow doing that, but not using standard data types. You can define a class for a polynomial and then define any methods or functions to get the highest power or anything else. But Polynomial is not a built-in data type. There may be some good libraries defining such classes, though.

这篇关于Python:如何创建一个函数?例如f(x)= ax ^ 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆