All Fundamentals of Python Functions that You Should Know – A Quick Brush Up!

Chirag Goyal Last Updated : 12 Nov, 2024
8 min read

This article was published as a part of the Data Science Blogathon

Introduction

In this article, you’ll learn about Python functions and their applications while we writing the python programs in an optimized manner. You will learn starting from what they’re, their syntax, and also see the examples to use them in Programs.

Note: If you are more interested in learning concepts in an Audio-Visual format, So to learn the basic concepts you may see this video.

Link

The topics which we will be covered in this article are as follows:

  • What are Python Functions?
  • How many types of Functions are there?
  • How to create a function in Python?
  • How to call a function in Python?
  • What is the role of the return statement in Python Functions?
  • What are Arguments in Function?
  • Discuss some examples to understand more about Python Functions.
  • What are the Advantages of Functions in Python?
cs250 - Benjamin Dicken - python structures

                                                 Image Source: Link

 

What are Python Functions?

In this section, we first learn the basics of Python Functions, and then in the next section, we will apply these concepts to some problems and write the codes.

Let’s first discuss what exactly is a Python Function:

In Python, a function is a group of related statements that performs a specific task.

With the help of Functions, we can break our program into smaller and modular chunks. So, when our program grows larger and larger, functions help us to make it more organized and manageable.

Furthermore, with the help of function, we can avoid repetition and makes our code reusable.

Mainly, there are two types of functions:

  • User-defined functions – These functions are defined by the user to perform a specific task.
  • Built-in functions – These functions are pre-defined functions in Python.

Creating a Function

To define the function in Python, it provides the def keyword. Now, let’s see the syntax of the defined function.

Syntax:

def my_function(parameters):
            function_block
return expression  

Let’s understand the syntax of functions definition:

  • To define the function, we use the def keyword, along with the function name.
  • The identifier rule must follow the function name.
  • A function accepts the parameter (argument), and it can be optional.
  • The function block is started with the help of colon (:), and block statements must be at the same indentation.
  • To return the value from the function, we use the return statement. A function can have only one return statement involved in it.

Function Calling

In Python, after the function is created, we can call it with the help of another function.

Important: A function must be defined before the function call; otherwise, the Python interpreter gives an error. To call the function, we use the function name followed by the parentheses.

Consider the following example of a simple example that prints the message “Analytics Vidhya”.
Python Code:

def my_function():
   print("Analytics Vidhya")
# function calling
my_function()

The return statement

In a function, we use the return statement at the end of the function and it helps us to return the result of the function. This statement terminates the function execution and transfers the result where the function is called.

Note that we cannot use the return statement outside of the function.

Syntax:

return [expression_list]
 

It can contain the expression which gets evaluated and the value is returned to the caller function. If the return statement has no expression or does not exist itself in the function then it returns the None object.

Consider the following example:

Example 1: Creating Function with Return Statement

# Defining function
def sum():
   a = 20
   b = 40
   c = a+b
   return c
# calling sum() function in print statement
print("The sum is given by:",sum())
 

Output:

The sum is given by: 60

In the above code, we have defined the function named sum, and it has a statement c = a+b, which computes the given values, and the result is returned by the return statement to the caller function.

Example 2: Creating function without return statement

# Defining function
def sum():
   a = 20
   b = 40
   c = a+b
# calling sum() function in print statement
print(sum())
 

Output:

None

In the above code, we have defined the same function but this time we use it without the return statement and we have observed that the sum() function returned the None object to the caller function.

Arguments in function

The arguments are types of information that can be passed into the function. The arguments are specified in the parentheses. We can pass any number of arguments to the functions, but we have to separate all the arguments with the help of a comma.

Let’s see the given example, which contains a function that accepts a string as the argument.

Example 1

# Defining the function
def func (name):
    print("Hi ",name)
# Calling the function
func("Chirag")
 

Output:

Hi Chirag

Example 2

Python Function to find the sum of two variables:

# Defining the function for sum of two variables
def sum (num1,num2):
  return num1+num2;
# Taking values from the user as an input
num1 = int(input("Enter the value of num1: "))
num2 = int(input("Enter the value of num2: "))
# Calculating and Printing the sum of num1 and num2
print("Sum = ",sum(num1,num2))
 

Output:

Enter the value of num1: 20
Enter the value of num2: 40
Sum =  60

 

Python Function Examples

In this section, we will look at some of the examples of Python Functions to gain a clear and better understanding of the Functions in Python.

1. Write a Python program to find the maximum from the given three numbers.

Program to implement the given functionality:

def max_of_two( x, y ): 
       if x > y: 
          return x 
      return y 
def max_of_three( x, y, z ): 
      return max_of_two( x, max_of_two( y, z ) )

Sample Example to test the Program:

print(max_of_three(3, 6, -5))
# Output: 6

Explanation of the Program: 

In this example first, we will make a user-defined function named max_of_two to find the maximum of two numbers and then utilizes that function to find the maximum from the three numbers given by using the function max_of_three. For finding the maximum from three numbers, we pick two numbers from those three and apply the max_of_two function to those two, and again apply the max_of_two  function to the third number and result of the maximum of the other two.

