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: 
def function_name(parameters):
    # block of code
    # ...
    return result  # optional
  • def: This keyword is used to begin the function definition.
  • function_name: This is the name you give to your function. It should follow the rules for naming identifiers in Python.
  • parameters: These are the input values that the function takes. They are optional, and if a function doesn’t require any parameters, you can leave the parentheses empty.
  • block of code: This is the set of instructions that the function performs. It is indented under the def statement.
  • return: This keyword is used to specify the value that the function should return. The return statement is optional, and if it’s not present, the function returns None by default.

def keyword in Python

Simple example code.

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



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!")


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
        return -num



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

Discover more from Tutorial

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

Continue reading