Chapter 4
Writing Functions in
Contents:
• User-defined functions
• Recursive functions
• Python built-in functions
(c) Bharadwaj V Dept of ECE NUS (2023) 1
Functions – Towards a modular way of
solving a problem!
Different types of functions in Python!
• User-defined Functions
• Recursive Functions
• Lambda Functions (Advanced topic)
• Built-in Functions (~ 68 functions are available with Python
3.x – print(), len(), sum(), abs(), etc)
Refer to the following link for a list of built-in funcs:
> https://docs.python.org/3/library/functions.html#all
(c) Bharadwaj V Dept of ECE NUS (2023) 2
User-defined Functions
Observe this colon
Dummy arguments
Syntax to write a function:
def function_name (argument1, argument2, ...) :
statement_1
statement_2
....
return(a,b,…,z) # more than one value can be returned
def is a keyword; You can give any name to your
function (give a meaningful name); arguments
are the ones passed to the function for processing
(c) Bharadwaj V Dept of ECE NUS (2023) 3
def my_func(a,b): Function Mechanism
statement 1
statement 2
statement 3 Control jumps to
return statement 1 to begin
execution in the func
Statement a
Statement b
Statement c
my_func(x,y) # a func call is made here!
Statement e # after return the control comes back here to continue its
execution in the main program
Statement f
...
(c) Bharadwaj V Dept of ECE NUS (2023) 4
Run this code and see the action in pythontutor.com !
def add_numbers(x,y):
sum = x + y
return sum # this func returns the result
# following is your main program!
num1 = int(input('Enter an integer: '))
num2 = int(input('Enter another integer: '))
print("The sum is", add_numbers(num1, num2))
Here the function add_numbers() is “called” and we pass the required
arguments; Once the function is called the control jumps to the function
and the function executes. It then returns the result to the called program.
So, in our example, inside the print() function,add_numbers() is called
and hence it receives the the result “sum” and it is printed. 5
(c) Bharadwaj V Dept of ECE NUS (2023)
Passing arguments by Value versus Passing by
Reference – Concept!
(a) If an argument that is passed to a function is a mutable
type, then modifying a mutable type argument using a python
method (OR by directly referencing the contents of that
object), inside that function, will affect the original object!
(b) However, if you are using your own computation to modify
the passed object in the function, then it is considered only as
a local computation modifying that object, which means the
scope of the object is limited only to that function. Thus, when
the function exits, only the original value is retained! This is
even true for mutable object.
(c) Bharadwaj V Dept of ECE NUS 6(2023)
Passing arguments by Value versus Passing by
Reference – Concept!
(c) Now, if an argument that is passed is immutable then
modifying that argument inside the function has no effect
on the original value. Any modification made is only local to
that function.
Following tutorial would clarify this mechanism.
Tutorial 4.1: Demonstrate the mechanism of passing by
value and reference - PAY ATTENTION TO THE EXAMPLES
DEMONSTRATED IN THE LECTURE!
DIY! Create a string list; pass it to a function; use a
python method to modify and observe!
(c) Bharadwaj V Dept of ECE NUS (2023)
7
Tutorial 4.2 Design a simple pythonic (!) calculator that
can accept two numbers from the user and performs
basic arithmetic operations (add,sub,mult,div) based on
user’s choice. You may extend to other operations!
Tutorial 4.3 - Design a function to implement Tutorial 3.3
Tutorial 4.4 - Design a function to implement Tutorial 3.4
Tutorial 4.5 - Design a function to implement Tutorial 3.5
Tutorial 4.6 - Design a function to implement Tutorial 3.6
Tutorials 4.3 to 4.6 – Discussions in the classroom; You should attempt to write in func()
form. (c) Bharadwaj V Dept of ECE NUS (2023) 8
Bonus Problem!
Random number generation satisfying certain criteria.
Write the following using functions.
• Generate a set of 10 random numbers in the range (-
20,20) and generated numbers must skip the
following numbers: 0,-2,2,-11,17,19,-7
• Write a func() to determine smallest and largest
number in the generated numbers;
• Write a compute func() to determine all prefix-sums
for this generated list of numbers(refer to Chap 3)
Bonus Problem!
Write your “Cards Dealer” code (Chap 3 – Bonus problem!) as a
python function. Which part(s) of the code you will write
as a function? (c) Bharadwaj V Dept of ECE NUS (2023) 9
Bonus Problem! Word list analyzer - Classroom discussions
towards designing and writing a code! No code will be provided and you can
practice, if you wish. Possible solutions will be discussed during the lecture.
(Your contribution to this course!)
You are given 10,000 words as a list. See the code
provided to you! Write the following using functions.
• Write a function to determine the number of words (a
word should be at least with 2 characters) starting with each
alphabet and store your count in a dictionary as a
key:value pair. You can consider returning key & value
from your func() and add to a dictionary;
• Write a function to determine which alphabet has the
max and min number of words; In case of a tie, report
any one of them;(c) Bharadwaj V Dept of ECE NUS (2023) 10
Writing Recursive Functions
Function calling itself!
Example:
def my_first_recursion(k):
if(k>0):
result = k + my_first_recursion(k-1) How does this
print(result) recursion work?
else: Pay attention to
result = 0 this example demo.
return result Let us visualize on
pythontutor.com
n = int(input(‘Input an integer >0: ‘)
print(‘Result from the recursion: ‘)
my_first_recursion(n) # first time calling the func here
(c) Bharadwaj V Dept of ECE NUS (2023) 11
Tutorial 4.7 Write a recursion to compute factorial for a
given integer n from a user.
Tutorial 4.8 Write a recursion to compute the first n
terms in a Fibonacci series!
Start to think in terms of recursion! It simplifies your
coding effort to a significant extent and also gives
clarity to the code.
DIY! (Challenge) Write a function to check if a given
positive integer number is a Fibonacci number!
(Not for exam! )
(c) Bharadwaj V Dept of ECE NUS (2023) 12