Python Functions are a block of statements that does a specific task. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.

Defining a Function
We can define a function in Python, using thedef keyword. A function might take input in the form of parameters.
The syntax to declare a function is:
Syntax of Python Function DeclarationHere, we define a function using def that prints a welcome message when called.
Pythondeffun():print("Welcome to GFG")Calling a Function
After creating a function in Python we can call it by using the name of the functions followed by parenthesis containing parameters of that particular function.
Pythondeffun():print("Welcome to GFG")fun()# Driver code to call a functionFunction Arguments
Arguments are the values passed inside the parenthesis of the function. A function can have any number of arguments separated by a comma.
Syntax:
def function_name(parameters):
"""Docstring"""
# body of the function
return expression
We will create a simple function in Python to check whether the number passed as an argument to the function is even or odd.
PythondefevenOdd(x):if(x%2==0):return"Even"else:return"Odd"print(evenOdd(16))print(evenOdd(7))
Types of Function Arguments
Python supports various types of arguments that can be passed at the time of the function call. In Python, we have the following function argument types in Python, Let's explore them one by one.
1. Default Arguments
Adefault argument is a parameter that assumes a default value if a value is not provided in the function call for that argument.
PythondefmyFun(x,y=50):print("x: ",x)print("y: ",y)myFun(10)2. Keyword Arguments
In keyword arguments, values are passed by explicitly specifying the parameter names, so the order doesn’t matter.
Pythondefstudent(fname,lname):print(fname,lname)student(fname='Geeks',lname='Practice')student(lname='Practice',fname='Geeks')
OutputGeeks PracticeGeeks Practice
3. Positional Arguments
In positional arguments, values are assigned to parameters based on their order in the function call.
PythondefnameAge(name,age):print("Hi, I am",name)print("My age is ",age)print("Case-1:")nameAge("Suraj",27)print("\nCase-2:")nameAge(27,"Suraj")OutputCase-1:Hi, I am SurajMy age is 27Case-2:Hi, I am 27My age is Suraj
4. Arbitrary Arguments
In Python Arbitrary Keyword Arguments,*args and **kwargs can pass a variable number of arguments to a function using special symbols. There are two special symbols:
- *args in Python (Non-Keyword Arguments)
- **kwargs in Python (Keyword Arguments)
This code separately shows non-keyword (*args) and keyword (**kwargs) arguments in the same function.
PythondefmyFun(*args,**kwargs):print("Non-Keyword Arguments (*args):")forarginargs:print(arg)print("\nKeyword Arguments (**kwargs):")forkey,valueinkwargs.items():print(f"{key} =={value}")# Function call with both types of argumentsmyFun('Hey','Welcome',first='Geeks',mid='for',last='Geeks')OutputNon-Keyword Arguments (*args):HeyWelcomeKeyword Arguments (**kwargs):first == Geeksmid == forlast == Geeks
Function within Functions
A function defined inside another function is called aninner function (or nested function). It can access variables from the enclosing function’s scope and is often used to keep logic protected and organized.
Pythondeff1():s='I love GeeksforGeeks'deff2():print(s)f2()f1()
OutputI love GeeksforGeeks
Anonymous Functions
In Python, ananonymous 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.
Pythondefcube(x):returnx*x*x# without lambdacube_l=lambdax:x*x*x# with lambdaprint(cube(7))print(cube_l(7))
Return Statement in Function
Thereturnstatement ends a function and sends a value back to the caller. It can return any data type, multiple values (packed into a tuple), or None if no value is given.
Syntax:
return [expression]
Parameters: returnends the function, [expression]is the optional value to return (defaults to None).
Pythondefsquare_value(num):"""This function returns the square value of the entered number"""returnnum**2print(square_value(2))print(square_value(-4))
Pass by Reference and Pass by Value
In Python, variables are references to objects. When we pass them to a function, the behavior depends on whether the object is mutable (like lists, dictionaries) or immutable (like integers, strings, tuples).
- Mutable objects: Changes inside the function affect the original object.
- Immutable objects: The original value remains unchanged.
Python# Function modifies the first element of listdefmyFun(x):x[0]=20lst=[10,11,12,13]myFun(lst)print(lst)# list is modified# Function tries to modify an integerdefmyFun2(x):x=20a=10myFun2(a)print(a)# integer is not modified
Note:Technically, Python uses "pass-by-object-reference". Mutable objects behave like pass by reference, while immutable objects behave like pass by value
Recursive Functions
Arecursive function is a function that calls itself to solve a problem. It is commonly used in mathematical and divide-and-conquer problems. Always include a base case to avoid infinite recursion.
Pythondeffactorial(n):ifn==0:return1else:returnn*factorial(n-1)print(factorial(4))
Here we have created a recursive function to calculate the factorial of the number. It calls itself until a base case (n==0) is met.
Related Links:
Recommended Problems:

Python Functions

How Functions Work in Python

Applications of Functions.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice