Introduction

One of the most important concepts of programming is to understand is functions. Functions are essential building blocks in any programming language, including Python. They allow you to break down complex tasks into smaller, more manageable pieces of code that can be reused and organized more efficiently. In this tutorial, we will explore what functions are, how they work in Python, and why they are so useful. By the end of this tutorial, you'll be able to create your own Python functions and use them to streamline your code and make it more modular. So, let's get started!

What is a Function?

  • A function is a subprogram that performs a specific task. 
  • In other words a function is a code block that is written to accomplish a particular task.
  • This code block has a unique name.
  • When need arises in the main program to perform this task, we can directly call the function.
  • The function can be called by using its name.
  • In this way this code block can be reused again and again.
  • When a function is called, the computer executes the code in the function. 
  • Once the function's task is complete, 
    • the control comes back to place from where the function was called.
    • and the execution of the program continues from next line as normal.
  • The function can also return a value to the calling code.
  • This returned value is usually stored in some variable.
  • The function can take arguments
  • The arguments are the values that are passed to the function. 
  • Sample code : Below is a sample code of a simple function in Python that 
    • adds two numbers. 
    • It then returns the sum to the calling code.

# Defining function add
def add(a, b): 
	sum = a + b
	return sum

x = int(input("Enter the first number : "))
y = int(input("Enter the second number : "))

# calling the function add
s = add(x, y)  

print("The sum of the two numbers is : ", s)

# Output
# Enter the first number : 2
# Enter the second number : 4
# The sum of the two numbers is :  6

# Here add(a, b) is a function
# The function add takes two parameters 'a' and 'b'
# Values for a, b should be passed at the time of calling
# This function is called in the line s = add (x, y)
# x and y are the arguments passed to the function
# function add finds the sum of the two values
# It then returns the sum to the calling code.
# The calling code stores the value returned in the variable s

Prev. Tutorial : Enumerate function

Next Tutorial : Functions in Python