Skip to content

def keyword in Python | Keyword

  • by

In Python def keyword is used to create, (or define) a function. With function, you can break the program into smaller and modular chunks.

def Keyword is placed before a function name that is provided by the user to create a user-defined function.

def function_name: 
    statements...

def keyword in Python

Simple example code.

def my_function():
    print("Hello from a function")


my_function()

Output:

def keyword in Python

Parameters (arguments) through to a function. It’s optional.

def greet(name):
    """
    This function greets to
    the person passed in as
    a parameter
    """
    print("Hello, " + name + ". Good morning!")


greet('JOHN')

Output: Hello, JOHN. Good morning!

The return statement is used to exit a function and go back to the place from where it was called.

def absolute_value(num):
    """This function returns the absolute
    value of the entered number"""

    if num >= 0:
        return num
    else:
        return -num


print(absolute_value(2))

print(absolute_value(-4))

Do comment if you have any doubts or suggestions on this Python keyword 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

Your email address will not be published. Required fields are marked *