Defining a function
So we have called built-in functions. But what if we want to define our own functions?
Easy. Let’s say we want to define a function that squares a number, \(f(x) = x^2\).
In Python, this is how you do it:
def f(x):
return x**2
Using your newly minted function is simply a matter of calling it as usual:
y = f(3)
print(y)
Let us dissect our codes.
def
is a keyword to indicate a function definition.
f
is the name of the function. You should probably give a more semantically meaningful name like square
! Function names are usually verbs.
x
is called the parameter of the function. These are variables that have not yet been defined. Again, use a semantically meaningful name when relevant. You can name it x
if this is a mathematical function, of course!
During the function call f(3)
, the argument 3 is assigned to the parameter x
in the function. The program will then execute the body of your function definition and return an object (including None
).
If you do not include a return statement, the function will automatically return None
.
Note the distinction between the terms parameter and argument. In analogy to variable assignments, parameter is the variable name, and argument is the concrete value/object referred to by the variable.
You can make a call to another function from inside a function definition.
def f(x):
return x**2
def g(x):
return f(x)**2 + 0.5 * f(6)
y = g(4)
Of course, you can have multiple parameters.
def compute_something(x, y, z):
a = x + 2 * y
a = z * a + 3 * x
return a
results = compute_something(1, 3, 2)
print(results)
Although you can only return one object, that object can be a sequence (e.g. tuple
), so technically you can return more than one object!
def do_more(x, y):
return (2*y, x+y)
results = do_more(1, 2)
print(type(results))
x, y = do_more(1, 2)
print(type(x))
print(type(y))