- Python Basics
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python Control Statements
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Object & Classes
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Useful Resources
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
- Python - Programming Examples
- Python - Quick Guide
- Python - Useful Resources
- Python - Discussion
Python - Functions
A Python function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
A top-to-down approach towards building the processing logic involves defining blocks of independent reusable functions. A Python function may be invoked from any other function by passing required data (called parameters or arguments). The called function returns its result back to the calling environment.
Types of Python Functions
Python provides the following types of functions −
Functions defined in built-in modules
User-defined functions
Python's standard library includes number of built-in functions. Some of Python's built-in functions are print(), int(), len(), sum(), etc. These functions are always available, as they are loaded into computer's memory as soon as you start Python interpreter.
The standard library also bundles a number of modules. Each module defines a group of functions. These functions are not readily available. You need to import them into the memory from their respective modules.
In addition to the built-in functions and functions in the built-in modules, you can also create your own functions. These functions are called user-defined functions.
Defining a Python Function
You can define custom functions to provide the required functionality. Here are simple rules to define a function in Python.
Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement; the documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
Syntax to Define a Python Function
def functionname( parameters ): "function_docstring" function_suite return [expression]
By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.
Once the function is defined, you can execute it by calling it from another function or directly from the Python prompt.
Example to Define a Python Function
The following example shows how to define a function greetings(). The bracket is empty so there aren't any parameters.
The first line is the docstring. Function block ends with return statement. when this function is called, Hello world message will be printed.
def greetings(): "This is docstring of greetings function" print ("Hello World") return greetings()
Calling a Python Function
Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt.
Example to Call a Python Function
Following is the example to call printme() function −
# Function definition is here def printme( str ): "This prints a passed string into this function" print (str) return; # Now you can call printme function printme("I'm first call to user defined function!") printme("Again second call to the same function")
When the above code is executed, it produces the following output −
I'm first call to user defined function! Again second call to the same function
Pass by Reference vs Value
The function calling mechanism of Python differs from that of C and C++. There are two main function calling mechanisms: Call by Value and Call by Reference.
When a variable is passed to a function, what does the function do to it? If any changes to its variable doesnot get reflected in the actual argument, then it uses call by value mechanism. On the other hand, if the change is reflected, then it becomes call by reference mechanism.
C/C++ functions are said to be called by value. When a function in C/C++ is called, the value of actual arguments is copied to the variables representing the formal arguments. If the function modifies the value of formal aergument, it doesn't reflect the variable that was passed to it.
Python uses pass by reference mechanism. As variable in Python is a label or reference to the object in the memory, the both the variables used as actual argument as well as formal arguments really refer to the same object in the memory. We can verify this fact by checking the id() of the passed variable before and after passing.
def testfunction(arg): print ("ID inside the function:", id(arg)) var="Hello" print ("ID before passing:", id(var)) testfunction(var)
If the above code is executed, the id() before passing and inside the function is same.
ID before passing: 1996838294128 ID inside the function: 1996838294128
The behaviour also depends on whether the passed object is mutable or immutable. Python numeric object is immutable. When a numeric object is passed, and then the function changes the value of the formal argument, it actually creates a new object in the memory, leaving the original variable unchanged.
def testfunction(arg): print ("ID inside the function:", id(arg)) arg=arg+1 print ("new object after increment", arg, id(arg)) var=10 print ("ID before passing:", id(var)) testfunction(var) print ("value after function call", var)
It will produce the following output −
ID before passing: 140719550297160 ID inside the function: 140719550297160 new object after increment 11 140719550297192 value after function call 10
Let us now pass a mutable object (such as a list or dictionary) to a function. It is also passed by reference, as the id() of lidt before and after passing is same. However, if we modify the list inside the function, its global representation also reflects the change.
Here we pass a list, append a new item, and see the contents of original list object, which we will find has changed.
def testfunction(arg): print ("Inside function:",arg) print ("ID inside the function:", id(arg)) arg=arg.append(100) var=[10, 20, 30, 40] print ("ID before passing:", id(var)) testfunction(var) print ("list after function call", var)
It will produce the following output −
ID before passing: 2716006372544 Inside function: [10, 20, 30, 40] ID inside the function: 2716006372544 list after function call [10, 20, 30, 40, 100]
Python Function Arguments
The process of a function often depends on certain data provided to it while calling it. While defining a function, you must give a list of variables in which the data passed to it is collected. The variables in the parentheses are called formal arguments.
When the function is called, value to each of the formal arguments must be provided. Those are called actual arguments.
Example
Let's modify greetings function and have name an argument. A string passed to the function as actual argument becomes name variable inside the function.
def greetings(name): "This is docstring of greetings function" print ("Hello {}".format(name)) return greetings("Samay") greetings("Pratima") greetings("Steven")
It will produce the following output −
Hello Samay Hello Pratima Hello Steven
Types of Python Function Arguments
Based on how the arguments are declared while defining a Python function, they are classified into the following categories −
In the next few chapters, we will discuss these function arguments at length.
Order of Python Function Arguments
A function can have arguments of any of the types defined above. However, the arguments must be declared in the following order −
The argument list begins with the positional-only args, followed by the slash (/) symbol.
It is followed by regular positional args that may or may not be called as keyword arguments.
Then there may be one or more args with default values.
Next, arbitrary positional arguments represented by a variable prefixed with single asterisk, that is treated as tuple. It is the next.
If the function has any keyword-only arguments, put an asterisk before their names start. Some of the keyword-only arguments may have a default value.
Last in the bracket is argument with two asterisks ** to accept arbitrary number of keyword arguments.
The following diagram shows the order of formal arguments −
Python Function with Return Value
The return keyword as the last statement in function definition indicates end of function block, and the program flow goes back to the calling function. Although reduced indent after the last statement in the block also implies return but using explicit return is a good practice.
Along with the flow control, the function can also return value of an expression to the calling function. The value of returned expression can be stored in a variable for further processing.
Example
Let us define the add() function. It adds the two values passed to it and returns the addition. The returned value is stored in a variable called result.
def add(x,y): z=x+y return z a=10 b=20 result = add(a,b) print ("a = {} b = {} a+b = {}".format(a, b, result))
It will produce the following output −
a = 10 b = 20 a+b = 30