Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Recursion in Python
Next article icon

Python Functions is 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.

Benefits of Using Functions

Python Function Declaration

The syntax to declare a function is:

Python Functions
Syntax of Python Function Declaration

Types of Functions in Python

Below are the different types of functions in Python:

Creating a Function in Python

We can define a function in Python, using thedef keyword. We can add any type of functionalities and properties to it as we require.

What is def ?

The def keywordstands for define. It is used to create a user-defined function. It marks the beginning of a function block and allows you to group a set of statements so they can be reused when the function is called.

Syntax:

def function_name(parameters):

# function body

Explanation:

Example:Let’s understand this with a simple example. Here, we define a function using def that prints a welcome message when called.

Python
deffun():print("Welcome to GFG")

For more information, refer to this article:Python def Keyword

Calling a Function in Python

After creating a function in Python we can call it by using the name of the functions Python followed by parenthesis containing parameters of that particular function. Below is the example for calling def function Python.

Python
deffun():print("Welcome to GFG")# Driver code to call a functionfun()

Output
Welcome to GFG

Python Function 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 for functions with arguments:

def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression

data_typeandreturn_typeare optional in function declaration, meaning the same function can also be written as:

def function_name(parameter) :
"""Docstring"""
# body of the function
return expression

Let's understand this with an example, we will create a simple function in Python to check whether the number passed as an argument to the function is even or odd.

Python
defevenOdd(x:int)->str:if(x%2==0):return"Even"else:return"Odd"print(evenOdd(16))print(evenOdd(7))

Output
EvenOdd

The above function can also be declared withouttype_hints, like this:

Python
defevenOdd(x):if(x%2==0):return"Even"else:return"Odd"print(evenOdd(16))print(evenOdd(7))

Output
EvenOdd

Types of Python 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:

  • Default argument
  • Keyword arguments (named arguments)
  • Positional arguments
  • Arbitrary arguments (variable-length arguments *args and **kwargs)

Let's discuss each type in detail. 

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. The following example illustrates Default arguments to write functions in Python.

Python
defmyFun(x,y=50):print("x: ",x)print("y: ",y)myFun(10)

Output
x:  10y:  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 the caller does not need to remember the order of parameters.

Python
defstudent(fname,lname):print(fname,lname)student(fname='Geeks',lname='Practice')student(lname='Practice',fname='Geeks')

Output
Geeks PracticeGeeks Practice

Positional Arguments

We used thePosition argument during the function call so that the first argument (or value) is assigned to name and the second argument (or value) is assigned to age. By changing the position, or if you forget the order of the positions, the values can be used in the wrong places, as shown in the Case-2 example below, where 27 is assigned to the name and Suraj is assigned to the age.

Python
defnameAge(name,age):print("Hi, I am",name)print("My age is ",age)print("Case-1:")nameAge("Suraj",27)print("\nCase-2:")nameAge(27,"Suraj")

Output
Case-1:Hi, I am SurajMy age is  27Case-2:Hi, I am 27My age is  Suraj

Arbitrary Keyword  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)

Example 1: Variable length non-keywords argument

Python
defmyFun(*argv):forarginargv:print(arg)myFun('Hello','Welcome','to','GeeksforGeeks')

Output
HelloWelcometoGeeksforGeeks

Example 2:Variable length keyword arguments

Python
defmyFun(**kwargs):forkey,valueinkwargs.items():print("%s ==%s"%(key,value))myFun(first='Geeks',mid='for',last='Geeks')

Output
first == Geeksmid == forlast == Geeks

Docstring

The first string after the function is called the Document string orDocstring 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

Python
defevenOdd(x):"""Function to check if the number is even or odd"""if(x%2==0):print("even")else:print("odd")print(evenOdd.__doc__)

Output
Function to check if the number is even or odd

Python Function within Functions

A function that is defined inside another function is known as theinner function ornested function. Nested functions can access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function.

Python
deff1():s='I love GeeksforGeeks'deff2():print(s)f2()f1()

Output
I love GeeksforGeeks

Anonymous Functions in Python

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.

Python
defcube(x):returnx*x*x# without lambdacube_l=lambdax:x*x*x# with lambdaprint(cube(7))print(cube_l(7))

Output
343343

Return Statement in Python Function

Thereturnstatement in Python is used to exit a function and send a value back to the caller. It can return anydata type, and if multiple values are separated by commas, they are automatically packed into atuple. If no value is specified, the function returnsNoneby default.

Syntax:

return [expression]

Explanation:

  • return:Ends the function and optionally sends a value to the caller.
  • [expression]:Optional value to return, defaults to None if omitted.

Example: Python Function Return Statement

Python
defsquare_value(num):"""This function returns the square    value of the entered number"""returnnum**2print(square_value(2))print(square_value(-4))

Output
416

For more information, refer to this article: Python return statement

Pass by Reference and 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 Python, a new reference to the object is created. Parameter passing in Python is the same as reference passing in Java.

Python
# Here x is a new reference to same list lstdefmyFun(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)

Output
[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 parameters is broken. For example, consider the below program as follows:

Python
defmyFun(x):x=[20,30,40]lst=[10,11,12,13,14,15]myFun(lst)print(lst)

Output
[10, 11, 12, 13, 14, 15]

Another example demonstrates that the reference link is broken if we assign a new value (inside the function). 

Python
defmyFun(x):x=20x=10myFun(x)print(x)

Output
10

Exercise: Try to guess the output of the following code. 

Python
defswap(x,y):temp=xx=yy=tempx=2y=3swap(x,y)print(x)print(y)

Output
23

Recursive Functions in Python

Recursionin Python refers to when a function calls itself. There are many instances when you have to build a recursive function to solveMathematical and Recursive Problems.

Using a recursive function should be done with caution, as a recursive function can become like a non-terminating loop. It is better to check your exit statement while creating a recursive function.

Python
deffactorial(n):ifn==0:return1else:returnn*factorial(n-1)print(factorial(4))

Output
24

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.

Quiz:

Related Posts:

Recommended Problems:


Python Functions
Visit Courseexplore course icon
Video Thumbnail

Python Functions

Video Thumbnail

How Functions Work in Python

Improve

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp