Python: How to create a function? e.g. f(x) = ax^2

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 (and most other computer languages) don't do algebra, which is what you'll need if you want symbolic output like this. But you could have a function f(a,x) which returns the result for particular (numerical) values of a:

def f(a, x):
   return a*x*x

But if you want a program or language which actually does algebra for you, check out sympy or commercial programs like Mathematica.

If you are just working with polynomials, and you just need a data structure which deals well with them, check out numpy and its polynomial class.