Thursday, 4 April 2024

Python Function

 

Function


A function in Python is an aggregation of related statements designed to perform a computational, logical, or evaluative task. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can call the function. 


Functions can be both built-in or user-defined. It helps the program to be concise, non-repetitive, and organized.

Syntax: 

def function_name(parameters):

    """docstring"""

    statement(s)


Example:

Program:

# 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

evenOdd(2)

evenOdd(3)

# Scripts Ends 

Output:

even

odd

 

Rules for naming python function (identifier)

  1. It can begin with either of the following: A-Z, a-z, and underscore(_).

  2. The rest of it can contain either of the following: A-Z, a-z, digits(0-9), and underscore(_).

  3. A reserved keyword may not be chosen as an identifier.

It is good practice to name a Python function according to what it does.


Python Function Parameters

Sometimes, you may want a function to operate on some variables, and produce a result. Such a function may take any number of parameters. Let’s take a function to add two numbers.

Example:

Program:

def sum(a,b):

    c=a+b

    print(c)

#Function complete


#call sum function with parameters

sum(5,6)

# Scripts Ends 

Output:

11


Python return statement

A Python function may optionally return a value. This value can be a result that it produced on its execution. Or it can be something you specify- an expression or a value.

Example:

Program:

def sum(a,b):

    return a+b


print(sum(2,3))

# Scripts Ends 

Output:

5


No comments:

Post a Comment

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts