Python Functions

A function is a code block that runs only when called.

You can pass data (known as parameters) into a function.

Functions can return data as a result.

to create a function

In Python, use def Keyword to define a function:

Example

def my_function():
  print("Hello from a function")

Function call

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

Example

def my_function():
  print("Hello from a function")
my_function()

Run Instance

Parameters

Information can be passed to a function as a parameter.

Parameters are specified in the parentheses after the function name. You can add any number of parameters as needed, just separate them with commas.

The following example has a function with a parameter (fname). When calling this function, we pass a name and use it inside the function to print the full name:

Example

def my_function(fname):
  print(fname + " Gates")
my_function("Bill")
my_function("Steve")
my_function("Elon")

Run Instance

Default parameter values

The following example shows how to use default parameter values.

If we call the function without any arguments, the default value will be used:

Example

def my_function(country = "China"):
  print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Run Instance

Passing as List

The parameters you send to a function can be any data type (string, number, list, dictionary, etc.), and they will be treated as the same data type within the function.

For example, if you send a List as a parameter, it will still be a List (list) when it reaches the function:

Example

def my_function(food):
  for x in food:
    print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)

Run Instance

Return value

To make a function return a value, use return Statement:

Example

def my_function(x):
  return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))

Run Instance

Keyword arguments

You can also send parameters using the syntax key = value.

The order of parameters does not matter.

Example

def my_function(child3, child2, child1):
  print("The youngest child is " + child3)
my_function(child1 = "Phoebe", child2 = "Jennifer", child3 = "Rory")

Run Instance

In the Python documentation, the term 'keyword arguments' is usually abbreviated as kwargs.

Arbitrary parameters

If you don't know how many parameters will be passed to your function, add * before the parameter name in the function definition.

In this way, the function will receive a tuple of parameters and can access each item accordingly:

Example

If the number of parameters is unknown, add * before the parameter name:

def my_function(*kids):
  print("The youngest child is " + kids[2])
my_function("Phoebe", "Jennifer", "Rory")

Run Instance

pass statement

The function definition cannot be empty, but if you write an empty function definition for some reason, please use the pass statement to avoid errors.

Example

def myfunction:
  pass

Run Instance

Recursion

Python also accepts function recursion, which means that the defined function can call itself.

Recursion is a common mathematical and programming concept. It means a function calls itself. The benefit of this is that it can iterate over data to achieve results.

Developers should be very careful with recursion because it is easy to write a function that never terminates or uses an excessive amount of memory or processor power. However, when written correctly, recursion can be a very effective and mathematically elegant programming method.

In this example,tri_recursion() is defined as a function that calls itself ("recurse"). We use the k variable as data and decrement it (-1) each time it recurses. The recursion ends when the condition is not greater than 0 (for example, when it is 0).

For new developers, it may take some time to understand how it works, and the best way is to test and modify it.

Example

Recursive Example:

def tri_recursion(k):
  if(k > 0):
    result = k + tri_recursion(k - 1)
    print(result)
  else:
    result = 0
  return result
print("\n\nRecursion Example Results")
tri_recursion(6)

Run Instance