Functions

Defining

A function is a group of instructions that perform a task. We can define functions in Python like this:

>>> def greet(name):
...     print("Hello {}".format(name))
...

The name of the function is greet, and name is the input parameter or argument to the function. We can call (execute) our function like this:

>>> greet("Trey")
Hello Trey
>>> greet("world")
Hello world

Let’s make a function for our greetings module. Change your greetings.py script to look like this:

import sys


def greet(name):
    print("Hello {}!".format(name))


if __name__ == "__main__":
    greet(sys.argv[1])

Now we can run our program like this:

$ python greetings.py Trey
Hello Trey!

We can also import our greet function and use it:

>>> from greetings import greet
>>> greet("Trey")
Hello Trey!

Return

Functions in Python can also have return values. We can use a return statement to return something from our function:

>>> def multiply(x, y):
...     return x * y
...
>>> multiply(7, 3)
21

What if we need multiple return values? We probably won’t need this often, but it’s nice to know, and you will see this now and then in the real world. The idiomatic way to do this in Python is to use a tuple. We will talk more about tuples in future workshops, but for now you can think of them as a special collection of items.

Let’s make a function that returns the number of cakes and wine bottles that we need for a party, given a number of guests.

>>> def get_cake_and_wine(guests):
...     cakes = guests / 8
...     wine_bottles = guests / 3
...     return cakes, wine_bottles
...
>>> get_cake_and_wine(10)
(1.25, 3.3333333333333335)

Note the return statement has multiple items. Python puts the two items together into a tuple and returns the tuple. Later we will go into how to do “tuple unpacking”, which is one way of using the return tuple.

Keyword Arguments

Python also allows you to specify arguments by their name when calling functions. When arguments are specified this way they are called “keyword arguments”:

Let’s try this with our greet function:

>>> from greetings import greet
>>> greet(name="Trey")
Hello Trey!
>>> greet("Trey")
Hello Trey!

Default Arguments

We can also specify default values for arguments when defining our functions. This makes an argument optional, so when the function is called, if no argument is supplied, it gets the default value:

>>> def greet(name="world"):
...     print("Hello {}!".format(name))
...
>>> greet()
Hello world!
>>> greet("Trey")
Hello Trey!
>>> greet(name="Trey")
Hello Trey!

This can be extremely useful for functions that can have a number of inputs, but where, most of the time, they would always be the same. By supplying the default values, a programmer using the function would not have to worry about supplying these arguments all the time.

Note that while good code practice is to put spaces around operators such as = in assignments, this is not the case for keyword arguments and default arguments. It is considered a best practice not to put spaces around the equal sign when specifying keyword arguments and default arguments.

Function Exercises

Hypotenuse

Make a function that returns the hypotenuse of a right triangle given the other two sides. Your function should work like this:

>>> get_hypotenuse(3, 4)
5.0
>>> get_hypotenuse(5, 12)
13.0

Hint: to get the square root of a number, raise it to the power of 0.5.

To Celsius

Make a function that accepts a temperature in Fahrenheit and returns a temperature in Celsius.

>>> to_celsius(212)
100.0

Is Leap Year

Make a function that takes a year and returns True if and only if the given year is a leap year.

  • Leap years are years that are divisible by 4
  • Exception: centennials (years divisible by 100) are not leap years
  • Exception to exception: years divisible by 400 are leap years

You may find this pseudocode from Wikipedia helpful.

Perfect Square

A perfect square is a number which is the square of an integer. For example 25 (5 * 5), 49 (7 * 7) and 81 (9 * 9) are all perfect squares.

Make a function that returns True if the given number is a perfect square.