Page 213 - Computer Science V2.0 Class 11
P. 213
The syntax for defining a function is as follows:
def function_name (comma_separted_dummy arguments):
Sequence of statements—Body of the function
Function definition begins with the keyword def, followed by the name of the function, followed by a pair of parenthesis
that encloses a list of dummy arguments (if any) separated by commas. Dummy arguments are used as names of
the objects for describing the computations inside a function. When a function is invoked, its dummy arguments
(also called formal parameters or input parameters) are replaced by actual arguments. Thus, dummy arguments act as
placeholders for the actual arguments. For, example, consider the built-in function abs():
>>> help(abs)
Help on built-in function abs in module builtins:
abs(x, /)
Return the absolute value of the argument.
>>> abs(-24)
24
When we invoked the function abs() with the actual argument -24, the dummy argument x (used inside the
function abs() for computing the absolute value) was replaced by the argument -24.
The rules for naming a function are the same as those for naming an identifier. Recall that name of an identifier should
not be a Python keyword. The first line of a function definition that ends with a colon is known as the function header.
The sequence of statements followed by the colon is right indented and forms the function's body (also called function
block). The sequence of statements included in a function's body is executed when it is invoked.
1. What is wrong with the following function header?
Def test():
2. What is wrong with the following function header?
def test()
3. What is wrong with the following function definition?
def test():
print("Hello")
Now we are ready to define the functions triangle() and rhombus() which form part of program 8.2a.
● In Line 1, the function header for the triangle() is defined.
● Note that the function definition begins with the keyword def, followed by the name of the function triangle(),
the parenthesis, and a colon at the end of the line. Lines 02–10, comprise a sequence of statements forming the
function's body.
● The Lines 02–06, span a multi-line string(called a docstring) enclosed within triple quotes for documentation
purposes and are ignored by the Python interpreter. *Further, as the triangle has a fixed structure, we do not
require user inputs.
● The Lines 07–10, print the triangle. Similarly, in lines 07–10, we develop another user-defined function rhombus(),
that prints the rhombus.
Program 8.2a: The program defines functions to display a triangle and a rhombus.
01 def triangle():
02 '''
03 Objective: To print the triangle
Introduction to Functions 199

