Functions

Functions are blocks of code that perform some useful action. Functions can be defined once and run many times in code. Functions are useful for organizing code and making code easier to test.

Learning Objectives

You should be able to:

  • Describe the benefits of using functions
  • Write Python functions

Video Walkthrough

Use this video to follow along with the steps in this lab.

Using Functions

Functions are blocks of code that perform some kind of action. Functions might update data, draw pictures, create lists, access variables, or anything else that you could do outside of a block. Variables created inside a function will die when the function ends. Functions can return variables when they finish. The return value can be stored as a variable.

Built-in Functions

Python has many built-in functions you can use. Examples include:

  • print(): Prints a message to the console.
  • len(): Returns the length of a string or list.
  • str(): Converts a number to a string.
  • int(): Converts a string to an integer.
  • float(): Converts a string to a float.
  • type(): Returns the type of an object.
  • input(): Accepts user input.
  • range(): Generates a list of numbers.
  • min(): Returns the smallest number in a list.
  • max(): Returns the largest number in a list.

Python developers wrote these functions and included them in the Python language. It is often necessary to write your own functions to solve problems. The next section will show you how to write functions.

Function Inputs

Functions can accept inputs. Inputs are called parameters or arguments. Parameters are variables that are used in the function definition. Arguments are the values that are passed to the function when it is called. Functions can accept multiple parameters or no parameters. Parameters are specified in the function definition. Arguments are passed to the function when it is called.

Return Values

Functions can return values. The return keyword is used to send a value back to the caller. The return keyword can be used to return a single value or multiple values. The return keyword can also be used to return nothing. If a function does not have a return statement, it will return None by default.

Imagine that a gumball machine is a function. The gumball takes an input (a coin), and returns candy. The candy machine doesn't care what you do with that candy. You can eat it, throw it away, or give it to a friend. The candy machine doesn't care. Functions are like the candy machine. They take input, do something, and return output. The caller can do whatever they want with the output.

An arcade video game is like a function. You put money in, play the game, and see the score, but it does not return anything to you. Functions can be like video games. They can do something, but not return anything. For example, a function might print a message to the console, but not return anything.

Writing Functions

  • The following code defines (using def) a function named add that accepts two input parameters: number1 and number2. After the function is defined, the function is called. Functions must be used afterthey have been defined, so coders typically put functions at the top of a Python file. Theadd` function returns the sum of the two numbers, meaning that the result can be stored in a variable or printed. Or, the return value can be ignored.
def add(number1, number2):
    return number1 + number2

# The `add` function's return value is stored in the variable `result`
result = add(5, 7)
print(result)

# The `add` function is called, but the return value is not stored in a variable
add(12, 9)

# This line does not store the result in a variable, it is just printed
print(add(3,4))
  • The following code defines a function that does not return anything. The function accepts the day of the week as an input parameter. The function simply prints a message.
def display_message(day_of_week):
    print("Today is " + day_of_week)
display_message("Monday")
display_message("Friday")
  • Generally, functions are multiple lines long and do some sort of calculation or carry out logic. For example, consider the following function that evaluates a student's fitness for graduation. The function accepts a dictionary as an input parameter. After the function is defined, a sample student dictionary is created. Then the student dictionary is passed to the function.
def evaluate_for_graduation(student):
    if student['coursework'] == "complete" and student['gpa'] >= 2.0:
        student['graduated'] = True
        print("The student " + student['name'] + " has been approved for graduation.")
    else:
        student['graduated'] = False
        print("The student " + student['name'] + " has not met all graduation requirements.")
student = {"name": "Ricky Bobby", "coursework": "complete", "gpa": 3.5, "graduated": "False"}
evaluate_for_graduation(student)

In the next section, you will write several functions and test them.

  • Create a file called convert.py with the following code.
celsius = 30
print(str(celsius) + " degrees Celsius in Farenheight is: " + str(celsius * 9 / 5 + 32))
celsius = 20
print(str(celsius) + " degrees Celsius in Farenheight is: " + str(celsius * 9 / 5 + 32))
  • The code does the following.
    • Line 1 creates the celsius variable that holds a temperature.
    • Line 2 converts Celsius to Farenheight and displays the conversion.
    • Line 3 updates the value of the celsius variable.
    • Line 4 again converts celsius to Farenheight and displays the conversion. There is a design problem with the code. If we wanted to convert 50 temperatures, we would have to copy the code 50 times. If we happened to have an error in the calculation, we would have to fix it in many places.
  • Save the file and run the code to verify that it works.

You should see the following output.

30 degrees Celsius in Farenheight is: 86.0
20 degrees Celsius in Farenheight is: 68.0
  • Edit the code to match the code below. Be sure to indent the lines properly.
def convert(celsius):
    f = celsius * 9 / 5 + 32
    return str(celsius) + " degrees C in F is: " + str(f)
print(convert(30))
print(convert(20))
  • Lines 1-3 define the convert function. Line 1 starts with "def" which defines a function's name. The function is named "convert." Variables that can be sent to the function are included in parentheses. In this case, only a single variable ("celsius") is included, but functions often accept multiple variables. Functions might also accept no variables.
  • Line 2 performs the calculation.
  • Line 3 prints the formatted output.
  • Lines 4 and 5 call the convert function and print the result.
  • The above code is better with functions. If we had an error in our calculation, we could fix it once in the function.

Function Challenge

  • Create a file called greet.py.
  • In the first line, define a function named greet.
    • The greet function should have a parameter called name.
    • The greet function should return a string with the text "Hello name" but with the value of the variable name in the output.
  • After the function, create a list of names (strings).
  • Loop through the names, and for each name, print the result of calling the greet function.

Your code should have a structure similar to the following redacted code sample.

xxx xxxxx(xxxx):
    xxxxxx xxxxxxx x xxxx
xxxxx = xxxxxxx xxxxxx xxxxxx xxxxxxx
xxx xxxx xx xxxxx:
    xxxxxxxxxxxxxxxxxx

Function Challenge 2

  • Create a file called loopconvert.py.
  • Write a function called convert that accepts a list of Celsius integers as a parameter.
  • In the function, loop through the list of integers and convert them to Farenheight. Print the result in the loop.
  • After the function, create a list of Celcius integers.
  • Call the convert function by passing the list of integers.

Function Challenge 3

  • Create a file called comparenames.py.
  • Write a function named compare that accepts two parameters: name1, and name2.
  • In the function, determine which name is longer using the len() function.
  • If name1 is longer, output the value of name1 and " is longer."
  • If name2 is longer, output the value of name2 and " is longer."
  • If the names are the same length, print, "The names are the same length."
  • Call the function several times.

The following table shows sample inputs and expected outputs.

Name 1 Name 2 Output
Alice Bob Alice is longer
Joe Jenny Jenny is longer
Abe Sue The names are the same length

Reflection

  • How can using functions make it easier to write correct code?
  • Why would it be a bad practice to copy and paste calculations many times instead of using functions?

Key Terms

  • Function: A block of organized, reusable code that performs a specific task. Functions help in breaking down complex problems into smaller, manageable parts and promote code reusability. In Python, functions are defined using the def keyword followed by the function name and parentheses.
  • Function Arguments: Values that are passed to a function when it is called. Arguments allow functions to accept input and perform operations based on that input. In Python, arguments are specified within the parentheses in the function definition
  • Function Return: The value that a function gives back after completing its task. The return statement is used to specify the value to be returned. In Python, if no return statement is used, the function returns None by default.