This article was published as a part of the Data Science Blogathon
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.
The topics which we will be covered in this article are as follows:
Image Source: Link
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:
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:
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()
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:
# 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.
# 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.
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.
# Defining the function def func (name): print("Hi ",name) # Calling the function func("Chirag")
Output:
Hi Chirag
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
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.
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.
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.
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.
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.
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:
Image Source: Link
The running of the above recursive program is done in the following manner:
Image Source: Link
The advantages of Python functions are as follows:
You can also check my previous blog posts.
Previous Data Science Blog posts.
Here is my Linkedin profile in case you want to connect with me. I’ll be happy to be connected with you.
For any queries, you can mail me on [email protected]
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. 😉
Very clear explanation ! Thanks
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
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.