Search⌘ K
AI Features

Define and Use the Functions

Explore how to define and utilize functions in Python to organize code efficiently. Understand function structure, naming rules, parameter use, and the return statement. Practice creating reusable functions and interpreting their execution order to build modular programs.

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 (AZ and az) and the underscore symbol (_). It may also contain digits (09), but the function name can’t start with those. For example, Key_2 is a valid function name, but 2_key is not. Function names are case-sensitive, meaning that name, Name, and NAME 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 keywordThe keywords are predefined by the language. 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.

Python 3.10.4
def sayHello(): # Definition of function
print ("Hello")
sayHello()

In the last line, we’re telling the program to run the function sayHello(). This line is known as the function call or calling the function.

Execution sheet for function calls

Let’s look at the following code before working on its execution sheet:

Python 3.10.4
def first():
print('Now inside the function "first".')
def second():
print('Now inside the function "second".')
print('Main program is starting here.')
first() # calling first
print('Back in main program.')
second()# calling second
print('Back in main program again.')

In the program above:

  • We defined two simple functions—first() and second().
  • We demonstrate the sequence of execution with the help of print() statements.
Execution flow of function calling
Execution flow of function calling

The most important column to understand the sequence of execution is the PS# column. The sequence of PS# for the above program is 7,8,1,2,9,10,4,5,117, 8, 1, 2, 9, 10, 4, 5, 11.

Here’s another code snippet to help us understand the execution sequence of function calls. The sequence of PS# for the following program is 9,10,4,5,6,1,2,7,119, 10, 4, 5, 6, 1, 2, 7, 11.

Python 3.10.4
def deeper() :
print('Now inside the function "deeper".')
def deep() :
print('Now inside the function "deep".')
deeper(); # Call function deeper
print('Now back in "deep".')
print('Main program is starting here.')
deep() # Call function deep
print('Back in the main program.')

The execution sequence can also be visualized as follows:

The above illustration shows the PS# and the depth of each function call more clearly. The first two statements are from the main program, the next three from the function deep(), the next one from the function deeper(), and the last one again from the main program. The main program is the caller of the deep() function. The deep() function is the caller of deeper().

The return statement

The following figure illustrates another function that returns a value. The example shows (1) how to use the return statement in the function body and (2) how to write the parameters (a,b) in the function header.

Note: Every function in Python is a value-returning function. When we don’t have a return statement, Python implicitly returns None.

Let’s write out the code for the above example.

Python 3.10.4
def getSum(a,b): # Definition of the function
mysum = a + b # Adding a and b and assigning the result in variable mysum
return mysum # returning mysum value
print(getSum(5,6))

In the above code:

  • The last line calls the print() function. It invokes the getSum() function with the values 5 and 6 as arguments for the parameters a and b, respectively.
  • The variable mysum holds the sum of a and b, which is 11.
  • The statement return mysum returns 11 to the print() statement as a result of the function call.

Practice creating and calling functions

The following are a few example programs to practice creating and calling functions. By clicking on the “Show Solution” button, you’ll find a program that solves the respective problem. You may copy and paste the given solution into the code widget to make sure that the output of your solution matches the given solution. There may be several ways of writing correct solutions in programming.

Function to create a multiplication table

Write a function showTableOf4() that displays 20 terms of the table of 4. Call your function to display the results.

Sample output

4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40
4 x 11 = 44
4 x 12 = 48
4 x 13 = 52
4 x 14 = 56
4 x 15 = 60
4 x 16 = 64
4 x 17 = 68
4 x 18 = 72
4 x 19 = 76
4 x 20 = 80
Python 3.10.4
# Write your code below

Function to search a string in a list

Write a function that checks if a string or character is present in the list. If it’s present, display its index in the list. Call your function to display the results.

Sample input 1

  • First parameter: list
    ['2','55','888','9','30','45']
    
  • Second parameter: string
    '888'
    

Sample output 1

 888 is found at index 2

Sample input 2

  • First parameter: list
    ['2','55','888','9','30','45']
    
  • Second parameter: string
    '50'
    

Sample output 2

50 is not found in the list
Python 3.10.4
# Write your code below

Function to display Fibonacci sequence

A Fibonacci sequence is a sequence in which each number is the sum of the two preceding ones. Write a function, fibo(), that receives the parameter n to specify the number of terms of the Fibonacci sequence. That function will return a list containing the sequence. Call your function to display the results.

Sample input

10

Sample output

First 10 terms of Fibonacci sequence are:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
*** End of generating Fibonacci Numbers ***
Python 3.10.4
# Write your code below