Skip to content

Python user-defined functions | Basics

  • by

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.

def function_name(parameters):
    # Function body
    # Perform operations
    # Return a value (optional)
  • def: It’s the keyword used to define a function.
  • function_name: This is the name you choose for your function. It should follow the Python naming conventions.
  • parameters: These are optional inputs that you can pass to the function. You can have zero or more parameters separated by commas.
  • function body: This is the block of code that gets executed when the function is called. It should be indented under the def statement.
  • return (optional): It specifies the value that the function should return. If no return statement is used, the function returns None by default.

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

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading