Define and Use the Functions
Learn to divide a program into functions or subprograms in Python.
Function
We can divide a program into procedural components or modules called functions in Python. We are already familiar with functions like print()
, input()
, range()
and len()
. Functions can be reused in a programming technique called the modular or procedural approach, also known as the divide and conquer approach. We should always try to design functions that can be copied and reused in other programs too.
Broadly, there are two types of functions, which we’ll explore in the following sections.
Structure of a function
The following slides illustrate various parts of a function definition:
A function name can only contain letters (
A
—Z
anda
—z
) and the underscore symbol (_
). It may also contain digits (0
–9
), but the function name can’t start with those. For example,Key_2
is a valid function name, but2_key
is not. Function names are case-sensitive, meaning thatname
,Name
, andNAME
are three different functions.
There are two main parts of a function definition:
- Header: The first line, ending on the colon.
- Body: The block of statements below the function header.
The function header contains the def
, the function name sayHello
, the parameters in ()
, and :
to indicate the end of the header. All the statements in the function body are written with indentation (extra spaces at the start of each line).
Let’s write code for the above example.
def sayHello(): # Definition of functionprint ("Hello")sayHello()
In the last line, we’re telling the program to run the function sayHello()
...