Introduction Variables Data Types Numbers Casting Strings Boolean Operators Lists Tuples Dictionaries If-Else While Loops For Loops Functions Arrays Scope Modules User Input File Handling Python Maths

Welcome to the lesson on Python Functions

Functions

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

Creating Functions

In Python a function is defined using the def keyword:

Example:

syntax

Calling a Function

To call a function, use the function name followed by parenthesis:

Examples:

syntax
Try it out yourself

Arguments

Information can be passed into functions as arguments.

Examples:

syntax

Parameters or Arguments?

A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that is sent to the function when it is called.

Number of Arguments

By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.

Examples: This function expects 2 arguments, and gets 2 arguments:

syntax
Try it out yourself

If you try to call the function with 1 or 3 arguments, you will get an error:

Examples:

syntax
Try it out yourself

Keyword Arguments

You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Examples:

syntax
Try it out yourself

Default Parameter Value

The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:

Examples:

syntax

Passing a List as an Argument

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

if you send a List as an argument, it will still be a List when it reaches the function

Examples:

syntax

Return Values

To let a function return a value, use the return statement:

Examples:

syntax
Try it out yourself

The pass Statement

function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error

Examples:

syntax
Try it out yourself

End of Python Functions

You have learned Functions in simple terms. Let's proceed on to Quiz.

Quiz Time!
Next Lesson
Back To Top