Movatterモバイル変換


[0]ホーム

URL:


Open In App

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.

use_of_function_in_javascript_12.webp

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:

Python Functions
Syntax of Python Function Declaration

Here, we define a function using def that prints a welcome message when called.

Python
deffun():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.

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

Output
Welcome to GFG

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:

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.

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

Output
EvenOdd

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.

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

Output
x:  10y:  50

2. Keyword Arguments

In keyword arguments, values are passed by explicitly specifying the parameter names, so the order doesn’t matter.

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

Output
Geeks PracticeGeeks Practice

3. Positional Arguments

In positional arguments, values are assigned to parameters based on their order in the function call.

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

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.

Python
defmyFun(*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')

Output
Non-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.

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

Output
I 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.

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 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).

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

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

Output
[20, 11, 12, 13]10

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.

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.

Related Links:

Recommended Problems:


Python Functions
Visit Courseexplore course icon
Video Thumbnail

Python Functions

Video Thumbnail

How Functions Work in Python

Video Thumbnail

Applications of Functions.

Improve
Improve

Explore

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