python怎么创建函数,Python:如何创建一个函数?例如f(x)= ax ^ 2

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值