Mark As Completed Discussion

In this lesson, we will learn about functions in a program, with a focus on the following key points,

  1. What are functions, and why do we use them?
  2. Working with function parameters, return, and call statements.

For the Javascript version of this lesson, please click here.

In this lesson, we will learn about a fundamental concept in programming called functions. Functions provide a modular structure to the code. They perform a single action and provide a method to reuse a code block in different parts of the program. Functions are known by various terminologies in computer science. Methods, procedures, and subroutines are some of the common ones.

Functions

A function is a block of code in a programming language that encloses a set of statements. Once implemented, this block of code is reusable throughout the program. Functions make it easier to organize and reuse code.

A function generally follows the following structure in a program.

Functions

Let's discuss each of these components of functions in the next sections.

Types of Functions

In programming languages, there are usually two types of functions; built-in functions and user-defined functions. Built-in functions are pre-defined by the programming language itself. We've already seen built-in functions in previous lessons such as print(). User-defined functions are functions that are defined by the user to dedicate a block of code to perform a specific task.

In this lesson, we will discuss how you can create and use your functions within your program.

Creating Functions

Function declaration or creating functions is different in different programming languages. Usually, a function keyword is specified, followed by the function name, parenthesis (with function parameters, if any), and then comes the body of the function.

Now let's see how we can create functions in Python.

In Python, the def keyword is used as the function keyword. This is followed by the function name, parenthesis, and a colon. The body of the function is denoted by an indentation.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Calling Functions

In our last code example we created a function, but as you may have checked, it did not produce any output. Why? Because functions need to be invoked by a call to use them in a program. Calling a function means to specify the function name of the function that we want to use in the program. This executes all the statements present inside the function.

Consider the same example as before. Now we specify a statement which denotes the function name along with the parenthesis, after the function implementation. This statement invokes the call to the function. The code block below demonstrates this behavior.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Build your intuition. Is this statement true or false?

We can call a function before implementing it.

Press true if you believe the statement is correct, or false otherwise.

Function Parameters

Functions can take in external information in the form of variables or directly through function parameters. They are specified inside the parenthesis after the function name. Multiple parameters can be separated by commas.

Function parameters are given a variable name inside the parenthesis during function declaration. The desired values are passed when the function call is invoked. Below code block demonstrate some examples of specifying function parameters and calling functions with parameters.

1void func1(String name) {
2    System.out.println("Hello I am " + name);
3}
4
5void add(int a, int b, int c) {
6    int d = a + b + c;
7    System.out.println("Sum of a, b, and c is: " + d);
8}
9
10func1("Beth");
11add(2, 3, 4);

Note: Here the variable d is of type int. We usestr(d)to convert the type of variabledfrominttostring, as string concatenation only works with two variables of typestring. Concatenation ofstringandint` would generate an error.

Are you sure you're getting this? Is this statement true or false?

There is no limit to the number of parameters that we can specify for a function.

Press true if you believe the statement is correct, or false otherwise.

Returning Functions

Functions stop executing at two points; when it finishes executing all statements in the function body or when it encounters a return statement. This return statement mostly also has a return value associated with it, which is returned to the caller.

The function add(a, b, c) in the following code block implements the sum of three numbers and returns the sum. This sum is then returned to the variable that calls the function, which is named as result here. Printing the value of result tells us the value of the sum computed by the function.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Build your intuition. Fill in the missing part by typing it in.

What will be printed by the variable result, in the following code block in Python?

1public static double div(double a, double b) {
2    double c = b / a;
3    return c;
4}
5
6public static void main(String[] args) {
7    double result = div(15, 5);
8    System.out.println(result);
9}

Write the missing line below.

Try this exercise. Click the correct answer from the options.

What is the output for the following code?

1public int compareNum(int a, int b) {
2    if (a > b) {
3        System.out.println("a is greater than b");
4        return a;
5    } else if (a == b) {
6        System.out.println("a is equal to b");
7        return a;
8    } else {
9        System.out.println("a is less than b");
10        return b;
11    }
12}
13int result = compareNum(4, 2);
14System.out.println(result);

Click the option that best answers the question.

  • 'a is greater than b', 2
  • 'a is less than b', 2
  • 'a is greater than b', 4
  • 'a is equal to b', 4

Summary

Functions are an extremely helpful technique to reuse and organize code. With specifying parameters and return statements, we can do more with functions that are just combining a set of statements, and even specify different values from the entirety of the program that we want to work upon. A common beginner's mistake is to forget to call the implemented functions when using them in code. Don't fall for it!

One Pager Cheat Sheet

  • We will learn about functions, their parameters and working statements to create modular and reusable code blocks.
  • Functions enclose a set of statements to make it easier to organize and reuse code, following a specific structure.
  • We will learn to create and use our own user-defined functions in our program, as well as review existing built-in functions.
  • Creating functions in Python requires a def keyword followed by the function name, parenthesis (with function parameters, if any), a colon, and an indented body.
  • We can make a function work in our program by calling it with its name, followed by parentheses ( ).
  • It is not possible to call a function before it has been defined and implemented with all its statements and parameters established.
  • Functions can take in external information through function parameters specified inside the parenthesis after the function name, which is then passed to the function call when invoked.
  • There is no upper limit to the number of function parameters that can be specified, provided they are separated correctly and referenced correctly within the function.
  • A return statement in a function can allow the function to pass back a return value to the variable that called it.
  • The variable result is set to None implicitly returned by the div() function, resulting in None being printed when printing the value of result.
  • The variable result contains 4, the larger value returned by the function compare_num(), which compares a (4) and b (2) and prints out "a is greater than b" when a is the greater value.
  • With functions, we can reuse and organize code more efficiently, avoiding the mistake of forgetting to call them.