Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

CAT With Python - An Introduction to Functions (1)

This document introduces functions in Python, explaining their purpose in reducing code repetition by allowing named code blocks to be reused. It covers the concept of variable scope, distinguishing between local and global variables, and emphasizes the importance of functions in organizing code and enhancing readability. The document concludes by encouraging the practice of using functions, lists, and dictionaries for improved coding skills.

Uploaded by

dolphinwalk5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

CAT With Python - An Introduction to Functions (1)

This document introduces functions in Python, explaining their purpose in reducing code repetition by allowing named code blocks to be reused. It covers the concept of variable scope, distinguishing between local and global variables, and emphasizes the importance of functions in organizing code and enhancing readability. The document concludes by encouraging the practice of using functions, lists, and dictionaries for improved coding skills.

Uploaded by

dolphinwalk5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

CAT with Python - An introduction to Functions

February 5, 2023

# This is version 3 of this document


NOTE: If you are already familiar with functions, skip the first two introductory sections and jump
straight to the section about the scope of variables in page 3.

1 A repetitive example to begin with


The repetitive code below adds two numbers.
Notice how code has been copied, pasted and modified. We want to avoid doing this.
Shortly, functions will allow us to name code blocks so that we can invoke them repeatedly.
[1]: a = 3
b = 4

total = a + b

print(total)

# to add 5 and 7 we need to copy, paste and modify

a = 5
b = 7

total = a + b

print(total)

7
12

2 Still repetitive, but with named code blocks


A function is a named code block that performs a certain task.
All we have done below is to name the code blocks so that we can activate them as needed.
DEFining a function (i.e. naming the code block) does not do anything else. It does not run the
code.

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)

# above are just function definitions

# main program; call the two functions


add_3_and_4()
add_5_and_7()

7
12

3 Using functions to avoid repetition


We will now define a function that accepts two numbers (a and b).
The function will add them to create a total, then ‘return’ the total back to the caller.
The call to the function will send the two values to be added and the returned results will be stored
in variables.
[3]: def add(a, b):
total = a + b
return total

# main program
my_sum = add(3, 4)
another_sum = add(5,7)

# the returned totals get stored in my_sum and another_sum

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)

NameError: name 'my_number' is not defined

5 Reusing variable names due to different scopes (avoid this!)


In the code below, the x created inside the function is not visible outside the function.
The x created outside the function is a totally different x. They share the same name but are
independent of each other.
Calling the function does not make any difference.
Reusing variable names can be confusing so apply this wisely in your code. Actually no. Just don’t.
[5]: def my_function():
x = 10
print("x inside function is", x)

# 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

6 Sending local variables to the main program


We can allow the main program to see what the local variables contain by ‘returning’ them.
Also notice the description of what the function does enclosed by three single quotes ’ ’ ’. This is
good practice.
[6]: def my_function():
'''This function declares and returns four local variables'''
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}

return my_number, my_string, my_list, my_dictionary

# main program
a,b,c,d = my_function()

# the order of a,b,c,d matches the order of returned items

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}

7 Functions can see “main program” variables


When you create variables outside of all functions (i.e. in the “main program”), these variables are
accessible by all functions.
They are called “global” variables.
If you reuse a global variable name inside a function, the name becomes a brand new local variable
having nothing to do with the outside global variable. Remember, variable names created inside a
function are local and private to the function.

4
[7]: def my_function():
print(my_number)
print(my_string)

# You can see but not modify the original number and string

# my_number = 3.14 # will not change the original


# my_string = "new sentence" # neither will this

# this will be explained in the next section

def my_other_function():
print(my_list)
print(my_dictionary)

# you CAN modify the original list and 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}

8 Functions can modify the originals of certain data types


In the code block below, we create four (global) variables in the main program (a number, a string,
a list, and a dictionary).
We then call my_function() and send it the four items. You will recall this is not necessary because
the function can already ‘see’ these global variables. This is, however, a good convention that makes
it easy to see which function is accessing and changing what variables.

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}

# call the function and send it the four globals


my_function(my_number, my_string, my_list, my_dict)

# check if the originalss were changed


print(my_number)
print(my_string)
print(my_list)
for row in my_dict.items():
print(row)

6.28
onyx of black quartz, judge my vow
[1, 2, 3, 4, 5, 999]
('language', 'Python')
('rating', 10)
('learning_curve', 'shallow')

9 “Originals” of lists, dictionaries and sets are sent to functions


Once back to the main program, we notice that the number and the string have remained unchanged,
but the list and the dictionary have been modified, even though we did not ‘return’ anything!

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.

10 You must use functions in all future investigations (for at least


3 good reasons)
Because functions allow you to name code blocks, at a minimum, you will be able to organise your
code better.
Being able to send values to functions and returning the outcome means you can logically organise
your program, with clearly defined parts of your code doing a certain task.
Finally, because you can call the function as needed, you elimiate repetition and a function can be
shared by different parts of your program. You can even create helper functions that your functions
can call.
Functions, lists and dictionaries are very important at an intermediate level of coding skill, so make
sure to practice using them in your code. Refer to Grok Learning’s “Introduction to programming
II (Python)” course which is at an intermediate level.
Remember that as always, you can email isaac.kigodi@education.wa.edu.au if you are having any
difficulties, or you can come to the Maths office.

You might also like