Functions in Python - CNDRO.LLC
3176
post-template-default,single,single-post,postid-3176,single-format-standard,wp-custom-logo,theme-bridge,bridge-core-2.9.4,woocommerce-no-js,tribe-no-js,ehf-template-bridge,ehf-stylesheet-bridge-child,qode-page-transition-enabled,ajax_fade,page_not_loaded,,qode-title-hidden,qode_grid_1300,footer_responsive_adv,hide_top_bar_on_mobile_header,columns-4,qode-child-theme-ver-1.0.0,qode-theme-ver-27.8,qode-theme-bridge,qode_header_in_grid,wpb-js-composer js-comp-ver-6.7.0,vc_responsive,elementor-default,elementor-kit-2634

Functions in Python

Photo by Procreator UX Design Studio on Unsplash

Functions in Python can be defined as a group of related statements used to perform a specific task. Functions are usually useful for breaking programs into smaller and modular chunks thereby making the code looks more organized and manageable.

Functions can be both built-in or user-defined. It helps the program to be succint, non-repetitive, and as well arranged.

Function Syntax usually looks like this:

1 def function_name(parameters):
2 """hello"""
3 statement(s)
4 return expression

 

We’ll look at the following four key things:

  • How to Define a Function
  • How to Call a Function
  • How to Add Docstring to a Function

Now, let’s look at each of these one after the other.

How to Define a Function

We define a function to provide the required functionality for it. The rules below demonstrate how we can define a function in Python.

  1. We use the keyword def to declare the function or to begin the function blocks and then the function name and parentheses ( ( ) ) follow.
  2. Parameters are also added to the function, any input parameters or arguments should be placed within the parentheses we defined earlier, then we end the line with a colon.
  3. We add the statements we want our functions to execute.
  4. Now we end our function with a return statement. Without the return statement, our function will return an object None

We can check the examples below;

1 def my_function():
2 print("Hello, you're welcome!")
1 def cube(side): 
2  volume = side **3 
3  surface_area = 6 * (side**2) 
4  return volume, surface_area

 

We can go in-depth with our parameters and use them accordingly to what we have in mind.

How to Call a Function

As we have defined our function earlier, we need to call it because if we don’t, we might not see any output. We can call a function by using another function or directly from our Python Prompt. We’ll see various examples of how we can call functions.

Let’s use one of the examples below;

1 #defining our function with its parameters
2 def cube(side):
3 volume = side **3
4 surface_area = 6 * (side**2)
5 #we use the return to parse our result
6 return volume, surface_area
7
8 #calling our function - means we want it to return the volume and surface area we defined
9
10 print(cube(3))

 

Output

1  (27, 54)

Now we’ll look at how to call a function from another function

1 def sportClub():
2 return ("Manchester")
3 def sports(): # function definition
4 print ("There are different sport club that values Ronaldo")
5 print("we know he plays for", sportClub()) # now call sportClub in this present function
6
7 sports()

 

How to Add Docstring to a Function

It’s also good to add a docstring to our function. Docstrings are useful for describing what function does. These descriptions usually serve as documentation for our function. If anyone reads it, it’s easier for them to understand, without having to trace through all the code in the function definition.

We can implement this in our code using the example we have below.

1 def my_function():
2 """Prints "Hello, you're welcome!".
3
4 Returns:
5 None
6 """
7 print("Hello, you're welcome!")
8 return

 

Now, we need to look at the different Function Arguments we have;

Function Arguments

The different types of arguments below show us how we can call a function;

  • Required arguments
  • Default arguments
  • Keyword arguments
  • Variable-length arguments

Required Arguments

These are the arguments we must pass to a function in the right order. Whenever we’re doing this, the number of arguments we’re passing to the function must match with the function definition or requirements.

1 def student(name):
2 "This prints a whatsoever we pass into this function"
3 print(name)
4 return;
5
6 # Now you can call student function
7 student()

 

This will definitely give us an error because we didn’t pass the required argument to it.

1 TypeError Traceback (most recent call last)
2 <ipython-input-17-ce9e9cc0b820> in <module>
3 5
4 6 # Now you can call student function
5----> 7 student()
6
7 TypeError: student() missing 1 required positional argument:'name' 8

 

Default Arguments

Default arguments are described as function that allows a default value even if no argument value is passed during the function call. It is possible to assign this default value by using the assignment operator =. Let’s see the example below;

1 #defining our function
2 def invalues(x ,y= 2):
3 return x + y
4
5 #let's call invalues with first parameter 'x'
6 invalues(x=1)
7
8 #let's call invalues with first, second parameter 'x' and 'y', whereby we changed y value
9 invalues(x=1, y=5)

 

 Keyword Arguments

Keywords are very helpful whenever we want to call our function and we want all parameters to be in the right order. This means we can identify the arguments by their parameter name. An example is implemented below;

1 # Defining our function
2 def invalues(x, y):
3 return x + y
4
5 # let's call the invalues function with keyword arguments 6invalues(x=1, y=5)

Variable-length arguments

Variable-length arguments are usually used whenever there is a need to add more arguments to a function than you specified while defining it. These arguments are referred to as variable-length arguments.

We can use the *args, let’s see an example below;

1 def addition_(*args):
2 total_sum = 0
3 for i in args:
4 total_sum += i
5 return total_sum
6
7 # Calculate the total sum
8 addition_(11, 14, 19, 21)

 

Thanks for reading this article.

No Comments

Post A Comment