Python Functions
Python Functions are very easy to write in python and all non-trivial programs will have functions. Function names have the same rules as variable names. The function 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 again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.
Functions can be both built-in or user-defined. It helps the program to be concise, non-repetitive, and organized.
Syntax 1:
def function_name(parameters):
"""docstring"""
# body of the function
return expressionIf you have experience in C/C++ or Java then you must be thinking about the return type of the function and data type of arguments. That is possible in Python as well (specifically for Python 3.5 and above).
Syntax 2:
def function_name(parameter: data_type) -> return_type:
"""Doctring"""
# body of the function
return expressionCreating a Function
We can create a Python function using the def keyword.
Example: Define a function
Python3
# A simple Python functiondef fun(): print("Welcome to GFG") |
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.
Example: Python Calling Function
Python3
# A simple Python functiondef fun(): print("Welcome to GFG") # Driver code to call a functionfun() |
Welcome to GFG
Example: Define a function using syntax 2 and call it
The following example uses arguments that you will learn later in this article so you can come back on it again if not understood. It is defined here for people with prior experience in languages like C/C++ or Java.
Python3
def add(num1: int, num2: int) -> int: """Add two numbers""" num3 = num1 + num2 return num3# Driver codenum1, num2 = 5, 15ans = add(num1, num2)print(f"The addition of {num1} and {num2} results {ans}.") |
Some more examples are as follows:
Note: The following examples are defined using syntax 1, try to convert them in syntax 2 for practice.
Python3
# some more functionsdef is_prime(n): if n in [2, 3]: return True if n % 2 == 0: return False r = 3 while r * r <= n: if n % r == 0: return False r += 2 return Trueprint(is_prime(78), is_prime(79)) |
False True
Another example is as follows:
Python3
def vowel_count(s): """Counts the number of vowels in s and returns the same Ignores case of letters""" VOWELS = "aeiouAEIOU" vc = 0 for ch in s: if ch in VOWELS: vc += 1 return vcprint(vowel_count("GFG is the best platform to learn from.")) |
9
Arguments of a Function
Arguments are the values passed inside the parenthesis of the function. A function can have any number of arguments separated by a comma.
Example: Python Function with arguments
In this example, we will create a simple function to check whether the number passed as an argument to the function is even or odd.
Python3
# A simple Python function to check# whether x is even or odddef evenOdd(x): if (x % 2 == 0): print("even") else: print("odd")# Driver code to call the functionevenOdd(2)evenOdd(3) |
even odd
Types of Arguments
Python supports various types of arguments that can be passed at the time of the function call. Let’s discuss each type in detail.
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. The following example illustrates Default arguments.
Python3
# Python program to demonstrate# default argumentsdef myFun(x, y=50): print("x: ", x) print("y: ", y)# Driver code (We call myFun() with only# argument)myFun(10) |
x: 10 y: 50
Like C++ default arguments, any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values.
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.
Python3
# Python program to demonstrate Keyword Argumentsdef student(firstname, lastname): print(firstname, lastname)# Keyword argumentsstudent(firstname='Geeks', lastname='Practice')student(lastname='Practice', firstname='Geeks') |
Geeks Practice Geeks Practice
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)
- **kwargs (Keyword Arguments)
Example 1: Variable length non-keywords argument
Python
# Python program to illustrate# *args for variable number of argumentsdef myFun(*argv): for arg in argv: print(arg)myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks') |
Hello Welcome to GeeksforGeeks
Example 2: Variable length keyword arguments
Python3
# Python program to illustrate# *kwargs for variable number of keyword argumentsdef myFun(**kwargs): for key, value in kwargs.items(): print("%s == %s" % (key, value))# Driver codemyFun(first='Geeks', mid='for', last='Geeks') |
first == Geeks mid == for last == Geeks
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__)
Example: Adding Docstring to the function
Python3
# A simple Python function to check# whether x is even or odddef 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 functionprint(evenOdd.__doc__) |
Function to check if the number is even or odd
return statement:
The 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]
The return statement can consist of a variable, an expression, or a constant which is returned to the end of the function execution. If none of the above is present with the return statement a None object is returned.
Example: Python Function Return Statement
Python3
def square_value(num): """This function returns the square value of the entered number""" return num**2print(square_value(2))print(square_value(-4)) |
4 16
Is Python Function Pass by Reference or pass by value?
One important thing to note is, 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.
Example:
Python3
# Here x is a new reference to same list lstdef myFun(x): x[0] = 20# Driver Code (Note that lst is modified# after function call.lst = [10, 11, 12, 13, 14, 15]myFun(lst)print(lst) |
[20, 11, 12, 13, 14, 15]
When we pass a reference and change the received reference to something else, the connection between the passed and received parameter is broken. For example, consider the below program as follows:
Python3
def myFun(x): # After below line link of x with previous # object gets broken. A new object is assigned # to x. x = [20, 30, 40]# Driver Code (Note that lst is not modified# after function call.lst = [10, 11, 12, 13, 14, 15]myFun(lst)print(lst) |
[10, 11, 12, 13, 14, 15]
Another example to demonstrate that the reference link is broken if we assign a new value (inside the function).
Python3
def myFun(x): # After below line link of x with previous # object gets broken. A new object is assigned # to x. x = 20# Driver Code (Note that lst is not modified# after function call.x = 10myFun(x)print(x) |
10
Exercise: Try to guess the output of the following code.
Python3
def swap(x, y): temp = x x = y y = temp# Driver codex = 2y = 3swap(x, y)print(x)print(y) |
2 3
Anonymous functions:
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. Please see this for details.
Python3
# Python code to illustrate the cube of a number# using lambda functiondef cube(x): return x*x*xcube_v2 = lambda x : x*x*xprint(cube(7))print(cube_v2(7)) |
343 343
Python Function within Functions
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.
Python3
# Python program to# demonstrate accessing of# variables of nested functionsdef f1(): s = 'I love GeeksforGeeks' def f2(): print(s) f2()# Driver's codef1() |
I love GeeksforGeeks
Quick Links :
- Quiz on Python Functions
- Difference between Method and Function in Python
- First Class functions in Python
- Recent articles on Python Functions.

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.


.png)