User-defined functions

tags: #python/documentation/python_functions

What is a user-defined function?

User-defined functions are functions created by the programmer to perform specific tasks. These functions are defined by the user based on the requirements of their program.

Advantages

  1. Allows for customization according to the needs of the program by allowing programmers to define their own logic and algorithms within these function.
  2. Provide added control over the flow of the program (e.g., encapsulation of complex logic behind a simple interface)

How can we define a user function?

We can define a function using the def keyword and a function identifier (name), followed by optional parameters in parentheses and a colon.

def function_name(<parameters>):
	# body of the function/sequence of statements to be executed by Python
	# this block of code only runs when called
	<statement>
	<statement>
	...

To call the function or execute the body of the function, we need to invoke it:

function_name()

# to assign the return value of a function to a variable
var = function_name()

Function Definition

A function definition specifies the name of a new function and the sequence of statements that is executed when the function is called. Once a function is defined, it can be reused throughout the program.

General Structure

The first line of the function definition is called the header, the rest is called the body:

  • The header begins with the def keyword and ends with a colon.
  • The body of a function is indented and can contain any number of statemetns.
  • To indicate the end of a block of code that makes up a function, you need to de-indent a line of code to the same indentation level of the def keyword.
  • Defining a function essentially creates a variable with the same name (storing the sequence of code to perform a task).

Rules for Function Names

Follows the same rules as variable names and no reserved words.

Tip!

Avoid having a variable and a function with the same name.


Type Annotations

Type Annotations

Type annotations is an optional notation that specifies the type of a parameter or function result. It tells the programmer using the function what of data to pass to the function and what type of data to expect when the function returns a value.

To indicate the intended type of the function parameters and type of the function's return value in a function definition, we can use the following syntax:

def function_name(parameter1: type1, parameter2: type2, ...) -> return_type:
    # Function body
    # ...
    return result

NOTE! Adding type annotations to a function definition does NOT cause the Python interpreter to check whether the values passed to a function are the expected types, OR cause the returned value to be converted to the expected type.

Powered by Forestry.md