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 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
return: This keyword is used to specify the value that the function should return. The
returnstatement is optional, and if it’s not present, the function returns
def keyword in Python
Simple example code.
def my_function(): print("Hello from a function") my_function()
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!
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)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.