Python Program

Calling Function in Python

Calling a Function in Python

After creating a function in Python we can call it by using the name of the functions Python followed by parenthesis containing parameters of that particular function. Below is the example for calling def function Python.

# A simple Python function
def fun():
print(“Welcome to tech dcode”)

# Driver code to call a function
fun()

OUTPUT

Welcome to tech dcode

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 .

Python Function Syntax with Parameters

def function_name(parameter: data_type) -> return_type:
    """Docstring"""
    # body of the function
    return expression

The following example uses arguments and parameters that you will learn later in this article so you can come back to it again if not understood.

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}.”)

OUTPUT

The addition of 5 and 15 results 20.

# some more functions
def is_prime(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r = 3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True
print(is_prime(78), is_prime(79))

OUTPUT
False True

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)

 

OUTPUT

even

odd

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 function argument types in Python:

  • Default argument
  • Keyword arguments (named arguments)
  • Positional arguments
  • Arbitrary arguments (variable-length arguments *args and **kwargs)

 

 

Leave a Reply

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