Python def function full form is User-Defined Functions. Where the def keyword is used to define a function.
def function_name: statements...
Or
def function_name(arguments):
# function body
return
def
– keyword used to declare a functionfunction_name
– any name given to the functionarguments
– any value passed to functionreturn
(optional) – returns a value from a function
Python def function example
Simple example code where a function doesn’t have any arguments and doesn’t return any values.
def greet():
print('Hello World! Def function')
greet()
Output:
Define Python Function with Arguments
def add_numbers(num1, num2):
sum = num1 + num2
print('Sum: ', sum)
add_numbers(100, 200)
Output: Sum: 300
Function with return Statement
If we want our function to return some value then use the return
statement.
def find_square(num):
result = num * num
return result
square = find_square(3)
print('Square:',square)
Do comment if you have any doubts or suggestions on this Python basic 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.