Quantcast
Channel: Cloud Training Program
Viewing all articles
Browse latest Browse all 1891

Python Functions: Overview, Types, Arguments, Doctstirng

$
0
0

In this blog, we are going to cover a brief overview of Python Functions, the syntax to create and call a function, types of arguments, docstring, and more.

Table of Content:

  1. Python Functions Overview
  2. Why Functions are needed?
  3. Basic Syntax
  4. Python Function Arguments
  5. Docstring
  6. Return Statement
  7. Anonymous Function

Python Functions Overview

Python Functions is a block of related statements designed to perform a computational, logical, or evaluative task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code multiple times for different inputs, function calls can be done to reuse the code contained in it numerous times.

functions representation

Functions can be both built-in or user-defined. It helps the program to be concise, non-repetitive, and organized.

Mainly, there are three types of functions:

  • User-defined functions – functions defined by a user to perform a specific task.
  • Built-in functionspre-defined functions in python.
  • Anonymous functions (also known as lambda functions)– they are not declared with the standard-def keyword.

Why Functions Are Needed?

Virtually all programming languages support a form of user-defined functions (the name may differ). In other languages, you may see them referred to as one of the following:

  • Subroutines
  • Procedures
  • Methods
  • Subprograms

So, now the question arises that why should we bother defining the functions? Here are a few reasons:

  • Abstraction & Reusability
  • Modularity: Functions allow complex processes to be broken up into smaller steps.
  • Namespace Separation: A namespace is a region of a program in which identifiers have meaning. When a Python function is called, a new namespace is created for that function, one that is distinct from all other namespaces that already exist.

Functions: Basic Syntax

Let’s understand the basic syntax of a function and its working.

Syntax:

def function_name(parameters):
    """docstring"""
    statement(s)
    return expression

Above shown is a function definition that consists of the following components.

  1. Keyword def marks the start of the function header.
  2. A function name to uniquely identify the function.
  3. Parameters (arguments) through which we pass values to a function. They are optional.
  4. A colon (:) to mark the end of the function header.
  5. Optional documentation string (docstring) to describe what the function does.
  6. One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
  7. An optional return statement to return a value from the function.

Python Function Syntax

Create A Python Function

We can create a  Python function using the def keyword.

def my_function():
  print("Hello from a function")

Calling A Function

After creating a function we can call it by using the name of the function followed by parenthesis containing parameters of that particular function.

def my_function():
  print("Hello from a function")

#driver code to call python function
my_function()

Note: In python, the function definition should always be present before the function call.

Arguments In Python Functions

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.

# 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))

Python Functions Argument Passing

Types of Arguments

Python Functions supports various types of arguments that can be passed at the time of the function call. Let’s discuss each type in detail.

1.) Default Arguments

A default argument is a parameter that assumes a default value if a value is not provided in the function call for that argument.

# Python program to demonstrate default arguments

def Func(x, y=100):
    print("x: ", x)
    print("y: ", y)
 
# Driver code (We call Func() with only argument)
Func(20)

Default Argument

2.) Keyword Arguments

The idea is to allow the caller to specify the argument name with values so that caller does not need to remember the order of parameters.

# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
    print(firstname, lastname)
 
# Keyword arguments
student(firstname='K21', lastname='Academy')
student(lastname='Academy', firstname='K21')

Keyword Argument

3.) Variable-length Arguments

In Python, we can pass a variable number of arguments to a function using special symbols. There are two special symbols:

  • *args (Non-Keyword Arguments)
# Python program to illustrate *args for variable number of arguments
 
def Func(*argv):
    for arg in argv:
        print(arg)
 
Func('Hello', 'Welcome', 'to', 'K21Academy')

Variable length argument: args

  • **kwargs (Keyword Arguments)
# Python program to illustrate *kargs for variable number of keyword arguments

def Func(**kwargs):
    for key, value in kwargs.items():
        print("%s == %s" % (key, value))

# Driver code
Func(first='Welcome', mid='to', last='K21Academy')

Variable length argument: kwargs

Docstring

The first string after the function is called the Document string or Docstring in short. This is used to describe the functionality of the function. The use of docstring in functions is optional but it is considered a good practice.

The below syntax can be used to print out the docstring of a function:

Syntax: print(function_name.__doc__)

# A simple Python function to check whether x is even or odd
 
def evenOdd(x):
    """Function to check if the number is even or odd"""
     
    if (x % 2 == 0):
        print("even")
    else:
        print("odd")
 
# Driver code to call the function
print(evenOdd.__doc__)

Python Functions: Docstring

Return Statement

The python function return statement is used to exit from a function and go back to the function caller and return the specified value or data item to the caller.

Syntax: return [expression_list]

def square_value(num):
    """This function returns the square
    value of the entered number"""
    return num**2

print(square_value(2))
print(square_value(-4))

Python Function: return statement

Anonymous Function (lambda function)

In Python, an anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.

# Python code to illustrate the cube of a number using lambda function
 
def cube(x): return x*x*x
 
cube_v2 = lambda x : x*x*x
 
print(cube(7))
print(cube_v2(7))

Anonymous or lambda function

> Is Python Function Pass by Reference or pass by value?

One of the most commonly asked questions in interviews is that python functions are passed by reference or by value. So here is the explanation:

In Python, every variable name is a reference. When we pass a variable to a function, a new reference to the object is created. Parameter passing in Python is the same as reference passing in Java.

pass by reference

> Can we have a Python Function within Functions?

Yes, we can have. A function that is defined inside another function is known as the inner function or nested function. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function.

This was all a brief overview of the Python Functions. Stay tuned for more such blogs covering basic python concepts!

Related References

Next Task For You…

Python’s growth is very promising in the near future. Gaining the right skills through the right platform will get you to the perfect job.

We are launching our course Python For Data Science (AI/ML) & Data Engineers (Python For Beginners) which will you help and guide you towards your first steps to Python.  Join our FREE CLASS to know more about it.

Free Class Python

The post Python Functions: Overview, Types, Arguments, Doctstirng appeared first on Cloud Training Program.


Viewing all articles
Browse latest Browse all 1891

Trending Articles