2. Write a Python program to calculate the sum of all the numbers present in a list.

Program to implement the given functionality:

def sum(numbers): 
     total = 0 
     for element in numbers: 
           total += element 
     return total

Sample Example to test the Program:

print(sum((8, 2, 3, 0, 7)))
# Output: 20

Explanation of the Program:

In this example, we define a function named sum() that takes a list of numbers as input and we initialized a variable total to zero. Then, with the help of a for loop, we traverse the complete list and then update the value of the total variable to its previous value plus the value traversed at that time. We do the updation of the total variable until we reach the last of the list and then finally we return the value of the total variable.

3. Write a Python program to calculate the multiplication of all the numbers present in a list.

Program to implement the given functionality:

def multiply(numbers): 
 total = 1
 for element in numbers: 
     total *= element
 return total

Sample Example to test the Program:

print(multiply((8, 2, 3, -1, 7)))
# Output: -336

Explanation of the Program:

In this example, we define a function named multiply() that takes a list of numbers as input and we initialized a variable total to one. Then, with the help of a for loop, we traverse the complete list and then update the value of the total variable to its previous value multiply by the value traversed at that time. We do the updation of the total variable until we reach the last of the list and then finally we return the value of the total variable.

4. Write a Python program that takes a string as an input and calculates the number of upper case and lower case letters present in the string.

Program to implement the given functionality:

def string_test(string): 
    d={"UPPER_CASE":0, "LOWER_CASE":0} 
    for character in string: 
         if character.isupper(): 
              d["UPPER_CASE"]+=1 
         elif character.islower(): 
              d["LOWER_CASE"]+=1 
         else:  
              pass
    print ("Original String: ", string) 
    print ("No. of Upper case characters: ", d["UPPER_CASE"]) 
    print ("No. of Lower case Characters: ", d["LOWER_CASE"])

Sample Example to test the Program:

string_test('The quick Brown Fox')
# Output:
Original String:  The quick Brow Fox
No. of Upper case characters :  3
No. of Lower case Characters:  13

Explanation of the Program:

In this example, we initialized a dictionary having two keys named UPPER_CASE and LOWER_CASE with values 0. Then, with the help of a for loop, we traverse the string and check whether each character is either lower case or upper case and whatever that character is we increment the value of that variable by one, and we do the same process until we reached upto the end of the string.

5. Write a Python program that takes a number(non-negative integer) as an argument and calculates its factorial.

Program to implement the given functionality:

def factorial(number):
    if number == 0: 
        return 1 
    else: 
        return number * factorial(number-1)

Sample Example to test the Program:

number = int(input("Input a number to compute the factorial : ")) 
print(factorial(number))
# Output:
Input a number to compute the factorial : 5
120

Explanation of the Program:

To implement this functionality, we use the concept of recursion with the base condition. Here we make a function named factorial that takes a number as an input and then recursively calls the same function up to we reach the base condition included in that function.

To understand the recursive definition of the program, let’s understand the below image:

Recursive Functions in Python with Examples - Dot Net Tutorials

                                                      Image Source: Link

The running of the above recursive program is done in the following manner:

Recursion In C - Subhash Programming Classes Python Functions

                                            Image Source: Link

 

Advantages of Functions in Python

The advantages of Python functions are as follows:

  • With the help of functions, we can avoid rewriting the same logic or code again and again in a program.
  • In a single Program, we can call Python functions anywhere and also call multiple times.
  • We can track a large Python program easily when it is divided into multiple functions.
  • The main achievement of Python functions is its Reusability.
  • However, In a Python program, Function calling is always overhead.

Other Blog Posts by Me

You can also check my previous blog posts.

Previous Data Science Blog posts.

LinkedIn

Here is my Linkedin profile in case you want to connect with me. I’ll be happy to be connected with you.

Email

For any queries, you can mail me on [email protected]

End Notes

Thanks for reading!

I hope that you have enjoyed the article. If you like it, share it with your friends also. Something not mentioned or want to share your thoughts? Feel free to comment below And I’ll get back to you. 😉

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

I am a B.Tech. student (Computer Science major) currently in the pre-final year of my undergrad. My interest lies in the field of Data Science and Machine Learning. I have been pursuing this interest and am eager to work more in these directions. I feel proud to share that I am one of the best students in my class who has a desire to learn many new things in my field.

Responses From Readers

Clear

Wouters Marc
Wouters Marc

Very clear explanation ! Thanks

Arun
Arun

Hi, I am 18 yrs experienced IT professional. I am a technical lead and considering Python certification. Which one is official and recognized? Does Python developer have better paying jobs in USA

Lilith Karri
Lilith Karri

Well articulated information 👏. Your blog is exceptionally good for beginners who are interested to learn Python. Bro please do the same for Loops and transformers and for all the topics. This kind of root level knowledge will help us to learn and build Python foundations.

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details