Page 81 - Touhpad Ai
P. 81
User-Defined Functions
User-defined functions are created by the user according to the need of the program. Once the user defines a function,
the user can call it in the same way as the built-in functions. User-defined functions are divided into various categories
based on the parameters and return type. The functions that do not take any parameter or return anything are called
type 1 functions.
The type 2 functions take parameters but do not return anything. The type 3 functions take parameters and return output.
Creating a Function
We can create a function in the following steps:
u Defining a Function: We use the def keyword to begin the function definition.
u Naming a Function: Provide a meaningful name to your function.
u Supply Parameters: The parameters (separated by commas) are given in the parenthesis following the name of the
function. These are basically the input values we pass to the function.
u Body of the function: The body of the function contains Python statements that make our function perform the
required task. Syntax of creating a function is:
def < name of the function > (list of parameters)
<body>
Calling a Function
A function can be called anytime from other functions or from the command prompt after the definition. For calling a
function, we type the function and pass the parameters.
To call a function.
def my_function( ): Name of a function
print("Hello") Body of a function
my_function( ) Function call
Program 23: To add two numbers using all the three types of built-in functions.
# Typel Function:
def add1():
a = int (input("Enter the first number: "))
b = int (input("Enter the second number: "))
c = a+b
print("The sum of both the numbers is " + str(c))
# Type2 Function:
def add2(a, b):
c = a+b
print("The sum of both the numbers is " + str(c))
# Type3 Function:
def add3(a, b):
c = a+b
return (c)
print("Calling Typel function")
add1()
Basic Concepts of Artificial Intelligence 79

