Creating a Function in Python
We can create a user-defined function in Python, using the def keyword. We can add
any type of functionalities and properties to it as we require.
# A simple Python function
def fun():
print("Welcome to GFG")
# Driver code to call a function
fun()
2222222222222
Python Function with Parameters
If you have experience in C/C++ or Java then you must be thinking about the return
type of the function and data type of arguments. That is possible in Python as well
(specifically for Python 3.5 and above).
def add(num1: int, num2: int) -> int:
"""Add two numbers"""
num3 = num1 + num2
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
3333333333
Python Function Arguments
Arguments are the values passed inside the parenthesis of the function. A function
can have any number of arguments separated by a comma.
In this example, we will create a simple function in Python to check whether the
number passed as an argument to the function is even or odd.
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)
Default Arguments
A default argument is a parameter that assumes a default value if a value is not
provided in the function call for that argument. The following example illustrates
Default arguments.
# Python program to demonstrate
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Driver code (We call myFun() with only
# argument)
myFun(10)
Types of Python Function Arguments
Python supports various types of arguments that can be passed at the time of the
function call. In Python, we have the following 4 types of function arguments.
Default argument
Keyword arguments (named arguments)
Positional arguments
Arbitrary arguments (variable-length arguments *args and **kwargs)
Let’s discuss each type in detail.
Default Arguments
A default argument is a parameter that assumes a default value if a value is not
provided in the function call for that argument. The following example illustrates
Default arguments.
# Python program to demonstrate
# Python program to demonstrate
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Driver code (We call myFun() with only
# argument)
myFun(10)