CAT With Python - An Introduction to Functions (1)
CAT With Python - An Introduction to Functions (1)
February 5, 2023
total = a + b
print(total)
a = 5
b = 7
total = a + b
print(total)
7
12
1
In order to invoke the function, we need to ‘call’ it using its name followed by brackets.
[2]: def add_3_and_4():
a = 3
b = 4
total = a + b
print(total)
def add_5_and_7():
a = 5
b = 7
total = a + b
print(total)
7
12
# main program
my_sum = add(3, 4)
another_sum = add(5,7)
print(my_sum)
print(another_sum)
7
12
2
4 The scope of variables
Variables CREATED inside a function only exist within the function.
They are called “local” variables and cannot be ‘seen’ by code outside the function.
[4]: def my_function():
my_number = 6.28
# main program
print(my_number)
# the code above fails because the variable is local to the function
# Python complains that the variable is not defined in the main program
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [4], in <cell line: 6>()
2 my_number = 6.28
5 # main program
----> 6 print(my_number)
# main program
x = 99
print("x in the main program is", x)
my_function()
print("x in the main program is still", x)
# the function call does not modify the x in the main program
3
x in the main program is 99
x inside function is 10
x in the main program is still 99
# main program
a,b,c,d = my_function()
print(a)
print(b)
print(c)
print(d)
6.28
onyx of black quartz, judge my vow
[1, 2, 3, 4, 5]
{'language': 'Python', 'rating': 10}
4
[7]: def my_function():
print(my_number)
print(my_string)
# You can see but not modify the original number and string
def my_other_function():
print(my_list)
print(my_dictionary)
# my_list.append(1000)
# my_dictionary['awesomeness']='maximum'
# this behaviour will be explained shortly but suffice it to say that ...
# ... ONLY the originals of lists, dictionaries and sets can be modified
# main program
my_number = 6.28
my_string = "onyx of black quartz, judge my vow"
my_list = [1,2,3,4,5]
my_dictionary = {'language':'Python','rating':10}
my_function()
my_other_function()
6.28
onyx of black quartz, judge my vow
[1, 2, 3, 4, 5]
{'language': 'Python', 'rating': 10}
5
The function my_function() attempts to:
1. Halve the number
2. Join ‘once again’ to the end of the string
3. Append 999 to the list
4. Insert a new key:value pair to the dictionary
Nothing is ‘returned’ to the main program.
# HINT: When reading code that makes use of functions, you should start with ...
# the main program, then read the functions as you encounter them.
# That way you get to understand the flow of the program.
[8]: def my_function(my_number, my_string, my_list, my_dict):
my_number = my_number / 2
my_string = my_string + ' once again'
my_list.append(999)
my_dict['learning_curve'] = 'shallow'
# main program
# create the four global variables
my_number = 6.28
my_string = "onyx of black quartz, judge my vow"
my_list = [1,2,3,4,5]
my_dict = {'language':'Python','rating':10}
6.28
onyx of black quartz, judge my vow
[1, 2, 3, 4, 5, 999]
('language', 'Python')
('rating', 10)
('learning_curve', 'shallow')
6
Memorize the fact that Python functions get ‘copies’ of the variables below and so the originals
cannot be changed…
• Numbers (integers, decimals e.t.c.)
• Strings
• Tuples (safe to ignore for now, or look them up if curious!)
Memorize that Python functions will receive the originals and thus be able to modify the following…
• Lists
• Dictionaries
• Sets (ignore for now, or look them up - quite useful)
Keep the above in mind when coding because not knowing when a function modifies the originals
can introduce hard-to-find bugs in your code.
Of course you can prevent the original from being changed. Simply create a copy of the list (or
dictionary or set) before sending to a function.
# copy the list
copy_of_list = original_list.copy()
# call a function and send it the copy
my_function(copy_of_list)
# you can copy a dictionary and a set in the same way
Advanced: The preceeding discussion is a simplified version of what is actually going on! To get
the real story look up ‘mutable’ and ‘immutable’ Python data types (lists, dictionaries and sets are
‘mutable’ data types). You can also look up variable scope, the ‘global’ keyword and the various
ways that variables can be sent to (and accepted by) functions.