Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Go Programs
    • Python Programs
    • Java Programs

Functions in Python

by suresh

Python Function is a piece of code or any logic that performs the specific operation. We already saw some Python functions until now, and you may not notice them. For instance, print(), factorial(), round(), etc., are few of the built-in functions in Python programming language.

Let us see the Function definition, declaration, syntax, and example of using functions in Python.

Types of Functions in Python

There are two types of functions in the Python Programming language:

  • Library Functions: Built-in functions in Python Programming Language called a Library function. We don’t have to bother about the logic inside the Library functions. In our previous articles, We used many library functions such as print(), factorial(), round() etc.
  • User Defined Functions: Instead of relying on built-in functions, Python programming language allows us to create our own functions called as user defined functions. For example, if we want to implement some mathematical calculations, then put them in separate functions with the correct function name. Then we can call that function multiple times.

Advantages of functions in Python

  1. It helps to divide the large programs into small groups so that we can read the code, and debug the program faster and better.
  2. Python Functions stop us from writing the same logic various times. We can bind the logic in one function and then call the same over and over.
  3. Many persons can work on the same program by assigning different functions to each of them.
  4. It encourages us to call the same function with different inputs over multiple times.

Python Functions Syntax

The syntax of the Functions in Python Programming is

def Function_Name (Parameters):
        Local Variable Declaration
        Programming Logic
        Executable Statement 1
        ……
        return
  • def: Keyword def is the introduction to the function definition. Remember, the Python def keyword must immediately follow by Function_Name.
  • Function_Name: It can be any name you wish to give other than the system reserved keywords.
  • Parameters: Every python function accepts 0 or more parameters. It completely depends upon the user requirements.
  • Local Variable Declaration: Sometimes, we may need some temporary variable only for that particular function, then we can declare them inside the function. It is not compulsory, entirely depends upon user requirements. Remember, these variables are available to this particular function only, and we can’t access them outside the function.
  • Logic: Any mathematical or any code or calculations you need to implement in this particular function.
  • Executable Statement: Any print statements to print some data from this particular function.
  • return: This keyword is required to return something from the function. For example, returning the sum of two integers, etc.

User Defined Functions in Python implementation

To implement the user defined functions in the Python program, we have to follow a few rules, such as:

Python Function Declaration

It informs about the function name and number of arguments.

def Function_Name (Parameters):

For example,

def Add(a, b):

Python Function call

Nothing, but calling the original function with a valid number of arguments. For example, Add (2, 3). And remember, User defined function name should exactly match with the calling function.

Function Definition

It is the place where we are going to put all the logic, calculations, etc. For example,

def Adding(a, b):
    Sum = a + b
    return Sum
print("After Calling the Function:", Adding(3, 4))
Functions in Python 1

NOTE: Please don’t forget the return keyword, otherwise the program not return anything.

Python Function to find Sum and Average of 3 Numbers

In this functions program, the user asked to enter three numbers. Then by calling the function, we calculate the Sum and Average of that three numbers.

# Functions Example
def sumAndAverage(x, y, z):
    Sum = x + y + z
    Average = Sum/3
    print("\n %d is the Total Sum of three Numbers." %Sum)
    print("\n %d is the Average of three Numbers.\n" %Average)
    
# Allows User to enter three values
a = int(input("\nPlease Enter the First Value. a =  "))
b = int(input("\nPlease Enter the Second Value. b =  "))
c = int(input("\nPlease Enter the Third Value. c =  "))

# Calling the Function
sumAndAverage(a, b, c)
sumAndAverage(10, 20, 30)
Functions in Python 2

It is called a function declaration. If you forget this function declaration, then it throws an error.

def sumAndAverage(x, y, z):

The below statements ask the user to enter 3 numbers and store the user input values in a, b, c variables

a = int(input("\nPlease Enter the First Value. a =  "))
b = int(input("\nPlease Enter the Second Value. b =  "))
c = int(input("\nPlease Enter the Third Value. c =  "))

In the next line, we are calling the function multiple times. First, with user-specified values, and then static 10, 20, 30.

sumAndAverage(a, b, c)
sumAndAverage(10, 20, 30)

When it reaches this function, it traverses to check for the sumAndAverage() function. If the function fails to identify the function name, then it throws an error.

Function Definition

Within the Python function,

def sumAndAverage(x, y, z):
    Sum = x + y + z
    Average = Sum/3

We declared 2 local variables, Sum and Average. In the next line, we calculated the sum and average of three numbers using Assignment Operators.

Sum = x + y + z
Sum = 10 + 20 + 30 = 60

Average = Sum / 3
Average = 60 / 3 = 20

The below print statements are to print the sum and average to the output.

 print("\n %d is the Total Sum of three Numbers." %Sum)
 print("\n %d is the Average of three Numbers.\n" %Average)

In the next line, We called Average() one more time, this time, we passed local variables as function arguments. We called 2 times because it helps you to understand that, we can call the function n number of times.

Placed Under: Python

  • Download and Install Python
  • Python Arithmetic Operators
  • Python Assignment Operators
  • Python Bitwise Operators
  • Python Comparison Operators
  • Python Logical Operators
  • Python If Statement
  • Python If Else
  • Python Elif Statement
  • Python Nested If
  • Python For Loop
  • Python While Loop
  • Python Break
  • Python Continue
  • Python Dictionary
  • Python datetime
  • Python String
  • Python Set
  • Python Tuple
  • Python List
  • Python List Comprehensions
  • Python Lambda Function
  • Python Functions
  • Python Types of Functions
  • Python Iterator
  • Python File Handling
  • Python Directory
  • Python Class
  • Python classmethod
  • Python Inheritance
  • Python Method Overriding
  • Python Static Method
  • Connect Python and SQL Server
  • Python SQL Create DB
  • Python SQL Select Top
  • Python SQL Where Clause
  • Python SQL Order By
  • Python SQL Select Statement
  • Python len Function
  • Python max Function
  • Python map Function
  • Python print Function
  • Python sort Function
  • Python range Function
  • Python zip Function
  • Python Math Functions
  • Python String Functions
  • Python List Functions
  • Python NumPy Array
  • NumPy Aggregate Functions
  • NumPy Arithmetic Operations
  • Python Numpy Bitwise operators
  • Numpy Comparison Operators
  • Numpy Exponential Functions
  • Python Numpy logical operators
  • Python numpy String Functions
  • NumPy Trigonometric Functions
  • Python random Array
  • Python numpy concatenate
  • Python numpy Array shape
  • Python pandas DataFrame
  • Pandas DataFrame plot
  • Python Series
  • Python matplotlib Histogram
  • Python matplotlib Scatter Plot
  • Python matplotlib Pie Chart
  • Python matplotlib Bar Chart
  • Python List Length
  • Python sort List Function
  • Python String Concatenation
  • Python String Length
  • Python substring
  • Python Programming Examples

Copyright © 2021 · All Rights Reserved by Suresh

About Us | Contact Us | Privacy Policy