Functions

Acknowledgement : the contents of this notebook are partially based on the book "Starting Out with Python (3rd Edition)".

A function is a group of statements that exist within a program for the purpose of performing a specific task. Benefits of breaking down a function into functions include

  • simpler code
  • code reuse
  • better testing
  • faster development
  • facilitation of teamwork

Defining and calling a void function

The code for a function is known as a function definition. To execute the function, you write a statement that calls it.

To create a function, you write

def function_name():
     statement
     statement
     etc.

In [1]:
# define a function
def message():
    print('This is a function')
    print('We call it message()')
In [2]:
# call a function
message()
This is a function
We call it message()
In [3]:
# we can also define multiple functions

# define the main function
def main():
    print('Starting a program.')
    message()
    print('Good bye')
    
# define the message function
def message():
    print('This is a message from a message function.')
    
# call the main function
main()
Starting a program.
This is a message from a message function.
Good bye
In [ ]:
# indentation in a function is very important!
In [4]:
# pausing execution until the user presses enter
input('Press enter to continue...')
Press enter to continue...
Out[4]:
''

Local variables

A local variable is created inside a function and cannot be accessed by statements that are outside the function. Different functions can have local variables with the same names because the functions cannot see each other's local varaibles.

In [6]:
# define the main function : below the variable "name" is defined in get_name() function.
# Hence, it is a local variable and cannot be used in the main() function.

def main():
    get_name()
    print('Hello',name)

# define the get_name function
def get_name():
    name = input('Enter your name: ')
    
# call the main function
main()
Enter your name: Krikamol
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-750ef3eae3b9> in <module>()
     11 
     12 # call the main function
---> 13 main()

<ipython-input-6-750ef3eae3b9> in main()
      4 def main():
      5     get_name()
----> 6     print('Hello',name)
      7 
      8 # define the get_name function

NameError: name 'name' is not defined
In [9]:
# a local variable cannot be accessed by code that appears 
# before the variable has been created.
def bad_function():
    print('The value is ',val)
    val = 99
    
# call the function
bad_function()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-9-1c1ae2b060b3> in <module>()
      6 
      7 # call the function
----> 8 bad_function()

<ipython-input-9-1c1ae2b060b3> in bad_function()
      2 # before the variable has been created.
      3 def bad_function():
----> 4     print('The value is ',val)
      5     val = 99
      6 

UnboundLocalError: local variable 'val' referenced before assignment
In [10]:
# functions can have their own local variables
def func_1():
    x = 10
    print('X = ',x)
    
def func_2():
    x = 15
    print('X = ',x)
    
def main():
    x = 20
    func_1()
    func_2()
    print('X = ',x)
    
# call the main function
main()
X =  10
X =  15
X =  20

Passing arguments to functions

An argument is any piece of data that is passed into a function when the function is called. A parameter is a variable that receives an argument that is passed into a function.

In [11]:
# function with an argument
def main():
    value = 5
    show_square(value)

def show_square(number):
    result = number ** 2
    print(result)

# call the main function
main()
25
In [13]:
# call the same function with different argument.
show_square(20)
400

Passing multiple arguments

In [14]:
# define main function
def main():
    print('The sum of 5 and 10 is ')
    show_sum(5,10)

# define show_sum function
def show_sum(num1,num2):
    result = num1+num2
    print(result)
    
# call the main function
main()
The sum of 5 and 10 is 
15
In [15]:
show_sum(14,100)
114
In [16]:
# print first name and last name in a reverse order
def main():
    first_name = input('Enter your first name : ')
    last_name = input('Enter your last name : ')
    print('Your name reversed is ')
    reverse_name(first_name,last_name)
    
def reverse_name(first,last):
    print(last,first)
    
# call the main function
main()
Enter your first name : Krikamol
Enter your last name : Muandet
Your name reversed is 
Muandet Krikamol
In [17]:
# any changes that are made to the parameter variable will not affect the argument.
def main():
    value = 99
    print('[main] The value is ',value)
    change_value(value)
    print('[main] The value is ',value)

def change_value(arg):
    arg = 0
    print('[change_value] The value is ', arg)
    
