Lecture 06
Lecture 06
-
Functions
Fall 2021
Functions
Definition
A function is a named sequence of statements that performs a specific
task or useful operation
Benefits of Modularizing
Simpler Code: much easier to read
Code Reuse: execute function any time it is needed
Better Testing: isolating errors is easier when programs are
modularized
Faster Development: some common tasks can be re-used for other
programs
Introduction to Computer Programming - Fall 2021 2 / 57
Functions Void functions Value-Returning functions Strings as Objects
Functions
Schematic
INPUTS OUTPUT
Argument1
Argument2
Function Returned Value
Argument3
function name
Argumentn
Inputs/Outputs
Functions
Function names
Just like variables, functions are named
Functions
2 types of functions
We will learn to write 2 types of functions:
Void functions (without output)
Value-Returning functions (with an output)
Void functions
It executes the statements it contains and then terminates
Value-Returning functions
It executes the statements it contains and then returns a value back
to the statement that called it
Void functions
Defining a function
To create a function, you write its definition
Syntax:
def function name(): # function header
statement1 # function body
statement2
statement3
...
Calling a function
To execute a function, you must call it
Syntax:
function name()
Introduction to Computer Programming - Fall 2021 6 / 57
Functions Void functions Value-Returning functions Strings as Objects
Void functions
display pattern.py
Output:
1 #This program demonstrates a void function
2 |#####|
3 #First, we define a function named display | |
4 def display(): | |
5 for i in range(3): |#####|
6 print('|#####|') | |
7 print('| |') | |
8 print('| |') |#####|
9 | |
10 #Second, we call the display function | |
11 display()
Link to PythonTutor
Void functions
display pattern2.py
Void functions
Local variables
a local variable is a variable created inside a function’s definition
another way of saying this is: all of the variables in your function
definition are local to that function
they cannot be used / accessed by statements outside of the
current function definition
different functions can have local variables of the same name, and
they will not interfere with each other
Void functions
Namespaces
A namespace is:
a mapping of names to values
a collection of identifiers (variable names, function names, etc.) that
belong to a module or a function
All variables and function names that are built-in or that you create
are part of a namespace
the name print identifies a function named print()
Scope
the scope of a variable is the part of the program where this
variable can be accessed
a variable is only visible to statements in the variable’s scope
the scope of a variable defined within a function is the body of the
function itself
in the context of namespaces, a scope is the textual region of a
program where names in a namespace are directly accessible
Introduction to Computer Programming - Fall 2021 10 / 57
Functions Void functions Value-Returning functions Strings as Objects
Void functions
bad scope.py
3 #definition of print_value
4 def print_value():
5 print(value)
6
7 #definition of assign_value
8 def assign_value():
9 value = 'Hello World!'
10
Link to PythonTutor
Introduction to Computer Programming - Fall 2021 11 / 57
Functions Void functions Value-Returning functions Strings as Objects
Void functions
3 scopes in Python
local scope - identifiers (variables, function names, etc.) declared
within a function
these identifiers are kept in the namespace that belongs to the
function
each function has its own namespace
global scope - all identifiers (variables, function, names, etc.)
declared within the current module, or file
built-in scope - all identifiers built into Python
identifiers that can be used without having to import anything
( range , print , etc.)
(almost) always available
Void functions
Scope
identifiers in the global scope (that is, the file), are available
everywhere, even in functions
however, within a function, identifiers in the local scope take
precedence
identifiers within a function’s local scope are not available outside
of the function
Void functions
global variable.py
3 #definition of print_value
4 def print_value():
5 print(value)
6
7 #Global variable
8 value = 'Hello World'
9 #print the value
10 print_value()
Link to PythonTutor
Void functions
global variable2.py
3 #definition of print_value
4 def print_value():
5 value = 'Local or global?'
6 print(value)
7
8 #Global variable
9 value = 'I am global'
10 #call print_value
11 print_value()
12 #print the value
13 print(value)
Void functions
Scope Summary
variables and function definitions declared outside of a function (in
the global scope) can be accessed within a function
variables declared inside of a function (local) cannot be accessed
outside of a function (they are out of scope)
variables declared within a function do not override those declared
outside of a function
global variable
Inside a function, a global variable can be read.
Void functions
10 access_to_global()
11
12 print(a)
Void functions
Passing data into a function
Sometimes, it is useful to send one or more pieces of data into a function.
name of function(5,'Hello')
Introduction to Computer Programming - Fall 2021 18 / 57
Functions Void functions Value-Returning functions Strings as Objects
Void functions
Link to PythonTutor
Introduction to Computer Programming - Fall 2021 19 / 57
Functions Void functions Value-Returning functions Strings as Objects
Void functions
two parameters.py
Link to PythonTutor
Void functions
Void functions
two parameters2.py
Link to PythonTutor
In this example, it still works but the function was not intended this way
(according to parameters names)!!!
Void functions
main() function
It is common for a program to have a main() function that is called
when the program starts
Void functions
Flowchart
Print
|#####|
Ask for ladder height
→ height range(height param)
Print
| |
Void functions
1 #definition of the main function
2 def main():
3 height = int(input('Height of the ladder?\n> '))
4 display_ladder(height)
5
11 #fdefinition of display_one_step
12 def display_one_step():
13 print('|#####|')
14 print('| |')
15 print('| |')
16
Void functions
Exercise
Create a function called compute area rectangle()
it should take two arguments, length and width of a rectangle
it will calculate rectangle’s area
. . . and print out the resulting area
Void functions
Exercise
Create a function called compute area rectangle()
it should take two arguments, length and width of a rectangle
it will calculate rectangle’s area
. . . and print out the resulting area
Void functions
Exercise
Write a program using the previous function that:
asks the user for a length
asks the user for a width
prints out the resulting area
Void functions
Exercise
Write a program using the previous function that:
asks the user for a length
asks the user for a width
prints out the resulting area
1 def main():
2 length_rectangle = int(input("Length of rectangle:\n> "))
3 width_rectangle = int(input("Width of rectangle:\n> "))
4 compute_area_rectangle(length_rectangle, width_rectangle)
5
10 main()
Introduction to Computer Programming - Fall 2021 29 / 57
Functions Void functions Value-Returning functions Strings as Objects
Value-Returning functions
Output of a function
So far, we have defined functions that only execute statements
(Void functions)
Known examples
math.randint(1,6) str(54)
int("156") range(10)
input('foo') len("qwertyuiop")
type("Hello") print("abc") ???
Value-Returning functions
No return value
Actually, if you call a function that seemingly does not return one. . .
you do get a value!
you get a special value called None , of NoneType type
None represents the absence of a value!
>>> a = print('abc')
abc
>>> type(a)
<class 'NoneType'>
>>> print(a)
None
Value-Returning functions
Returning values
we can create fruitful functions, that is. . .
value-returning functions
just use the keyword return , followed by the value that you want
to give back
here is one of our previous example rewritten so that rather than
printing out the new greeting, it returns a string
1 #this function has two parameters: greeting and num
2 def greet_more_input(greeting, num):
3 s = greeting * num
4 return s
5
Value-Returning functions
return statement
return statement immediately stops the execution of a function
. . . and returns the value that follows it to the function call
statement
the value can be any value!
it can even be an expression
Value-Returning functions
Exercise
These functions are contrived examples of what you can do with return.
What type and value do they return?
def foo():
return "foo"
def bar():
return "b" + "ar"
import math
def baz():
return str(math.sqrt(100)) + "!"
Value-Returning functions
Exercise
These functions are contrived examples of what you can do with return.
What type and value do they return?
def foo():
return "foo"
def bar():
return "b" + "ar"
import math
def baz():
return str(math.sqrt(100)) + "!"
Value-Returning functions
Value-Returning functions
4 def area(R):
5 a = math.pi * (R ** 2)
6 return a
Value-Returning functions
4 def area(R):
5 return math.pi * (R ** 2)
Value-Returning functions
print vs return
What’s the difference between printing in a function and returning a
value from a function?
printing alone will not give you back a value for a function!
however, you can print and return
useful for debugging
see the example below. . . where we print out what s is before
returning it
Value-Returning functions
Stopping Execution
The return statement stops execution of your function immediately.
What gets printed in the following example?
1 def foo():
2 print("one")
3 print("two")
4 return "foo"
5 print("three")
6
7 foo()
Value-Returning functions
Stopping Execution
The return statement stops execution of your function immediately.
What gets printed in the following example?
1 def foo():
2 print("one")
3 print("two")
4 return "foo"
5 print("three")
6
7 foo()
Output:
one
two
Value-Returning functions
1 def absolute_value(x):
2 if x >= 0:
3 return x
4 else:
5 return -x
Value-Returning functions
Value-Returning functions
1 def two_things():
2 return "two", "things"
3
4 a, b = two_things()
5 print(b, a)
Strings as Objects
Strings as Objects
Calling Methods
How do you call a method?
For example, if you had a particular object named leo , how would you
call the get an oscar() method on it to tell it to go get its Oscar?
leo = Actor()
Strings as Objects
Strings as Objects
Yes. Strings are objects. So they have functions at their disposal that
they can call on themselves.
Strings as Objects
Strings as Objects
1 print("123".isdigit())
2 print("1.23".isdigit())
3 print("one two three".isdigit())
4 print("onetwothree".isalpha())
5 print("one two three".isalpha())
6 print("one!".isalpha())
7 print("1".isalpha())
Strings as Objects
Output:
1 print("123".isdigit()) True
2 print("1.23".isdigit()) False
3 print("one two three".isdigit()) False
4 print("onetwothree".isalpha()) True
5 print("one two three".isalpha()) False
6 print("one!".isalpha()) False
7 print("1".isalpha()) False
Strings as Objects
find() method
find() returns the first index where the argument (a character or
substring) is found.
It returns -1 if the substring is not in the original string.
Optional arguments can be provided to set the starting and ending
characters in the string. . .
3 print(sentence.find("h"))
4 print(sentence.find("x"))
5 print(sentence.find("lo"))
6 print(sentence.find("World"))
Strings as Objects
find() method
find() returns the first index where the argument (a character or
substring) is found.
It returns -1 if the substring is not in the original string.
Optional arguments can be provided to set the starting and ending
characters in the string. . .
Output:
1 sentence = 'hello world!'
2
0
3 print(sentence.find("h"))
-1
4 print(sentence.find("x"))
3
5 print(sentence.find("lo"))
-1
6 print(sentence.find("World"))
Strings as Objects
strip() method
strip() removes leading and trailing whitespace (it can also remove
other leading and trailing characters when a parameter is given).
Strings as Objects
Programming Challenge
Write a function that returns the first word in a sentence where words are
separated by spaces.
it should take one argument, a string, and return a string
if the original string is only one word, return that word
if the original string is empty or starts with space, return an empty string
does not use looping at all
Strings as Objects
Programming Challenge
Write a function that returns the first word in a sentence where words are
separated by spaces.
it should take one argument, a string, and return a string
if the original string is only one word, return that word
if the original string is empty or starts with space, return an empty string
does not use looping at all
1 def get_first_word(s):
2 pos = s.find(" ")
3 if (len(s) == 0) or (pos == 0): # is empty or starts wit
4 return ""
5 elif (pos == -1): # the string is only one word
6 return s
7 else: # slices the string and returns the first word
8 return s[:pos]
9 print(get_first_word("hi there!"))
Introduction to Computer Programming - Fall 2021 55 / 57
10 print(get_first_word("hi"))
Functions Void functions Value-Returning functions Strings as Objects
Strings as Objects
Programming Challenge
Create a function called is digit that determines whether a string
only has numbers (0-9) in it.
it should take one argument, a string
it should return True only if the all characters in it are 0 through 9
if the original string is empty, return False
hint: a single line of code should do the trick
Strings as Objects
Programming Challenge
Create a function called is digit that determines whether a string
only has numbers (0-9) in it.
it should take one argument, a string
it should return True only if the all characters in it are 0 through 9
if the original string is empty, return False
hint: a single line of code should do the trick
1 def is_digit(s):
2 return s.isdigit()
3
4 print(is_digit("43"))
5 print(is_digit("4ab5"))