Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python User Defined Functions
Next article icon

A User-Defined Function (UDF) is a function created by the user to perform specific tasks in a program. Unlikebuilt-in functions provided by a programming language, UDFs allow for customization and code reusability, improving program structure and efficiency.

Example:

Python
# function definationdeffun(x):if(x%2==0):print("even")else:print("odd")fun(2)# function calling

Output
even

Explanation: fun(x) checks if a number is even or odd using x % 2. If divisible by 2, it prints "even", otherwise "odd".

Syntax of User defined Functions

Function Defination:

def function_name(parameters):

# Function body

return result

Function call:

function_name(arguments)

Types of Users defined functions

1. Parameterized Functions

These functions accept parameters (arguments) to process and return results dynamically. Parameters allow for flexibility, enabling the function to handle different inputs each time it is called.

Python
# function definitiondeffun(name):print("Hello,",name)# function callfun("shakshi")

Output
Hello, shakshi

Explanation: fun(name) prints a greeting with the provided name. When called with "shakshi", it outputs "Hello, shakshi".

2. Functions with default arguments

A function can have default values assigned to its parameters. If no argument is provided when calling the function, it takes the default value.

Python
# function definition:deffun(x,y=50):print("x:",x)print("y:",y)# function callfun(10)

Output
x: 10y: 50

Explanation: fun(x, y=50)takes two parameters, wherey has a default value of 50. It prints the values ofx andy. When called with fun(10), it uses 10 forx and the default value 50 fory .

3. Keyword argument functions

Function arguments can be passed using keywords to improve code readability. This ensures the correct mapping of values to parameters, regardless of their order.

Python
# function definitiondeffun(name,age):print(name,"is",age,"years old.")# function callfun(age=21,name="shakshi")

Output
shakshi is 21 years old.

Explanation: fun(name, age) prints the name and age with the message "is [age] years old." It is called usingkeyword arguments(age=21, name="shakshi"), which assigns the values explicitly tonameandage.

4. Variable length argument functions

When the number of arguments is unknown, a function can accept multiple arguments using*args (for non-keyword arguments) or**kwargs (for keyword arguments).

Python
# function definationdeffun(*args):forarginargs:print(arg)# function callingfun("Python","Java","C++")

Output
PythonJavaC++

Explanation: fun(*args) uses a variable-length argument list, allowing it to accept any number of arguments. It then iterates through each argument and prints it.

5. Functions with Return value

A function can return a value using the return statement. This allows the function to send back a result for further computation.

Python
# function definationdeffun(num):returnnum*num# function callingres=fun(5)print(res)

Output
25

Explanation: fun(num) takes a numbernumas input and returns its square(num * num). When called withfun(5), it calculates 5 * 5 and stores the result inres.

6. Lambda functions

Alambda function is an anonymous (nameless) function that is defined in a single line using the lambda keyword. It is used for short, simple operations where defining a full function is unnecessary.

Python
# lambda function definition:res=lambdax:x*xprint(res(4))

Output
16

Explanation: lambda x: x * x takes one inputx and returns its square(x * x). When res(4) is called, it computes 4 * 4, resulting in 16 .

Pass by reference or Pass by value in Python

Python handles argument passing by reference for mutable objects (e.g.,lists,dictionaries) and by value for immutable objects (e.g.,integers,strings,tuples). If an immutable object is modified inside a function, a new object is created, whereas changes to mutable objects reflect outside the function.

Example :Pass by reference (Immutable data types)

Python
# function definitiondeffun(x):print("Value received:",x,"id:",id(x))# driver codex=12print("Value passed:",x,"id:",id(x))# function callfun(x)

Output
Value passed: 12 id: 140027364606256Value received: 12 id: 140027364606256

Explanation: fun(x)prints the value of x and its memory identifier usingid(). In the driver code,x is assigned the value 12 and before calling the function, both the value andid of x are printed. When the function is called, it prints the same information for x.

Example: Pass by Reference (Mutable Data Types)

Python
# Function definitiondeffun(a):a[0]=100# Changing the first element of the listprint("Inside function - lst:",a)# Driver codea=[1,2,3]# List is mutableprint("Before function call - lst:",a)# Function callfun(a)print("After function call - lst:",a)# List is modified outside the function

Output
Before function call - lst: [1, 2, 3]Inside function - lst: [100, 2, 3]After function call - lst: [100, 2, 3]

Explanation: fun(a)modifies the first element of the passed list([0] = 100). Since lists are mutable in Python, the change is reflected outside the function. Before the call,a is [1, 2, 3], and after the call, it becomes [100, 2, 3].


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