What is Function?
The function is a block of code that performs a specific task. In Python programming define a function we use the def keyword. The function provides reusable pieces of code. The function is mainly two types:
- Built-in functions
- User-defined functions
Built-in functions:
These functions are defined and pre-coded in Python. Some examples of built-in functions are as follows:
- min()
- max()
- len()
- sum()
- type()
- range()
- dict()
- list()
- tuple()
- set()
- print()
User-defined functions:
That function is defined by the developer according to the user’s requirement, that is user-defined functions. In Python using def keywords we can create functions. Let’s see how we can create functions:
Syntax:
def function_name(parameters):
# Function body
# Code to perform a specific task
Example:
def greet():
# This function greets the user with the provided name.
print("Hello Priti!")
# Function call
greet()
we will call by function name to execute the block of code.
The Output Of This Code Will Be:
Hello Priti!
Function With Parameters:
We can specify the parameters in the function definition. Parameters are the values that the function receives when you call it. Let’s see the example:
def greet(name):
# This function greets the user with the provided name.
print("Hello", name)
# Function call
greet("Priti)
The Output Of This Code Will Be:
Hello Priti!
Let’s see another example for a better understanding.
def add_numbers(x, y):
sum_result = x + y
print (sum_result)
# Function call
add_numbers(5, 3)
In this example, the add_numbers function has two parameters, x and y. When calling the function [add_numbers(5, 3)] we can pass the value. This is called arguments and x, and y are parameters.
The Output Of This Code Will Be:
8
Return Statement:
The function can return a result. The return keyword is used to return some value from the function. User-defined functions help in making your code modular, and they assist you in managing a task by dividing it into different functions. Let’s see an example:
def add_numbers(x, y):
sum_result = x + y
return sum_result
# Function call
result = add_numbers(5, 3)
print("Sum:", result)
The Output Of This Code Will Be:
Sum: 8
Default Arguments:
We can set default values in the function. If we do not provide any values at function calling time this default value will be used.
def greet_with_name(name="Guest"):
print("Hello, " + name + "!")
# Call the function:
greet_with_name()
greet_with_name("Shivam")
The Output Of This Code Will Be:
Hello, Guest!
Hello, Shivam!
If you don’t know the most important topic from the interview point of view “Break and Continue Statement In Python” just click on read more.
I hope you understand Functions in Python. If you do not understand this topic just comment below with your email ID, and I will mail back to you.