Functions

What is a Function

A function is a block of code that only executes when called. You can supply parameters—data—to a function and a function may return data. Simply put It is a way of letting you define something you do over and over again. So if you have some code that repeats a lot in you code then its a good candidate for a function.

Creating a function

To create a function in Python, we use the keyword def.

 def function_name(input):
     output = action
     return output

A function may take parameter/argument. The function below does not take an argument or parameter.

 def function_name():
     output = action
     return output

Calling a Function

Use the function name in parenthesis to invoke the function.

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

 hello()  #this will execute the function

Arguments

Functions accept arguments . The function name is followed by parenthesis that list the arguments. Simply separate each argument with a comma to add as many as you like.

The function in the following example only takes one argument (fname). A first name is passed to the function when it is called, and it is utilized there to print the whole name:

 def hello(fname):
    print("Hello " + fname)

 hello("Yaw")
 hello("Yaw")
 hello("Ama")

Note: Information that is supplied into a function can be referred to as both an argument and a parameter.

From the viewpoint of a function:

  • The variable in the function definition that is listed between parentheses is referred to as a parameter.
  • When a function is called, a value is passed as an argument.

A function must always be called with the appropriate number of parameters by default. In other words, if your function requires 2 arguments, you must call it with 2 arguments, not more or fewer.

 def hello(fname, lname):
  print("Hello "+ lname + " " + fname)

 hello("Emil") # this will generate an error because the function expects 2 arguments, but gets only 1:

Types of Arguments

Arbitrary Arguments, *args

Add a * before the parameter name in the function specification if you are unsure of the number of arguments that will be given to your function. The function will then receive a tuple of parameters and be able to access the components as necessary. Arbitrary Arguments are often shortened to *args in Python documentations.

 def display_region(*regions):
  print("Region name is " + regions[2])

 display_region("Western", "Northern", "Volta")

Keyword Arguments

The key = value syntax allows you to send parameters as well. This makes the arguments’ chronological order irrelevant.

 def display_region(region3, region1, region2):
    print("The best region is " + region1)

 display_region(region1 = "Greater Accra", region2 = "Central", region3 = "Volta")

Arbitrary Keyword Arguments, **kwargs

Add two asterisks: ** before the parameter name in the function definition if you are unsure of the number of keyword arguments that will be supplied to your function. This will allow the function to access the items appropriately after receiving a dictionary of arguments. Arbitrary Keyword Arguments are often shortened to **kwargs in Python documentations.

 # If the number of keyword arguments is unknown, add a double ** before the parameter name:

 def league_champions(**clubs):
    print("2022 Football League was won by  " + clubs["club2"])

 league_champions(club2 = "Kumasi Asante Kotoko", club1 = "Hearts of Oak", club3="RTU")


Default Parameter Value

If you create a function with a default parameter value and you do not provide any parameter when you call the function, then the default parameter will be used:

 def display_letters(letter = "A"):
  print(letter +" is an alphabet")

 display_letters("C")
 display_letters()
 display_letters("Z")
 

Passing other datatypes as an Argument

Any data type can be passed as an argument to a function (string, number, list, dictionary, etc.), and the function will treat it as that data type.

 # Passing a list datatype parameter into the function
 def display_vowels(vowels):
  for vowel in vowels:
    print(vowel)

 vowels = ["a", "e", "i", "o", "u"]

 display_vowels(vowels)

Pass Statement

Although function definitions cannot be empty, if for some reason you find one that is empty, add the pass statement to prevent an error.

 def hello():
   pass

Return Values

So far all the function examples, have not return any output. If you want your function to return an output you will use the return statement

 def hello(name):
   return "Hello "+name

Note that the example above will return the output but not display it, so you will have to assign the output to a variable or call the function within a print statement to display the output

  def multiplication(x):
  return 5 * x

  print(multiplication(10))
  print(multiplication(2))
  print(multiplication(4))

Recursion

Python also permits function recursion, allowing defined functions to call one another. A frequent idea in math and programming is recursion. It denotes that a function makes a call to itself. This has the advantage of allowing you to loop through data to arrive at a conclusion. The developer should exercise extreme caution when using recursion because it is quite simple to write a function that never ends or consumes excessive amounts of memory or processing resources. Recursion, however, can be a very effective and mathematically elegant technique to programming when used properly.

 def get_value(k):
  if(k > 0):
    result = k + get_value(k - 1)
    print(result)
  else:
    result = 0
  return result

 get_value(6)