Functions

Structuring Computer Programs

Functions

The function is a very old concept from mathematics that is now central to all programming languages.

Python comes with a set of built-in functions, and allow you to create your own.

What is a Function?

  • A function is a reusable set of statements that performs a specific task.
  • Functions have inputs called parameters.
  • Functions generate an output called a return value.
  • Once defined functions are called or executed as often as you like.

Built-In Functions

Python comes with many built-in functions, some of which you may have seen before:

>>> print("hello world!")
Hello World
>>> len("Hello World!")
12

Problem Solving

When creating a program to perform a particular task it is often useful to decompose a large problem into several smaller parts that are easier to understand and test.

Consider how to make a peanut butter & jelly sandwich:

  1. Get two pieces of bread. 🍞
  2. Spread jelly on one piece of bread. 🍓
  3. Spread peanut butter on the other piece of bread. 🥜
  4. Put the two pieces of bread together. 🥪

Python Functions

Python functions are declared using the def keyword followed by the name for your function. After the name is a set of parentheses containing an optional list of parameters, followed by a colon, which begins the block of your function.

def say_hello(name):
    print("Hello", name)

say_hello("Alice")
Hello Alice

Return Values

Python functions usually return a value. For example here’s a function that calculates the area of a circle using a radius parameter that is passed in:

def area(r):
    return 3.1415792 * r ** 2

print(area(20))

1256.63168

A function can contain multiple statements. Here’s a function that calculates the number seconds in a given number of years.

def hours_in_year(year):
    days = year * 365
    hours = days * 24
    return hours

print(hours_in_year(5))

43800

Can you modify the hours_in_year function to return the seconds in a year:

def seconds_in_year(year):
    days = year * 365
    hours = days * 24
    ...

print(seconds_in_year(3))

Modify the hours_in_year function to return the seconds in a year:

def seconds_in_year(year):
    days = year * 365
    hours = days * 24
    minutes = hours * 60
    seconds = minutes * 60
    return seconds

print(seconds_in_year(3))

94608000

Modules

Python comes with lots of functions that are organized into modules, which we’ll be talking about later in the semester.

import random

x = random.randint(0, 50)
print(x)

31

Review

  • Functions are a useful organizational technique for solving problems.
  • Use the def keyword to declare a function that can have optional paramters.
  • Every function has a return value.
  • You call a function using its name and by passing any variables as arguments.
  • Functions can be organized into modules (we’ll cover this later)