Python Basics - functions

Posted by joquius on Wed, 12 Jan 2022 09:06:58 +0100

function

What are the functions in Python?

In Python, function is a set of related statements that perform a specific task.

Function helps to decompose our program into smaller modular blocks. As our plans grow, features make them more organized and manageable.

In addition, it avoids duplication and makes code reusable

Syntax for creating functions

def function_name(parameters):
	"""docstring"""
	statement(s)    

Shown above is a function definition, which consists of the following components.

  1. The keyword def marks the beginning of the function header.
  2. The name of the function that uniquely identifies it. Function naming follows the same rules as writing identifiers in Python.
  3. Parameter (parameter), through which we pass the value to the function. They are optional.
  4. A colon (:) marks the end of the function header.
  5. Optional document string (docstring) used to describe the function function.
  6. One or more valid python statements that make up the body of a function. Statements must have the same indentation level (usually 4 spaces).
  7. An optional return statement used to return a value from a function.

How do I call functions in python?

Once we define a function, we can call it from another function, program or even Python prompt. To call the function, we simply type the function name with the appropriate parameters

In [2]

name = "Emma"

def greet(name):
	"""This function greets to
	the person passed in as
	parameter"""
	print("Hello, " + name + ". Good morning!")

greet(name)
Hello, Emma. Good morning!

Document string

The first string after the function header is called docstring, which is the abbreviation of document string. It is used to briefly explain the function.

Although optional, documentation is a good programming habit. Unless you can remember the dinner you had last week, please record your code.

In the above example, we have a docstring directly below the function header. We usually use three quotation marks so that docstring can be extended to multiple lines. We can use this string as the of the function__ doc__ Property use.

For example:

In [3]

 print(greet.__doc__)
This function greets to
	the person passed in as
	parameter

Return statement

The return statement is used to exit the function and return to the location where the function was called. As follows:

return [expression_list]

This statement can contain an expression that requires evaluation and return a value. If there is no expression in the statement, or the return statement itself does not exist inside the function, the function returns a None object.

For example:

In [5]

print(greet("May"))
Hello, May. Good morning!
None

Here, None is the return value

Another example

In [6]

def absolute_value(num):
	"""This function returns the absolute
	value of the entered number"""

	if num >= 0:
		return num
	else:
		return -num

# Output: 2
print(absolute_value(2))

# Output: 4
print(absolute_value(-4))
2
4

Range and life of variables

The range of variables is the part of the program that identifies variables. Parameters and variables defined within a function are not visible externally. Therefore, they have local scope.

The life cycle of a variable is the time period during which the variable exits in memory. The life cycle of internal variables of a function is as long as the execution time of the function.

Once we return from the function, they are destroyed. Therefore, the function does not remember the value of the variable previously called.

The following is an example to illustrate the range of variables inside a function.

In [7]

def my_func():
	x = 10
	print("Value inside function:",x)

x = 20
my_func()
print("Value outside function:",x)
('Value inside function:', 10)
('Value outside function:', 20)

Here, we can see that the value of x is initially 20. Even if the function my_func() changes the value of x to 10, and it does not affect values outside the function.

This is because the variable x inside the function is different from the external variable x (local to the function). Although they have the same name, they are two different variables with different ranges.

On the other hand, variables outside the function are visible from the inside. They have global scope.

We can read these values from within the function, but we cannot change (write) them. In order to modify the values of function external variables, they must be declared as global variables using the keyword global.

parameter

In the above case, we learned to define a function and call it. Otherwise, the function call will cause an error. This is an example.

In [8]

def greet(name,msg):
   """This function greets to
   the person with the provided message"""
   print("Hello",name + ', ' + msg)

greet("Monica","Good morning!")
('Hello', 'Monica, Good morning!')

Here, the function greet () has two parameters.

Because we call this function with two parameters, it runs smoothly and we won't receive any errors.

If we call it with a different number of parameters, the interpreter will report an error. The following is the call to this function, which contains a parameter without parameters and their respective error messages.

In [9]

 greet("Monica")
 
 greet() 

TypeErrorTraceback (most recent call last)<ipython-input-9-7765bb020128> in <module>() ----> 1 greet("Monica") 2 3 greet() TypeError: greet() takes exactly 2 arguments (1 given)

Variable function parameters

So far, the function has a fixed number of arguments. In Python, there are other ways to define a function that can accept a variable number of parameters.

Three different forms of this type are described below.

Python default parameters

Function parameters can have default values in Python.

We can use the assignment operator (=) to provide default values for parameters. This is an example.

In [10]

def greet(name, msg = "Good morning!"):
   """
   This function greets to
   the person with the
   provided message.

   If message is not provided,
   it defaults to "Good
   morning!"
   """

   print("Hello",name + ', ' + msg)

greet("Kate")
greet("Bruce","How do you do?")
('Hello', 'Kate, Good morning!')
('Hello', 'Bruce, How do you do?')

In this function, the parameter name has no default value and is required during the call (required).

On the other hand, the default value of the parameter msg is "good morning!". Therefore, it is optional during a call. If a value is provided, it overrides the default value.

Any number of parameters in a function can have default values. However, once we have a default parameter, all parameters on the right must also have default values.

This means that non default parameters cannot follow the default parameters. For example, if we define the above function header as:

def greet(msg = "Good morning!", name):

We will receive an error:

SyntaxError: non-default argument follows default argument

Python keyword parameters

When we call a function with certain values, these values are assigned to parameters according to their location.

For example, in the above function greet (), when we call it greet ("Bruce", "how do you do?") The value "Bruce" is assigned to the parameter name, similarly to the how do you do message

Python allows functions to be called with keyword parameters. When we call a function in this way, we can change the order (position) of the parameters. The following calls to the above functions are valid and produce the same results.

>>> # 2 keyword arguments
>>> greet(name = "Bruce",msg = "How do you do?")

>>> # 2 keyword arguments (out of order)
>>> greet(msg = "How do you do?",name = "Bruce") 

>>> # 1 positional, 1 keyword argument
>>> greet("Bruce",msg = "How do you do?") 

We can see that we can mix positional parameters with keyword parameters during function calls. But we must remember that keyword parameters must follow positional parameters.

Using positional parameters after keyword parameters will result in errors.

Python arbitrary parameters

Sometimes we don't know in advance the number of arguments to be passed to the function Python allows us to handle this situation through function calls with any number of arguments.

In the function definition, we use an asterisk (*) before the parameter name to represent this parameter. This is an example.

In [11]

def greet(*names):
   """This function greets all
   the person in the names tuple."""

   # names is a tuple with arguments
   for name in names:
       print("Hello",name)

greet("Monica","Luke","Steve","John")
('Hello', 'Monica')
('Hello', 'Luke')
('Hello', 'Steve')
('Hello', 'John')

Here, we call the function with multiple parameters. These parameters are wrapped in tuples before being passed to the function. Inside the function, we use the for loop to retrieve all parameters.

Python functions: removing duplicate objects from the list

In [4]

# Python code to remove duplicate elements from list

def remove_duplicates(duplicate): 
    uniques = [] 
    for num in duplicate: 
        if num not in uniques: 
            uniques.append(num) 
    return(uniques)
      
duplicate = [2, 4, 10, 20, 5, 2, 20, 4] 
print(remove_duplicates(duplicate)) 
[2, 4, 10, 20, 5]

Another thing worth mentioning when you use the return statement is that you can use it to return multiple values. Therefore, you can use tuples.

Topics: Python Back-end