Python user-defined functions | Basics

Functions that are defined by the developer/programmer for specific tasks are referred to as user-defined functions in Python. You have to use a def keyword is used to declare user-defined functions.

def function_name():
    statements
    .
    .

There are some built-in functions that are part of Python. Besides that, you can define functions according to project needs.

Example user-defined functions in Python

Simple example code.

Simple function

# Declaring a function
def myfun():
    print("Hello function")


# Calling function
myfun()

Output:

Python user-defined functions

Parameterized Function

The function that may take arguments(s) is called the parameters function. Users can also define Parameterized functions in Python.

def even_odd(x):
    if x % 2 == 0:
        print("even")
    else:
        print("odd")


# Driver code
even_odd(2)
even_odd(3)

Output: odd

One more example of a user-defined function

The defined function my_addition() adds two numbers and returns the result.

def add_numbers(x, y):
    res = x + y
    return res


print(add_numbers(5, 5))

Output: 10

Do comment if you have any doubts or suggestions on this Python function topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.