Python Morsels: How to Make a Function

Related article:

Transcript:

How can you make your own function in Python?

Defining a function

Let's make a function called greet that prints out "Hello world".

>>> def greet():...     print("Hello world")...

You can put as many statements as you like in a function, but we've chosen to just put one statement in this greet function.

When we call greet (by specifying the name of the function and open and close parentheses) Python will execute the statements inside that function:

>>> greet()Hello world

If we pass an argument to the greet function, we'll get an error:

>>> greet("Trey")Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: greet() takes 0 positional arguments but 1 was given

We got an error because we passed an argument to greet but the greet function takes zero positional arguments.

Accepting arguments

To make a function that accepts arguments, you put the arguments in the parentheses when defining it.

Here we'll modify our greet function to print out "Hello" and a name variable (instead of "world"):

>>> def greet(name):...     print("Hello", name)...

If we call this new greet function, we can pass a value to the name argument to print out that name:

>>> greet("Trey")Hello Trey

So we use def to define a function, we type the name of the function we're defining, and then we put parentheses.Inside the parenthesis we put any arguments that our function accepts (if there's more than one argument, they're separated by commas).That first line is always followed by a colon, which indicates the start of a block of code (meaning all the statements in the function are indented).

Positional vs keyword arguments

If we take the greet function and call it with Trey, this is a positional argument.We can also pass in a keyword argument or a named argument.

We could pass the name in using a keyword argument like this:

>>> greet(name="Trey")Hello Trey

Default argument values

If we don't give any arguments to this function we'll see an error because the greet function accepts a name argument, and it's required:

>>> greet()Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: greet() missing 1 required positional argument: 'name'

Function arguments are required by default in Python.If you want to make optional arguments, you need to provide a default value.We can specify a default value with an equals sign:

>>> def greet(name="world"):...     print("Hello", name)...

Note: that equals sign doesn't have anything to do with keyword arguments.When you call a function an equal sign specifies a keyword argument.When you define a function, an equal sign defines a default value for an argument.

If we call this function with an argument it does the same thing as before:

>>> greet("Trey")Hello Trey

But if we don't supply an value for that argument, name will default to world.

>>> greet()Hello world

Return values

Let's take a function, product that accepts two arguments, numbers and start (which defaults to 1):

>>> def product(numbers, start=1):...     total = start...     for n in numbers:...         total *= n...     print(total)...

This product function doesn't really work the way it probably should.

When we call product with some numbers, 6 is printed out:

>>> total = product([2, 1, 3])6

We would expect the variable total to be 6.But it's not 6: it is None!

>>> total>>> print(total)None

None is the default return value for all functions.

Arguments are the inputs to a function.The return value is the output of a function.

Normally you'll want your functions to have a return statement.

Let's change the product function to return instead of calling print:

>>> def product(numbers, start=1):...     total = start...     for n in numbers:...         total *= n...     return total...

Now that we've changed print to return, if we execute the same sort of code as before we'll see nothing is printed out.

>>> total = product([2, 1, 3, 4])

But total is 24 now:

>>> total24

When you call a function, it's return value will be passed back to you, the caller of that function, and we can capture that into a variable or pass it off somewhere else.

Summary

To define a function in Python, you use the def keyword.You put the name of the function, open and close parentheses, with any arguments inside those parentheses.If any of the arguments are optional, you'll need to give them default values.

Then you put a colon, to start defining the body of the function (a colon means you've got a block of code that's going to be indented).The statements you write will be executed when that function is called.

Importantly functions have inputs, which are their arguments and also an output, which is the return value of that function, which isn't required, but most functions have a return value.

That's how you make a function in Python!

POst ID: 2648942815