# call the main function
main()
[main] The value is  99
[change_value] The value is  0
[main] The value is  99
In [18]:
# pass-by-value vs pass-by-reference

Keyword arguments

parameter_name=value

In [20]:
def main():
    show_values(5,10,12)
    print('')
    show_values(arg2=10,arg1=5,arg3=12)
    
def show_values(arg1,arg2,arg3):
    print('Arg1 = ',arg1)
    print('Arg2 = ',arg2)
    print('Arg3 = ',arg3)
    
# call the main function
main()
Arg1 =  5
Arg2 =  10
Arg3 =  12

Arg1 =  5
Arg2 =  10
Arg3 =  12

Global variables and global constants

A global variable is accessible to all the functions in a program file.

In [21]:
# create a global varaible
my_var = 10

def show_value():
    my_var = 20
    print(my_var)
    
show_value()
print(my_var)
20
10
In [22]:
# assign a value to global variable in function

# create a global variable 
number = 0

def main():
    global number
    number = int(input('Enter a number : '))
    show_number()
    
def show_number():
    print('The number you entered is ',number)
    
# call the main function
main()
Enter a number : 10
The number you entered is  10

Value-returning functions

A value-returning function is a function that returns a value back to the part of the program that called it.

In [23]:
# standard library functions and the import statement
import math
In [24]:
# generating random numbers
import random

number = random.randint(1,100)
print(number)
48
In [25]:
# another example
import random

def main():
    for count in range(10):
        # get a random number
        number = random.randint(1,10)
        
        # display the number
        print('The number is ',number)
        
# call the main function
main()
The number is  3
The number is  4
The number is  8
The number is  4
The number is  5
The number is  8
The number is  2
The number is  7
The number is  6
The number is  8
In [26]:
# the randrange, random, and uniform functions
import random

number = random.randrange(100)
print(number)
48
In [27]:
print(random.randrange(5,10))
5
In [28]:
print(random.randrange(0,101,10))
80
In [29]:
number = random.random()
print(number)
0.7535830801229281
In [30]:
number = random.uniform(1.0,10.0)
print(number)
2.8351295394992295
In [31]:
# random number seeds
random.seed(5)

for i in range(10):
    print(random.randint(1,10))
10
5
6
9
1
8
4
1
3
2

Writing your own value-returning functions

A value-returning function has a return statement that returns a value back to the part of the program that called it.

def function_name():
      statement
      statement
      etc.
      return expression

In [32]:
# example
def sum(num1,num2):
    return (num1 + num2) 
In [33]:
# call the sum function
res = sum(20,20)
print(res)
40
In [34]:
# return strings
def get_name():
    # get the user's name
    name = input('Enter your name : ')
    
    # return the name 
    return name

my_name = get_name()
print(my_name)
Enter your name : Krikamol
Krikamol
In [35]:
# returning boolean values
def is_even(number):
    if (number % 2) == 0:
        status = True
    else:
        status = False
        
    return status

# the program
number = int(input('Enter a number : '))
if is_even(number):
    print('The number is even.')
else:
    print('The number is odd.')
Enter a number : 19
The number is odd.
In [36]:
# returning multiple values
def get_name():
    first = input('Enter your first name : ')
    last = input('Enter your last name : ')
    
    # return both names
    return first, last

# a program
first_name, last_name = get_name()
print(first_name,last_name)
print(type(first_name))
Enter your first name : Krikamol
Enter your last name : Muandet
Krikamol Muandet
<class 'str'>
In [ ]:
# the math module
# the math.pi and math.e values
In [37]:
import math
math.e
Out[37]:
2.718281828459045

Storing functions in modules

A module is a file that contains Python code. Large programs are easier to debug and maintain when they are divided into modules.

In [38]:
# use circle module
import circle

radius = 5

area = circle.area(radius)
circ = circle.circumference(radius)

print('Area = ',area,', Circumference = ',circ)
Area =  78.53981633974483 , Circumference =  31.41592653589793
In [39]:
# use rectangle module
import rectangle

width = 5
length = 10

area = rectangle.area(width,length)
peri = rectangle.perimeter(width,length)

print('Area = ',area,', Perimeter = ',peri)
Area =  50 , Perimeter =  30
In [ ]: