Python Tutorial

Introduction Python Features Python Applications System requirements for Python Python Installation Python Basics Python Variables Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python If-else statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Lists vs Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Anonymous/Lambda Function in Python

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Classes & Objects in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor Static Variables in Python Abstraction in Python

Python Iterators

Iterators in Python Yield Statement In Python

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Calendar Module  

Python MySQL

Python MySQL Python MySQL Update Operation Python MySQL Delete Operation

Python MongoDB

Python MongoDB

Python Data Structure Implementation

Python Stack Python Queue Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Collections in python Python Enumerate Python Debugger Python DefaultDict

Misc

Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering List Comprehension in Python3 NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Logical Operators Python Multiprocessing Python History Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Design patterns in python Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python Abstract design pattern in python Builder design pattern in python Prototype design pattern in Python Creational design patterns in Python

How to

How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python Singleton design pattern in python

Python Function

Python Function

A Python function is a reusable, organized block of code that is used to perform the specific task. The functions are the appropriate way to divide an extensive program into a useful block. It also provides reusability to our program. A code block can be reused by calling the function.

All functions are treated as an object in Python, so it is more flexible than other programming languages.

 In Python, there are two types of functions:

  • Built-in functions – These functions are the part of the Python libraries and packages. These are also called as pre-defined functions. You can learn it from here.( https://www.tutorialandexample.com/python-built-in-functions/)
  • User-defined functions – These functions are defined by the user as per their requirement. We will learn the user-defined function in this tutorial.

Creating a function

Below are the basic steps to create a user-defined function.

  • The def keyword is used to define function followed by the function name.
  • Arguments should be written inside the opening and closing parentheses of the function, and end the declaration with a colon.
  • Write the program statements to be executed within the function body.
  • The return statement is optional. It should be written at the end of the function.

The syntax is given below:

def function_name(argument list):
    The function body
     ………………
     ………………     
     return 

The argument list can contain none or more arguments. The arguments are also called parameters. The function body contains indented statements. The function body gets executed whenever the function is called.  The arguments can be optional or mandatory.

Calling a Function

After declaring a function, it must be called using function name followed by parentheses with appropriate argument.

Note: It is necessary to define a function before calling; otherwise, it will give an error.

Consider the following examples:

Example-1

def hello():

    print('Hello')

hello()

Output:

Hello

Example-2

def sum(a,b):
 # define a function sum with two argument
    c=a+b
    return c 
 #returning the value to calling function

z=sum(10,20)
print("The sum is:",z) 

Output:

The sum is: 30

Parameter Passing

There are two most common strategies of passing an argument to a function.

  • Call by Value

This strategy is used in C, C++ or Java but not used in Python. In call by value, the values of actual parameters are copied to function’s formal parameters, and both types of parameters are stored in separate memory locations. So if we made any changes in formal parameters, that changes will not be reflected in actual parameters of the caller function.

  • Call by Reference

The functions are called by reference in Python, which means all the changes performed to the inside the function reflected in an actual parameter.

Consider the following examples:

Example 1:

def mul(m,n):
    c=m*n
    return c
a=int(input("Enter the number:"))
b=int(input("Enter the number:"))
z=mul(a,b)
print("The multiply is:",z)

Output:

Enter the number: 60
Enter the number: 50
The sum is: 110 

In the above program, defined function is mul(m,n), where m and n are formal arguments, and caller function is mul(a,b), where a and b are the actual argument.

Example-2

 Write a program to take a list and return list with a unique element

def dup_list(list):

    list1=[]

    for i in list:

        if i not in list1:

            list1.append(i)

    return list1

list = [1,1,2,1,3,3,4,4,5,6,5,7]
print('The duplicate list is:',list)

z=dup_list(list)

print('The unique list is:',z)

Output:

The duplicate list is:[1,1,2,1,3,3,4,4,5,6,5,7]
The unique list is: [1, 2, 3, 4, 5, 6, 7]  

Types of arguments

There may be several types of arguments, which are listed below

  1. Required arguments
  2. Default arguments
  3. Keyword arguments
  4. Variable-length arguments
  1. Required Arguments

The required arguments are those arguments which are mandatory to pass at the time of function calling with exact match their positions in the function call and function definition. If the argument is not provided in the function call or made any changes in arguments position, then Python interpreter will show an error.

Example 1

def sqr_list(list):

    emp_list= []

    for i in list:

        emp_list.append(i**2)

    print(emp_list)



sqr_list([1,2,3,4,5,6,7,8,9,10])

Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 Example 2.

defsum(a,b):

    c=a+b

    return c
 
print(sum(20))#There is only one argument is passed. 

Output:

line 4, in <module>
     print(sum(20))
 TypeError: sum() missing 1 required positional argument: 'b' 
  •  Default argument

The default arguments are those arguments that assign a value with the argument at the time of function definition. If the argument is not specified at the time of function call, then it will be initialized with the value which was given in the definition. For example

Example 1

def student(name,age=21):
    print('My name is:',name)
    print('My age is',age)
student('Dev') #Here argument age is not passed default value is provided in definition
student('Himanshu',25) # The value of age is overwritten

Output:

My name is: Dev
My age is 21
My name is: Himanshu
My age is 25 
  • Keyword arguments

The benefit of keyword arguments is that we can pass the argument in the random order, which means the order of passing arguments doesn’t matter. Each argument treated as the keyword. It will match argument names in the function definition and function call.  If

 Example-1

def employee(id,name,age):

    print('Employee Id:',id,'\nEmployee
Name:',name,'\nEmployee
Age:',age)

employee(age=30,id=1,name='Sushant')

Output:

Employee Id: 1 
Employee Name: Sushant 
Employee Age: 30 

In the above program, we have passed the arguments in a different order in function calls. The name of arguments must be the same as function definition; otherwise, it will show an error.

  • We can pass keyword argument and required argument together. For example:
def employee(name,amount,message):

    print(message,name,'amount
credited',amount)

employee('Robert',message='Hello',amount=20000)

Output:

Hello Robert amount credited 20000

In the above program, the first argument is the required argument followed by two keyword arguments.

Note: It is important to remember that required argument must not pass after keyword argument; otherwise, it will show an error.

  • Variable-length arguments

Sometimes we are not sure about numbers of argument that can be passed to a function, for such scenario, we use variable-length arguments.

There are two types of variable-length argument in a function:

  • *args (Non-Keyword argument)
  • *kwargs (Keyword argument)

*args (Non-Keyword argument)

Python provides *args which allows to pass the variable number of argument in a function.

We should use an asterisk ( * ) before the argument name to pass variable length arguments. The arguments are passed as a tuple, and these passed arguments make tuple inside the function with the same name as the argument excluding asterisk *. For example:

def variable(*names):

    for i in names:

        print(i)



variable('Devansh','Himanshu','Anubhav','Ashraf')

Output:

Devansh
Himanshu
Anubhav
Ashraf 

**kwarg arguments

We cannot pass the keyword argument using *args. Python provides **kwargs; It allows us to pass variable-length of keyword argument to the function.

We must use the double-asterisk ** before the argument name to denote this type of argument. The arguments are passed as a dictionary, and these arguments make a dictionary inside the function with name same as the parameter without double asterisk **. For example:

def variable(**names):

    for key,value in names.items():

        print(key,value)



variable(first_name="John",last_name='Wick',Age=25,Salary=34000)

Output:

first_name John
last_name Wick
Age 25
Salary 34000 

Lambda (Anonymous) Function

Python lambda is also known as an anonymous function, which means function is declared with no name. Lambda functions are different than a regular function. It has a more concise syntax. The syntax is following

lambda arguments : expression

The lambda is used to define an anonymous function. It can consist number of argument, but can consist only one expression.

z = lambda x:x**2

print("The square is:",z(10))

Output:

The square number is : 100

Scope of Variable

The scope of variables can be defined by the place where the variables have declared. Variables can be defined with two types of scope.

  1. Global Variable

The global variables are defined outside the function, hence global variables can be accessed throughout the program.

  • Local Variable

The local variables are defined inside the function, hence local variables can be accessed only inside the function.

Consider the following example:

Example-1 Global Variable

sum = 0
# variable defined outside the function
def add(a,b):
 sum = a+b #  the variable sum accessed inside the function
    print(sum)
add(54,65)
 print('The value of sum ouside the function:',sum) 

Output:

The sum is: 119
The value od sum ouside the function: 0 

Example-2 Local Variable

def mul(a,b):

    c = a*b # The variable c is defined inside the function

    print('The multiply is:',c)

mul(20,30)

print(c) # The variable c is local variable cannot access outside the function

Output:

The multiply is: 600
line 6, in <module>
NameError: name 'c' is not defined 



ADVERTISEMENT
ADVERTISEMENT