About Python Functions

tags: #python/documentation/python_functions

What is a Function?

In the context of programming, a function is a reusable block of code that contains a sequence of statements that perform a certain task.

Calling a Function: Passing Arguments

To call ("invoke") the function, use the function name followed by parentheses:

function_name()

When a function is called, some may require us to specify input values (arguments) for the parameters in the function.

A function can have multiple input parameters separated by commas:

a_function(param1=arg1, param2=arg2,...)
How are arguments passed?

Arguments passed to a function is based on their position in the function call. Therefore, the order in which values for an argument need to correspond to the listed variable in the function definition (parameter).

Example:

def greet(name, greeting)
	print(f"{greeting}, {hello}!")

greet(Eva, Good Morning) # do not need to explicity specify the parameter name
Good morning, Eva!
Do we have to pass arguments in the function?

Not all parameters are required (i.e., can be optional) and can be assigned default values.

The Return Keyword (Return Value)

In Python, you can use the return keyword to exit a function so it goes back to where it was called. That is, send something out of the function.

In these cases, the function will have a return statement in the body of the function to send the value back to the "caller"[1]:

def function_name():
	# statements
	return <statement>

Example:

def multiplyNum(num1):
    return num1 * 8 # specifying that you want the return value to returned to caller

result = multiplyNum(8)
print(result)

# Output: 64
Execution Flow

  1. The execution flow starts from the caller, which decides to call a specific function.
  2. The function's code is then executed, and
  3. The result (if any) is returned to the caller.


Types of Functions

There are two main types of function in Python:

  1. Built-in Functions: Built-in functions are functions that come pre-defined in the programming language. They are part of the standard library and cover a wide range of common tasks that can be accessed without users needing to define the function.

  2. User-Defined Functions & Type Annotations


  1. A caller refers to the part of the program or code that "invokes" or "calls" a particular function. A function is a reusable block of code that can be executed when needed. The part of the code that executes or calls the function is referred to as the "caller" and receives the return value of the function. ↩︎

Powered by Forestry.md