Table of Contents
A function is considered a block that will run a particular task. Let’s look into the article to learn more about Python Functions.
What are Python Functions?
Python Functions are the blocks of statements that will return the specific task. The main goal is to put some repeatedly done tasks together and thus, create a function. This will allow us to write the code repeatedly for several inputs. Hence, we do this function calls to reuse code in it repeatedly.
What is the Syntax of Python Function Declaration?
The syntax of the Python Function declaration is given below:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
What are the types of Functions in Python?
1. Built-in Library Function- This is known as the standard function in Python which is available to utilize.
2. User-defined Function- Through this, it is possible to make our functions depending on the requirements.
Creating a Function in Python
Python function can be defined using the def keyword. According to the requirements, you can add any types of functionalities and properties to it.
Look at the example given below:
# A simple Python function
def fun():
print("Welcome to SV")
Calling a Python Function
Thus, after creating the function. It can be named with the name of the function and is followed by the parenthesis that has parameters of the specific function.
# Define a function
def greet(name):
return f"Hello, {name}!"
# Call the function
result = greet("John")
# Print the result
print(result)
Output
Hello, John!
Python Function with Parameters
In Python, the return type of the function and data type of arguments is possible. This function is possible in Python and in several versions of Python including Python 3.5 and above.
Defining and Calling a function with Parameters
The syntax is provided below:
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
Example
# Define a function with parameters
def add_numbers(a, b):
result = a + b
return result
# Call the function with arguments
sum_result = add_numbers(5, 7)
# Print the result
print("Sum:", sum_result)
Output
Sum: 12
What is Python Function Arguments
Arguments are referred to as the value that will be passed inside the parenthesis of the function. The function consists of the number of arguments that are separated by a comma.
Look into the example given below:
# Function to check if a number is even or odd
def even_or_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
# Function with default argument (exponent) using even or odd numbers
def power(base, exponent=2):
return base ** exponent
# Calling functions with even and odd numbers
number_to_check = 7
result_even_odd = even_or_odd(number_to_check)
power_result = power(number_to_check, exponent=3) # Using odd number with a different exponent
# Printing the results
print(f"{number_to_check} is {result_even_odd}")
print(f"Power of {number_to_check} to the 3rd exponent:", power_result)
Output
7 is Odd
Power of 7 to the 3rd exponent: 343
What are the types of Python Function Arguments?
It is known that Python will allow several types of arguments that will be passed at the time of a function call. In Python, there are 4 types of function calls.
a. Default argument
b.Keyword argument
c. Positional argument
d. Arbitrary argument
What is a Default Argument?
The default argument is referred to as a parameter that will predict a default value when the value is not assigned in the function call for the argument.
# Function with default argument
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# Calling the function with and without providing the default argument
result1 = greet("Alice") # Uses the default greeting
result2 = greet("Bob", "Hi") # Provides a custom greeting
# Printing the results
print(result1)
print(result2)
Output
Hello, Alice!
Hi, Bob!
What is Keyword Argument?
In Python, the keyword Argument will allow the caller to mention the argument name along with the values, in which it is not required to remember the order of parameters.
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname='Skill', lastname='Vertex')
student(lastname='Vertex', firstname='Skill')
What are Positional Arguments?
The Position Arguments is used during the function call as the first argument will be given a name, and the second argument will be provided to age.
Example
# Function with positional arguments
def add_numbers(a, b):
result = a + b
return result
# Calling the function with positional arguments
sum_result = add_numbers(5, 7)
# Printing the result
print("Sum:", sum_result)
Output
Sum: 12
What is Docstring?
The first string after the function is referred to as the document string. The main goal of this Docstring is to define the functionality of the function.
The syntax of Docstring is given below:
Syntax: print(function_name.__doc__)
Example
def greet(name):
"""
This function takes a name as a parameter and returns a greeting message.
Parameters:
- name (str): The name of the person to greet.
Returns:
str: A greeting message.
"""
return f"Hello, {name}!"
# Accessing the docstring
print(greet.__doc__)
# Calling the function
result = greet("Alice")
# Printing the result
print(result)
Output
This function takes a name as a parameter and returns a greeting message.
Parameters:
- name (str): The name of the person to greet.
Returns:
str: A greeting message.
Hello, Alice!
What are Recursive Functions in Python?
Recursive in Python will be used when a function calls by itself. Hence, it states that it is required to create the recursive function to solve the Mathematical and Recursive Problems.
def factorial(n):
"""
Recursive function to calculate the factorial of a number.
Parameters:
- n (int): The number for which to calculate the factorial.
Returns:
int: The factorial of the input number.
"""
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Calling the recursive function
result = factorial(5)
# Printing the result
print("Factorial:", result)
Output
Factorial: 120
Note: Use the Recursive function with a warning, as it will turn into a/ non-terminating loop.
What is a Return Statement in Python Function?
The return statement functions to exit from the function and return back to the function caller . Thus it will get a specified value
The syntax is provided below
return [expression_list]
Example
def add_numbers(a, b):
"""
This function takes two numbers as parameters and returns their sum.
Parameters:
- a (int): The first number.
- b (int): The second number.
Returns:
int: The sum of the two numbers.
"""
result = a + b
return result
# Calling the function and storing the result
sum_result = add_numbers(3, 7)
# Printing the result
print("Sum:", sum_result)
Output
Sum: 10
What is Pass by Reference and Pass by Value?
In Python, every variable name has a reference. In which, when the variable is passed, then the new reference of the object is made. Parameter passing in Python is considered similar to that of reference passing in Java.
# Pass by assignment example
# Function modifying a mutable object (list)
def modify_list(my_list):
my_list.append(4)
my_list[0] = 99
# Function modifying an immutable object (integer)
def modify_integer(my_integer):
my_integer = 10
# Original list and integer
original_list = [1, 2, 3]
original_integer = 5
# Call functions with the original objects
modify_list(original_list)
modify_integer(original_integer)
# Print the original objects after function calls
print("Modified List:", original_list) # [1, 2, 3, 4, 99]
print("Modified Integer:", original_integer) # 5
Output
Modified List: [1, 2, 3, 4, 99]
Modified Integer: 5
Conclusion
In summary, Python functions are versatile tools that help organize code into reusable and manageable blocks. They allow developers to define specific tasks or operations that can be executed with different inputs. With parameters, default values, and return statements, functions provide flexibility in handling various scenarios.
Additionally, docstrings serve as valuable documentation to understand a function’s purpose and usage.
Python Functions- FAQs
Q1.What is a Python function?
Ans. It is referred to as a block of statements that does a particular task.
Q2. How to define a function?
Ans. The relation between a set of inputs having one output each will define the function.
Q3. What is a def in Python example?
Ans. def is referred to as a block keyword that is followed by the function name and the block name.
Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together