Start learning free

LESSON 26 OF 569 · FUNCTIONS I

Functions in Python

Lesson

Video Lesson:


Lesson Transcript:

A function is a container for a few lines of code that perform a specific task.

Functions allow us to organize our code a lot better by breaking the code into smaller, more manageable chunks that are doing specific things.

Here's how a function definition looks like in Python:

def function_name():
  # function body (where all the instructions are written)

There are two main components of a function:

1. The function header:

It consists of:

  • def keyword which is short for "define". It tells Python that we are about to define a function
  • function_name is the function's name, a unique identifier we use to refer to the function
  • Parentheses (()). We'll learn more about their use in next lessons
  • A colon (:) that marks the end of the function header


2. The function body:

This is the code that Python executes whenever the function is called (where we have our Python comment). It consists of one or more indented Python statements.

Here's an example of a function:

def say_hello():
  print("Hello World")

Notice that we indented (added two whitespaces before) our print("Hello World").

Python uses indentation to indicate which lines of code are part of a function and which are not. We'll learn more about this in the next lesson.


Calling a function

If you copy paste the code we've written above in an editor and run it, you'll notice that nothing is being printed to the console.

That's because a function declaration alone does not ask the code inside the function body to run, it just declares the existence of the function.

The code inside a function body runs, or executes, only when the function is called.

You can call or invoke a function by typing its name followed by parentheses, like this:

# Function declaration:
def say_hello():
	print("Hello World")
	
# Function call:
say_hello() # Output: Hello World

All of the code inside the function body will be executed every time the function is called.

In our example, each time the function is called it will print out the message Hello World on the dev console.

We can call a function as many times as it is needed.


Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check