Python Tutorials · Python Functions

Python Functions

Learn all about Python Functions in this comprehensive tutorial.

5 min read beginner
  • A function is a block of code which only runs when it is called.
  • In Python, a function is defined using the def keyword, followed by a function name and parentheses:
  • To call a function, write its name followed by parentheses:
  • Function names follow the same rules as variable names in Python:
  • Imagine you need to convert temperatures from Fahrenheit to Celsius several times in your program.
  • Functions can send data back to the code that called them using the return statement.
  • Function definitions cannot be empty.

Python Functions

A function is a block of code which only runs when it is called.

A function can return data as a result.

A function helps avoiding code repetition.

Creating a Function

In Python, a function is defined using the def keyword, followed by a function name and parentheses:

python

This creates a function named my_function that prints "Hello from a function" when called.

Note: The code inside the function must be indented. Python uses indentation to define code blocks.

Calling a Function

To call a function, write its name followed by parentheses:

python

You can call the same function multiple times:

python

Function Names

Function names follow the same rules as variable names in Python:

  • A function name must start with a letter or underscore
  • A function name can only contain letters, numbers, and underscores
  • Function names are case-sensitive (myFunction and myfunction are different)
python
Note: It's good practice to use descriptive names that explain what the function does.

Why Use Functions?

Imagine you need to convert temperatures from Fahrenheit to Celsius several times in your program. Without functions, you would have to write the same calculation code repeatedly:

python

With functions, you write the code once and reuse it:

python

Return Values

Functions can send data back to the code that called them using the return statement.

When a function reaches a return statement, it stops executing and sends the result back:

python

You can use the returned value directly:

python
Note: If a function doesn't have a return statement, it returns None by default.

The pass Statement

Function definitions cannot be empty. If you need to create a function placeholder without any code, use the pass statement:

python

The pass statement is often used when developing, allowing you to define the structure first and implement details later.

Module quiz

2 questions
1

Which of the following is true about Python Functions?

2

What is the most common pitfall when working with Python Functions?

Answer all questions to submit.